{"id":7618,"library":"pytest-mysql","title":"pytest-mysql","description":"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.","status":"active","version":"4.0.0","language":"en","source_language":"en","source_url":"https://github.com/dbfixtures/pytest-mysql","tags":["pytest","mysql","mariadb","testing","fixtures","database","integration-testing"],"install":[{"cmd":"pip install pytest-mysql","lang":"bash","label":"Install pytest-mysql"},{"cmd":"pip install pymysql pytest","lang":"bash","label":"Install with a common MySQL connector and pytest"}],"dependencies":[{"reason":"pytest is the core testing framework this plugin extends.","package":"pytest"},{"reason":"Common Python client library for connecting to MySQL, often used in conjunction with pytest-mysql fixtures for database interaction. The 'mysql' fixture provides a PyMySQL connection object.","package":"PyMySQL","optional":true},{"reason":"The plugin starts a MySQL/MariaDB process; a local installation or Docker-managed instance is required. Version 5.7.6+ is required for pytest-mysql >= 3.0.","package":"MySQL/MariaDB Server","optional":false}],"imports":[{"note":"Used to create custom MySQL process or client fixtures with specific configurations.","symbol":"factories","correct":"from pytest_mysql import factories"}],"quickstart":{"code":"import pytest\nimport pymysql # Often used to interact with the database fixture\n\ndef test_mysql_connection(mysql):\n    \"\"\"\n    Demonstrates a basic connection and a simple query using the 'mysql' fixture.\n    The 'mysql' fixture provides a PyMySQL connection object and drops the \n    test database after each test function.\n    \"\"\"\n    assert isinstance(mysql, pymysql.connections.Connection)\n    cursor = mysql.cursor()\n    cursor.execute(\"SELECT 1 + 1\")\n    result = cursor.fetchone()[0]\n    assert result == 2\n    cursor.close()\n\ndef test_create_table_and_insert(mysql):\n    \"\"\"\n    Shows how to create a table and insert data. The database will be \n    cleaned up after this test completes due to the 'mysql' fixture's scope.\n    \"\"\"\n    cursor = mysql.cursor()\n    cursor.execute(\"CREATE TABLE IF NOT EXISTS my_table (id INT AUTO_INCREMENT PRIMARY KEY, value VARCHAR(255))\")\n    cursor.execute(\"INSERT INTO my_table (value) VALUES (%s)\", (\"test_value\",))\n    mysql.commit() # Commit changes to the temporary database\n\n    cursor.execute(\"SELECT value FROM my_table WHERE id = 1\")\n    fetched_value = cursor.fetchone()[0]\n    assert fetched_value == 'test_value'\n    cursor.close()\n\n# To run these tests:\n# 1. Ensure MySQL/MariaDB server is installed and accessible (pytest-mysql will start it).\n# 2. Save the above code as e.g., `test_database.py`.\n# 3. Run `pytest` in your terminal in the same directory.","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade your MySQL/MariaDB server to version 5.7.6+ or downgrade `pytest-mysql` to version 2.0.3 (`pip install 'pytest-mysql<3'`).","message":"pytest-mysql versions 3.0.0 and above (including 4.0.0) only support MySQL/MariaDB server versions 5.7.6 and up. If you are using an older MySQL server, you must use `pytest-mysql` version 2.0.3.","severity":"breaking","affected_versions":"3.x.x, 4.x.x"},{"fix":"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.","message":"Configuration options for MySQL instances (e.g., port, user, executable path) follow a specific precedence: Fixture factory arguments override command-line options, which in turn override settings in `pytest.ini`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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.","message":"Relying on external or pre-existing MySQL instances without proper fixture usage can lead to test failures due to stale data. The `mysql_noproc` fixture connects to an existing instance but relies on external cleanup if not configured otherwise.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"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)`.","cause":"The `pytest-mysql` plugin failed to start the MySQL process, or the path to MySQL executables (`mysqld`, `mysqladmin`) is incorrect, or a port conflict exists.","error":"pymysql.err.OperationalError: (2002, \"Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)\") OR pymysql.err.OperationalError: (2003, \"Can't connect to MySQL server on 'localhost' (111 Connection refused)\")"},{"fix":"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.","cause":"Database state is not being correctly isolated or reset between test runs. This typically happens if a session-scoped fixture (`mysql_proc`, `mysql_noproc`) is used, but a test modifies the database in a way that affects subsequent tests without proper cleanup, or if the `mysql` fixture isn't effectively cleaning up.","error":"Failed: Database 'test_...' already exists / Table '...' already exists (when running multiple tests)"},{"fix":"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`.","cause":"The `pytest-mysql` library is not installed in your current Python environment, or the environment where `pytest` is being run is not the one where `pytest-mysql` was installed.","error":"ModuleNotFoundError: No module named 'pytest_mysql'"}]}