diff --git a/flask_fixtures/__init__.py b/flask_fixtures/__init__.py index 7ca506f..d8518fb 100644 --- a/flask_fixtures/__init__.py +++ b/flask_fixtures/__init__.py @@ -104,14 +104,7 @@ def setup(obj): # Load all of the fixtures for filename in obj.fixtures: - for directory in fixtures_dirs: - filepath = os.path.join(directory, filename) - if os.path.exists(filepath): - # TODO load the data into the database - load_fixtures(obj.db, loaders.load(filepath)) - break - else: - raise IOError("Error loading '{0}'. File could not be found".format(filename)) + load_fixtures_from_file(obj.db, filename, fixtures_dirs) def teardown(obj): @@ -121,6 +114,19 @@ def teardown(obj): pop_ctx() +def load_fixtures_from_file(db, fixture_filename, fixtures_dirs=[]): + fixtures_dirs = set(fixtures_dirs) + fixtures_dirs.add('.') + for directory in fixtures_dirs: + filepath = os.path.join(directory, fixture_filename) + if os.path.exists(filepath): + # TODO load the data into the database + load_fixtures(db, loaders.load(filepath)) + break + else: + raise IOError("Error loading '{0}'. File could not be found".format(fixture_filename)) + + def load_fixtures(db, fixtures): """Loads the given fixtures into the database. """ @@ -251,4 +257,3 @@ class FixturesMixin(six.with_metaclass(MetaFixturesMixin, object)): fixtures = None app = None db = None - diff --git a/tests/test_load_fixtures_from_file.py b/tests/test_load_fixtures_from_file.py new file mode 100644 index 0000000..854ed0b --- /dev/null +++ b/tests/test_load_fixtures_from_file.py @@ -0,0 +1,41 @@ +from __future__ import absolute_import + +import os +import unittest + +from myapp import app +from myapp.models import db, Book, Author + +from flask_fixtures import load_fixtures_from_file, push_ctx, pop_ctx + +# Configure the app with the testing configuration +app.config.from_object('myapp.config.TestConfig') +fixtures_dirs = [os.path.join(app.root_path, 'fixtures')] + +class TestLoadFixturesFromFile(unittest.TestCase): + def setUp(self): + push_ctx(app) + # Setup the database + db.create_all() + # Rollback any lingering transactions + db.session.rollback() + + def tearDown(self): + db.session.expunge_all() + db.drop_all() + pop_ctx() + + def test_load_fixtures_file_json(self): + load_fixtures_from_file(db, 'authors.json', fixtures_dirs) + assert Author.query.count() == 1 + assert Book.query.count() == 3 + + def test_load_fixtures_file_json_abs(self): + load_fixtures_from_file(db, 'myapp/fixtures/authors.json') + assert Author.query.count() == 1 + assert Book.query.count() == 3 + + def test_load_fixtures_file_yaml(self): + load_fixtures_from_file(db, 'authors.yaml', fixtures_dirs) + assert Author.query.count() == 1 + assert Book.query.count() == 3 diff --git a/tox.ini b/tox.ini index 2d92a85..6db93bb 100644 --- a/tox.ini +++ b/tox.ini @@ -15,3 +15,4 @@ deps = discover nose pytest + pyyaml