Skip to content

Instantly share code, notes, and snippets.

@chronossc
Created March 28, 2016 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chronossc/7f7c55156203b8a66179 to your computer and use it in GitHub Desktop.
Save chronossc/7f7c55156203b8a66179 to your computer and use it in GitHub Desktop.
Load a json for current tests module in tests/fixtures directory.
# -*- coding: UTF-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import json
import inspect
from os.path import abspath, dirname, join, isdir, isfile, sep
def load_json(path):
"""
Load a json for current tests module in tests/fixtures directory.
For instance, consider the fixture:
foobar/tests/fixtures/some/dir/with/a/deep/tree/fixtures.json
The test file: foobar/tests/foobar/test_foobar.py
In foobar.py you load the fixtures.json calling like:
load_json("some/dir/with/a/deep/tree/fixtures.json")
"""
# get the filename where load_json was called
filename = inspect.currentframe().f_back.f_code.co_filename
directory = dirname(abspath(filename))
parts = directory.split(sep)
# assert that there is a tests folder in path
try:
test_index = parts.index("tests")
tests_path = \
abspath(join(directory, *[".."] * len(parts[test_index:-1])))
assert isdir(tests_path)
except (AssertionError, ValueError):
raise ValueError("Base \"tests\" folder can not be found.")
# load the fixture
fixtures_path = abspath(join(tests_path, 'fixtures', path))
if isfile(fixtures_path):
with open(fixtures_path, 'r') as f:
return json.loads(f.read())
raise IOError("File \"{}\" can't be found.".format(fixtures_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment