Pytest cannot test multiple cases with @pytest.mark.parametrize

36 Views Asked by At

I defined UserFactory class in tests/factories.py as shown below following the doc. *I use pytest-django and pytest-factoryboy in Django:

# "tests/factories.py"

import factory

from django.contrib.auth.models import User

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

And, I defined test_user_instance() with @pytest.mark.parametrize() to test 4 users as shown below:

# "tests/test_ex1.py"

import pytest
from django.contrib.auth.models import User

@pytest.mark.parametrize(
    "username, email",
    {
        ("John", "[email protected]"), # Here
        ("John", "[email protected]"), # Here
        ("John", "[email protected]"), # Here
        ("John", "[email protected]")  # Here
    }
)
def test_user_instance(
    db, user_factory, username, email
):
    user_factory(
        username=username,
        email=email
    )

    item = User.objects.all().count()
    assert item == True

But, only one user was tested as shown below:

$ pytest -q
.                                [100%]
1 passed in 0.65s

So, how can I test 4 tests?

1

There are 1 best solutions below

0
Super Kai - Kazuya Ito On

You should use [] instead of {} to surround 4 users as shown below:

# "tests/test_ex1.py"

import pytest
from django.contrib.auth.models import User

@pytest.mark.parametrize(
    "username, email",
    [ # <- Here
        ("John", "[email protected]"),
        ("John", "[email protected]"),
        ("John", "[email protected]"),
        ("John", "[email protected]")
    ] # <- Here
)
def test_user_instance(
    db, user_factory, username, email
):
    user_factory(
        username=username,
        email=email
    )

    item = User.objects.all().count()
    assert item == True

Then, you can test 4 users as shown below:

$ pytest -q
....                             [100%]
4 passed in 0.68s