I’ve been working on the second iteration of the hpflsk backend and have decided to follow best practice and create test Facebook users to play around with (before, we were using our personal accounts as test accounts and causing all sorts of mayhem). The backend is, again, implemented in django – the web framework for hipsters, with deadlines.
My original plan was to create a new batch of test users for every test (in the setUp process) and delete them again after each test (during tearDown). However, I found one of the limitations of the Facebook API is that not all user fields are updatable – notably location and timezone. To get around this, I decided to create 10 static test users and manually update their details by logging in (through the roles sections of the app development page). Hopefully I only need to do this once. Here’s the code to create the test users:
from django.conf import settings
import requests
import json
def create_test_user(name, locale='en_US', permissions=[]):
r = requests.get("https://graph.facebook.com/%s/accounts/test-users"
% settings.FACEBOOK_APP_ID,
params={
'installed': 'true',
'name': name,
'locale': locale,
'permissions': ','.join(permissions),
'method': 'post',
'access_token': settings.FACEBOOK_APP_TOKEN,
})
return json.loads(r.text)
def delete_test_user(id, access_token):
r = requests.get("https://graph.facebook.com/%s?" % id,
params={
'method': 'delete',
'access_token': access_token,
})
return r.text
Another limitation I found with using Facebook test users is that you can’t extend the life of their access token using the method described here. By default, test users are issued with a short term (1 hour) access token. But I want these users to be accessible by my test suite for all eternity! Here’s the trick: every time you fetch a list of your test users, their access tokens will be updated for another hour. So all you need to do is follow the process here (see the Accessing section) and you’ll get a list of all of your test users id’s and updated access tokens. You can then update your test users with the latest access tokens like so (I use the brilliant django-social-auth to handle all my social logins):
from django.conf import settings
from social_auth.models import UserSocialAuth
import requests
def refresh_test_users():
r = requests.get("https://graph.facebook.com/%s/accounts/test-users" % settings.FACEBOOK_APP_ID,
params = {
'access_token': settings.FACEBOOK_APP_TOKEN
})
j = json.loads(r.text)
for u in UserSocialAuth.objects.all():
user_data = [i for i in j['data'] if i['id'] == u.uid][0]
u.extra_data['access_token'] = user_data['access_token']
u.save()
I run this refresh script every time my test suite starts so that I have a fresh set of access tokens before I start the integration tests with Facebook.