我正在使用pytest编写用于数据验证的单元测试用例,每个测试用例都写在方法内部。当我单独运行每个测试用例时,它会给出正确的结果,但是当我尝试一起运行所有测试用例时,它会通过失败的测试用例。我会使用 pytest 排序,但我有 400 个测试用例。谁能建议我一个解决方案?
示例测试用例
import pymongo
import re
import unittest
import pytest
myclient = pymongo.MongoClient("mongodb://root:[email protected]: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:[email protected]: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
每次这样你都会得到一个新的光标。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句