【问题标题】:Fixtures are not meant to be called directly夹具并不意味着直接调用
【发布时间】:2026-01-31 00:20:07
【问题描述】:

我正在使用 Django 3.0.5pytest 5.4.1pytest-django 3.9.0。我想创建一个夹具,它返回一个 User 对象以在我的测试中使用。 这是我的 conftest.py

import pytest
from django.contrib.auth import get_user_model


@pytest.fixture
def create_user(db):
    return get_user_model().objects.create_user('user@gmail.com', 'password')

这是我的 api_students_tests.py

import pytest
from rest_framework.test import APITestCase, APIClient


    class StudentViewTests(APITestCase):

        user = None

        @pytest.fixture(scope="session")
        def setUp(self, create_user):
            self.user = create_user

        def test_create_student(self):
            assert self.user.email == 'user@gmail.com'  
            # other stuff ...

我不断收到以下错误

Fixture "setUp" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.

我反复阅读this previous question,但找不到解决方案。此外,在那个问题中,夹具没有返回任何内容,而在我的情况下,它应该返回一个对象(不知道它是否可以产生任何影响)

【问题讨论】:

  • 您应该使用 pytest 夹具或 UnitTest 设置函数。两者都使用没有意义。 (ps:使用example.com作为域名进行测试等)
  • @thebjorn 对不起,我想我还是想念一些东西。所以我有两个选择: 1 --> 使用夹具来创建用户; 2 --> 在 setUp 方法中创建该用户。正确的?但是在选项 #2 的情况下,我应该为每个需要用户对象的测试重写相同的代码,不是吗?有没有办法重用逻辑在setUp中创建一个用户而不从头开始重写?

标签: django unit-testing pytest fixtures django-testing


【解决方案1】:

跳过setUp

@pytest.fixture(scope='session')
def create_user(db):
    return get_user_model().objects.create_user('user@gmail.com', 'password')


class StudentViewTests(APITestCase):

    def test_create_student(self, create_user):
        assert user.email == 'user@gmail.com'  
        # other stuff ...

【讨论】:

  • 它不起作用,失败并出现以下错误FAILED errepiuapp/tests/mock_tests.py::StudentViewTests::test_create_student - TypeError: test_create_student() missing 1 required positional argument: 'create_user'
  • 你的测试是如何运行的?
  • 我已将您的 sn-p 复制到一个文件中,然后运行 ​​pytest -vs
  • 有什么解决办法吗?
  • 应该断言 create_user.email == 'user@gmail.com'
最近更新 更多