Tutorial - Testing Python Social Auth

Tutorial - 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": "[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!

Originally published by *Paul Bailey *at** hackernoon.com

===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Using Django DRF JWT Authentication with Django Channels

An A-Z of useful Python tricks

What exactly can you do with Python? Here are Python’s 3 main applications.

python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().