Created
December 28, 2013 08:57
-
-
Save easonhan007/8157488 to your computer and use it in GitHub Desktop.
how to use python to test a json based api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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