importunittestimportrequestsimportjsonclassTestInterFace(unittest.TestCase):defsetUp(self):#print "xxxx"
self.domain='http://localhost:12888'self.json_headers={"content-type":'application/json'}print "before each test"
deftearDown(self):print "End One Testcase"
deftest_get_all_posts(self):print "test get all posts"result=requests.get(self.url_test("/posts")).json()
self.assertEqual(len(result),3)printlen(result)
self.assertEqual(result[0]['title'],'first post')#print 'xxx'
self.assertEqual(result[0]['url'],'/posts/1')
self.assertEqual(result[-1]['title'],'how to learn interface test')
self.assertEqual(result[-1]['url'],'/posts/3')deftest_get_first_post(self):print "test get first post"result=requests.get(self.url_test("/posts/1")).json()
self.assertEqual(len(result),2)
self.assertEqual(result['title'],'first post')
self.assertEqual(result['content'],'this is my first post')defurl_test(self,path):return self.domain +pathdeftest_create_post(self):#headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.post(self.url_test('/posts'),data=json_data,headers=self.json_headers)printresult.status_codeprintresult.text
self.assertEqual(result.status_code,200)
self.assertEqual(result['sucess'],'true')deftest_modify_post(self):
headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.put(self.url_test('/posts/1'),data=json_data,headers=self.json_headers)printresult.status_codeprintresult.text
self.assertEqual(result.status_code,200)#self.assertTrue
deftest_delete_post(self):
headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.delete(self.url_test('/posts/2'))printresult.status_codeprintresult.text
self.assertEqual(result.status_code,200)#self.assertTrue
if __name__=='__main__':
unittest.main()