Skip to content

🐬 MySQL Container Testing

Master MySQL Testing with Testcontainers

Build bulletproof MySQL integration tests that survive real-world chaos

5 test cases
2 chaos scenarios
100% coverage

🎯 Why MySQL?

πŸš€ Popular & Fast

Extremely popular in web applications, fast to spin up in containers

πŸ§ͺ Perfect for Chaos

Great candidate for chaos testing in CI/CD pipelines

πŸ”§ Easy Integration

Simple setup with Testcontainers and comprehensive testing


βœ… Test Cases Implemented

Test Case 1 β€” Check MySQL Version

βœ… Passed

Runs a query to ensure MySQL is running and accessible.

Python
result = conn.execute(text("SELECT VERSION();")).fetchone()
assert "MySQL" in result[0] or "MariaDB" in result[0]

Test Case 2 β€” Insert and Query

βœ… Passed

Inserts a single record and retrieves it.

Python
conn.execute(text("INSERT INTO users (name) VALUES ('Alice');"))
result = conn.execute(text("SELECT name FROM users;")).fetchone()
assert result[0] == "Alice"

Test Case 3 β€” Insert Multiple Rows

βœ… Passed

Adds multiple rows and verifies the total count.

Python
conn.execute(text("INSERT INTO users (name) VALUES ('Bob'), ('Charlie');"))
result = conn.execute(text("SELECT COUNT(*) FROM users;")).fetchone()
assert result[0] == 3

Test Case 4 β€” Primary Key Constraint

βœ… Passed

Verifies the primary key prevents duplicate entries.

Python
conn.execute(text("INSERT INTO users (id, name) VALUES (1, 'David');"))
with pytest.raises(Exception):
    conn.execute(text("INSERT INTO users (id, name) VALUES (1, 'Eve');"))

Test Case 5 β€” Truncate Table

βœ… Passed

Clears the table and confirms it's empty.

Python
conn.execute(text("TRUNCATE TABLE users;"))
result = conn.execute(text("SELECT COUNT(*) FROM users;")).fetchone()
assert result[0] == 0

πŸš€ How to Run the Tests

Quick Start

Terminal
pytest -v testcontainers/test_mysql_container.py

βœ… Expected Output:

5 passed in X.XXs

Useful Commands

See running containers:

docker ps

Check MySQL logs:

docker logs <container_id>

πŸ§ͺ Chaos Testing Scenarios

Real-World Failure Simulation

Test your application's resilience against common MySQL failures

Scenario 1: Connection Failures

Connection Error

Test that your app handles MySQL connection failures gracefully

Python
def test_mysql_connection_failure():
    """Test that our app handles MySQL connection failures gracefully"""
    with MySqlContainer("mysql:8.0") as mysql:
        # Simulate connection failure
        mysql.get_docker_client().stop(mysql.get_container_id())

        # Verify our app handles the failure
        with pytest.raises(ConnectionError):
            create_connection(mysql.get_connection_url())

Scenario 2: Slow Queries

Performance Issue

Test that your app handles slow MySQL queries within timeouts

Python
def test_mysql_slow_query_handling():
    """Test that our app handles slow MySQL queries"""
    with MySqlContainer("mysql:8.0") as mysql:
        conn = create_connection(mysql.get_connection_url())

        # Simulate slow query
        import time
        start_time = time.time()

        # Execute a potentially slow query
        conn.execute(text("SELECT SLEEP(2)"))

        # Verify it completes within reasonable time
        assert time.time() - start_time < 5.0

πŸ“Š Monitoring & Reporting

Generate Beautiful Reports

Create comprehensive HTML reports for stakeholders

πŸ“Š Generate HTML Report

Terminal
pytest testcontainers/test_mysql_container.py \
  --html=reports/mysql-test-report.html \
  --self-contained-html

Creates a beautiful HTML report with test results and metrics

πŸ“‹ View Container Logs

Terminal
# Get container ID
docker ps | grep mysql

# View logs
docker logs <container_id>

Monitor container behavior and debug issues