Kent Martin
Kent Martin

Reputation: 235

Testing views with 'logged in user' without accessing database

I have written som arbitrary code to test a view-class with and without a logged in user. However, while doing that I have to create a user, which accessed the database. To follow good practice for TDD unittests I would try to avoid accessing the database, but I don't know how

I've briefly tried to patch different modules, but I haven't figured out exactly how or what to patch

This is the solution I'm using today:


@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", "[email protected]", "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"

The code works, I would just like to modify it so that it don't have to access the database.

Thanks in advance for your help!

Upvotes: 0

Views: 273

Answers (2)

Umair Mohammad
Umair Mohammad

Reputation: 4635

I think you should use forcing_authentication()

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

Upvotes: 0

jdeanwallace
jdeanwallace

Reputation: 1156

You can create the user in the test's setUp method (link), so that you don't pollute your actual test method (as that's what I'm assuming you're trying to avoid). FYI: this still hits the database.

class TestTreaterProfile:
    ...
    def setUp(self):
        self.user = User.objects.create_user("user", "[email protected]", "password")
    ...
    def test_get_with_logged_in_user(self):
        ...
        request.user = self.user
        ...

Upvotes: 1

Related Questions