Implement Unit Test for OAuth Flow in Django app

Viewed 18

I integrated OAuth into my Django app. OAuth has 2 steps:

  1. Redirect to OAuth provider domain name
  2. Callback to Django app with token

I would like to implement TestCase units for the above flow. Here is what I wrote for testing step 1:

def test_connect_with_oauth_provider(self):
    """Test connecting with OAuth provider."""
    url = signin_url("oauth-provider")

    res = self.client.get(url)
    self.assertEqual(res.status_code, status.HTTP_200_OK)

However, the test uses testcase domain not my real domain and thus the test fails. Can you please help me implement tests for both steps? Thanks!

1 Answers

I recommend using the python native unittest.mock library in this case. Using the mock library allows you to create a function or provide a fake value that is used only in your tests.

Recently, I wrote a blog post about using mock (Correct! Shameless self-promotion), but also I stated that mock has some caveats. You can also go with the official documentation, if you like.

As your test is given in your post, I do not know another way to go than using unittest.mock. However, be aware that this library may cause confusion, because it can have some counterintuitive behavior.

I would recommend you to test your redirect in a real unit test (your provided case is more an integration test) by testing a single function that does the work.

Related