Python doctest:如何测试数据库插入或删除功能?
问题描述:
这个问题很简单,我不知道的答案...Python doctest:如何测试数据库插入或删除功能?
我是新手测试和我有问题测试类驱动sql3数据库。测试这种类的最佳方式是什么?测试类或测试init功能不是问题,但其他?测试插入一个测试行?
import sqlite3
class DataBase:
def __init__(self):
self._database_path = 'data.sql'
self._conn = sqlite3.connect(self._database_path)
self._cursor = self._conn.cursor()
def get(self, sql):
# select
self._cursor.execute(sql)
dataset = []
for row in self._cursor:
dataset.append(row)
return dataset
def post(self, sql):
# insert
self._cursor.execute(sql)
self._conn.commit()
谢谢大家,谢谢你的回答!
答
您可以使用数据库的回滚功能。 只需将self._conn.commit()
替换为self._conn.rollback()
,即可测试sql的有效性,但不会影响数据。
如果您需要测试一系列操作(即:获取数据 - >修改数据 - >插入新数据 - >删除一些数据 - >再次获取数据),您可以删除代码中的所有_conn.commit()
,运行测试并最终致电_conn.rollback()
。
例子:
import sqlite3
class DataBase:
def __init__(self):
self._database_path = 'data.sql'
self._conn = sqlite3.connect(self._database_path)
self._cursor = self._conn.cursor()
def get(self, sql):
# select
self._cursor.execute(sql)
dataset = []
for row in self._cursor:
dataset.append(row)
return dataset
def post(self, sql):
# insert
self._cursor.execute(sql)
def delete(self, sql):
# delete
self._cursor.execute(sql)
def rollback(self):
self._conn.rollback()
# You do your tests:
db = DataBase()
data = db.get('select name from table')
new_data = ['new' + name for name in data]
db.post('insert into table values {}'.format(','.join('({})'.format(d) for d in new_data)))
db.delete('delete from table where name = \'newMario\'')
check = bool(db.get('select name from table where name = \'newMario\''))
if check:
print('delete ok')
# You make everything as before the test:
db.rollback()
答
我想在正式sqlite3的测试CursorTests
就是一个很好的例子。
https://github.com/python/cpython/blob/master/Lib/sqlite3/test/dbapi.py#L187
你可以写setUp
和tearDown
方法来设置和回滚数据库。
from unittest import TestCase
class TestDataBase(TestCase):
def setUp(self):
self.db = DataBase()
def test_get(self):
pass # your code here
def test_post(self):
pass # your code here
+0
非常感谢您的回答,但是:如果我必须使用DocTest进行操作,该怎么办?这是可能的?? – user1936566
非常感谢您的回答,但是:如果我必须使用DocTest进行操作,该怎么办?有可能在DocTest中运行extense代码? – user1936566