ktosiek / pytest-vcr

Py.test integration with VCR.py
MIT License
150 stars 25 forks source link

Using custom Serializer and Persister does, creates cassettes but never uses them for subsequent test runs. #39

Open akintaylor opened 4 years ago

akintaylor commented 4 years ago

Hello, I created a serializer and persister class. After the first run of tests, the cassettes are created, but when I run subsequently, network calls are made rather than using the stored cassettes. Does the current version have this functionality, it is mentioned in the docs but no extensive explanation is given. You can review the code samples below, perhaps there's something I am missing. Cheers

Here is a snippet of the serializer and persister classes:

import os
import pickle

class BinarySerializer:
    @classmethod
    def deserialize(cls, binary):
        return pickle.loads(binary)

    @classmethod
    def serialize(cls, string):
        return pickle.dumps(string)

class CustomPersister:
    @classmethod
    def load_cassette(cls, cassette_path, serializer=BinarySerializer):
        try:
            with open(cassette_path) as f:
                cassette_content = f.read()
        except OSError:
            raise ValueError("Cassette not found.")
        cassette = serializer.deserialize(cassette_content)
        return cassette

    @staticmethod
    def save_cassette(cassette_path, cassette_dict,
                      serializer=BinarySerializer):
        data = serializer.serialize(cassette_dict)
        dirname, filename = os.path.split(cassette_path)
        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)
        with open(cassette_path, "wb") as f:
            f.write(data)

Here is the snippet of vcr config:

@pytest.fixture()
def vcr(vcr):
    vcr.path_transformer = VCR.ensure_suffix('.pickle')
    vcr.register_serializer(name='binary', serializer=BinarySerializer())
    vcr.serializer = 'binary'
    vcr.register_persister(CustomPersister)
    return vcr