Skip to content

Instantly share code, notes, and snippets.

@easonhan007
Created December 28, 2013 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save easonhan007/8157488 to your computer and use it in GitHub Desktop.
Save easonhan007/8157488 to your computer and use it in GitHub Desktop.
how to use python to test a json based api
import unittest, httplib, urllib, json
class ApiTestCase(unittest.TestCase):
def setUp(self):
self.conn = httplib.HTTPConnection('localhost', 5000)
def tearDown(self):
if self.conn is not None: self.conn.close()
def get(self, path='/'):
self.conn.request('GET', path)
return self.conn.getresponse()
def post(self, path='/', params={}):
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "application/json"}
self.conn.request('POST', path, params, headers)
return self.conn.getresponse()
def test_index(self):
res = self.get('/')
self.assertEqual(res.status, 200)
data = json.loads(res.read())
self.assertEqual(data['hello'], 'world')
def test_add_user(self):
params = {'name': 'jerry', 'age': '20', 'sex': 'male'}
res1 = self.post('/add', params)
self.assertEqual(res1.status, 200)
# get find user
res2 = self.get('/find_user?name=' + 'jerry')
self.assertEqual(res2.status, 200)
data = json.loads(res2.read())
self.assertEqual(data['name'], 'jerry')
self.assertEqual(data['age'], 20)
self.assertEqual(data['sex'], 'male')
if __name__ == '__main__': unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment