/Loader.py Secret
Last active
October 6, 2022 01:13
Loader module for flask testing
This file contains 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 json | |
import os | |
from sqlalchemy import Table | |
from app import app, db | |
class Loader(object): | |
""" | |
Reusable class for loading fixture data into test databases. | |
""" | |
# TODO: Accept the app as a param to look up configs | |
# TODO: Load JSON files here instead of in the test | |
def __init__(self, db, filename): | |
self.connection = db.engine.connect() | |
self.filename = filename | |
self.metadata = db.metadata | |
def load(self): | |
with open(self.filename) as file_in: | |
self.data = json.load(file_in) | |
return self.load_from_file() | |
def load_from_file(self): | |
table = Table(self.data[0]['table'], self.metadata) | |
self.connection.execute(table.insert(), self.data[0]['records']) | |
return | |
class SomeTest(TestBase): | |
def setUp(self) -> None: | |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" | |
app.config['TESTING'] = True | |
db.create_all() | |
fixtures = [ | |
'courses.json', | |
'locations.json', | |
'roles.json', | |
'users.json', | |
] | |
self.client = app.test_client() | |
conn = db.engine.connect() | |
metadata = db.metadata | |
for filename in fixtures: | |
filepath = os.path.join(app.config['FIXTURES_DIR'], filename) | |
if os.path.exists(filepath): | |
loader = Loader(db, filepath) | |
loader.load() | |
else: | |
raise IOError("Error loading {0}: File could not be found".format(filepath)) | |
def tearDown(self): | |
db.drop_all() | |
db.session.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment