pytest-mysql is a pytest plugin, version 4.0.0, that facilitates testing code reliant on a running MySQL/MariaDB database. It provides pytest fixtures for managing MySQL process lifecycle (`mysql_proc`) and client connections (`mysql`, `mysql_noproc`), ensuring isolated and repeatable database environments for tests. It automatically handles starting and stopping MySQL instances for test sessions and can clean up test databases per function. The project is actively maintained, with the latest version released in December 2024.
pip install pytest-mysqlVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates using the function-scoped `mysql` fixture provided by `pytest-mysql`. This fixture provides a PyMySQL connection to a temporary database, which is created and dropped for each test function, ensuring test isolation. The `mysql_proc` fixture (session-scoped) is also available for starting and stopping the MySQL server once per test session. You might need to install `pymysql` to interact with the connection object.
Upgrade your MySQL/MariaDB server to version 5.7.6+ or downgrade `pytest-mysql` to version 2.0.3 (`pip install 'pytest-mysql<3'`).
Always check the fixture factory arguments first, then command-line options (`--mysql-port=...`), and finally `pytest.ini` (`[pytest] mysql_port = ...`) to understand which setting is active.
For function-level database isolation, use the `mysql` fixture, which automatically drops the test database after each test. If connecting to a pre-existing instance with `mysql_noproc`, ensure your test setup/teardown explicitly manages database state (e.g., truncating tables, recreating schema) for repeatability.
Ensure MySQL/MariaDB server is properly installed and its executables are in your system's PATH. Check the `pytest` output for startup errors. You can manually specify executable paths and ports in `pytest.ini` or when creating custom fixtures using `factories.mysql_proc(executable='/path/to/mysqld', port=3307)`.
For individual test function isolation, ensure you are using the `mysql` fixture, which ensures the test database is dropped after each test. If you need a session-scoped database for performance, implement explicit database cleanup (e.g., `TRUNCATE TABLE` or schema recreation) in setup/teardown fixtures within your tests.
Activate the correct Python virtual environment (if used) and run `pip install pytest-mysql`. If `pymysql` is also needed for database interaction, install it with `pip install pymysql`.