SQLAlchemy doesn't let me set up Flask apps multiple times in a test fixture - flask

I am writing a Flask application that uses SQLAlchemy for its database backend.
The Flask application is created with an app factory called create_app.
from flask import Flask
def create_app(config_filename = None):
app = Flask(__name__)
if config_filename is None:
app.config.from_pyfile('config.py', silent=True)
else:
app.config.from_mapping(config_filename)
from .model import db
db.init_app(app)
db.create_all(app=app)
return app
The database model consists of a single object called Document.
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Document(db.Model):
id = db.Column(db.Integer, primary_key=True)
document_uri = db.Column(db.String, nullable=False, unique=True)
I am using pytest to do unit testing. I create a pytest fixture called app_with_documents that calls the application factory to create an application and adds some Document objects to the database before the test is run, then empties out the database after the unit test has completed.
import pytest
from model import Document, db
from myapplication import create_app
#pytest.fixture
def app():
config = {
'SQLALCHEMY_DATABASE_URI': f"sqlite:///:memory:",
'TESTING': True,
'SQLALCHEMY_TRACK_MODIFICATIONS': False
}
app = create_app(config)
yield app
with app.app_context():
db.drop_all()
#pytest.fixture
def app_with_documents(app):
with app.app_context():
document_1 = Document(document_uri='Document 1')
document_2 = Document(document_uri='Document 2')
document_3 = Document(document_uri='Document 3')
document_4 = Document(document_uri='Document 4')
db.session.add_all([document_1, document_2, document_3, document_4])
db.session.commit()
return app
I have multiple unit tests that use this fixture.
def test_unit_test_1(app_with_documents):
...
def test_unit_test_2(app_with_documents):
...
If I run a single unit test everything works. If I run more than one test, subsequent unit tests crash at the db.session.commit() line in the test fixture setup with "no such table: document".
def do_execute(self, cursor, statement, parameters, context=None):
> cursor.execute(statement, parameters)
E sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: document [SQL: 'INSERT INTO document (document_uri) VALUES (?)'] [parameters: ('Document 1',)] (Background on this error at: http://sqlalche.me/e/e3q8)
What I expect is that each unit test gets its own brand-new identical prepopulated database so that all the tests would succeed.
(This is an issue with the database tables, not the unit tests. I see the bug even if my unit tests consist of just pass.)
The fact that the error message mentions a missing table makes it look like the db.create_all(app=app) in create_app is not being called after the first unit test runs. However, I have verified in the debugger that this application factory function is called once for every unit test as expected.
It is possible that my call to db.drop_all() is an incorrect way to clear out the database. So instead of an in-memory database, I tried creating one on disk and then deleting it as part of the test fixture cleanup. (This is the technique recommended in the Flask documentation.)
#pytest.fixture
def app():
db_fd, db_filename = tempfile.mkstemp(suffix='.sqlite')
config = {
'SQLALCHEMY_DATABASE_URI': f"sqlite:///{db_filename}",
'TESTING': True,
'SQLALCHEMY_TRACK_MODIFICATIONS': False
}
yield create_app(config)
os.close(db_fd)
os.unlink(db_filename)
This produces the same error.
Is this a bug in Flask and/or SQLAlchemy?
What is the correct way to write Flask test fixtures that prepopulate an application's database?
This is Flask 1.0.2, Flask-SQLAlchemy 2.3.2, and pytest 3.6.0, which are all the current latest versions.

In my conftest.py I was importing the contents of model.py in my application like so.
from model import Document, db
I was running the unit tests in Pycharm using Pycharm's pytest runner. If instead I run tests from the command line with python -m pytest I see the following error
ModuleNotFoundError: No module named 'model'
ERROR: could not load /Users/wmcneill/src/FlaskRestPlus/test/conftest.py
I can get my tests running from the command line by fully-qualifying the import path in conftest.py.
from myapplication.model import Document, db
When I do this all the unit tests pass. They also pass when I run the unit tests from inside Pycharm.
So it appears that I had incorrectly written an import statement in my unit tests. However, when I ran those unit tests via Pycharm, instead of seeing an error message about the import, the scripts launched but then had weird SQL errors.
I still haven't figured out why I saw the strange SQL errors I did. Presumably something subtle about the way global state is being handled. But changing the import line fixes my problem.

Related

What's the best way to load stored procedures into the Django unit test database?

I've got some Postgres stored procedures that my selenium tests will depend on. In development, I load them with a line in a script:
cat stored_procedures.sql | python manage.py dbshell
This doesn't work when unit testing, since a fresh database is created from scratch. How can I load stored procedures saved in a file into the test database before unit tests are run?
I think you have few ways to make this. In my opinion, the best solution - to add migration with your custom SQL. In future, you'll need that migration not only at development, but also at production stage. So, It would be not clear deploy procedure, if you'll store change to DB in few places.
Other way - just to add execution of your SQL to setUp method of testCase.
Additional migration
You should create a new empty migration ./manage.py makemigrations --empty myApp
Add your SQL code to operations list
operations = [
migrations.RunSQL('RAW SQL CODE')
]
Another solution to this is to create a management command that executes the required SQL Query and then just execute this command at the very beginning of your tests.
Below is my case:
Management command:
import os
from django.core.management import BaseCommand
from django.db import connection
from applications.cardo.utils import perform_query
from backend.settings import BASE_DIR
class Command(BaseCommand):
help = 'Loads all database scripts'
def handle(self, **options):
db_scripts_path = os.path.join(BASE_DIR, 'scripts', 'database_scripts')
utils_path = os.path.join(db_scripts_path, 'utils.sql')
with open(utils_path, mode='r') as f:
sql_query = f.read()
with connection.cursor() as cursor:
cursor.execute(sql_query)
Now you can just go to the terminal and type
python manage.py load_database_scripts
and the scripts will be loaded.
With a helper function like this one
def load():
with django_db_blocker.unblock():
call_command('load_database_scripts')
You just call this load function before the test suite runs.

flask test_client() unittest

I am new to programming in general and this is my first web application in python (flask, sqlalchemy, wtforms, etc). I have been using the realpython.com course 2 as my study material on this subject. I have gotten to the point where i am learning about unit testing and i having trouble getting it to work correctly. I have compared the course example to the examples i found online and i am not seeing the issue with my code.
The problem i am encountering is that the test.py script correctly creates my test.db database but when it attempts to insert a test customer and it puts it into my production db (madsenconcrete.db) instead of my test db (test.db). If i remove the production db from the script directory it will raise this error when it cant find the db because its looking for madsenconcrete.db not test.db.
OperationalError: (sqlite3.OperationalError) no such table: customer [SQL: u'INSERT INTO customer (name, email, telephone, created_date) VALUES (?, ?, ?, ?)'] [parameters: ('Acme Company', 'acme#domain.com', '6125551000', '2016-01-03')]
I am not sure how to troubleshoot this issue. I have doing a lot of stare and compares and i do not see the difference.
import os
import unittest
import datetime
import pytz
from views import app, db
from _config import basedir
from models import Customer
TEST_DB = 'test.db'
class AllTests(unittest.TestCase):
############################
#### setup and teardown ####
############################
# executed prior to each test
def setUp(self):
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB)
app.config['SQLALCHEMY_ECHO'] = True
self.app = app.test_client()
db.create_all()
# executed after each test
def tearDown(self):
db.session.remove()
db.drop_all()
# each test should start with 'test'
def test_customer_setup(self):
new_customer = Customer("Acme Company", "acme#domain.com", "6125551000",
datetime.datetime.now(pytz.timezone('US/Central')))
db.session.add(new_customer)
db.session.commit()
if __name__ == "__main__":
unittest.main()
There would be an extensive amount of code i would have to paste so show all the dependencies. You can find the source code here.
https://github.com/ande0581/madsenconcrete
Thanks
Ultimately, the problem is that you are creating your db object from an already configured app:
# config
app = Flask(__name__)
app.config.from_object('_config')
db = SQLAlchemy(app)
If you use the create_app pattern (documented in more detail in this answer) you will be able to alter the configuration you are loading for your test application.

Running django unit tests from shell with ipython notebook has strange behavior

I'm using an ipyhton notebook connected to Django shell to run some tests. I am on django 1.4.
First, if I run as configured below sometimes it works perfectly and other times, it just hangs with no output and no errors. I have to completely kill the ipyhton kernel and close all notebooks and try again (when the hang event occurs, all open notebooks stop working)
If i inherit from unittest.TestCase instead of django.test.TestCase it works perfect every time. However, I need the latter so i can use the django's TestCase.client in my actual tests.
NOTE: In both cases I am skipping the test database because I'm getting a failure on a missing celery database. I will cross that bridge at another time.
The notebook:
from django.utils import unittest
from django.test import TestCase
from django.test.utils import setup_test_environment
from django.test.simple import DjangoTestSuiteRunner
class MyTestCase(TestCase):
def test_001(self):
print "ok"
def test_002(self):
self.assertEqual(True , True)
if __name__ == '__main__':
setup_test_environment()
runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
#old_config = runner.setup_databases()
result = runner.run_suite(suite)
#runner.teardown_databases(old_config)
runner.suite_result(suite, result)
In my case, I just created a test_runner function that accepts a test_class parameter, like this:
def test_runner(test_class):
from django.utils import unittest
from django.test.utils import setup_test_environment
from django.test.simple import DjangoTestSuiteRunner
setup_test_environment()
runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
result = runner.run_suite(suite)
runner.suite_result(suite, result)
After that, you could just run:
test_runner(MyTestCase)
in ipython notebook.
Make sure to use the one that's provided by django-extensions, by running:
manage.py shell_plus --notebook
Hope that helps.

Emulating an app with models in a django unittest

Im writing some code which retrieves info about installed apps, especially defined models, and then does stuff based on that information, but Im having some problems writing a clean, nice unittest. Is there a way to emulate or add an app in unittests without have to run manage.py startproject, manage.py startapp in my testsfolder to have a test app available for unittests?
Sure, try this on for size:
from django.conf import settings
from django.core.management import call_command
from django.test.testcases import TestCase
from django.db.models import loading
class AppTestCase(TestCase):
'''
Adds apps specified in `self.apps` to `INSTALLED_APPS` and
performs a `syncdb` at runtime.
'''
apps = ()
_source_installed_apps = ()
def _pre_setup(self):
super(AppTestCase, self)._pre_setup()
if self.apps:
self._source_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = settings.INSTALLED_APPS + self.apps
loading.cache.loaded = False
call_command('syncdb', verbosity=0)
def _post_teardown(self):
super(AppTestCase, self)._post_teardown()
if self._source_installed_apps:
settings.INSTALLED_APPS = self._source_installed_apps
self._source_installed_apps = ()
loading.cache.loaded = False
Your test case would look something like this:
class SomeAppTestCase(AppTestCase):
apps = ('someapp',)
In case you were wondering why, I did an override of _pre_setup() and _post_teardown() so I don't have to bother with calling super() in setUp() and tearDown() in my final test case. Otherwise, this is what I pulled out of Django's test runner. I whipped it up and it worked, although I'm sure that, with closer inspection, you can further optimize it and even avoid calling syncdb every time if it won't conflict with future tests.
EDIT:
So I seem to have gotten out of my way, thinking you need to dynamically add new models. If you've created an app for testing purposes only, here's what you can do to have it discovered during your tests.
In your project directory, create a test.py file that will contain your test settings. It should look something like this:
from settings import *
# registers test app for discovery
INSTALLED_APPS += ('path.to.test.app',)
You can now run your tests with python manage.py test --settings=myproject.test and your app will be in the installed apps.

How to use test fixtures with other framework then unit tests

I'm using lettuce framework for testing and i would like to run tests with fresh database with some test fixtures loaded. similarly to unit tests run, when test fixtures are defined
is it possible?
Here is a code snippet that loads the fixtures that's mostly taken from the Django test case. You just need to make sure that "db" points to the correct db (the test db). I do this by just passing in a custom settings file. "db" here points to just an alias, not an actual connection. If you are only using one database (not counting the test db) you just set this to 'default'. So if you test has a class attribute of 'fixtures' it will load the fixtures with the same rules as the loaddata management command.
if getattr(self, 'multi_db', False):
databases = connections
else:
databases = [DEFAULT_DB_ALIAS]
for db in databases:
if hasattr(self, 'fixtures'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
call_command('loaddata', *self.fixtures,
**{'verbosity': 0, 'database': db})
You will need to
import from django.core.management import call_command
to make this work.