Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Created September 21, 2025 16:21
Show Gist options
  • Select an option

  • Save oofnivek/a07030c236a07c5712b8eaca0676d419 to your computer and use it in GitHub Desktop.

Select an option

Save oofnivek/a07030c236a07c5712b8eaca0676d419 to your computer and use it in GitHub Desktop.
import pytest
import mysql.connector
def debug_log(file_path, mode, message):
with open(file_path, mode) as f:
print(message, file=f)
@pytest.fixture(scope="session")
def db_connection():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="classicmodels"
)
yield connection
except mysql.connector.Error as err:
pytest.fail(f"Could not connect to the database: {err}")
finally:
if 'connection' in locals() and connection.is_connected():
connection.close()
print("\nDatabase connection closed.")
def test_customer_count(db_connection):
"""
Asserts the total number of customers in the 'customers' table.
"""
cursor = db_connection.cursor()
query = "SELECT COUNT(*) FROM customers;"
cursor.execute(query)
result = cursor.fetchone()
# According to the classicmodels schema, there are 122 customers.
expected_count = 122
assert result[0] == expected_count, f"Expected {expected_count} customers, but found {result[0]}"
cursor.close()
def test_product_details(db_connection):
"""
Asserts the details of a specific product.
"""
cursor = db_connection.cursor(dictionary=True) # Use dictionary=True for easier access to columns
product_code = "S10_1678"
query = "SELECT productName, buyPrice FROM products WHERE productCode = %s;"
cursor.execute(query, (product_code,))
result = cursor.fetchone()
# Assertions based on the known data for this product
assert result is not None, f"Product with code {product_code} not found."
assert result['productName'] == "1969 Harley Davidson Ultimate Chopper"
assert float(result['buyPrice']) == 48.81 # Use float for numeric comparisons
cursor.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment