def setUp(self): self.s = six.StringIO() self.mdlw = PrintQueryMiddleware(self.s) self.mdlw.colors = { 'reset': "", 'yellow': "", 'red': "", 'green': "", 'purple': "", 'white': "", } self.cnx = ApiConnexion(url='http://localapi/v2/') self.cnx.push_middleware(self.mdlw, 3) self.cnx.push_middleware( MockDataApiMiddleware({ '/a': [{ 'data': { 'res': 'a' } }], 'b': { 'data': { 'res': 'b' } }, 'c': { 'data': { 'res': object() } } }))
class TestApiConnexionUrlReslving(TestCase): def setUp(self): self.c = ApiConnexion("http://localhost/api/v2/", auth=('user1', 'badpasswd')) def test_auto_fix_url(self): c = ApiConnexion("http://localhost/api/v2", auth=('user1', 'badpasswd')) self.assertEqual(c.url, "http://localhost/api/v2/") # plus final / def test_url_relative(self): self.assertEqual(self.c.get_final_url('pizza'), "http://localhost/api/v2/pizza") def test_url_relative_end_slash(self): self.assertEqual(self.c.get_final_url('pizza/'), "http://localhost/api/v2/pizza/") def test_url_absolute(self): self.assertEqual(self.c.get_final_url('/pizza'), "http://localhost/pizza") def test_url_absolute_end_slash(self): self.assertEqual(self.c.get_final_url('/pizza/'), "http://localhost/pizza/")
def setUp(self): super(TestMockDataError, self).setUp() self.mdlwr = MockDataApiMiddleware({ 'a': {'data': {'result': 'a'}}, 'b': {'data': {'result': 'b'}}, 'c': {'filter': {'method': 'post'}, 'data': {'result': 'b'}}, }) self.cnx = ApiConnexion(url='http://localapi/v2/') self.cnx.push_middleware(self.mdlwr, 3)
def test_auth_forbiden(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=None) self.assertRaises(ProgrammingError, c.patch, 'authpizza/1', json={'pizza': { 'price': 0 }})
def test_auth_no_rigth(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=('user1', 'user1')) self.assertRaises(ProgrammingError, c.patch, 'authpizza/1', json={'pizza': { 'price': 0 }})
class TestPrintQueryMiddleware(TestCase): def setUp(self): self.s = six.StringIO() self.mdlw = PrintQueryMiddleware(self.s) self.mdlw.colors = { 'reset': "", 'yellow': "", 'red': "", 'green': "", 'purple': "", 'white': "", } self.cnx = ApiConnexion(url='http://localapi/v2/') self.cnx.push_middleware(self.mdlw, 3) self.cnx.push_middleware( MockDataApiMiddleware({ '/a': [{ 'data': { 'res': 'a' } }], 'b': { 'data': { 'res': 'b' } }, 'c': { 'data': { 'res': object() } } })) def test_print_null_settings_missings(self): res = self.cnx.get('b', params={'name': 'rest'}) self.assertEqual(res.status_code, 200) self.assertEqual( self.s.getvalue(), """## BEGIN GET b => <truncated by missing settings.REST_API_OUTPUT_FORMAT> ## END GET b <= """) def test_print_null_settings_null(self): with self.settings(REST_API_OUTPUT_FORMAT='null'): res = self.cnx.get('b', params={'name': 'rest'}) self.assertEqual(res.status_code, 200) self.assertEqual( self.s.getvalue(), """## BEGIN GET b => <truncated by settings.REST_API_OUTPUT_FORMAT="null"> ## END GET b <= """) def test_keep_call_middleware(self): for i in range(50): self.mdlw.process_request({}, i + 700, self.cnx) self.assertEqual(len(self.mdlw.reqid_to_url), 50) self.cnx.get('b') self.assertEqual(len(self.mdlw.reqid_to_url), 50) def test_bug_call_middleware(self): for i in range(550): self.mdlw.process_request({}, i + 700, self.cnx) self.assertEqual(len(self.mdlw.reqid_to_url), 49) self.cnx.get('b') self.assertEqual(len(self.mdlw.reqid_to_url), 49) def test_print_pprint(self): self.mdlw.format = 'pprint' res = self.cnx.get('b', params={'name': 'rest', 'l': list(range(15))}) self.assertEqual(res.status_code, 200) output = self.s.getvalue() split_output = output.split('\n') self.assertEqual(split_output[0], "## BEGIN GET b =>") if six.PY2: expected = "u'params': {u'l': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], u'name': u'rest'}}," else: expected = "'params': {'l': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'name': 'rest'}}," for l in split_output: if expected in l: break else: self.fail("%s not found in %s" % (expected, split_output)) self.assertEqual(len(split_output), 8) def test_print_pprint_long(self): self.mdlw.format = 'pprint' res = self.cnx.get('b', params={ 'name': 'rest', 'l': list(range(255)) }) # generate many lines self.assertEqual(res.status_code, 200) self.assertEqual(self.s.getvalue().count('\n'), 3) def test_print_pprint_long2(self): self.mdlw.format = 'pprint' res = self.cnx.get('/a', params={ 'name': 'rest', 'l': list(range(255)) }) # generate many lines self.assertEqual(res.status_code, 200) self.assertEqual(self.s.getvalue().count('\n'), 3) def test_print_json(self): self.maxDiff = None self.mdlw.format = 'json' res = self.cnx.get('b', params={'name': 'rest', 'l': list(range(15))}) self.assertEqual(res.status_code, 200) output = self.s.getvalue() split_output = output.split('\n') self.assertEqual(split_output[0], "## BEGIN GET b =>") self.assertEqual(split_output[1], "{") self.assertEqual(split_output[2], ' "filter": {') self.assertEqual(len(split_output), 33) def test_print_json_long(self): self.mdlw.format = 'json' res = self.cnx.get('b', params={ 'name': 'rest', 'l': list(range(255)) }) # generate many lines self.assertEqual(res.status_code, 200) self.assertEqual(self.s.getvalue().count('\n'), 3) def test_unserializable(self): self.mdlw.format = 'json' res = self.cnx.get('c') # generate many lines self.assertEqual(res.status_code, 200) getvalue = self.s.getvalue() if six.PY2: self.assertIn("u'exception': TypeError('<object object at ", getvalue) self.assertIn("u'text': \"{u'res': <object object at ", getvalue) elif sys.version_info[:2] >= (3, 6): self.assertIn( "'exception': TypeError(\"Object of type 'object' is not JSON serializable\"", getvalue) self.assertIn("'text': \"{'res': <object object at ", getvalue) else: self.assertIn("'exception': TypeError('<object object at ", getvalue) self.assertIn("'text': \"{'res': <object object at ", getvalue)
def get_new_connection(self, conn_params): return ApiConnexion(**conn_params)
def test_auth_admin(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=('admin', 'admin')) r = c.patch('authpizza/1', json={'pizza': {'price': 0}}) self.assertEqual(r.status_code, 200)
def test_api_connectionerror(self): c = ApiConnexion("http://127.0.0.1:7777") self.assertRaisesMessage(FakeDatabaseDbAPI2.OperationalError, 'Is the API', c.get, '')
def setUp(self): self.live_server_url = LocalApiAdapter.SPECIAL_URL self.client = ApiConnexion(self.live_server_url + "/api/v2/", auth=None)
class TestLocalApiHandler(TestCase): fixtures = ['data.json'] def setUp(self): self.live_server_url = LocalApiAdapter.SPECIAL_URL self.client = ApiConnexion(self.live_server_url + "/api/v2/", auth=None) def test_api_connectionerror(self): c = ApiConnexion("http://127.0.0.1:7777") self.assertRaisesMessage(FakeDatabaseDbAPI2.OperationalError, 'Is the API', c.get, '') def test_api_get(self): r = self.client.get("pizza/1/") self.assertEqual(r.json()['pizza']['id'], 1) def test_api_filter(self): r = self.client.get('pizza/', params={ 'filter{id}': '1', 'include[]': 'toppings.*' }) data = r.json() self.assertEqual(data['pizzas'][0]['id'], 1) self.assertEqual(len(data['toppings']), len(data['pizzas'][0]['toppings'])) def test_api_post(self): r = self.client.post('pizza/', json=dict( pizza={ "toppings": [2, 3, 5], "from_date": "2016-11-15", "price": 13.0, "to_date": "2016-11-20T08:46:02.016000", "name": "chévre", "id": 1, })) self.assertEqual(r.status_code, 201) data = r.json() self.assertGreater(data['pizza']['id'], 3) # 3 is the id of the fixture def test_api_put(self): rget = self.client.get('pizza/1') data = rget.json() self.assertEqual(data['pizza']['price'], 10.0) data['pizza']['price'] = 0. rput = self.client.put('pizza/1', json=data) self.assertEqual(rput.status_code, 200) self.assertEqual(rput.json()['pizza']['price'], 0) rget2 = self.client.get('pizza/1') self.assertEqual(rget2.json()['pizza']['price'], 0) def test_api_patch(self): rget = self.client.get('pizza/1') data = rget.json() self.assertEqual(data['pizza']['price'], 10.0) rput = self.client.patch('pizza/1', json={'pizza': {'price': 0}}) self.assertEqual(rput.status_code, 200) self.assertEqual(rput.json()['pizza']['price'], 0) rget2 = self.client.get('pizza/1') self.assertEqual(rget2.json()['pizza']['price'], 0) def test_api_delete(self): rget = self.client.get('pizza/1') self.assertEqual(rget.status_code, 200) self.client.delete('pizza/1') rget2 = self.client.get('pizza/1') self.assertEqual(rget2.status_code, 404) def test_api_options(self): rget = self.client.options('pizza/1') self.assertEqual(rget.status_code, 200) data = rget.json() self.assertIn('include[]', data['features']) def test_auth_forbiden(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=None) self.assertRaises(ProgrammingError, c.patch, 'authpizza/1', json={'pizza': { 'price': 0 }}) def test_auth_admin(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=('admin', 'admin')) r = c.patch('authpizza/1', json={'pizza': {'price': 0}}) self.assertEqual(r.status_code, 200) def test_auth_no_rigth(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=('user1', 'user1')) self.assertRaises(ProgrammingError, c.patch, 'authpizza/1', json={'pizza': { 'price': 0 }})
def setUp(self): self.client = ApiConnexion(self.live_server_url + "/api/v2/", auth=None) super(TestApiConnexion, self).setUp()
def test_auto_fix_url(self): c = ApiConnexion("http://localhost/api/v2", auth=('user1', 'badpasswd')) self.assertEqual(c.url, "http://localhost/api/v2/") # plus final /
def setUp(self): self.c = ApiConnexion("http://localhost/api/v2/", auth=('user1', 'badpasswd'))
def test_url_resolving(self): c = ApiConnexion(self.live_server_url + "/api/v2/", auth=('admin', 'admin')) r = c.get('/other/view/', json={'result': 'ok'}) self.assertEqual(r.status_code, 200)
class TestMockDataError(TestCase): def setUp(self): super(TestMockDataError, self).setUp() self.mdlwr = MockDataApiMiddleware({ 'a': {'data': {'result': 'a'}}, 'b': {'data': {'result': 'b'}}, 'c': {'filter': {'method': 'post'}, 'data': {'result': 'b'}}, }) self.cnx = ApiConnexion(url='http://localapi/v2/') self.cnx.push_middleware(self.mdlwr, 3) def test_not_found(self): with self.assertRaises(Exception) as e: self.cnx.get('dada') self.assertEqual(e.exception.args, ("the query 'dada' was not provided as mocked data: " "urls was %s" % ['a', 'b', 'c'], )) def test_not_found_abs(self): with self.assertRaises(Exception) as e: self.cnx.get('/dada') self.assertEqual(e.exception.args, ("the query 'http://localapi/dada' was not provided as mocked data: " "urls was %s" % ['a', 'b', 'c'],)) def test_found_bad_filters(self): with self.assertRaises(Exception) as e: self.cnx.get('c') self.assertTrue(e.exception.args[0].startswith("the query 'c' was not provided as mocked data: " "1 fixture for this url, but filter did not match. " "got " )) def test_ok(self): self.cnx.post('c', data={}) self.cnx.get('a')