首页 > 解决方案 > 用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

标签: pythonpython-3.xpytest

解决方案


如果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

每次这样你都会得到一个新的光标。


推荐阅读