【发布时间】:2018-04-19 23:22:43
【问题描述】:
我正在使用 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。
【问题讨论】:
-
模拟数据库将是一个选项
https://docs.python.org/3/library/unittest.mock.html -
快速评论:也许
connectDB可能不是执行查询的方法的最佳名称:)
标签: python python-2.7 unit-testing python-unittest python-unittest.mock