Last active
May 14, 2020 15:11
-
-
Save ramnes/6ecbeb99632282ae51febff1a9c9d032 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import json | |
import os.path | |
from pytest import fixture | |
def load_fixture(filepath): | |
with open(filepath) as file: | |
return json.load(file) | |
def autoload_fixture(caller=None): | |
"""Automatically load a JSON file named after the caller function name. | |
The fixture's JSON file path is guessed with the test name and path. For a | |
test called "test_something" located in | |
:code:`tests/foo/bar.py`, the file used to load the data | |
will be :code:`fixtures/foo/bar/test_something.json`. | |
""" | |
if not caller: | |
frame = inspect.stack()[1] | |
caller = frame[0].f_globals[frame[3]] | |
path = caller.__module__ | |
path = path.split('.')[1:] | |
path = '/'.join(path) | |
filename = "{}.json".format(caller.__name__) | |
filepath = os.path.join("fixtures/", path, filename) | |
return load_fixture(filepath) | |
@fixture | |
def autofixture(request): | |
"""Fixture that returns a dict from a JSON file named after the test. | |
See :func:`autoload_fixture` for more information on this fixture behavior. | |
""" | |
return autoload_fixture(caller=request.node.function) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment