使用“已登录用户”测试视图而无需访问数据库

时间:2019-08-05 10:06:23

标签: django python-3.x unit-testing

我编写了som任意代码来测试有和没有登录用户的视图类。但是,这样做时,我必须创建一个访问数据库的用户。为了遵循TDD单元测试的良好做法,我会尽量避免访问数据库,但是我不知道如何

我曾经尝试过修补不同的模块,但是我还没有弄清楚修补的方式或内容

这是我今天使用的解决方案:


@pytest.mark.django_db
class TestTreaterProfile:
    """
    get with anonymous
    get with logged-in user
    """
    [...]

    def test_get_with_logged_in_user(self):
        status_code = [200]
        view_class = ClientProfile

        client = Client()
        user = User.objects.create_user("user", "my@email.com", "password")
        client.force_login(user)

        # create request and retrieve response
        request = RequestFactory().get("/")
        request.user = user
        response = view_class.as_view()(request, *[], **{})

        assert response.status_code in status_code, "Should have status_code 200 - OK"

代码有效,我只想对其进行修改,以使其不必访问数据库。

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用测试的setUp方法(link)创建用户,这样就不会污染您的实际测试方法(这就是我假设您要避免的方法) )。仅供参考:这仍然会影响数据库。

class TestTreaterProfile:
    ...
    def setUp(self):
        self.user = User.objects.create_user("user", "my@email.com", "password")
    ...
    def test_get_with_logged_in_user(self):
        ...
        request.user = self.user
        ...

答案 1 :(得分:0)

我认为您应该使用forcing_authentication()

参考:https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication