Pytest对象未在更新视图中更新

时间:2019-05-07 13:04:32

标签: python django pytest

我的视图 user_actions 允许将用户设置为非活动状态。方法如下:

def user_update_details(request, username=None):
    user = get_object_or_404(User, username=username)
    if 'set_inactive' in request.POST:
        user.is_active = False
        user.save()
    return redirect(reverse('dashboard_staff:user_details',
                            kwargs={'username': username}))

我经常使用这种简单的模式,并且效果很好。我想现在进行测试。我的用户测试如下创建。

@pytest.fixture
def user(db) -> settings.AUTH_USER_MODEL:
    return UserFactory()

和工厂类别:


class UserFactory(DjangoModelFactory):

    username = Faker("user_name")
    email = Faker("email")
    first_name = Faker("first_name")
    last_name = Faker("last_name")

    @post_generation
    def password(self, create: bool, extracted: Sequence[Any], **kwargs):
        password = Faker(
            "password",
            length=42,
            special_chars=True,
            digits=True,
            upper_case=True,
            lower_case=True,
        ).generate(extra_kwargs={})
        self.set_password(password)

    class Meta:
        model = get_user_model()
        django_get_or_create = ["username"]

这是测试失败的地方:

class TestUserActions:
    url = "dashboard_staff:user_actions"

    def test_set_user_inactive(self, user):
        assert user.is_active
        url = reverse(self.url, kwargs={'username': user.username})
        resp = Client().post(url, data={'set_inactive': ''}, follow=True)
        assert resp.status_code == 200
        user.refresh_from_db()
        assert user.is_active is False

和例外情况:

        assert customer_manager.is_active
E       assert False
E        +  where False = <Customer: Adrian Huynh>.is_active

1 个答案:

答案 0 :(得分:0)

正如评论中所说,我找到了一种解决方法。出于未知原因,如果使用follow=True参数,则该视图似乎不会更新实例。因此,为了对其进行测试:

class TestUserActions:
    url = "dashboard_staff:user_actions"

    def test_set_user_inactive(self, user):
        assert user.is_active
        url = reverse(self.url, kwargs={'username': user.username})
        resp = Client().post(url, data={'set_inactive': ''})
        assert resp.status_code == 302
        user.refresh_from_db()
        assert user.is_active is False

我没有检查status_code == 200,而是简单地检查了重定向,并且实例已正确更新。