Python单元测试:如何对包含数据库操作的模块进行单元测试?

2024-04-25 01:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pymysql客户端库连接到真实的数据库。我在模块中有一个函数,我使用pymysql连接到数据库,只做数据库插入操作,如何在python中对这个函数进行单元测试,而不去真正的数据库呢?

import pymysql

def connectDB(self):

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db')

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('newuser@some.com', 'newpassword'))


    connection.commit()

我的python版本是2.7。


Tags: 模块函数import数据库客户端dbsqldef
3条回答

您可以使用patch,如下所示:

from unittest.mock import patch, MagicMock

@patch('mypackage.mymodule.pymysql')
def test(self, mock_sql):
    self.assertIs(mypackage.mymodule.pymysql, mock_sql)

    conn = Mock()
    mock_sql.connect.return_value = conn

    cursor      = MagicMock()
    mock_result = MagicMock()

    cursor.__enter__.return_value = mock_result
    cursor.__exit___              = MagicMock()

    conn.cursor.return_value = cursor

    connectDB()

    mock_sql.connect.assert_called_with(host='localhost',
                                        user='user',
                                        password='passwd',
                                        db='db')

    mock_result.execute.assert_called_with("sql request", ("user", "pass"))

您需要一系列名为stub的伪数据库,它们返回硬编码值。在测试期间,将使用这些存根而不是实际的数据库。我不熟悉Python,但是C++中的一种方法是让对象将数据库作为构造函数参数接收。在生产代码中,使用真实的数据库参数,在测试存根时使用。这是因为构造函数需要指向公共基类的指针。即使它不是为Python编写的,我建议阅读Roy Osherove的第一章:单元测试的艺术。这本书清楚地解释了为什么这些假数据库是存根而不是模拟。

您刚刚重新发现了测试之所以重要的一个最有说服力的原因:它告诉您什么时候设计不好。

换言之,可测试性是质量的良好一级代理。请考虑以下几点:

class DB(object):
    def __init__(self, **credentials):
        self._connect = partial(pymysql.connect, **credentials)

    def query(self, q_str, params):
        with self._connect as conn:
            with conn.cursor() as cur:
                cur.execute(q_str, params)
                return cur.fetchall()

# now for usage

test_credentials = {
    # use credentials to a fake database
}

test_db = DB(**test_credentials)
test_db.query(write_query, list_of_fake_params)
results = test_db.query(read_query)
assert results = what_the_results_should_be

如果使用多个数据库,可以使用多态性,或者根据API的相似性,将特定的DB作为对象的构造函数参数。

相关问题 更多 >