python - 用pytest编写测试用例进行数据验证,测试用例的性质随组执行而变化
问题描述
我正在使用pytest编写单元测试用例进行数据验证,每个测试用例都写在方法内部。当我单独运行每个测试用例时,它会给出正确的结果,但是当我尝试一起运行所有测试用例时,它会通过失败的测试用例。我会使用 pytest 排序,但我有 400 个测试用例。谁能建议我一个解决方案?
样本测试用例
import pymongo
import re
import unittest
import pytest
myclient = pymongo.MongoClient("mongodb://root:mongodbadmin@18.223.241.113:27017")
mydb = myclient["Ecomm_Product_db"]
mycol = mydb["products"]
cursor = mycol.find({})
class Data_Validation(unittest.TestCase):
def test_category_name(self):
'''Asserts given special characters are not available in the category name'''
regex = re.compile('[@_!#$/%^*()<>?|}{~:],')
for name in cursor:
assert regex.search(name['category'])==None
def test_category_type(self):
'''Asserts category name value type is an string '''
for name in cursor:
assert type(name['category'])==str
def test_category_minlength(self):
'''Asserts given min length condition for category name '''
for name in cursor:
assert len(name['category'])>=5
def test_category_maxlength(self):
'''Asserts given max length condition for category name '''
for name in cursor:
assert len(name['category'])<=50
解决方案
如果cursor
是全局范围内的生成器,则第一个使用它的测试将耗尽它,因此对于所有其余的测试用例,它将为空。由于断言都在循环中,因此它们不会运行。最好使用pytest 夹具。,看起来像:
import pymongo
import re
import unittest
import pytest
from contextlib import closing
@pytest.fixture
def cursor():
with closing(pymongo.MongoClient("mongodb://root:mongodbadmin@18.223.241.113:27017")) as myclient:
mydb = myclient["Ecomm_Product_db"]
mycol = mydb["products"]
yield mycol.find({})
def test_category_name(cursor):
'''Asserts given special characters are not available in the category name'''
regex = re.compile('[@_!#$/%^*()<>?|}{~:],')
for name in cursor:
assert regex.search(name['category'])==None
def test_category_type(cursor):
'''Asserts category name value type is an string '''
for name in cursor:
assert type(name['category'])==str
def test_category_minlength(cursor):
'''Asserts given min length condition for category name '''
for name in cursor:
assert len(name['category'])>=5
def test_category_maxlength(cursor):
'''Asserts given max length condition for category name '''
for name in cursor:
assert len(name['category'])<=50
每次这样你都会得到一个新的光标。
推荐阅读
- javascript - 在 React Component 与“ref”中调用“document.getElementByID”
- python - QuTiP:解决不一致的 Qobj 形状
- javascript - 如何正确同时使用 searchFile 和 searchFolder?- 应用脚本
- ios - iPad 应用程序未使用全屏
- mongodb - 如何让 mongodb-compass 的多个实例并行运行
- python - 如何从用户那里获取输入,并让乌龟绘制它?
- reactjs - React Uncaught SyntaxError: Unexpected token < 中的延迟加载
- wcf - WCF SSL 服务给 404 未找到
- ios - 您的 Info.plist 中缺少 fbauth2
- python - 随机森林分类器准确率不高于 50%