Paul Bailey

Father, web developer, and pizza maker; Software Entomologist @saltstack

Quick Tip: Testing Python Social Auth

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": "narf@aol.com",
        }

#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!

Tags

Comments

More by Paul Bailey

Topics of interest