paint-brush
Quick Tip: Testing Python Social Authby@pizzapanther
1,102 reads
1,102 reads

Quick Tip: Testing Python Social Auth

by Paul BaileyAugust 17th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Python Social Auth is a great library to integrate 3rd party logins into your web application. Here is a quick way to test without having to mock HTTP calls or hit live external endpoints. The test is based off of Github so you may need to override more methods for other backends. The first one overrides state validation so we can use made up tokens. The second overrides fetching data about the user so we don't need to make external calls. Test redirect to third party site. Simulate successful return and verify account is created and/or logged in.
featured image - Quick Tip: Testing Python Social Auth
Paul Bailey HackerNoon profile picture

Python Social Auth is a great library to integrate 3rd party logins into your web application. It supports multiple frameworks and multiple 3rd party logins. It is also great because if a 3rd party isn't supported, it is pretty easy to add a new one.

I recently built a custom integration and so I wanted to do some extra automated testing of the integration. Here is a quick way to test without having to mock HTTP calls or hit live external endpoints.

#1 Create a Mock Backend

I based my test off of Github so you may need to override more methods for other backends. Basically you need to override 2 methods. The first one overrides state validation so we can use made up tokens, and the second overrides fetching data about the user so we don't need to make external calls.

from social_core.backends.github import GithubOAuth2


class GithubFake(GithubOAuth2):
    def validate_state(self):
        return 'good'

    def get_json(self, url, *args, **kwargs):
        return {
            "id": 12345,
            "login": "pizzapanther",
            "expires": None,
            "auth_time": 1565736030,
            "token_type": "bearer",
            "access_token": "narf-token",
            "email": "[email protected]",
        }

#2 Write Your Test

This code snippet will be a little less helpful because it uses some customized things in my project's pytest environment. But hopefully it will give you the gist of how you can test.

  1. Set mock backend.
  2. Test redirect to third party site.
  3. Simulate successful return and verify account is created and/or logged in.

Note: that since we are using the mock backend, the

code
and
state
parameters can now be invalid.

import pytest
import requests

GITHUB_CONFIG = {
  'backends': ['myapp.backends.github.GithubFake'],
  'settings': {
    'github_secret': 'super-long-secret',
    'github_key': 'super-short-secret',
  }
}


@pytest.mark.app_config(config=GITHUB_CONFIG, key='auth_backends')
def test_psa_login_flow(base_url):
    # test login init
    response = requests.get(
        f'{base_url}/auth/login/github',
        allow_redirects=False
    )
    assert response.status_code == 302
    assert response.headers['Location'].startswith(
        'https://github.com/login/oauth/authorize'
    )

    # test login return
    response = requests.get(
        f'{base_url}/auth/complete/github?code=TEST&state=TEST',
        allow_redirects=False
    )
    assert response.status_code == 302
    assert 'Set-Cookie' in response.headers
    assert 'login_token=' in response.headers['Set-Cookie']

Have fun testing!