使用@pytest.mark.parametrize无法执行多测试案例的问题解决
问题:pytest.mark.parametrize传入重复参数仅执行一次测试
在Django项目中使用pytest-django和pytest-factoryboy工具,已按照官方文档在tests/factories.py中定义了UserFactory类。随后在tests/test_ex1.py中使用@pytest.mark.parametrize装饰器为test_user_instance函数传入四组相同的username和email参数,期望执行4次测试,但实际仅运行了一次。
相关代码
tests/factories.py
import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User
tests/test_ex1.py(原错误代码)
import pytest from django.contrib.auth.models import User @pytest.mark.parametrize( "username, email", { ("John", "test@test.com"), ("John", "test@test.com"), ("John", "test@test.com"), ("John", "test@test.com") } ) def test_user_instance( db, user_factory, username, email ): user_factory( username=username, email=email ) item = User.objects.all().count() assert item == True
执行测试输出(原错误情况)
$ pytest -q . [100%] 1 passed in 0.65s
问题原因
- 参数容器类型错误:
@pytest.mark.parametrize的参数列表用了集合(set),集合的特性是自动去重重复元素,四组完全相同的参数会被合并为一组,因此仅执行一次测试。 - 断言逻辑不规范:
User.objects.all().count()返回整数类型,直接与布尔值True比较属于不规范写法,应明确断言计数结果。
修复方案
将参数容器从集合改为列表(list),同时修正断言逻辑:
修改后的tests/test_ex1.py
import pytest from django.contrib.auth.models import User @pytest.mark.parametrize( "username, email", [ ("John", "test@test.com"), ("John", "test@test.com"), ("John", "test@test.com"), ("John", "test@test.com") ] ) def test_user_instance( db, user_factory, username, email ): user_factory( username=username, email=email ) item_count = User.objects.all().count() assert item_count == 1
修复后执行输出
$ pytest -q .... [100%] 4 passed in 0.82s
内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito
相关产品推荐
相关产品推荐

