Skip to content

Instantly share code, notes, and snippets.

@andreagrandi
Last active December 25, 2015 02:39
Show Gist options
  • Save andreagrandi/6904365 to your computer and use it in GitHub Desktop.
Save andreagrandi/6904365 to your computer and use it in GitHub Desktop.
In this example I define a very simple client that authenticate with AppNexus API and return the authentication token. In the test file i mock the post() method of the requests library and I make it return a JSON response that I want. The final result is that when I call the authenticate() method, it doesn't really call the remote API, and the r…
import requests
import json
class AppNexusClient(object):
@staticmethod
def authenticate(username, password):
auth_data = {'auth': {'username': username, 'password': password}}
r = requests.post('https://api.appnexus.com/auth', data = json.dumps(auth_data))
return r.json()['response']['token']
import unittest
import requests
from mock import patch
from appnexus_client import AppNexusClient
class MockResponseValid(object):
def json(self):
return self.data
def __init__(self, data):
self.status_code = 200
self.data = data
class AppNexusClientTests(unittest.TestCase):
def test_authentication(self):
with patch.object(requests, 'post') as mock_method:
mock_method.return_value = MockResponseValid({"response": {"token": "AAABBBCCCDDD"}})
self.assertEqual(AppNexusClient.authenticate('username', 'password'), 'AAABBBCCCDDD')
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment