Created
June 22, 2017 16:08
-
-
Save wimglenn/f032328a6b6a32422adc50db3fb957fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@pytest.fixture(autouse=True, scope='session') | |
def inject_test_settings(tmpdir_factory): | |
# cleans environment vars, sets up some temp space and data, etc | |
@pytest.fixture(autouse=True, scope='session') | |
def test_db(inject_test_settings): | |
# creates the test database [once] at the beginning of the test suite. | |
# drops it at the end of the suite. | |
@pytest.fixture(autouse=True, scope='session') | |
def test_engine(test_db): | |
# turn SAWarnings into exceptions when running tests | |
warnings.simplefilter('error', SAWarning) | |
if 'test' not in config.db_name: | |
# Sanity check to ensure that the `inject_test_settings` fixture has applied correctly. | |
pytest.fail(msg='The test settings have not been injected yet!') | |
db_url = ... # point it at test db created by prev fixture | |
engine = create_engine(db_url) | |
Session.configure(bind=engine) | |
Base.metadata.create_all(bind=engine) # create tables at the beginning of test suite | |
yield engine | |
Base.metadata.drop_all(bind=engine) # drop tables at the end of test suite | |
@pytest.fixture | |
def session(test_engine): | |
connection = test_engine.connect() | |
transaction = connection.begin() | |
Session.configure(bind=connection) | |
the_session = Session(bind=connection) | |
yield the_session | |
# you don't actually need to use this session if you wan't to, but it can be convenient. | |
# new sessions created from Session() will also be bound to the test engine's connection. | |
the_session.close() | |
transaction.rollback() | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment