一种方法可以是,通过在子测试之前unittest
附加子测试_
,然后构建一个基于正确执行这些子操作顺序的测试用例,以使这些子测试不被模块视为测试。
这比依赖unittest
模块的排序顺序要好,因为明天可能会改变,并且按顺序实现拓扑排序也不会很简单。
从此处获取 此方法的示例(免责声明:我自己的模块),如下所示。
在这里,测试用例运行独立的测试,例如检查表参数not set(test_table_not_set
)或test_primary_key
仍然并行测试主键(),但是CRUD测试只有在按正确顺序执行且由先前操作设置的状态下才有意义。因此,这些测试只是分开进行unit
而不是进行测试。test_CRUD
然后,另一个测试()为这些操作建立正确的顺序并进行测试。
import os
import sqlite3
import unittest
from sql30 import db
DB_NAME = 'review.db'
class Reviews(db.Model):
TABLE = 'reviews'
PKEY = 'rid'
DB_SCHEMA = {
'db_name': DB_NAME,
'tables': [
{
'name': TABLE,
'fields': {
'rid': 'uuid',
'header': 'text',
'rating': 'int',
'desc': 'text'
},
'primary_key': PKEY
}]
}
VALIDATE_BEFORE_WRITE = True
class ReviewTest(unittest.TestCase):
def setUp(self):
if os.path.exists(DB_NAME):
os.remove(DB_NAME)
def test_table_not_set(self):
"""
Tests for raise of assertion when table is not set.
"""
db = Reviews()
try:
db.read()
except Exception as err:
self.assertIn('No table set for operation', str(err))
def test_primary_key(self):
"""
Ensures , primary key is honored.
"""
db = Reviews()
db.table = 'reviews'
db.write(rid=10, rating=5)
try:
db.write(rid=10, rating=4)
except sqlite3.IntegrityError as err:
self.assertIn('UNIQUE constraint failed', str(err))
def _test_CREATE(self):
db = Reviews()
db.table = 'reviews'
db.write(tbl='reviews', rid=1, header='good thing', rating=5)
db.create(tbl='reviews', rid=2, header='good thing', rating=5)
db.write(tbl='reviews', rid=3, header='good thing', rating=5)
db.create(tbl='reviews', rid=4, header='good thing', rating=5)
db.commit()
def _test_READ(self):
db = Reviews()
db.table = 'reviews'
rec1 = db.read(tbl='reviews', rid=1, header='good thing', rating=5)
rec2 = db.read(rid=1, header='good thing')
rec3 = db.read(rid=1)
self.assertEqual(rec1, rec2)
self.assertEqual(rec2, rec3)
recs = db.read()
self.assertEqual(len(recs), 4)
def _test_UPDATE(self):
db = Reviews()
db.table = 'reviews'
where = {'rid': 2}
db.update(condition=where, header='average item', rating=2)
db.commit()
rec = db.read(rid=2)[0]
self.assertIn('average item', rec)
def _test_DELETE(self):
db = Reviews()
db.table = 'reviews'
db.delete(rid=2)
db.commit()
self.assertFalse(db.read(rid=2))
def test_CRUD(self):
self._test_CREATE()
self._test_READ()
self._test_UPDATE()
self._test_DELETE()
def tearDown(self):
os.remove(DB_NAME)