当 Python 的单元测试 运行 时,为什么对 MySQL 的写入无法持续?

Why do writes to MySQL fail to persist when run from Python's unittest?

我目前正在使用 Python 3.8 中的单元测试为新创建的 MySQL 数据库编写测试用例。该数据库是一个 AWS RDS 实例 运行ning Aurora MySQL 5.6 — 它有一个 table users 和一个主键字段 uuid VARCHAR(36)。测试用例如下:

import unittest
import mysql.connector
from config import MYSQL_CONNECTION_INFO

class SQLSchemaTests(unittest.TestCase):
    """Verifies the correct behavior of the schema itself. (i.e. that the tables were set up correctly)"""
    
    def setUp(self):
        self.cnxn = mysql.connector.connect(**MYSQL_CONNECTION_INFO)
        self.cursor = self.cnxn.cursor()
        
    def tearDown(self):
        self.cnxn.close()
    
    def test_create_users(self):
        """Verify that a client can create user entries in the data store with appropriate parameters."""
        self.cursor.execute("SELECT COUNT(*) from users")
        user_entries_count = self.cursor.fetchone()[0]
        self.assertEqual(user_entries_count, 0)
        
        self.cursor.execute("INSERT INTO users (uuid) VALUES ('aaa-bbb-ccc-ddd-eee')")
        
        self.cursor.execute("SELECT COUNT(*) from users")
        user_entries_count = self.cursor.fetchone()[0]
        self.assertEqual(user_entries_count, 1)

让我感到困惑的是,这个测试用例每次都通过 运行 — 换句话说,我没有执行任何清理操作,它不会因重复条目而失败。我使用 PyCharm 的调试器在 INSERT 语句之后放置一个断点,然后在测试执行暂停时在单独的数据库控制台中 运行 SELECT COUNT(*) from users :结果来了归零。更重要的是,当我使用数据库控制台向 users table 写入相同的条目时,只有 测试因重复条目而失败。

我想了解以下内容:

为了在测试之间看到插入持续存在,我需要在 INSERT 语句上调用 execute 之后添加 self.cnxn.commit()Python connector docs 指定 auto-commit 默认禁用。

此外,我可以从 测试中而不是从单独的数据库控制台中获取更新计数的原因是 事务隔离 在数据库级别(在这种情况下,设置为 REPEATABLE-READ)。有关数据库隔离的 MySQL docs and in the Wikipedia article 中提供了更多信息。