pytest-mysql

4.0.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import pytest
import pymysql # Often used to interact with the database fixture

def test_mysql_connection(mysql):
    """
    Demonstrates a basic connection and a simple query using the 'mysql' fixture.
    The 'mysql' fixture provides a PyMySQL connection object and drops the 
    test database after each test function.
    """
    assert isinstance(mysql, pymysql.connections.Connection)
    cursor = mysql.cursor()
    cursor.execute("SELECT 1 + 1")
    result = cursor.fetchone()[0]
    assert result == 2
    cursor.close()

def test_create_table_and_insert(mysql):
    """
    Shows how to create a table and insert data. The database will be 
    cleaned up after this test completes due to the 'mysql' fixture's scope.
    """
    cursor = mysql.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS my_table (id INT AUTO_INCREMENT PRIMARY KEY, value VARCHAR(255))")
    cursor.execute("INSERT INTO my_table (value) VALUES (%s)", ("test_value",))
    mysql.commit() # Commit changes to the temporary database

    cursor.execute("SELECT value FROM my_table WHERE id = 1")
    fetched_value = cursor.fetchone()[0]
    assert fetched_value == 'test_value'
    cursor.close()

# To run these tests:
# 1. Ensure MySQL/MariaDB server is installed and accessible (pytest-mysql will start it).
# 2. Save the above code as e.g., `test_database.py`.
# 3. Run `pytest` in your terminal in the same directory.

view raw JSON →