Newer
Older
"""
Fonctions génériques de pytest
"""
import msgpack
from lib.serializers import encode_datetime, decode_datetime
import re
import os
import json
# Passer à True pour génerer des JSON à côté des MP (plus lisible)
DEBUG_OUTPUT_JSON = False
def _sanitize(name):
"""
Replace certain characters (which might be problematic when contained in
strings which will be used as file names) by '-'s.
import from https://github.com/betamaxpy/betamax/blob/master/src/betamax/fixtures/pytest.py
"""
return re.sub(r'[\s/<>:\\"|?*]', '-', name)
@pytest.fixture
def load_object(request):
module = request.module.__name__
node = _sanitize(request.node.name).replace("test_fix_field_types",
'test_get_entries_from_postgis')
def load_file(file_path_template):
file_path = file_path_template.format(node)
with open(file_path, 'rb') as file_stream:
expected_data = msgpack.unpackb(file_stream.read(), raw=False, object_hook=decode_datetime)
return expected_data
yield load_file
@pytest.fixture
def verify_objects(request):
"""
fixture than compares data to expected data in file
If the file data doesn't exists, it whill be created with current data
"""
module = request.module.__name__
node = _sanitize(request.node.name)
def check_data(data, iteration=None):
if iteration is not None:
file_path = f'tests/data/{module}.{node}.{iteration}.mp'
else:
file_path = f'tests/data/{module}.{node}.mp'
if not os.path.exists(file_path):
with open(file_path, "wb") as file_stream:
the_body = msgpack.packb(data, use_bin_type=True, default=encode_datetime)
file_stream.write(the_body)
if DEBUG_OUTPUT_JSON:
with open(file_path+".json", "w") as file_stream:
the_body = json.dump(data, file_stream, default=encode_datetime, indent=4)
with open(file_path, 'rb') as file_stream:
expected_data = msgpack.unpackb(file_stream.read(), raw=False, object_hook=decode_datetime)
assert data == expected_data
return check_data