Created
June 15, 2012 15:11
-
-
Save carljm/2936937 to your computer and use it in GitHub Desktop.
Using py.test with Django
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 os | |
def pytest_sessionstart(session): | |
""" | |
Set up the test environment. | |
Sets DJANGO_SETTINGS_MODULE and sets up a test database. | |
""" | |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") | |
from django.test.simple import DjangoTestSuiteRunner | |
# we don't actually let Django run the tests, but we need to use some | |
# methods of its runner for setup/teardown of dbs and some other things | |
session.django_runner = DjangoTestSuiteRunner() | |
# this provides templates-rendered debugging info and locmem mail storage | |
session.django_runner.setup_test_environment() | |
# this sets up a clean test-only database | |
session.django_db_config = session.django_runner.setup_databases() | |
def pytest_sessionfinish(session): | |
"""Tear down the test environment, including databases.""" | |
# makes the output look a bit more organized | |
print("\n") | |
session.django_runner.teardown_databases(session.django_db_config) | |
session.django_runner.teardown_test_environment() | |
def pytest_runtest_setup(item): | |
""" | |
Per-test setup. | |
Starts a transaction and disables transaction methods for the duration of | |
the test. The transaction will be rolled back after the test. This prevents | |
any database changes made to Django ORM models from persisting between | |
tests, providing test isolation. | |
""" | |
from django.test.testcases import disable_transaction_methods | |
from django.db import transaction | |
transaction.enter_transaction_management() | |
transaction.managed(True) | |
disable_transaction_methods() | |
def pytest_runtest_teardown(item): | |
""" | |
Per-test teardown. | |
Rolls back the Django ORM transaction. | |
""" | |
from django.test.testcases import restore_transaction_methods | |
from django.db import transaction | |
restore_transaction_methods() | |
transaction.rollback() | |
transaction.leave_transaction_management() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment