How does the Data layer unit test in Example 12-15 avoid needing fake modules, and what environment variable is set before importing data modules?
The Data layer unit test avoids fake modules by configuring the Data layer to use an in-memory SQLite database instead of a file-based one, which requires no code changes to the Data modules. The environment variable set is CRYPTID_SQLITE_DB, and it is set to ":memory:" before importing the data modules.
In Example 12-15, the Data layer is tested in isolation without needing fake modules because it has no lower layer to accidentally call. The test sets the environment variable CRYPTID_SQLITE_DB to ":memory:" before importing the data modules. This instructs the Data layer to use an in-memory SQLite database, so the unit tests do not touch a real file-based database. The existing Data modules work unchanged, and the test only requires this one environment setting, unlike the Web and Service layer tests which import fake modules.
Key points
- No fake modules are needed for Data layer unit tests.
- The Data layer is pointed to a memory-only SQLite instance.
- The environment variable CRYPTID_SQLITE_DB is set to ":memory:".
- The environment variable is set before importing data modules.
- Existing Data modules require no changes for unit testing.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.