0

I am running numerous unit tests using pytest and have several types of database interactions occurring in each unit test module.

My ideal goal is to setup a single sqlite:///:memory: environment with tables pre-created, data inserted, etc only once (instead of doing this once for each module) that can be shared among my entire test suite, but I am just not sure how to do this properly.

Here is a sample of the tests package.

$ tree tests/
tests
├── __init__.py
├── conftest.py
├── test_thing1.py
├── test_thing2.py
└── test_thing3.py

I saw this related question but I would prefer to use sqlite in-memory for the obvious performance gains.

My conftest.py current contains:

@pytest.fixture(scope="session")
def test_db():
    """Returns an object for which a SqlAlchemy engine and session object can be obtained"""
    yield DatabaseThing(**db_conf)
user9074332
  • 2,336
  • 2
  • 23
  • 39
  • Use a session-scoped fixture for the db setup; this way, the db will be initialised once and shared between the tests in the test suite. – hoefling Aug 10 '19 at 17:12
  • Thanks. But can I have a fixture that references a another fixture? I currently have a fixture within `conftest.py` that yields an object from which a `SqlAlchemy` `engine` and `session` are tested from. I will update the question about to make this more clear. – user9074332 Aug 10 '19 at 17:29
  • You can reference other fixtures via fixture arguments, e.g. `test_db` variable in `def myfixture(test_db): ...` will have the return value of `test_db` fixture. – hoefling Aug 10 '19 at 17:39
  • 2
    Is it worth the bother? How much faster are your tests against an in-memory database than an on-disk one? Unless your test data are quite large, the disk I/O will likely be charged against the file buffer. – James K. Lowden Aug 10 '19 at 18:01
  • I am giving that a try now but not sure how to globally setup an environment across all the modules. I tried putting a `setup()` function in my `conftest.py` that contains the table creation, row insertion, etc but that doesnt appear to be working as hoped. – user9074332 Aug 11 '19 at 01:38

0 Answers0