def test_custom_with_trailing_slash(self): class CustomController(RestController): _custom_actions = { 'detail': ['GET'], 'create': ['POST'], 'update': ['PUT'], 'remove': ['DELETE'], } @expose() def detail(self): return 'DETAIL' @expose() def create(self): return 'CREATE' @expose() def update(self, id): return id @expose() def remove(self, id): return id app = TestApp(make_app(CustomController())) r = app.get('/detail') assert r.status_int == 200 assert r.body == b_('DETAIL') r = app.get('/detail/') assert r.status_int == 200 assert r.body == b_('DETAIL') r = app.post('/create') assert r.status_int == 200 assert r.body == b_('CREATE') r = app.post('/create/') assert r.status_int == 200 assert r.body == b_('CREATE') r = app.put('/update/123') assert r.status_int == 200 assert r.body == b_('123') r = app.put('/update/123/') assert r.status_int == 200 assert r.body == b_('123') r = app.delete('/remove/456') assert r.status_int == 200 assert r.body == b_('456') r = app.delete('/remove/456/') assert r.status_int == 200 assert r.body == b_('456')
def test_update_group(): c = Client(App()) response = c.post( "/login", json.dumps({ "email": "*****@*****.**", "password": "******" })) headers = {"Authorization": response.headers["Authorization"]} updateted_group_json = json.dumps( {"users": ["*****@*****.**", "*****@*****.**"]}) c.put("/groups/3", updateted_group_json, headers=headers) with db_session: g = Group[3] assert User[2] in g.users assert User[3] in g.users updateted_group_json = json.dumps({"name": "Moderator"}) response = c.put("/groups/1", updateted_group_json, headers=headers, status=409) assert response.json == {"validationError": "Group already exists"} updateted_group_json = json.dumps({"name": "Guru"}) c.put("/groups/1", updateted_group_json, headers=headers) with db_session: assert Group[1].name == "Guru"
class AuthenticationTests(unittest.TestCase): def setUp(self): app = wp_frontend.main({}, sql_init_function=tests.init_db, **tests.settings) self.testapp = TestApp(app) def tearDown(self): del self.testapp tests.getSession().remove() def test_login_and_logout(self): self.testapp.put('/login', valid_credentials, status=302) res = self.testapp.get('/home') self.assertNotIn('input type="password"', res.body) self.testapp.get('/logout') res = self.testapp.get('/home') self.assertIn('input type="password"', res.body) def test_failed_log_in(self): invalid_credentials = { 'user': '******', 'password': '******', 'came_from': '/', 'submit': '', } res = self.testapp.put('/login', invalid_credentials, status=200) res = self.testapp.get('/home') self.assertIn('input type="password"', res.body) def test_garbage_log_in(self): garbage_credentials = {'foo': 'baz', 'submit': ''} res = self.testapp.put('/login', garbage_credentials, status=200) self.assertIn('input type="password"', res.body) self.assertIn('There was a problem with your submission', res.body)
def test_users_put_same_twice(self): """ try to register the same user twice; must fail! """ app = TestApp(main({})) _name = 'john' _namejson = json.dumps({'name': _name}) res = app.put('/users', _namejson) # check response self.assertTrue("token" in str(res.body)) # did get a token self.assertTrue(_name in str(res.body)) # name found # do it again, try to register user of same name # expect "Bad Request (400)" res2 = app.put('/users', _namejson, status=400) #print(res2) # {"status": "error", # "errors": [{ # "location": "url", # "name": "name", # "description": "This user exists!"}]} _json2 = json.loads(res2.body) #print(_json2['status']) self.assertTrue( 'error' in _json2['status']) self.assertTrue( 'This user exists!' in _json2['errors'][0]['description'])
def test_users_put_same_twice(self): """ try to register the same user twice; must fail! """ app = TestApp(main({})) _name = 'john' res = app.put('/users', _name) # check response self.assertTrue("token" in str(res.body)) # did get a token self.assertTrue(_name in str(res.body)) # name found # do it again, try to register user of same name # expect "Bad Request (400)" res2 = app.put('/users', _name, status=400) #print(res2) # {"status": "error", # "errors": [{ # "location": "url", # "name": "name", # "description": "This user exists!"}]} _json2 = json.loads(res2.body) #print(_json2['status']) self.assertTrue( 'error' in _json2['status']) self.assertTrue( 'This user exists!' in _json2['errors'][0]['description'])
class FunctionalTest(unittest.TestCase): def setUp(self): self.app = TestApp(application) def test_index_returns_200(self): response = self.app.get('/', expect_errors=True) self.assertEquals("200 OK", response.status) def test_index_return_correct_mime_type(self): response = self.app.get('/', expect_errors=True) self.assertEquals(response.content_type, "text/html") def test_multiple_args_in_url(self): response = self.app.get('/foo/1/2', expect_errors=True) response.mustcontain("Hello World of 1 and 2") def test_put(self): response = self.app.put('/', expect_errors=True) self.assertEquals("200 OK", response.status) response.mustcontain("Hello World of Put") def test_404_handler(self): response = self.app.get('/does-not-exist', expect_errors=True) self.assertEquals("404 Not Found", response.status) def test_404_handler(self): response = self.app.get('/does-not-exist', expect_errors=True) self.assertEquals("404 Not Found", response.status) def test_HTTPResponseRedirect_handler(self): response = self.app.get('/bar', expect_errors=True) self.assertEquals("/", response.headers['Location']) self.assertEquals("301 Moved Permanently", response.status) def test_temporaty_HTTPResponseRedirect_handler(self): response = self.app.delete('/bar', expect_errors=True) self.assertEquals("/", response.headers['Location']) self.assertEquals("302 Found", response.status) def test_unregistered_post_request(self): response = self.app.post('/', expect_errors=True) self.assertEquals("405 Method Not Allowed", response.status) def test_unregistered_delete_request(self): response = self.app.delete('/', expect_errors=True) self.assertEquals("405 Method Not Allowed", response.status) def test_unregistered_put_request(self): response = self.app.put('/bar', expect_errors=True) self.assertEquals("405 Method Not Allowed", response.status) def test_query_string(self): response = self.app.get('/?test=test', expect_errors=True) self.assertEqual("test", response.request.GET['test']) self.assertEquals("200 OK", response.status) def test_addition_of_method_to_request(self): response = self.app.get('/', expect_errors=True) self.assertEqual("GET", response.request.method)
def test_view_organizations_order(gazette_app): client = Client(gazette_app) login_publisher(client) manage = client.get('/organizations') manage = manage.click('Ordnen') organizations = [ t.text.strip() for t in manage.pyquery('ul[data-sortable] li') ] assert organizations == [ 'State Chancellery', 'Civic Community', 'Municipality', 'Churches', 'Evangelical Reformed Parish', 'Sikh Community', 'Catholic Parish', 'Corporation', ] url = manage.pyquery('ul[data-sortable]')[0].attrib['data-sortable-url'] expected = ( '/move/organization/%7Bsubject_id%7D/%7Bdirection%7D/%7Btarget_id%7D' '?csrf-token=') assert expected in url # Move items session = gazette_app.session() query = session.query(Organization) subject = query.filter_by(title='State Chancellery').one().id target = query.filter_by(title='Municipality').one().id move = url.replace('%7Bsubject_id%7D', str(subject)) move = move.replace('%7Btarget_id%7D', str(target)) move = move.replace('%7Bdirection%7D', 'below') client.put(move) subject = query.filter_by(title='Catholic Parish').one().id target = query.filter_by(title='Sikh Community').one().id move = url.replace('%7Bsubject_id%7D', str(subject)) move = move.replace('%7Btarget_id%7D', str(target)) move = move.replace('%7Bdirection%7D', 'above') client.put(move) manage = client.get('/organizations') manage = manage.click('Ordnen') organizations = [ t.text.strip() for t in manage.pyquery('ul[data-sortable] li') ] assert organizations == [ 'Civic Community', 'Municipality', 'State Chancellery', 'Churches', 'Evangelical Reformed Parish', 'Catholic Parish', 'Sikh Community', 'Corporation', ]
def test_accept(self): # tests that the accept headers are handled the proper way app = TestApp(main({})) # requesting the wrong accept header should return a 406 ... response = app.get("/service2", headers={"Accept": "audio/*"}, status=406) # ... with the list of accepted content-types error_location = response.json["errors"][0]["location"] error_name = response.json["errors"][0]["name"] error_description = response.json["errors"][0]["description"] self.assertEquals("header", error_location) self.assertEquals("Accept", error_name) self.assertIn("application/json", error_description) self.assertIn("text/json", error_description) self.assertIn("text/plain", error_description) # requesting a supported type should give an appropriate response type response = app.get("/service2", headers={"Accept": "application/*"}) self.assertEqual(response.content_type, "application/json") response = app.get("/service2", headers={"Accept": "text/plain"}) self.assertEqual(response.content_type, "text/plain") # it should also work with multiple Accept headers response = app.get("/service2", headers={"Accept": "audio/*, application/*"}) self.assertEqual(response.content_type, "application/json") # and requested preference order should be respected headers = {"Accept": "application/json; q=1.0, text/plain; q=0.9"} response = app.get("/service2", headers=headers) self.assertEqual(response.content_type, "application/json") headers = {"Accept": "application/json; q=0.9, text/plain; q=1.0"} response = app.get("/service2", headers=headers) self.assertEqual(response.content_type, "text/plain") # test that using a callable to define what's accepted works as well response = app.get("/service3", headers={"Accept": "audio/*"}, status=406) error_description = response.json["errors"][0]["description"] self.assertIn("text/json", error_description) response = app.get("/service3", headers={"Accept": "text/*"}) self.assertEqual(response.content_type, "text/json") # Test that using a callable to define what's accepted works as well. # Now, the callable returns a scalar instead of a list. response = app.put("/service3", headers={"Accept": "audio/*"}, status=406) error_description = response.json["errors"][0]["description"] self.assertIn("text/json", error_description) response = app.put("/service3", headers={"Accept": "text/*"}) self.assertEqual(response.content_type, "text/json") # If we are not asking for a particular content-type, # we should get one of the two types that the service supports. response = app.get("/service2") self.assertIn(response.content_type, ("application/json", "text/plain"))
def test_put_bad_data(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.put('/api/1/walls/2/collections/3', params=dumps({'title': 123}), status=400)
def test_put_bad_data(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.put('/api/1/walls/2/relations/1', params=dumps({'members': 'Jeff & Stanley'}), status=400)
def test_accept_and_content_type(self): # tests that giving both Accept and Content-Type # request headers satisfy the requirement app = TestApp(main({})) # POST endpoint just has one accept and content_type definition response = app.post('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/json; charset=utf-8' }, status=200) self.assertEqual(response.json, "some response") response = app.post('/service7', headers={ 'Accept': 'text/plain, application/json', 'Content-Type': 'application/json; charset=utf-8' }, status=406) response = app.post('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, status=415) # PUT endpoint has a list of accept and content_type definitions response = app.put('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/json; charset=utf-8' }, status=200) self.assertEqual(response.json, "some response") response = app.put('/service7', headers={ 'Accept': 'audio/*', 'Content-Type': 'application/json; charset=utf-8' }, status=406) response = app.put('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, status=415)
def test_singular_resource(self, *a): View = get_test_view_class() config = _create_config() root = config.get_root_resource() root.add('thing', view=View) grandpa = root.add('grandpa', 'grandpas', view=View) wife = grandpa.add('wife', view=View, renderer='string') wife.add('child', 'children', view=View) config.begin() app = TestApp(config.make_wsgi_app()) self.assertEqual( '/grandpas/1/wife', route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1) ) self.assertEqual( '/grandpas/1', route_path('grandpa', testing.DummyRequest(), id=1) ) self.assertEqual( '/grandpas/1/wife/children/2', route_path('grandpa_wife:child', testing.DummyRequest(), grandpa_id=1, id=2) ) self.assertEqual(app.put('/grandpas').body, six.b('update_many')) self.assertEqual(app.head('/grandpas').body, six.b('')) self.assertEqual(app.options('/grandpas').body, six.b('')) self.assertEqual(app.delete('/grandpas/1').body, six.b('delete')) self.assertEqual(app.head('/grandpas/1').body, six.b('')) self.assertEqual(app.options('/grandpas/1').body, six.b('')) self.assertEqual(app.put('/thing').body, six.b('replace')) self.assertEqual(app.patch('/thing').body, six.b('update')) self.assertEqual(app.delete('/thing').body, six.b('delete')) self.assertEqual(app.head('/thing').body, six.b('')) self.assertEqual(app.options('/thing').body, six.b('')) self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace')) self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update')) self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete')) self.assertEqual(app.head('/grandpas/1/wife').body, six.b('')) self.assertEqual(app.options('/grandpas/1/wife').body, six.b('')) self.assertEqual(six.b('show'), app.get('/grandpas/1').body) self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body) self.assertEqual( six.b('show'), app.get('/grandpas/1/wife/children/1').body)
def test_accept_and_content_type(self): # Tests that using both the "Accept" and "Content-Type" # request headers satisfy the requirement. app = TestApp(main({})) # POST endpoint just has one accept and content_type definition response = app.post('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/json; charset=utf-8' }) self.assertEqual(response.json, "some response") response = app.post( '/service7', headers={ 'Accept': 'text/plain, application/json', 'Content-Type': 'application/json; charset=utf-8' }, status=406) response = app.post( '/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, status=415) # PUT endpoint has a list of accept and content_type definitions response = app.put('/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/json; charset=utf-8' }) self.assertEqual(response.json, "some response") response = app.put( '/service7', headers={ 'Accept': 'audio/*', 'Content-Type': 'application/json; charset=utf-8' }, status=406) response = app.put( '/service7', headers={ 'Accept': 'text/xml, application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, status=415)
def test_users_put(self): """ register a username, get an auth token, use it to get list of users """ app = TestApp(main({})) _name = "heinzi" res = app.put("/users", _name, status=200) # print(res) # uncomment to see the following output: # Content-Type: application/json; charset=UTF-8 # {"api-version": "0.1dev", # "token": "heinz-2354ed39ba5def1aef9f8a11997d8833df691f25"} self.assertTrue("application/json; charset=UTF-8" in res.headers["Content-Type"]) # store the body as json _json = json.loads(res.body) # print(_json['api-version']) self.assertTrue("0.1dev" in _json["api-version"]) self.assertTrue(_name in str(_json["token"])) _token = _json["token"] # print("the token from res: " + _token) _auth_header = {"X-Messaging-Token": str(_token)} # now we have a token and can authenticate... res2 = app.get("/users", headers=_auth_header, status=200) # print(res2) # Response: 200 OK # Content-Type: application/json; charset=UTF-8 # {"users": ["heinz"]} self.assertTrue("application/json; charset=UTF-8" in res2.headers["Content-Type"]) # store the body as json _json = json.loads(res2.body) # self.assertTrue('0.1dev' in _json['api-version']) self.assertTrue(_name in (_json["users"]))
def test_users_delete(self): """ register a username, get an auth token, delete user again idea: register second user to check """ app = TestApp(main({})) _name = "mary" res = app.put("/users", _name, status=200) self.assertTrue("application/json; charset=UTF-8" in res.headers["Content-Type"]) # store the body as json _json = json.loads(res.body) # print(_json['token']) self.assertTrue("0.1dev" in _json["api-version"]) self.assertTrue(_name in str(_json["token"])) _token = _json["token"] # print("the token from res: " + _token) # try using an invalid token: get coverage for the valid_token function _invalid_token = _token.replace("-", "") # removing the '-' # print("_invalid_token: " + _invalid_token) _auth_header = {"X-Messaging-Token": str(_invalid_token)} # calling with the invalid_token we expect 401: Unauthorized res2 = app.delete_json("/users", params=_name, headers=_auth_header, status=401) _auth_header = {"X-Messaging-Token": str(_token)} # now we have a token and can authenticate... and delete the user # delete the user # res2 = app.delete('/users', params=_name, res2 = app.delete_json("/users", params=_name, headers=_auth_header, status=200) # print(res2) self.assertTrue("goodbye" in json.loads(res2.body).keys()) self.assertTrue(_name in json.loads(res2.body).values())
class TestShield(unittest.TestCase): def setUp(self): self.app = TestApp(application) def test_shields(self): response = self.app.post_json('/api/_login', {"username": "******", "password": '******'}) self.assertEqual(200, response.status_int) response = self.app.get('/api/person/') self.assertEqual(200, response.status_int) self.app = TestApp(application) response = self.app.get('/api/person', expect_errors=True) self.assertEquals(401, response.status_int) self.app = TestApp(application) response = self.app.post('/api/person/', expect_errors=True) self.assertIsNot(401, response.status_int) self.app = TestApp(application) response = self.app.put('/api/person/', expect_errors=True) self.assertIsNot(404, response.status_int) self.app = TestApp(application) response = self.app.delete('/api/person/', expect_errors=True) self.assertIsNot(404, response.status_int)
class PutUnidadTrabajo(unittest.TestCase): """ @summary: Testea la modificacion de unidad de trabajo. """ def setUp(self): from yapp import main settings = { 'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp' } app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) def tearDown(self): del self.testapp from yapp.models import DBSession DBSession.remove() def test_it(self): dao = UnidadTrabajoDAO(None) nueva_unidad_trabajo = UnidadTrabajo("Prueba", "P", "Prueba", "0") dao.crear(nueva_unidad_trabajo) unidad = { "_nombre": "Prueba 1", "id": nueva_unidad_trabajo.id, "_etiqueta": "P", "_descripcion": "Prueba", "_color": "008000" } direccion = '/unidadtrabajo/' + str(nueva_unidad_trabajo.id) res = self.testapp.put(direccion, params=json.dumps(unidad)) print "Testeando modificar unidad de trabajo" self.failUnless('sucess' in res.body)
class ClientTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(ClientTest, self).__init__(*args, **kwargs) app.debug = True self.client = TestApp(app) def get(self, url, params=None, headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, xhr=False): self.resp = self.client.get(url, params, headers, extra_environ, status, expect_errors, xhr) return self.resp def post(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False): self.resp = self.client.post(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr) return self.resp def put(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False): self.resp = self.client.put(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr) return self.resp def delete(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, content_type=None, xhr=False): self.resp = self.client.delete(url, params, headers, extra_environ, status, expect_errors, content_type, xhr)
def test_users_put(self): """ register a username, get an auth token, use it to get list of users """ app = TestApp(main({})) _name = 'heinzi' res = app.put('/users', _name, status=200) # print(res) # uncomment to see the following output: # Content-Type: application/json; charset=UTF-8 # {"api-version": "0.1dev", # "token": "heinz-2354ed39ba5def1aef9f8a11997d8833df691f25"} self.assertTrue( 'application/json; charset=UTF-8' in res.headers['Content-Type']) # store the body as json _json = json.loads(res.body) # print(_json['api-version']) self.assertTrue('0.1dev' in _json['api-version']) self.assertTrue(_name in str(_json['token'])) _token = _json['token'] #print("the token from res: " + _token) _auth_header = {'X-Messaging-Token': str(_token)} # now we have a token and can authenticate... res2 = app.get('/users', headers=_auth_header, status=200) #print(res2) # Response: 200 OK # Content-Type: application/json; charset=UTF-8 # {"users": ["heinz"]} self.assertTrue( 'application/json; charset=UTF-8' in res2.headers['Content-Type']) # store the body as json _json = json.loads(res2.body) #self.assertTrue('0.1dev' in _json['api-version']) self.assertTrue(_name in (_json['users']))
def test_content_type_with_callable_returning_scalar(self): # Test that using a callable for content_type works as well. # Now, the callable returns a scalar instead of a list. app = TestApp(main({})) response = app.put("/service6", headers={"Content-Type": "audio/*"}, status=415) error_description = response.json["errors"][0]["description"] self.assertIn("text/xml", error_description)
def test_update_password(smtp): c = Client(App(), extra_environ=dict(REMOTE_ADDR="127.0.0.1")) new_user_json = json.dumps( {"nickname": "NewUser", "email": "*****@*****.**", "password": "******"} ) c.post("/users", new_user_json, status=201) assert len(smtp.outbox) == 1 update_password_json = json.dumps({"password": "******"}) response = c.put( "/users/4/reset/" + "Im5ld3VzZXJAZXhhbXBsZS5jb20i.WrongToken.JrUGhlAxao46VsQevI", update_password_json, status=403, ) assert response.json == { "validationError": "The password reset link is invalid or has been expired" } response = c.put( "/users/4/reset/" + "Im5ld3VzZXJAZXhhbXBsZS5jb20i.C40RUQ.5JhlEE36_JrUGhlAxao46VsQevI", update_password_json, status=403, ) assert response.json == { "validationError": "Your email must be confirmed before resetting the password" } c.get( "/users/4/confirm/" + "Im5ld3VzZXJAZXhhbXBsZS5jb20i.C3dnsw.2meomRPK3wnYwB2AERt2ygjFaRE", status=302, ) response = c.put( "/users/4/reset/" + "Im5ld3VzZXJAZXhhbXBsZS5jb20i.C40RUQ.5JhlEE36_JrUGhlAxao46VsQevI", update_password_json, ) ph = PasswordHasher() with db_session: assert ph.verify(User[4].password, "new_secret")
def test_bad_rest(self): class ThingsController(RestController): pass class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get_all r = app.get('/things', status=404) assert r.status_int == 404 # test get_one r = app.get('/things/1', status=404) assert r.status_int == 404 # test post r = app.post('/things', {'value': 'one'}, status=404) assert r.status_int == 404 # test edit r = app.get('/things/1/edit', status=404) assert r.status_int == 404 # test put r = app.put('/things/1', {'value': 'ONE'}, status=404) # test put with _method parameter and GET r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405) assert r.status_int == 405 # test put with _method parameter and POST r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=404) assert r.status_int == 404 # test get delete r = app.get('/things/1/delete', status=404) assert r.status_int == 404 # test delete r = app.delete('/things/1', status=404) assert r.status_int == 404 # test delete with _method parameter and GET r = app.get('/things/1?_method=DELETE', status=405) assert r.status_int == 405 # test delete with _method parameter and POST r = app.post('/things/1?_method=DELETE', status=404) assert r.status_int == 404 # test "RESET" custom action with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things', method='RESET', status=404) assert r.status_int == 404
def test_bad_rest(self): class ThingsController(RestController): pass class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get_all r = app.get('/things', status=405) assert r.status_int == 405 # test get_one r = app.get('/things/1', status=405) assert r.status_int == 405 # test post r = app.post('/things', {'value': 'one'}, status=405) assert r.status_int == 405 # test edit r = app.get('/things/1/edit', status=405) assert r.status_int == 405 # test put r = app.put('/things/1', {'value': 'ONE'}, status=405) # test put with _method parameter and GET r = app.get('/things/1?_method=put', {'value': 'ONE!'}, status=405) assert r.status_int == 405 # test put with _method parameter and POST r = app.post('/things/1?_method=put', {'value': 'ONE!'}, status=405) assert r.status_int == 405 # test get delete r = app.get('/things/1/delete', status=405) assert r.status_int == 405 # test delete r = app.delete('/things/1', status=405) assert r.status_int == 405 # test delete with _method parameter and GET r = app.get('/things/1?_method=DELETE', status=405) assert r.status_int == 405 # test delete with _method parameter and POST r = app.post('/things/1?_method=DELETE', status=405) assert r.status_int == 405 # test "RESET" custom action with warnings.catch_warnings(): warnings.simplefilter("ignore") r = app.request('/things', method='RESET', status=405) assert r.status_int == 405
def test_content_type_correct(self): # Tests that the Content-Type request header satisfies the requirement. app = TestApp(main({})) # Requesting with one of the allowed Content-Type headers should work, # even when having a charset parameter as suffix. response = app.put("/service5", headers={"Content-Type": "text/plain; charset=utf-8"}) self.assertEqual(response.json, "some response")
def test_content_type_with_callable_returning_scalar(self): # Test that using a callable for content_type works as well. # Now, the callable returns a scalar instead of a list. app = TestApp(main({})) response = app.put('/service6', headers={'Content-Type': 'audio/*'}, status=415) error_description = response.json['errors'][0]['description'] self.assertIn('text/xml', error_description)
class WsgiApiTests(BaseWsgiApiTests): @mock_iam def test_should_make_role(self): result = self.app.put('/role/testrole') self.assertEqual(result.status_int, 201) def test_status_good_case(self): result = self.app.get('/status') expected_json = {"status": "200", "message": "OK"} self.assertEqual(result.json, expected_json) def test_status_bad_case_with_missing_config(self): missing_config = os.path.join(self.config_path, "missing_config.yaml") env_with_wrong_config_path = {'CONFIG_PATH': missing_config} self.app = TestApp(wsgi_api.get_webapp(), extra_environ=env_with_wrong_config_path) result = self.app.get('/status', expect_errors=True) self.assertEqual(result.status_int, 500) def test_should_give_401_return_code(self): self.mock_boto_connection.create_role.side_effect = \ [boto.exception.BotoServerError('', '', {'Error': {"Code": "InvalidClientTokenId"}})] result = self.app.put('/role/testrole', expect_errors=True) self.assertEqual(result.status_int, 401) def test_should_give_509_return_code(self): self.mock_boto_connection.create_role.side_effect = \ [boto.exception.BotoServerError('', '', {'Error': {"Code": "LimitExceeded"}})] result = self.app.put('/role/testrole', expect_errors=True) self.assertEqual(result.status_int, 509) def test_should_give_502_return_code(self): self.mock_boto_connection.create_role.side_effect = \ [boto.exception.BotoServerError('', '', {'Error': {"Code": "CanNotContinueException"}})] result = self.app.put('/role/testrole', expect_errors=True) self.assertEqual(result.status_int, 502) @patch('afp_resource_maker.wsgi.yaml_load') def test_load_config_uses_default_path(self, mock_yaml_load): env_without_config_path = {} self.app = TestApp(wsgi_api.get_webapp(), extra_environ=env_without_config_path) wsgi_api.get_config() mock_yaml_load.assert_called_with('/etc/afp-resource-maker')
def test_error_handling_handles_unsupported_http_methods(): wsgi = graphql_wsgi(TestSchema, pretty=True) c = Client(wsgi) response = c.put('/?query={test}', status=405) assert response.json == { 'errors': [{'message': 'GraphQL only supports GET and POST requests.'}] }
def test_content_type_correct(self): # tests that the Content-Type request header satisfies the requirement app = TestApp(main({})) # requesting with one of the allowed Content-Type headers should work, # even when having a charset parameter as suffix response = app.put('/service5', headers={'Content-Type': 'text/plain; charset=utf-8'}, status=200) self.assertEqual(response.json, "some response")
def test_update_supercar(): supercars[1] = {'engine': '1'} app = TestApp(restserver.default_app()) # this MUST be json data! # resp = app.put('/supercars/1', json.dumps({'have_one': 'yes'}), content_type='application/json') # resp = app.put_json('/supercars/1', {'have_one': 'yes'}) resp = app.put('/supercars/1', '{"have_one": \n"yes"}', content_type='application/json') assert_equal(resp.status, '200 OK') assert_equal(supercars, {1: {'engine': '1', 'have_one': 'yes'}})
def test_content_type_correct(self): # Tests that the Content-Type request header satisfies the requirement. app = TestApp(main({})) # Requesting with one of the allowed Content-Type headers should work, # even when having a charset parameter as suffix. response = app.put( '/service5', headers={'Content-Type': 'text/plain; charset=utf-8'}) self.assertEqual(response.json, "some response")
class PutAtributoEsquema(unittest.TestCase): """ @summary: Testea la modificacion de atributos de esquema.. """ def setUp(self): from yapp import main settings = { 'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp' } app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) def tearDown(self): del self.testapp from yapp.models import DBSession DBSession.remove() def test_it(self): dao = ProyectoDAO(None) rol_dao = RolFinalDAO(None) autor = rol_dao.get_by_id(1) lider = rol_dao.get_by_id(1) nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba", "hoy", "hoy") dao.crear(nuevo_proyecto) dao = FaseDAO(None) nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba", "0") dao.crear(nueva_fase) esquemaDao = EsquemaDAO(None) nuevo_esquema = Esquema("Esquema", "_descripcion", "_etiqueta", "_color", nueva_fase.id) esquemaDao.crear(nuevo_esquema) atributoEsquemaDao = AtributoEsquemaDAO(None) nuevo_atributo = AtributoEsquema("_nombre", "_descripcion", "_tipo", "_valor", nuevo_esquema.id) atributoEsquemaDao.crear(nuevo_atributo) atributo = { "id": nuevo_atributo.id, "_nombre": "Prueba", "_descripcion": "prueba", "_tipo": "numerico", "valor": 10, "esquema_id": nuevo_esquema.id } direccion = '/atributosEsquemas/' + str(nuevo_atributo.id) res = self.testapp.put(direccion, params=json.dumps(atributo)) print "Testeando modificar atributo de esquemas" self.failUnless('sucess' in res.body)
def test_change_animal(): c = Client(App()) changed_animal_json = json.dumps( {"name": "Changed Fred", "species": "fish"} ) response = c.put('/animals/1', changed_animal_json) changed_animal_response = {"@id": "http://localhost/animals/1", "name": "Changed Fred", "species": "fish"} assert response.json == changed_animal_response
def test_method_not_allowed_put(self): class ThingsController(RestController): @expose() def get_one(self): return dict() app = TestApp(make_app(ThingsController())) r = app.put('/123', status=405) assert r.status_int == 405 assert r.headers['Allow'] == 'GET'
def test_change_todo(): c = Client(App()) changed_todo_json = json.dumps( {"title": "Changed Test", "completed": True} ) response = c.put('/todos/1', changed_todo_json) changed_todo_response = {"@id": "http://localhost/todos/1", "title": "Changed Test", "completed": True} assert response.json == changed_todo_response
def test_web_basic(): """The web basic test """ class TestService(Service): """The test service """ @get('/test/get') @post('/test/post') @put('/test/put') @delete('/test/delete') @head('/test/head') @patch('/test/patch') @options('/test/options') @endpoint() def test(self): """Test """ return 'OK' @get('/test2') @endpoint() def test2(self, param): """Test 2 """ return 'OK' adapter = WebAdapter() server = Server([ TestService() ], [ adapter ]) server.start() # Test app = TestApp(adapter) rsp = app.get('/test', expect_errors = True) assert rsp.status_int == 404 rsp = app.get('/test/get') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' rsp = app.post('/test/post') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' rsp = app.put('/test/put') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' rsp = app.delete('/test/delete') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' rsp = app.head('/test/head') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' rsp = app.patch('/test/patch') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' rsp = app.options('/test/options') assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK' # Too many parameters rsp = app.get('/test/get?a=1', expect_errors = True) assert rsp.status_int == 400 # Lack of parameters rsp = app.get('/test2', expect_errors = True) assert rsp.status_int == 400 rsp = app.get('/test2?param=1') assert rsp.status_int == 200 and rsp.text == 'OK'
def test_put(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) root, cred = self._fixture(request) response = app.put('/api/1/users/10', params=dumps({'first_name': 'Jane', 'last_name': 'Doe'}), headers={'Authorization': cred.header()}, status=200) self.assertEqual({"type_name": "User", "rid": 10, "data": {'first_name': 'Jane', 'last_name': 'Doe'}}, response.json_body)
def test_content_type_wrong_multiple(self): # tests that the Content-Type request header satisfies the requirement app = TestApp(main({})) # requesting the wrong Content-Type header should return a 415 ... response = app.put("/service5", headers={"Content-Type": "text/xml"}, status=415) # ... with an appropriate json error structure error_description = response.json["errors"][0]["description"] self.assertTrue("text/plain" in error_description) self.assertTrue("application/json" in error_description)
def test_put(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.put('/api/1/collections/3/cards/4', params=dumps({'title': 'Hello world!'}), status=200) self.assertEqual(response.json_body['rid'], 4) self.assertEqual(response.json_body['type_name'], 'Card')
def test_content_type_wrong_multiple(self): # tests that the Content-Type request header satisfies the requirement app = TestApp(main({})) # requesting the wrong Content-Type header should return a 415 ... response = app.put('/service5', headers={'Content-Type': 'text/xml'}, status=415) # ... with an appropriate json error structure error_description = response.json['errors'][0]['description'] self.assertTrue('text/plain' in error_description) self.assertTrue('application/json' in error_description)
def test_content_type_wrong_multiple(self): # Tests that the Content-Type request header satisfies the requirement. app = TestApp(main({})) # Requesting without a Content-Type header should # return "415 Unsupported Media Type" ... response = app.put("/service5", headers={"Content-Type": "text/xml"}, status=415) # ... with an appropriate json error structure. error_description = response.json["errors"][0]["description"] self.assertIn("text/plain", error_description) self.assertIn("application/json", error_description)
def test_accept_and_content_type(self): # tests that giving both Accept and Content-Type # request headers satisfy the requirement app = TestApp(main({})) # POST endpoint just has one accept and content_type definition response = app.post( "/service7", headers={"Accept": "text/xml, application/json", "Content-Type": "application/json; charset=utf-8"}, ) self.assertEqual(response.json, "some response") response = app.post( "/service7", headers={"Accept": "text/plain, application/json", "Content-Type": "application/json; charset=utf-8"}, status=406, ) response = app.post( "/service7", headers={"Accept": "text/xml, application/json", "Content-Type": "application/x-www-form-urlencoded"}, status=415, ) # PUT endpoint has a list of accept and content_type definitions response = app.put( "/service7", headers={"Accept": "text/xml, application/json", "Content-Type": "application/json; charset=utf-8"}, ) self.assertEqual(response.json, "some response") response = app.put( "/service7", headers={"Accept": "audio/*", "Content-Type": "application/json; charset=utf-8"}, status=406 ) response = app.put( "/service7", headers={"Accept": "text/xml, application/json", "Content-Type": "application/x-www-form-urlencoded"}, status=415, )
def test_put(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.put('/api/1/walls/2/relations/1', params=dumps({'members': [10, 20, 30]}), status=200) self.assertEqual({ 'members': [10, 20, 30], 'relation_id': 1 }, response.json_body)
def test_content_type_wrong_multiple(self): # Tests that the Content-Type request header satisfies the requirement. app = TestApp(main({})) # Requesting without a Content-Type header should # return "415 Unsupported Media Type" ... response = app.put('/service5', headers={'Content-Type': 'text/xml'}, status=415) # ... with an appropriate json error structure. error_description = response.json['errors'][0]['description'] self.assertIn('text/plain', error_description) self.assertIn('application/json', error_description)
def test_proper_allow_header_multiple_gets(self): class ThingsController(RestController): @expose() def get_all(self): return dict() @expose() def get(self): return dict() app = TestApp(make_app(ThingsController())) r = app.put('/123', status=405) assert r.status_int == 405 assert r.headers['Allow'] == 'GET'
def test_edit_previously_uneditable_field(self): def _update_handler(req, res): data = jsonutils.loads(res.body) data["uneditable"] = req.params["uneditable"] res.body = jsonutils.dumps(data) return res base_app = TestApp(setup_base_app()) response = base_app.put("/dummy_resources/1", {"uneditable": "new_value"}) self.assertEqual(response.json["uneditable"], "original_value") ext_app = self._setup_app_with_request_handler(_update_handler, "PUT") ext_response = ext_app.put("/dummy_resources/1", {"uneditable": "new_value"}) self.assertEqual(ext_response.json["uneditable"], "new_value")
class PutAtributoFase(unittest.TestCase): """ @summary: Testea la modificacion de atributos particulares de una fase. """ def setUp(self): from yapp import main settings = { 'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp' } app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) def tearDown(self): del self.testapp from yapp.models import DBSession DBSession.remove() def test_it(self): dao = ProyectoDAO(None) rol_dao = RolFinalDAO(None) autor = rol_dao.get_by_id(1) lider = rol_dao.get_by_id(1) nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba", "hoy", "hoy") dao.crear(nuevo_proyecto) dao = FaseDAO(None) nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba", "0") dao.crear(nueva_fase) dao = AtributoFaseDAO(None) nuevo_atributo = AtributoFase("Atributo de prueba", nueva_fase, "Prueba", "100") dao.crear(nuevo_atributo) direccion = '/atributofase/' + str(nuevo_atributo.id) atributo = { "_nombre": "Atributo 1", "id": nuevo_atributo.id, "_fase_id": nueva_fase.id, "_descripcion": "Prueba", "_valor": "100" } res = self.testapp.put(direccion, params=json.dumps(atributo)) print "Testeando modificar atributo de fase" self.failUnless('sucess' in res.body)
def test_edit_previously_uneditable_field(self): def _update_handler(req, res): data = jsonutils.loads(res.body) data['uneditable'] = req.params['uneditable'] res.body = jsonutils.dumps(data) return res base_app = TestApp(setup_base_app()) response = base_app.put("/dummy_resources/1", {'uneditable': "new_value"}) self.assertEqual(response.json['uneditable'], "original_value") ext_app = self._setup_app_with_request_handler(_update_handler, 'PUT') ext_response = ext_app.put("/dummy_resources/1", {'uneditable': "new_value"}) self.assertEqual(ext_response.json['uneditable'], "new_value")
def test_put(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.put('/api/1/walls/2/collections/3', params=dumps({'title': 'Hello world!'}), status=200) self.assertEqual( { "type_name": "Collection", "rid": 3, "data": { "title": "Hello world!" } }, response.json_body)
class PutFases(unittest.TestCase): """ @summary: Testea la modificacion de fases de un proyecto. """ def setUp(self): from yapp import main settings = { 'sqlalchemy.url': 'postgres://*****:*****@127.0.0.1:5432/yapp' } app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) def tearDown(self): del self.testapp from yapp.models import DBSession DBSession.remove() def test_it(self): dao = ProyectoDAO(None) rol_dao = RolFinalDAO(None) autor = rol_dao.get_by_id(1) lider = rol_dao.get_by_id(1) nuevo_proyecto = Proyecto("Test", autor, 1, "Prueba", lider, "Prueba", "hoy", "hoy") dao.crear(nuevo_proyecto) dao = FaseDAO(None) nueva_fase = Fase("Testeando", nuevo_proyecto, 2, "Prueba", "Prueba", "0") dao.crear(nueva_fase) direccion = '/fases/' + str(nueva_fase.id) fase = { "_nombre": "Fase 1", "id": nueva_fase.id, "_proyecto_id": nuevo_proyecto.id, "_orden": 1, "_comentario": "Defecto", "_estado": "Pendiente", "_color": "003366" } res = self.testapp.put(direccion, params=json.dumps(fase)) print "Testeando modificar fases" self.failUnless('sucess' in res.body)
def test_injector_PUT_no_effect(): bower = bowerstatic.Bower() components = bower.components('components', os.path.join( os.path.dirname(__file__), 'bower_components')) def wsgi(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html;charset=UTF-8')]) include = components.includer(environ) include('jquery/dist/jquery.js') return ['<html><head></head><body>Hello!</body></html>'] injector = bower.injector(wsgi) c = Client(injector) response = c.put('/') assert response.body == b'<html><head></head><body>Hello!</body></html>'
class ClientTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(ClientTest, self).__init__(*args, **kwargs) app.debug = True self.client = TestApp(app) def get(self, url, params=None, headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, xhr=False): self.resp = self.client.get(url, params, headers, extra_environ, status, expect_errors, xhr) return self.resp def post(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False): self.resp = self.client.post(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr) return self.resp def put(self, url, params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], upload_files=None, expect_errors=False, content_type=None, xhr=False): self.resp = self.client.put(url, params, headers, extra_environ, status, upload_files, expect_errors, content_type, xhr) return self.resp def delete(self,url ,params=u'', headers=None, extra_environ=None, status=[200, 201, 400, 401, 403, 404], expect_errors=False, content_type=None, xhr=False): self.resp = self.client.delete(url, params, headers, extra_environ, status, expect_errors, content_type, xhr)