class WsgiInterfaceTests(unittest2.TestCase): def setUp(self): self.app = TestApp(app.setup_app()) def test_get_all_tests(self, request): self.app.get('/v1/tests') def test_get_one_test(self, request): self.assertRaises(NotImplementedError, self.app.get, '/v1/tests/1') def test_get_all_testsets(self, request): self.app.get('/v1/testsets') def test_get_one_testset(self, request): self.app.get('/v1/testsets/plugin_test') def test_get_one_testruns(self, request): self.app.get('/v1/testruns/1') def test_get_all_testruns(self, request): self.app.get('/v1/testruns') @patch('ostf_adapter.wsgi.controllers.models') def test_post_testruns(self, models, request): testruns = [{ 'testset': 'test_simple', 'metadata': { 'cluster_id': 3 } }, { 'testset': 'test_simple', 'metadata': { 'cluster_id': 4 } }] request.body = json.dumps(testruns) models.TestRun.add_test_run.return_value = MagicMock(frontend={}) self.app.post_json('/v1/testruns', testruns) def test_put_testruns(self, request): testruns = [{ 'id': 2, 'metadata': { 'cluster_id': 3 }, 'status': 'non_exist' }, { 'id': 1, 'metadata': { 'cluster_id': 4 }, 'status': 'non_exist' }] request.body = json.dumps(testruns) request.storage.get_test_run.return_value = MagicMock(frontend={}) self.app.put_json('/v1/testruns', testruns) def test_get_last_testruns(self, request): self.app.get('/v1/testruns/last/101')
def test_PUT_article_empty_request(testapp: TestApp, democontent: None) -> None: """Test PUT /api/articles/{slug} with empty request, nothing happens.""" testapp.put_json( "/api/articles/foo", {"article": {}}, headers={"Authorization": f"Token {USER_ONE_JWT}"}, status=200, )
def test_colander_request_loader(): class User(object): def __init__(self, name, email): self.name = name self.email = email @deferred def validate_name(node, kw): def validate(node, value): if kw['request'].GET['entry'] != 'Correct': node.raise_invalid('A problem') return validate class UserSchema(Schema): name = SchemaNode( String(), missing=required, validator=validate_name ) email = SchemaNode( String(), missing=required, validator=Email() ) class App(ColanderApp): pass user = User('Somebody', '*****@*****.**') @App.path(model=User, path='/') def get_user(): return user @App.json( model=User, request_method='PUT', load=request_loader(UserSchema) ) def user_put(self, request, obj): for key, value in obj.items(): setattr(self, key, value) return 'correct' c = Client(App()) r = c.put_json('/?entry=Incorrect', { 'name': 'Somebody else', 'email': '*****@*****.**' }, status=422) assert r.json == {'name': 'A problem'} r = c.put_json('/?entry=Correct', { 'name': 'Somebody else', 'email': '*****@*****.**' }) assert r.json == 'correct' assert user.name == 'Somebody else'
class WsgiInterfaceTests(unittest2.TestCase): def setUp(self): self.app = TestApp(app.setup_app()) def test_get_all_tests(self, request): self.app.get('/v1/tests') def test_get_one_test(self, request): self.assertRaises(NotImplementedError, self.app.get, '/v1/tests/1') def test_get_all_testsets(self, request): self.app.get('/v1/testsets') def test_get_one_testset(self, request): self.app.get('/v1/testsets/plugin_test') def test_get_one_testruns(self, request): self.app.get('/v1/testruns/1') def test_get_all_testruns(self, request): self.app.get('/v1/testruns') @patch('ostf_adapter.wsgi.controllers.models') def test_post_testruns(self, models, request): testruns = [ {'testset': 'test_simple', 'metadata': {'cluster_id': 3} }, {'testset': 'test_simple', 'metadata': {'cluster_id': 4} }] request.body = json.dumps(testruns) models.TestRun.add_test_run.return_value = MagicMock(frontend={}) self.app.post_json('/v1/testruns', testruns) def test_put_testruns(self, request): testruns = [ {'id': 2, 'metadata': {'cluster_id': 3}, 'status': 'non_exist' }, {'id': 1, 'metadata': {'cluster_id': 4}, 'status': 'non_exist' }] request.body = json.dumps(testruns) request.storage.get_test_run.return_value = MagicMock(frontend={}) self.app.put_json('/v1/testruns', testruns) def test_get_last_testruns(self, request): self.app.get('/v1/testruns/last/101')
def test__subscribe_workspace__err__400__not_a_on_request_workspace( self, user_api_factory: UserApiFactory, workspace_api_factory: WorkspaceApiFactory, web_testapp: TestApp, subscription_lib_factory: SubscriptionLibFactory, admin_user: User, ): open_workspace = workspace_api_factory.get().create_workspace( "open", access_type=WorkspaceAccessType.OPEN, save_now=True) on_request_workspace = workspace_api_factory.get().create_workspace( "on_request", access_type=WorkspaceAccessType.ON_REQUEST, save_now=True) confidential_workspace = workspace_api_factory.get().create_workspace( "confidential", access_type=WorkspaceAccessType.CONFIDENTIAL, save_now=True) uapi = user_api_factory.get() profile = Profile.USER test_user = uapi.create_user( email="*****@*****.**", password="******", name="bob", profile=profile, timezone="Europe/Paris", lang="fr", do_save=True, do_notify=False, ) transaction.commit() web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) params = {"workspace_id": on_request_workspace.workspace_id} res = web_testapp.put_json( "/api/users/{}/workspace_subscriptions".format(test_user.user_id), status=200, params=params, ) params = {"workspace_id": open_workspace.workspace_id} res = web_testapp.put_json( "/api/users/{}/workspace_subscriptions".format(test_user.user_id), status=400, params=params, ) assert res.json_body["code"] == ErrorCode.INVALID_WORKSPACE_ACCESS_TYPE params = {"workspace_id": confidential_workspace.workspace_id} res = web_testapp.put_json( "/api/users/{}/workspace_subscriptions".format(test_user.user_id), status=400, params=params, ) assert res.json_body["code"] == ErrorCode.INVALID_WORKSPACE_ACCESS_TYPE
def test_marshmallow(): class User(object): def __init__(self, name, email): self.name = name self.email = email class UserSchema(Schema): name = fields.Str(required=True) email = fields.Email(required=True) user_schema = UserSchema() class App(MarshmallowApp): pass user = User('Somebody', '*****@*****.**') @App.path(model=User, path='/') def get_user(): return user @App.dump_json(model=User) def dump_user_json(self, request): return user_schema.dump(self).data @App.json(model=User) def user_default(self, request): return self @App.json(model=User, request_method='PUT', load=loader(user_schema)) def user_put(self, request, obj): for key, value in obj.items(): setattr(self, key, value) return self c = Client(App()) r = c.get('/') assert r.json == {'name': 'Somebody', 'email': '*****@*****.**'} r = c.put_json('/', { 'name': "Somebody else", "email": "*****@*****.**" }) assert r.json == { 'name': 'Somebody else', 'email': '*****@*****.**' } assert user.name == 'Somebody else' assert user.email == '*****@*****.**' r = c.put_json('/', {'name': 'Another'}, status=422) assert r.json == {'email': ['Missing data for required field.']}
def test__put_user_config_endpoint_with_update( self, user_api_factory: UserApiFactory, web_testapp: TestApp): uapi = user_api_factory.get() profile = Profile.USER test_user = uapi.create_user( email="*****@*****.**", password="******", name="bob", profile=profile, timezone="Europe/Paris", lang="fr", do_save=True, do_notify=False, ) transaction.commit() fixture_params1 = {"param1": 1, "param2": "two"} fixture_params2 = {"param2": 2, "param3": "hello"} expected_result = {"param1": 1, "param2": 2, "param3": "hello"} user_id = test_user.user_id web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) web_testapp.put_json( "/api/users/{user_id}/config".format(user_id=user_id), params={"parameters": fixture_params1}, status=204, ) web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) res = web_testapp.get( "/api/users/{user_id}/config".format(user_id=user_id), status=200) assert json.loads(res.body, encoding="utf-8")["parameters"] == fixture_params1 web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) web_testapp.put_json( "/api/users/{user_id}/config".format(user_id=user_id), params={"parameters": fixture_params2}, status=204, ) transaction.commit() web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) res = web_testapp.get( "/api/users/{user_id}/config".format(user_id=user_id), status=200) assert json.loads(res.body, encoding="utf-8")["parameters"] == expected_result
def test_marshmallow_context_loader(): class User(object): def __init__(self, name, email): self.name = name self.email = email class UserSchema(Schema): name = fields.Str(required=True) email = fields.Email(required=True) @validates_schema def validate(self, data): if self.context['entry'] != 'Correct': raise ValidationError("A problem") class App(MarshmallowApp): pass user = User('Somebody', '*****@*****.**') @App.path(model=User, path='/') def get_user(): return user def get_context(request): return {'entry': request.GET['entry']} @App.json(model=User, request_method='PUT', load=context_loader(UserSchema, get_context)) def user_put(self, request, obj): for key, value in obj.items(): setattr(self, key, value) return "correct" c = Client(App()) r = c.put_json('/?entry=Incorrect', { 'name': "Somebody else", "email": "*****@*****.**" }, status=422) assert r.json == {'_schema': ['A problem']} r = c.put_json('/?entry=Correct', { 'name': "Somebody else", "email": "*****@*****.**" }) assert r.json == "correct" assert user.name == 'Somebody else'
def test__put_user_config_endpoint__error__400__invalid_format( self, user_api_factory: UserApiFactory, web_testapp: TestApp, user_config: typing.Dict): uapi = user_api_factory.get() profile = Profile.USER test_user = uapi.create_user( email="*****@*****.**", password="******", name="bob", profile=profile, timezone="Europe/Paris", lang="fr", do_save=True, do_notify=False, ) transaction.commit() user_id = test_user.user_id web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) response = web_testapp.put_json( "/api/users/{user_id}/config".format(user_id=user_id), params={ "parameters": user_config }, status=400, ).json_body assert response["code"] == ErrorCode.GENERIC_SCHEMA_VALIDATION_ERROR assert response["message"] == "Validation error of input data"
def test_update_current_user(testapp: TestApp, democontent: None) -> None: """Test PUT /api/user.""" res = testapp.put_json( "/api/user", { "user": { "email": "*****@*****.**", "username": "******", "bio": "bio", "image": "image", } }, headers={"Authorization": f"Token {USER_ONE_JWT}"}, status=200, ) response = copy.deepcopy(res.json) response["user"]["token"] = jwt.decode( res.json["user"]["token"], "secret", algorithms=["HS512"] ) assert response == { "user": { "email": "*****@*****.**", "token": {"sub": USER_ONE_ID, "iat": 1546300800}, "username": "******", "bio": "bio", "image": "image", } }
def test_PUT_article(testapp: TestApp, democontent: None) -> None: """Test PUT /api/articles/{slug}.""" res = testapp.put_json( "/api/articles/foo", { "article": { "title": "New title", "description": "New description", "body": "New body", } }, headers={"Authorization": f"Token {USER_ONE_JWT}"}, status=200, ) assert res.json == { "article": { "author": { "bio": None, "following": False, "image": None, "username": "******", }, "body": "New body", "createdAt": "2019-01-01T01:01:01.000Z", "description": "New description", "favorited": False, "favoritesCount": 0, "slug": "foo", "tagList": ["dogs", "cats"], "title": "New title", "updatedAt": "2019-02-02T02:02:02.000Z", } }
def test_colander_schema_class(): class User(object): def __init__(self, name, email): self.name = name self.email = email class UserSchema(Schema): name = SchemaNode( String(), missing=required ) email = SchemaNode( String(), missing=required, validator=Email() ) class App(ColanderApp): pass user = User('Somebody', '*****@*****.**') @App.path(model=User, path='/') def get_user(): return user @App.json( model=User, request_method='PUT', load=loader(UserSchema) ) def user_put(self, request, obj): for key, value in obj.items(): setattr(self, key, value) return 'done' c = Client(App()) r = c.put_json('/', { 'name': 'Somebody else', 'email': '*****@*****.**' }) assert user.name == 'Somebody else' assert user.email == '*****@*****.**' r = c.put_json('/', {'name': 'Another'}, status=422) assert r.json == {'email': 'Required'}
class WsgiInterfaceTests(unittest2.TestCase): def setUp(self): self.app = TestApp(app.setup_app()) def test_get_all_tests(self, request): self.app.get("/v1/tests") def test_get_one_test(self, request): self.assertRaises(NotImplementedError, self.app.get, "/v1/tests/1") def test_get_all_testsets(self, request): self.app.get("/v1/testsets") def test_get_one_testset(self, request): self.app.get("/v1/testsets/plugin_test") def test_get_one_testruns(self, request): self.app.get("/v1/testruns/1") def test_get_all_testruns(self, request): self.app.get("/v1/testruns") @patch("fuel_plugin.ostf_adapter.wsgi.controllers.models") def test_post_testruns(self, models, request): testruns = [ {"testset": "test_simple", "metadata": {"cluster_id": 3}}, {"testset": "test_simple", "metadata": {"cluster_id": 4}}, ] request.body = json.dumps(testruns) models.TestRun.start.return_value = {} self.app.post_json("/v1/testruns", testruns) def test_put_testruns(self, request): testruns = [ {"id": 2, "metadata": {"cluster_id": 3}, "status": "non_exist"}, {"id": 1, "metadata": {"cluster_id": 4}, "status": "non_exist"}, ] request.body = json.dumps(testruns) request.storage.get_test_run.return_value = MagicMock(frontend={}) self.app.put_json("/v1/testruns", testruns) def test_get_last_testruns(self, request): self.app.get("/v1/testruns/last/101")
class TestIntegrated(unittest.TestCase): def setUp(self): self.app = TestApp(application) def test_columns(self): self.assertEqual(['age', 'id', 'name'], User.columns()) def _create(self, name=None, age=None): return self.app.post_json(build_url(), {'age': age, 'name': name}) def test_api(self): # test post create resp = self._create(name='felipe', age=22) result = resp.json['result'] self.assertEqual(result['name'], 'felipe') self.assertEqual(result['age'], 22) self.assertIsNotNone(result['id']) id_created = str(result['id']) self._create(name='john', age=26) # test get all resp = self.app.get(build_url()) result = resp.json['result'] names = ['felipe', 'john'] for user in result: self.assertTrue(user['name'] in names) self.assertIsNotNone(user['id']) # test get by id resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe', result['name']) self.assertEqual(22, result['age']) # test update resp = self.app.put_json(build_url(id_created), {'name': 'felipe volpone'}) self.assertEqual(200, resp.status_int) resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe volpone', result['name']) self.assertEqual(22, result['age']) self.assertEqual(int(id_created), result['id']) # test delete resp = self.app.delete(build_url(id_created)) self.assertEqual(200, resp.status_int) # test get resp = self.app.get(build_url(id_created), expect_errors=True) self.assertEqual(404, resp.status_int)
def test__accept_workspace_subscription__ok__200__nominal_case( self, user_api_factory: UserApiFactory, workspace_api_factory: WorkspaceApiFactory, web_testapp: TestApp, subscription_lib_factory: SubscriptionLibFactory, admin_user: User, ): on_request_workspace = workspace_api_factory.get().create_workspace( "on_request", access_type=WorkspaceAccessType.ON_REQUEST, save_now=True) uapi = user_api_factory.get() profile = Profile.USER test_user = uapi.create_user( email="*****@*****.**", password="******", name="bob", profile=profile, timezone="Europe/Paris", lang="fr", do_save=True, do_notify=False, ) subscription_lib_factory.get(test_user).submit_subscription( workspace=on_request_workspace) transaction.commit() params = {"role": "contributor"} web_testapp.authorization = ("Basic", ("*****@*****.**", "*****@*****.**")) web_testapp.put_json( "/api/workspaces/{}/subscriptions/{}/accept".format( on_request_workspace.workspace_id, test_user.user_id), status=204, params=params, ) web_testapp.authorization = ("Basic", ("*****@*****.**", "password")) web_testapp.get( "/api/workspaces/{}".format(on_request_workspace.workspace_id), status=200, )
class TestIntegrated(unittest.TestCase): def setUp(self): self.app = TestApp(application) def test_columns(self): self.assertEqual(['age', 'id', 'name'], User.columns()) def _create(self, name=None, age=None): return self.app.post_json(build_url(), {'age': age, 'name': name}) def test_api(self): # test post create resp = self._create(name='felipe', age=22) result = resp.json['result'] self.assertEqual(result['name'], 'felipe') self.assertEqual(result['age'], 22) self.assertIsNotNone(result['id']) id_created = str(result['id']) self._create(name='john', age=26) # test get all resp = self.app.get(build_url()) result = resp.json['result'] self.assertEqual(result[0]['name'], 'felipe') self.assertEqual(result[0]['age'], 22) self.assertIsNotNone(result[0]['id']) self.assertEqual(result[1]['name'], 'john') # test get by id resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe', result['name']) self.assertEqual(22, result['age']) # test update resp = self.app.put_json(build_url(id_created), {'name': 'felipe volpone'}) self.assertEqual(200, resp.status_int) resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe volpone', result['name']) self.assertEqual(22, result['age']) self.assertEqual(int(id_created), result['id']) # test delete resp = self.app.delete(build_url(id_created)) self.assertEqual(200, resp.status_int) # test get resp = self.app.get(build_url(id_created), expect_errors=True) self.assertEqual(404, resp.status_int)
def test_resource_colander_validation_error(): error = {'error': {'code': 400, 'message': '400 Bad Request'}} app = App() c = Client(app) response = c.put_json('/', {'password': '******'}, status=400) assert response.json == error response = c.patch_json('/', {'password': '******'}, status=400) assert response.json == error
class FunctionalTests(fake_filesystem_unittest.TestCase): def setUp(self): from website_editor import main settings = {'posts_dir_path': '/path/to/posts'} app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) self.setUpPyfakefs() self.fs.create_dir(settings['posts_dir_path']) def test_post_lifecycle(self): res = self.testapp.post_json('/api/posts', { 'file_path': '/path/to/posts/1.md', 'post_with_metadata': 'Hi!' }) self.assertEqual(200, res.status_int) res = self.testapp.get('/api/posts') self.assertEqual(200, res.status_int) self.assertEqual(1, len(res.json_body)) post_id = res.json_body['posts'][0]['post_id'] res = self.testapp.put_json('/api/posts/%d' % post_id, { 'file_path': '/path/to/posts/1.md', 'post_with_metadata': 'Hola!' }) self.assertEqual(200, res.status_int) res = self.testapp.get('/api/posts/%d' % post_id) self.assertEqual(200, res.status_int) self.assertEqual( { 'file_path': '/path/to/posts/1.md', 'post_with_metadata': 'Hola!', 'post_id': 0 }, res.json_body) res = self.testapp.delete('/api/posts/%d' % post_id) self.assertEqual(200, res.status_int) res = self.testapp.get('/api/posts/%d' % post_id, status=404) self.assertEqual(404, res.status_int)
def test_resource_marshmallow_validation(): app = App() c = Client(app) response = c.put_json('/', { 'email': '*****@*****.**', 'password': '******' }) assert response.json == {} response = c.patch_json('/', {'email': '*****@*****.**'}) assert response.json == {}
def put(self, wsgi: webtest.TestApp, uri, body, token=None, headers=None, **kwargs): if headers is None: headers = {} if token is not None: headers['Authorization'] = 'Bearer ' + token return wsgi.put_json(url=uri, headers=headers, params=body, **kwargs)
def test_resource_marshmallow_validation_error(): error = { 'error': { 'code': 400, 'message': { 'email': ['Missing data for required field.'] } } } app = App() c = Client(app) response = c.put_json('/', {'password': '******'}, status=400) assert response.json == error response = c.patch_json('/', {'password': '******'}, status=400) assert response.json == error
def test__accept_workspace_subscription__err__400__already_in( self, user_api_factory: UserApiFactory, workspace_api_factory: WorkspaceApiFactory, web_testapp: TestApp, subscription_lib_factory: SubscriptionLibFactory, role_api_factory: RoleApiFactory, admin_user: User, ): on_request_workspace = workspace_api_factory.get().create_workspace( "on_request", access_type=WorkspaceAccessType.ON_REQUEST, save_now=True) uapi = user_api_factory.get() profile = Profile.USER test_user = uapi.create_user( email="*****@*****.**", password="******", name="bob", profile=profile, timezone="Europe/Paris", lang="fr", do_save=True, do_notify=False, ) rapi = role_api_factory.get() rapi.create_one(test_user, on_request_workspace, UserRoleInWorkspace.READER, False) subscription_lib_factory.get(test_user).submit_subscription( workspace=on_request_workspace) transaction.commit() params = {"role": "contributor"} web_testapp.authorization = ("Basic", ("*****@*****.**", "*****@*****.**")) res = web_testapp.put_json( "/api/workspaces/{}/subscriptions/{}/accept".format( on_request_workspace.workspace_id, test_user.user_id), status=400, params=params, ) assert res.json_body["code"] == ErrorCode.USER_ROLE_ALREADY_EXIST
def test_PUT_url(testapp: TestApp, democontent: None) -> None: """Test PUT /api/urls/{slug}.""" res = testapp.put_json( "/api/urls/foo", { "title": "New title", "description": "New description", "href": "https://new", }, headers={"Authorization": f"Token {USER_ONE_JWT}"}, status=200, ) assert res.json == { "createdAt": "2019-01-01T01:01:01.000Z", "description": "New description", "href": "https://new", "slug": "foo", "title": "New title", "updatedAt": "2019-02-02T02:02:02.000Z", }
class TestEndpoint(unittest.TestCase): def setUp(self): self.app = TestApp(application) def testing_wrong_endpoints(self): response = self.app.get('/api/', expect_errors=True) self.assertEqual(502, response.status_int) response = self.app.get('/api/wrongurl', expect_errors=True) self.assertEqual(404, response.status_int) def __create(self): return self.app.post_json('/api/user', {"name": "felipe", "age": 22}) def test_post(self): resp = self.__create() result = resp.json self.assertEqual('felipe', result['result']['name']) self.assertEqual(201, resp.status_int) def test_get_all(self): self.__create() resp = self.app.get('/api/user') self.assertEqual(200, resp.status_int) def test_get(self): uuid_created = '1245' resp = self.app.get('/api/user/' + uuid_created) self.assertEqual(200, resp.status_int) def test_put(self): uuid_created = '1245' response = self.app.put_json('/api/user/' + uuid_created, {"name": "ray", 'uuid': uuid_created}) self.assertEqual(200, response.status_int) def test_delete(self): response = self.app.delete('/api/user/1245') self.assertEqual(200, response.status_int)
class TestProjectAPI(unittest.TestCase): def setUp(self): from nokkhumapi import main cfg = configparser.ConfigParser() cfg.read('../../../development.ini') settings = dict(cfg.items('app:main')) app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) args = dict(password_credentials={"email": "*****@*****.**", "password": "******"} ) response = self.testapp.post_json('/authentication/tokens', params=args, status=200) print("authentication: ") self.pp = pprint.PrettyPrinter(indent=4) self.pp.pprint(response.json) self.token = response.json['access']['token']['id'] self.project_id = 1 def tearDown(self): pass def test_projectview_can_push_data_to_database(self): args=dict( name = 'Test Project', description = '', status = 'active', user = {"id":1} ) response = self.testapp.post_json('/projects', params={'project':args}, headers=[('X-Auth-Token', self.token)], status=200) print("responce post :") self.pp.pprint(response.json) self.assertIn("id",response.json["project"]) self.project_id = response.json["project"]["id"] #retrieve project via project id response = self.testapp.get('/projects/%d'%self.project_id, headers=[('X-Auth-Token', self.token)], status = 200) print("response get") self.pp.pprint(response.json) self.assertEqual(response.json["project"]["id"], self.project_id) self.project_dict = response.json["project"] #try to change name self.project_dict['status'] = 'Delete' args = self.project_dict response = self.testapp.put_json('/projects/%d'%response.json["project"]["id"], params={'project':args}, headers=[('X-Auth-Token', self.token)], status=200) print("response update: ") self.pp.pprint(response.json) self.assertIn("id", response.json["project"]) response = self.testapp.delete('/projects/%d'%response.json["project"]["id"], headers=[('X-Auth-Token', self.token)], status=200) print("response delete: ") self.pp.pprint(response.json)
class BottleResourceTestCase(unittest.TestCase): def setUp(self): super(BottleResourceTestCase, self).setUp() self.app = bottle.Bottle() self.res = BtlTestResource() self.res.prepare_routes(self.app, '/mydata/') self.client = TestApp(self.app) # Just for the fake data. self.res.fake_init() def test_list(self): res = self.client.get('/mydata/') self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(json.loads(res.body.decode('utf-8')), { 'objects': [ { 'author': 'viniciuscainelli', 'body': 'Hello world!', 'id': 2, 'title': 'First post' }, { 'author': 'viniciuscainelli', 'body': 'Stuff here.', 'id': 4, 'title': 'Another' }, { 'author': 'viniciuscainelli', 'body': "G'bye!", 'id': 5, 'title': 'Last' } ] }) def test_detail(self): res = self.client.get('/mydata/4/') self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(json.loads(res.body.decode('utf-8')), { 'author': 'viniciuscainelli', 'body': 'Stuff here.', 'id': 4, 'title': 'Another' }) def test_create(self): res = self.client.post_json('/mydata/', { 'author': 'viniciuscainelli', 'body': 'Crazy thing', 'id': 9, 'title': 'Hey' }) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 201) self.assertEqual(res.content_length, 0) def test_update(self): new_data = { 'author': 'viniciuscainelli', 'body': 'Stuff here. - edited', 'id': 4, 'title': 'Another - edited' } res = self.client.put_json('/mydata/4/', new_data) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 202) self.assertEqual(res.content_length, 0)
class UserAPI(unittest.TestCase): def setUp(self): from service import main from paste.deploy import appconfig from webtest import TestApp # set settings os.environ['PYRAMID_SETTINGS'] = 'development.ini#main' self.settings = appconfig('config:{}'.format(os.environ['PYRAMID_SETTINGS']), relative_to='.') app = main({}, **self.settings) self.testapp = TestApp(app) self.config = testing.setUp(settings=self.settings) self.created = [] def tearDown(self): for obj in self.created: obj.delete() testing.tearDown() def test_user(self): response = self.testapp.post_json('/api/v1/users', {}, status=400) # create new user payload = { 'email': '*****@*****.**', 'password': '******', } response = self.testapp.post_json('/api/v1/users', payload, status=200) self.assertTrue(response.json['id']) # check duplicate response = self.testapp.post_json('/api/v1/users', payload, status=400) # check database user = User.get_by_email('*****@*****.**') self.assertTrue(user) self.created.append(user) # get user endpoint = '/api/v1/users/{}'.format(user.id) response = self.testapp.get(endpoint, status=200) self.assertTrue(response.json['id']) # update user payload = { 'active': True, 'email': '*****@*****.**', } endpoint = '/api/v1/users/{}'.format(user.id) response = self.testapp.put_json(endpoint, payload, status=200) user = User.get_by_id(user.id) self.assertTrue(user.active) # change password payload = { 'password': '******', } endpoint = '/api/v1/users/{}/password'.format(user.id) response = self.testapp.put_json(endpoint, payload, status=200) user = User.authenticate_user('*****@*****.**', 'world') self.assertTrue(user)
class UserServiceRestIntegrationTest(unittest.TestCase): """ Integration tests for UserServiceRest """ @classmethod def tearDownClass(cls): os.remove(db_filename) def setUp(self): create_db_tables(db_filename) self.populate_db_tables() settings = {'sqlalchemy.url': 'sqlite:///' + db_filename} app = main(None, **settings) self.testapp = TestApp(app) def tearDown(self): drop_db_tables(db_filename) def test_get_user_found(self): url = 'http://*****:*****@jazz.com' headers = {'Accept': 'application/json; charset=utf8'} res = self.testapp.get(url, headers=headers, status=200) res_dict = json.loads(str(res.body, 'utf-8')) self.assertEqual('*****@*****.**', res_dict['email']) self.assertEqual('Coltrane', res_dict['last_name']) self.assertEqual('34568', res_dict['address']['post_code']) def test_get_user_not_found(self): url = 'http://*****:*****@nowhere.com' headers = {'Accept': 'application/json; charset=utf8'} res = self.testapp.get(url, headers=headers, status=404) def test_add_user_ok(self): url = 'http://*****:*****@jazz.com", "middles": None, "address": { "country": "USA", "street": "5311 E 1st St", "city": "New York", "post_code": "10012", "state": "NY" }, "first_name": "Miles", "last_name": "Davis" } res = self.testapp.post_json(url, post_body, status=201) rows = execute_select(db_filename, "select * from people where email = '*****@*****.**'") self.assertEqual("Miles", rows[0][7]) def test_update_user_ok(self): url = 'http://*****:*****@jazz.com", "middles": "William", "address": { "country": "USA", "street": "123 Cool St", "city": "Chicago", "post_code": "34568", "state": "IL" }, "first_name": "John", "last_name": "Coltrance" } res = self.testapp.put_json(url, put_body, status=202) rows = execute_select(db_filename, "select * from people where email = '*****@*****.**'") self.assertEqual("John", rows[0][7]) self.assertEqual("William", rows[0][9]) def test_delete_user_found(self): url = 'http://*****:*****@jazz.com' self.testapp.delete(url, status=204) def test_delete_user_not_found(self): url = 'http://*****:*****@nowhere.com' res = self.testapp.delete(url, status=404) def populate_db_tables(self): execute_insert(db_filename, 'people', (123, 'Chicago', 'USA', '34568', 'IL', '123 Cool St', '*****@*****.**', 'John', 'Coltrane', ''), (124, 'New Paltz', 'USA', '12345', 'NY', '123 Main St', '*****@*****.**', 'Mike', 'Woinoski', '') )
class TestRayPeeweeAPI(unittest.TestCase): def setUp(self): database.drop_tables([User], safe=True) database.create_tables([User]) self.app = TestApp(application) def test_columns(self): self.assertEqual(['age', 'id', 'name'], User.columns()) def test_to_instance(self): new_user = User.to_instance({'age': 99, 'name': 'Frank Sinatra'}) self.assertEqual(99, new_user.age) self.assertEqual('Frank Sinatra', new_user.name) def test_database_methods(self): User.create(name='felipe', age=100) def _create(self, name=None, age=None): return self.app.post_json(build_url(), {'age': age, 'name': name}) def test_api(self): # test post create resp = self._create(name='felipe', age=22) result = resp.json['result'] self.assertEqual(result['name'], 'felipe') self.assertEqual(result['age'], 22) self.assertIsNotNone(result['id']) id_created = str(result['id']) self._create(name='john', age=26) # test get all resp = self.app.get(build_url()) result = resp.json['result'] self.assertEqual(result[0]['name'], 'felipe') self.assertEqual(result[0]['age'], 22) self.assertIsNotNone(result[0]['id']) self.assertEqual(result[1]['name'], 'john') # test get by id resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe', result['name']) self.assertEqual(22, result['age']) # test update resp = self.app.put_json(build_url(id_created), {'name': 'felipe volpone'}) self.assertEqual(200, resp.status_int) # testing if update worked resp = self.app.get(build_url(id_created)) result = resp.json['result'] self.assertEqual('felipe volpone', result['name']) self.assertEqual(22, result['age']) self.assertEqual(int(id_created), result['id']) # test delete resp = self.app.delete(build_url(id_created)) self.assertEqual(200, resp.status_int) # test get resp = self.app.get(build_url(id_created), expect_errors=True) self.assertEqual(404, resp.status_int)
class AppUser: """:class:`webtest.TestApp` wrapper for backend functional testing.""" def __init__(self, app, rest_url: str = 'http://localhost', base_path: str = '/', header: dict = None): """Initialize self.""" self.app = TestApp(app) """:class:`webtest.TestApp`to send requests to the backend server.""" self.rest_url = rest_url """backend server url to generate request urls.""" self.base_path = base_path """path prefix to generate request urls.""" self.header = header or {} """default header for requests, mostly for authentication.""" self._resolver = DottedNameResolver() def post_resource(self, path: str, iresource: IInterface, cstruct: dict) -> TestResponse: """Build and post request to create a new resource.""" url = self._build_url(path) props = self._build_post_body(iresource, cstruct) resp = self.app.post_json(url, props, headers=self.header, expect_errors=True) return resp def put(self, path: str, cstruct: dict = {}) -> TestResponse: """Put request to modify a resource.""" url = self._build_url(path) resp = self.app.put_json(url, cstruct, headers=self.header, expect_errors=True) return resp def post(self, path: str, cstruct: dict = {}) -> TestResponse: """Post request to create a new resource.""" url = self._build_url(path) resp = self.app.post_json(url, cstruct, headers=self.header, expect_errors=True) return resp def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict: return {'content_type': iresource.__identifier__, 'data': cstruct} def _build_url(self, path: str) -> str: if path.startswith('http'): return path return self.rest_url + self.base_path + path def batch(self, subrequests: list): """Build and post batch request to the backend rest server.""" resp = self.app.post_json(batch_url, subrequests, headers=self.header, expect_errors=True) return resp def get(self, path: str, params={}) -> TestResponse: """Send get request to the backend rest server.""" url = self._build_url(path) resp = self.app.get(url, headers=self.header, params=params, expect_errors=True) return resp def options(self, path: str) -> TestResponse: """Send options request to the backend rest server.""" url = self._build_url(path) resp = self.app.options(url, headers=self.header, expect_errors=True) return resp def get_postable_types(self, path: str) -> []: """Send options request and return the postable content types.""" resp = self.options(path) if 'POST' not in resp.json: return [] post_request_body = resp.json['POST']['request_body'] type_names = sorted([r['content_type'] for r in post_request_body]) iresources = [self._resolver.resolve(t) for t in type_names] return iresources
class BasicTest(unittest.TestCase): @classmethod def setUpClass(cls): renki.app.catchall = False def setUp(self): """ Initialize database and create tables, relations, indexes etc. """ connection.session.rollback() self.app = TestApp(renki.app) connection.conn.create_tables() connection.session.commit() self._users = {} # Create permissions for permission in permissions.PERMISSIONS: if not auth_db.Permissions.query().filter( auth_db.Permissions.name == permission).all(): p = auth_db.Permissions() p.name = permission p.save() def tearDown(self): """ Destroy tables, indexes and relations. """ try: connection.session.rollback() connection.conn.drop_tables() connection.session.commit() connection.session.flush() connection.session.session().close() except: connection.session.rollback() raise def _get_error(self, item): error = None try: if 'error' in item.json: error = item.json['error'] except (AttributeError, KeyError): pass return error def auth(self, user, password): """ Authenticate user and return authentiction key """ args = {'username': user, 'password': password} s = self.app.post('/login', params=args, status="*") self.assertStatus(s, STATUS_OK) return s.json['apikey'] def user(self, name, perms=[]): """ Create user with name `name` and permissions `permissins` return authenticated session """ if name not in self._users: pw = utils.generate_key() user = auth_db.Users() user.id = len(self._users) + 1 user.name = name user.set_password(pw) user.firstnames = 'test' user.lastname = 'test' user.save() connection.session.commit() for perm_name in perms: perm = auth_db.Permissions.query().filter( auth_db.Permissions.name==perm_name).one() user.permissions.append(perm) connection.session.commit() sessionkey = self.auth(user=name, password=pw) u = TestUser(name=name, password=pw, sessionkey=sessionkey, user=user) self._users[name] = u return self._users[name] def q(self, route, user, method='GET', args={}): """ Query route using `method` with args `args` as `user` returns response object """ if user: args['apikey'] = user.sessionkey elif 'apikey' in args: del args['apikey'] if method.upper() == 'GET': return self.app.get(route, params=args, status="*") elif method.upper() == 'POST': return self.app.post_json(route, params=args, status="*") elif method.upper() == 'PUT': return self.app.put_json(route, params=args, status="*") elif method.upper() == 'DELETE': if 'apikey' in args: route = "%s?apikey=%s" % (route, args['apikey']) return self.app.delete(route, params=args, status="*") self.fail("Method %s not implemented" % method) def assertContainsOne(self, database, cls = None): query = database.query() if cls is not None: query = query.filter(cls) self.assertEqual(query.count(), 1) def assertContainsMany(self, database, cls = None): query = database.query() if cls is not None: query = query.filter(cls) self.assertTrue(query.count() > 1) def assertContainsNone(self, database, cls = None): query = database.query() if cls is not None: query = query.filter(cls) self.assertEqual(query.count(), 0) def assertStatus(self, response, status): """ Assert that response status is `status` """ self.assertEqual(response.json['status'], status.JSON_STATUS, "Wrong JSON status code %s, excepted %s, error: %s" % ( response.json['status'], status.JSON_STATUS, self._get_error(response))) self.assertEqual(response.status_int, status.HTTP_STATUS, "Wrong HTTP status code %s, excepted %s" % (response.status_int, status.HTTP_STATUS)) def assertValidResponse(self, item, schema=[]): """ Validates that response is valid json response @param schema: optional json schema. """ if not schema: schema = [] else: # Copy schema schema = [i for i in schema] schema.append(JSONString('status', required=True)) d = { 'type': 'object', 'properties': {}, "additionalProperties": False, "required": [] } for i in schema: d['properties'][i.name] = i.as_property() for req in i.as_required(): if req not in d["required"]: d["required"].append(req) try: jsonschema_validate(item.json, schema=d) except JSONValidationError: self.fail("Response JSON is not valid") def assertQ(self, route, user, method='GET', args={}, status=None, schema=None): """ Sortcut to execute query and validate status and response schema. """ args = args.copy() if not schema and status and status != STATUS_OK: schema = status.FIELDS elif status and status != STATUS_OK: schema += status.FIELDS q = self.q(route=route, user=user, method=method, args=args) if status is not None: self.assertStatus(q, status) if schema: self.assertValidResponse(q, schema=schema)
class Actualizacion(TestCase): """ NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase TODO: Validar cambio de grupo principal TODO: Validar cambio de estado de la cuenta TODO: Validar cambios de grupos TODO: Validar cambio de contraseña """ @classmethod def setUpClass(self): # Cargamos los datos entidad = cargar_datos('usuario')[2] self.uid = entidad['uid'] self.datos = {'corpus': entidad} # Trabajamos en obtener un token self.token = cargar_credenciales() # Creamos nuestro objeto para pruebas from justine import main from webtest import TestApp app = main({}) self.testapp = TestApp(app) res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token) @classmethod def tearDownClass(self): res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token) if res.status_int == 200: self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token) def test_actualizacion(self): self.datos['corpus']['title'] = "Titulador" self.testapp.put_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token) res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token) respuesta = res.json_body['mensaje'][0]['title'] datos = self.datos['corpus']['title'] self.assertEqual(respuesta, datos) def test_actualizacion_displayName(self): sn = "Sotomayor" givenName = self.datos['corpus']['givenName'] displayName = givenName + " " + sn self.datos['corpus']['sn'] = sn self.testapp.put_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token) res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token) respuesta = res.json_body['mensaje'][0]['displayName'] self.assertEqual(respuesta, displayName) def test_uid_no_coincide_parametros_url(self): uid = 'fitzcarraldo' self.testapp.put_json('/usuarios/' + uid, status=400, params=self.datos, headers=self.token) def test_corpus_faltante(self): datos = {'cuerpo': self.datos['corpus'].copy()} self.testapp.put_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token) def test_json_malformateado(self): datos = "Mínimo esfuerzo para máximo daño" self.testapp.put_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token) def test_noexistente(self): uid = 'fitzcarraldo' datos = {'corpus': self.datos['corpus'].copy()} datos['corpus']['uid'] = uid self.testapp.put_json('/usuarios/' + uid, status=404, params=datos, headers=self.token) def test_claves_incompletas(self): cuerpo = self.datos['corpus'].copy() del cuerpo['sn'] del cuerpo['givenName'] datos = {'corpus': cuerpo} self.testapp.put_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token) def test_actualizacion_noauth(self): self.testapp.put_json('/usuarios/' + self.uid, status=403, params=self.datos)
class TestApiViews(unittest.TestCase): def setUp(self): my_settings = {"sqlalchemy.url": "sqlite:///:memory:", "api_auth_token": u"SECRETAUTHTOKEN"} self.config = testing.setUp() app = main({}, **my_settings) # set up the database engine = engine_from_config(my_settings) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: member1 = C3sMember( # german firstname=u"SomeFirstnäme", lastname=u"SomeLastnäme", email=u"*****@*****.**", address1=u"addr one", address2=u"addr two", postcode=u"12345", city=u"Footown Mäh", country=u"Foocountry", locale=u"de", date_of_birth=date.today(), email_is_confirmed=False, email_confirm_code=u"ABCDEFGFOO", password=u"arandompassword", date_of_submission=date.today(), membership_type=u"normal", member_of_colsoc=True, name_of_colsoc=u"GEMA", num_shares=u"23", ) DBSession.add(member1) member1.email_invite_token_bcgv16 = u"MEMBERS_TOKEN" DBSession.flush() self.testapp = TestApp(app) def tearDown(self): testing.tearDown() DBSession.close() DBSession.remove() def test_api_userinfo(self): """ Test the api_userinfo service. * must be a PUT, not a GET request * the auth header must be present * returns None if members refcode does not match * returns firstname, lastname, email, membership type """ # try a GET -- must fail res = self.testapp.get("/lm", status=405) self.assertTrue("405 Method Not Allowed" in res.body) self.assertTrue("The method GET is not allowed for this resource." in res.body) # try a PUT -- fails under certain conditions with self.assertRaises(ValueError): res = self.testapp.put("/lm", status=200) # ValueError: No JSON object could be decoded # try a PUT -- fails under certain conditions with self.assertRaises(KeyError): res = self.testapp.put_json("/lm", dict(id=1)) # status=200) # KeyError: 'token' # missing auth token -- must fail with self.assertRaises(KeyError): res = self.testapp.put_json("/lm", dict(token=1)) # status=200) # KeyError: 'HTTP_X_MESSAGING_TOKEN' # try false auth token -- must fail: 401 unauthorized _headers = {"X-messaging-token": "bar"} res = self.testapp.put_json("/lm", dict(token=1), headers=_headers, status=401) # now use the correct auth token _auth_info = {"X-messaging-token": "SECRETAUTHTOKEN"} # ..but a non-existing refcode (email_invite_token_bcgv16) # returns no user (None) res = self.testapp.put_json("/lm", dict(token="foo"), headers=_auth_info, status=200) # body: {"lastname": "None", "firstname": "None"} self.assertTrue(json.loads(res.body)["firstname"], "None") self.assertTrue(json.loads(res.body)["lastname"], "None") self.testapp.reset() m1 = C3sMember.get_by_id(1) # load member from DB for crosscheck # now try a valid refcode (email_invite_token_bcgv16) res2 = self.testapp.put_json("/lm", dict(token=m1.email_invite_token_bcgv16), headers=_auth_info, status=200) self.assertTrue(json.loads(res2.body)["firstname"], m1.firstname) self.assertTrue(json.loads(res2.body)["lastname"], m1.lastname) self.assertTrue(json.loads(res2.body)["email"], m1.email) self.assertTrue(json.loads(res2.body)["mtype"], m1.membership_type)
class FunctionalTests(unittest.TestCase): def setUp(self): from webtest import TestApp app = get_app('testing.ini#main') self.testapp = TestApp(app) def tearDown(self): self.delete_alarms('ed') self.delete_messages('ed') def create_alarm(self, owner, creator): params = { 'time': now(), 'creator': creator, 'message_source': creator, } res = self.testapp.post_json('/api/v1/alarms/%s' % owner, params) return res.json def delete_alarm(self, owner, id): self.testapp.delete('/api/v1/alarms/%s/%s' % (owner, id)) def get_alarms(self, owner): res = self.testapp.get('/api/v1/alarms/%s' % owner) return res.json def delete_alarms(self, owner): for alarm in self.get_alarms(owner): self.delete_alarm(owner, alarm['id']) def create_message(self, owner, name): params = { 'owner': owner, 'name': name } res = self.testapp.post_json('/api/v1/messages/%s' % owner, params) return res.json def delete_message(self, owner, id): url = '/api/v1/messages/%s/%s' % (owner, id) res = self.testapp.delete(url) def get_messages(self, owner): res = self.testapp.get('/api/v1/messages/%s' % owner) return res.json def get_message(self, owner, messageId): res = self.testapp.get('/api/v1/messages/%s/%s' % (owner, messageId)) return res.json def delete_messages(self, owner): for message in self.get_messages(owner): self.delete_message(owner, message['id']) def add_to_queue(self, owner, messageId, position): self.testapp.post_json('/api/v1/messages/%s/queue/%s' % (owner, position), {'id': messageId}) def append_to_queue(self, owner, messageId): self.testapp.post_json('/api/v1/messages/%s/queue' % owner, {'id': messageId}) def test_get_alarms(self): for i in range(3): self.create_alarm('ed', 'person%s' % i) res = self.testapp.get('/api/v1/alarms/ed', status=200) self.failUnless(len(res.json) is 3) def test_create_alarm(self): self.create_alarm('ed', 'creator') self.failUnless(len(self.get_alarms('ed')) == 1) def test_cancel_alarm(self): self.create_alarm('ed', 'person') alarm = self.get_alarms('ed')[0] self.delete_alarm('ed', alarm['id']) self.failUnless(not any(self.get_alarms('ed'))) def test_get_messages(self): self.create_message('ed', 'm1') self.failUnless(len(self.get_messages('ed')) == 1) def test_get_next_message_when_no_message_in_queue(self): try: res = self.testapp.get('/api/v1/messages/ed/queue/next') error = False except: error = True self.failUnless(error) def test_create_message(self): self.create_message('ed', 'm1') self.failUnless(len(self.get_messages('ed')) == 1) def test_delete_message(self): m1 = self.create_message('ed', 'm1') m2 = self.create_message('ed', 'm2') self.delete_message('ed', m1['id']) self.failUnless(len(self.get_messages('ed')) == 1) def test_get_queue(self): m1 = self.create_message('ed', 'm1') m2 = self.create_message('ed', 'm2') pass def test_add_to_queue(self): m = [self.create_message('ed', 'm%s' % i) for i in range(3)] for msg in m: self.add_to_queue('ed', msg['id'], 0) nextMsg = self.testapp.get('/api/v1/messages/ed/queue/next').json self.failUnless(nextMsg['id'] == 3) def test_append_to_queue(self): m = [self.create_message('ed', 'm%s' % i) for i in range(3)] for msg in m: self.append_to_queue('ed', msg['id']) queue = self.testapp.get('/api/v1/messages/ed/queue').json self.failUnless(queue[0]['id'] == 1 and queue[2]['id'] == 3) def test_remove_from_queue(self): m = [self.create_message('ed', 'm%s' % i) for i in range(3)] for msg in m: self.add_to_queue('ed', msg['id'], 0) nextMsg = self.testapp.get('/api/v1/messages/ed/queue/next').json self.failUnless(nextMsg['id'] == 3) self.testapp.delete('/api/v1/messages/ed/queue/0') nextMsg = self.testapp.get('/api/v1/messages/ed/queue/next').json self.failUnless(nextMsg['id'] == 2) def test_mark_as_played(self): m1 = self.create_message('ed', 'm1') playtime = '2011-04-02 02:45:11' self.failUnless(m1['plays'] == []) self.testapp.put_json('/api/v1/messages/ed/1/played', {'time_played': playtime}) m1 = self.get_message('ed', m1['id']) self.failUnless(m1['plays'] == [playtime]) def test_mark_as_unplayed(self): m = self.create_message('ed', 'm1') playtime = '2011-04-02 02:45:11' messages = self.get_messages('ed') self.failUnless(not any(messages[0]['plays'])) self.testapp.put_json('/api/v1/messages/ed/%s/played' % m['id'], {'time_played': playtime}) messages = self.get_messages('ed') self.failUnless(messages[0]['plays'] == [playtime]) self.testapp.put('/api/v1/messages/ed/%s/unplayed' % m['id']) messages = self.get_messages('ed') self.failUnless(not any(messages[0]['plays'])) def test_set_as_default(self): m = self.create_message('ed', 'm1') messages = self.get_messages('ed') self.failUnless(not messages[0]['is_default']) self.testapp.put('/api/v1/messages/ed/%s/default' % m['id']) messages = self.get_messages('ed') self.failUnless(messages[0]['is_default'])
class TestUser(MongoTestRunner): def setUp(self): self.api = TestApp(webapp.api) AppCrawlList([]).save() def test_create_user(self): user = create_user(self.api) user['_id'].should_not.eql(None) def test_sing_in_user(self): create_user(self.api, provider_id='me', first_name='Ivan') user = sign_in_user(self.api, provider_id='me').json user['firstName'].should.eql('Ivan') def test_add_new_user(self): sign_in_user(self.api, provider_id='me', status=401).status_int.should.eql(401) create_user(self.api, provider_id='me', first_name='Ivan') user = sign_in_user(self.api, provider_id='me').json user['firstName'].should.eql('Ivan') def test_register_user_with_friends(self): create_user(self.api, provider_id='id1') u = create_user(self.api, friend_ids=['id1']) len(u['friends']).should.eql(1) def test_user_mutual_friendship(self): create_user(self.api, provider_id='id1') create_user(self.api, friend_ids=['id1']) u = self.api.get('/users/' + 'id1').json len(u['friends']).should.eql(1) def test_register_user_with_installed_apps(self): create_app(self.api, 'com.app.example') u = create_user(self.api, installed_apps=['com.app.example']) len(u['installed_apps']).should.eql(1) def test_update_installed_apps(self): create_app(self.api, 'com.example') create_user(self.api, provider_id='id1', installed_apps=['com.example']) self.api.put_json('/users/' + 'id1' + '/update-app-list', {'installedApps':['com.app']}) crawl_list = get_crawl_list(self.api) crawl_list.should.eql(['com.app']) def test_remove_installed_apps_from_recommended(self): create_app(self.api, 'test1') create_app(self.api, 'test2') create_app(self.api, 'test3') create_app(self.api, 'test4') create_user(self.api, provider_id='me', installed_apps=['test1', 'test2', 'test3']) create_user(self.api, provider_id='u1', installed_apps=['test1', 'test2']) create_user(self.api, provider_id='u2', installed_apps=['test1', 'test2', 'test3', 'test4']) rate_app(self.api, 'me', 'test1', 4.0) rate_app(self.api, 'me', 'test2', 4.0) rate_app(self.api, 'me', 'test3', 5.0) rate_app(self.api, 'u1', 'test1', 3.0) rate_app(self.api, 'u1', 'test2', 1.0) rate_app(self.api, 'u2', 'test1', 2.5) rate_app(self.api, 'u2', 'test2', 5.0) rate_app(self.api, 'u2', 'test3', 4.0) rate_app(self.api, 'u2', 'test4', 5.0) self.api.put_json('/users/' + 'me' + '/update-app-list', {'installedApps':['test4']}) recommended_apps = self.api.get('/apps/recommend/me').json len(recommended_apps).should.eql(0)
class FlaskAdapterTests(unittest.TestCase): def setUp(self): from tests.example_app.flask_app import create_pale_flask_app self.flask_app = create_pale_flask_app() self.app = TestApp(self.flask_app) def assertExpectedFields(self, returned_dict, expected_fields): d = returned_dict.copy() # don't clobber the input for f in expected_fields: self.assertIn(f, d) val = d.pop(f) # don't check the val for now # make sure there's nothing extraneous left in the dict self.assertEqual(len(d.keys()), 0) return def test_successful_get_with_route_args(self): now = datetime.datetime.utcnow() resp = self.app.get('/api/arg_test/arg-a/arg-b') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.json, { "arg_a": "arg-a", "arg_b": "arg-b", }) def test_successful_get_without_params(self): now = datetime.datetime.utcnow() resp = self.app.get('/api/time/current') self.assertEqual(resp.status_code, 200) # Test _after_response_handlers self.assertIn("After-Response", resp.headers) self.assertEqual(resp.headers["After-Response"], 'OK') # Test CORS self.assertIn("Access-Control-Allow-Origin", resp.headers) self.assertEqual(resp.headers["Access-Control-Allow-Origin"], '*') # the 'time' value was set in the endpoint handler self.assertIn('time', resp.json_body) # the returned time value should match the resource defined # in tests.example_app.api.resources.py returned_time = resp.json_body['time'] # the endpoint specifies `fields=DateTimeResource._all_fields()` # so, we should expect to find all of them expected_fields = DateTimeResource._all_fields() self.assertExpectedFields(returned_time, expected_fields) self.assertEqual(returned_time['eurodate'], now.strftime("%d.%m.%Y")) def test_successful_post_with_required_params(self): # month is required in the endpoint definition, so we must pass # it in here resp = self.app.post('/api/time/parse', {'month': 2}) self.assertEqual(resp.status_code, 200) self.assertIn('time', resp.json_body) returned_time = resp.json_body['time'] # we didn't specify any other fields in the endpoint definition, # so this one should only get the defaults expected_fields = DateTimeResource._default_fields self.assertExpectedFields(returned_time, expected_fields) self.assertIn('Cache-Control', resp.headers) self.assertEqual('max-age=3', resp.headers['Cache-Control']) def test_successful_json_post_with_required_params(self): # this is the same as the above post, but passes json in the # request body, instead of x-www-form-urlencoded resp = self.app.post_json('/api/time/parse', {'month': 2}) self.assertEqual(resp.status_code, 200) self.assertIn('time', resp.json_body) returned_time = resp.json_body['time'] # we didn't specify any other fields in the endpoint definition, # so this one should only get the defaults expected_fields = DateTimeResource._default_fields self.assertExpectedFields(returned_time, expected_fields) def test_unsuccessful_post_missing_required_params(self): resp = self.app.post('/api/time/parse', status=422) self.assertIn('error', resp.json_body) def test_getting_with_nested_resources(self): test_duration = 60 * 1000 # one minute in milliseconds resp = self.app.get('/api/time/range', {'duration': test_duration}) self.assertEqual(resp.status_code, 200) self.assertIn('range', resp.json_body) returned_range = resp.json_body['range'] self.assertEqual(returned_range['duration_microseconds'], test_duration * 1000) # start has default fields start = returned_range['start'] expected_fields = DateTimeResource._default_fields self.assertExpectedFields(start, expected_fields) # end has all of them end = returned_range['end'] expected_fields = DateTimeResource._all_fields() self.assertExpectedFields(end, expected_fields) def test_resource(self): # Start by resetting the resource. # (multiple test runs from the same process will fail otherwise) resp = self.app.post('/api/resource/reset') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value'}) # Test creating a new resource resp = self.app.put_json('/api/resource', {'key': 'boop'}, headers={'Content-Type': 'application/json'}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'boop'}) # Test retrieving the resource. resp = self.app.get('/api/resource') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'boop'}) # Test patching the resource. # Without the correct Content-Type, we expect a 415 error. self.assertRaises(AppError, self.app.patch_json, '/api/resource', {'key': 'value2'}) resp = self.app.patch_json('/api/resource', {'key': 'value2'}, headers={'Content-Type': 'application/merge-patch+json'}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value2'}) # Test get to ensure the resource persists. resp = self.app.get('/api/resource') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value2'}) # A NoContentResource shouldn't have a Content-Type header (no content!) resp = self.app.post('/api/blank') self.assertEqual(resp.status_code, 204) self.assertEqual(resp.content_type, None)
class ApiTests(unittest.TestCase): """Tests for api views.""" def setUp(self): """Start up the app so that tests can send requests to it.""" app = get_app("development.ini") self.session = init_test_db() self.testapp = TestApp(app) def tearDown(self): """Tear down the test database.""" self.session.remove() def test_home(self): """Test home view.""" response = self.testapp.get("/", status=200) self.assertEqual("Home View", response.json.get("name")) def test_get_record(self): """Test get_record.""" # check record that exists response = self.testapp.get("/records/1", status=200) self.assertTrue(isinstance(response.json, dict)) # check record that does not exist self.testapp.get("/records/9999", status=404) # check non integer? def test_get_all_records(self): """Test return_records without search query.""" response = self.testapp.get("/records", status=200) self.assertTrue(isinstance(response.json, list)) def test_add_record(self): """Test adding a record.""" # test successful payload = { "timestamp": "2001-02-02T17:11:20.919467Z", "bp_upper": 100, "bp_lower": 40, } self.testapp.post_json("/records", payload, status=201) # test bad format payload = {"timestamp": "2001-02-02", "bp_upper": 100, "bp_lower": 40} self.testapp.post_json("/records", payload, status=400) def test_update_record(self): """Test modifying a record.""" # testing updating a record payload = { "timestamp": "2001-02-02T17:11:20.919467Z", "bp_upper": 300, "bp_lower": 40, } response = self.testapp.put_json("/records/1", payload, status=200) response = self.testapp.get("/records/1", status=200) self.assertEqual(300, response.json.get("bp_upper")) # testing updating a record that does not exist self.testapp.put_json("/records/9999", payload, status=201) # test bad payload payload = {"timestamp": "2001-02-02", "bp_upper": 100, "bp_lower": 40} self.testapp.put_json("/records/1", payload, status=400) def test_delete_record(self): """Test record deletion.""" # test deleting existing record self.testapp.delete("/records/1", status=202) # test deleting non-existing record self.testapp.delete("/records/1", status=204) def test_get_search_records(self): """Test return_records with search query.""" date = datetime.utcnow() + timedelta(hours=1) date = Record.get_timestamp(date).isoformat(timespec="seconds") # test return records due to end_date self.testapp.get("/records?end_date={}Z".format(date), status=200) # test return no records due to start date self.testapp.get("/records?start_date={}Z".format(date), status=204) # test bad date string self.testapp.get("/records?start_date=AAAAZ", status=400)
class CameraApiTest(unittest.TestCase): def setUp(self): from .. import main settings = {'mongodb.db_name': 'nokkhum', 'mongodb.host': 'localhost', 'nokkhum.auth.secret': 'nokkhum'} app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) args = dict(password_credentials= {"email": "*****@*****.**", "password": "******"} ) response = self.testapp.post_json('/authentication/tokens', params=args, status=200) print("authentication: ") self.pp=pprint.PrettyPrinter(indent=4) self.pp.pprint(response.json) self.token = response.json['access']['token']['id'] def test_cameraview_can_push_data_to_database(self): pp = pprint.PrettyPrinter(indent=4) # create camera args = dict(username='******', password='******', name='ierk hamham', host="127.0.0.1", port=8080, url='', image_size='', fps=5, storage_periods=1, project = dict(id = 1), user = dict(id = 1), model = dict(id = '5113b19c698a974f3ee2f69e'), ) print("args: ") pp.pprint(args) response = self.testapp.post_json('/cameras', params={'camera':args}, headers=[('X-Auth-Token', self.token)], status=200) print("response create: ") pp.pprint(response.json) self.assertIn("id", response.json["camera"]) self.camera_id = response.json["camera"]["id"] # retrieve camera via camera id response = self.testapp.get('/cameras/%d'%self.camera_id, headers=[('X-Auth-Token', self.token)], status=200) print( "response get: ") pp.pprint(response.json) self.assertEqual(response.json["camera"]["id"], self.camera_id) self.camera_dict = response.json["camera"] # # try to change name args = self.camera_dict args["name"] = '123' args["host"] = '172.30.23.2' response = self.testapp.put_json('/cameras/1', params={'camera':args},headers=[('X-Auth-Token', self.token)], status=200) print("response update: ") pp.pprint( response.json)
class Client(object): def __init__(self): self.core = Core(db_type="memory").execute_wsgi() self.test_core = TestApp(self.core) def migrate_in_memory(self, migrations_path, alembic_ini_path=None, connection=None, revision="head"): config = Config(alembic_ini_path) config.set_main_option("script_location", migrations_path) if connection is not None: config.attributes["connection"] = connection command.upgrade(config, revision) def get_api(self, api_url, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.get(__api_url) response.json = test_core_response.json response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body response.content_type = test_core_response.content_type return response def post_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.post_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def patch_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.patch_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def put_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.put_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def delete_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.delete_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response
class FunctionalTests(unittest.TestCase): def setUp(self): # from uploadserver import main # import paste # import os from pyramid import paster # NOTE! Be sure to run `export TEST_INI='development.ini'` so that # os.environ can find it! app = paster.get_app("test.ini") # os.environ['TEST_INI']) from webtest import TestApp self.testapp = TestApp(app) def _login(self, name="superuser", password="******"): # Can be used to log into the app params = { "name": name, "password": password, "form.submitted": "true", # The value of this field does not matter } return self.testapp.post("/login", params=params) def test_root(self): self._login() self.testapp.get("/") # self.failUnless(res.status == '200 ok') def test_login_valid_password(self): # First a legit login self.testapp.reset() res = self.testapp.get("/login") form = res.form form["name"] = "user" form["password"] = "******" res = form.submit("form.submitted") self.failUnless(res.status == "302 Found") res = res.follow() self.failUnless(res.request.url == "http://localhost/") # Duplicated login should redirect to root res = self.testapp.get("/login") self.failUnless(res.status == "302 Found") res = res.follow() self.failUnless(res.request.url == "http://localhost/") def test_login_invalid_password(self): self.testapp.reset() res = self.testapp.get("/login") form = res.form form["name"] = "user" form["password"] = "******" res = form.submit("form.submitted") self.failUnless(res.request.url == "http://localhost/login") def test_logout(self): self._login() # Normal logout res = self.testapp.get("/logout") self.failUnless(res.status == "302 Found") res = res.follow() self.failUnless(res.request.url == "http://localhost/") # Logout without login res = self.testapp.get("/logout") self.failUnless(res.status == "302 Found") res = res.follow() self.failUnless(res.request.url == "http://localhost/") def test_api_items_get(self): self._login() res = self.testapp.get("/api/items") json = res.json self.failUnless(len(json) > 0) _id = json[0].get("_id") res = self.testapp.get("/api/items/{0}".format(_id)) self.failUnless(str(res.json.get("_id")) == str(_id)) def test_api_assets_get(self): self._login() res = self.testapp.get("/api/assets") json = res.json self.failUnless(len(json) > 0) object_id = json[0].get("_id") short_id = json[0].get("id") res = self.testapp.get("/api/assets/{0}".format(object_id)) self.failUnless(str(res.json.get("_id")) == str(object_id)) res = self.testapp.get("/api/assets/{0}".format(short_id)) self.failUnless(str(res.json.get("id")) == str(short_id)) self.failUnless(len(res.json.keys()) > 2) def test_api_items_put_valid(self): self._login() res = self.testapp.get("/api/items") json = res.json self.failUnless(len(json) > 0) object_id = json[0].get("_id") params = dict(_id=object_id, listIndex=0, type="lesson", title="something or other", desc="Nothing", text="") self.testapp.put_json("/api/items/{0}".format(object_id), params=params) def test_api_items_put_invalid(self): self._login() res = self.testapp.get("/api/items") json = res.json self.failUnless(len(json) > 0) object_id = json[0].get("_id") # First test non-json put params = dict(_id=object_id, listIndex=0, type="lesson", title="something or other", desc="Nothing", text="") # Should return 406 Not Acceptable self.testapp.put("/api/items/{0}".format(object_id), params=params, status=406) # Test a request with no _id supplied params = dict(listIndex=0, type="lesson", title="something or other", desc="Nothing", text="") # Should return 503 self.testapp.put_json("/api/items/{0}".format(object_id), params=params, status=503) def test_api_assets_get_invalid_id(self): # self._login() self.testapp.get('/api/assets/#!@"()/[]}{+?\\&`', status=404) def test_misaka_post(self): import random import string char_list = string.letters + string.digits random_markdown = "" for i in range(100): random_markdown += random.choice(char_list) params = { "md": ( r"$ \alpha = \beta $" # Math syntax r"$ \alpha = \beta $" # Image cache hit r"$ {} $" # To ensure a cache miss "## Random heading" # Normal markdown "![Alt text goes here](id=4d)" # Image tags "![Alt text](id=nonexistant)" ).format(random_markdown) } self.testapp.post("/misaka", params=params, status=403) self._login() self.testapp.post("/misaka", params=params) def test_get_asset_thumb_image_valid_id(self): self._login() res = self.testapp.get("/api/assets") json = res.json short_id = json[0].get("id") res = self.testapp.get("/api/assets/{id}/thumb".format(id=short_id), status=303) self.failUnless("rackcdn.com" in res) res = self.testapp.get("/api/assets/{id}/image".format(id=short_id), status=303) self.failUnless("rackcdn.com" in res) # res.showbrowser() def test_api_item_get_not_logged_in(self): self.testapp.reset() self.testapp.get("/api/items", status=403) def test_api_asset_get_not_logged_in(self): self.testapp.reset() self.testapp.get("/api/assets", status=403)
class UserApiTest(unittest.TestCase): def setUp(self): from nokkhumapi import main cfg = configparser.ConfigParser() cfg.read('../../development.ini') settings = dict(cfg.items('app:main')) app = main({}, **settings) from webtest import TestApp self.testapp = TestApp(app) args = dict(password_credentials= {"email": "*****@*****.**", "password": "******"} ) response = self.testapp.post_json('/authentication/tokens', params=args, status=200) print("authentication: ") self.pp=pprint.PrettyPrinter(indent=4) self.pp.pprint(response.json) self.token = response.json['access']['token']['id'] self.camera_id = 1 def test_userview_can_push_data_to_database(self): # create camera args = dict(email = '*****@*****.**', password = '******', first_name = 'iErk', last_name = 'HamHam', status = "active" ) response = self.testapp.post_json('/users', params={'user':args}, headers=[('X-Auth-Token', self.token)], status=200) print("response create: ") self.pp.pprint(response.json) self.assertIn("id", response.json["user"]) self.user_id = 2 # retrieve camera via camera id response = self.testapp.get('/users/%d'%self.user_id, headers=[('X-Auth-Token', self.token)], status=200) print ("response get: ") self.pp.pprint(response.json) self.assertEqual(response.json["user"]["id"], self.user_id) self.user_dict = response.json["user"] # try to change name self.user_dict['status'] = 'suspend' args = self.user_dict response = self.testapp.put_json('/users/%d'%response.json["user"]["id"], headers=[('X-Auth-Token', self.token)], params={'user':args}, status=200) print("response update: ") self.pp.pprint(response.json) self.assertIn("id", response.json["user"]) response = self.testapp.delete('/users/%d'%response.json["user"]["id"], headers=[('X-Auth-Token', self.token)], params={'user':args}, status=200) print("response delete: ") self.pp.pprint(response.json)
class AutohubAPITests(unittest.TestCase): def setUp(self): app = main({"DB_NAME": "test.db"}) from webtest import TestApp self.testapp = TestApp(app) self.maxDiff = None self.kermit_car = { "id": 1, "owner": "Kermit the Frog", "name": "Silver Spur", "brand": "Rolls-Royce", "year": 1980, "engine": 6.75, "description": "This car can travel by map!", "picture": "http://localhost:6547/cars/1/File:Kermit%27s_car_hood_ornament.jpg" } self.count_car = { "id": 2, "owner": "Count von Count", "name": "Steamer", "brand": "Stanley Motor", "year": -1, "engine": -1.0, "description": "Can hold up to 99 bats!", "picture": "" } def tearDown(self): delete_db("test.db") def test_add_car_simple(self): input_car = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(res.json, self.kermit_car) def test_add_car_non_json(self): res = self.testapp.post('/api/cars', {"some": "stuff"}, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Body should be JSON"}) def test_add_car_invalid_json(self): res = self.testapp.post_json('/api/cars', '{"hello":"there"]', status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Problems parsing JSON"}) def test_add_car_missing_essential_fields(self): input_car = { "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Missing field", "field": "name"}) input_car["name"] = "Silver Spur" res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, { "error": "Missing field", "field": "owner" }) def test_add_car_missing_nonessential_fields(self): input_car = { "name": "Silver Spur", "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", } res = self.testapp.post_json('/api/cars', input_car) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(res.json["description"], "") self.assertEqual(res.json["engine"], -1) self.assertEqual(res.json["picture"], "") def test_add_car_non_unique_owner_name(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Silver Spur", "owner": "Kermit the Frog", } res = self.testapp.post_json('/api/cars', input_car1, status=200) res = self.testapp.post_json('/api/cars', input_car2, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Already existing car"}) def test_add_car_invalid_fields(self): input_car = { "name": "Silver Spur", "owner": "Kermit the Frog", "description": 1, "engine": "6.75", "brand": "Rolls-Royce", "year": 1980, } res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, { "error": "Invalid field format", "field": "engine" }) def test_list_cars_simple(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Steamer", "owner": "Count von Count", "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.post_json('/api/cars', input_car2) res = self.testapp.get('/api/cars') self.assertEqual(res.content_type, 'application/json') self.assertEqual(len(res.json), 2) self.assertEqual(res.json[0], self.kermit_car) self.assertEqual(res.json[1], self.count_car) def test_list_car_empty(self): res = self.testapp.get('/api/cars') self.assertEqual(res.content_type, 'application/json') self.assertEqual(len(res.json), 0) self.assertEqual(res.json, []) def test_list_car_simple(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.get('/api/cars/1') self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, self.kermit_car) def test_list_car_not_there(self): res = self.testapp.get('/api/cars/1', status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"}) def test_update_car(self): input_car = { "name": "Steamer", "owner": "Count von Count", } mod_car = { "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.post_json('/api/cars', input_car) res = self.testapp.put_json('/api/cars/{}'.format(res.json["id"]), mod_car) self.assertEqual(res.content_type, 'application/json') self.count_car["id"] = 1 self.assertEqual(res.json, self.count_car) def test_update_car_not_there(self): mod_car = { "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.put_json('/api/cars/{}'.format(1), mod_car, status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"}) def test_update_car_not_unique(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Steamer", "owner": "Count von Count", "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } mod_car = { "name": "Steamer", "owner": "Count von Count", } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.post_json('/api/cars', input_car2) res = self.testapp.put_json('/api/cars/1', mod_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Already existing car"}) def test_delete_car_simple(self): input_car = { "name": "Steamer", "owner": "Count von Count", } res = self.testapp.post_json('/api/cars', input_car) res = self.testapp.delete('/api/cars/1', status=200) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"Message": "Deleted car 1"}) res = self.testapp.get('/api/cars/1', status=404) def test_delete_car_not_there(self): res = self.testapp.delete('/api/cars/1', status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"})
class AppUser: """:class:`webtest.TestApp` wrapper for backend functional testing.""" def __init__(self, app, rest_url: str='http://localhost', base_path: str='/', header: dict=None): """Initialize self.""" self.app = TestApp(app) """:class:`webtest.TestApp`to send requests to the backend server.""" self.rest_url = rest_url """backend server url to generate request urls.""" self.base_path = base_path """path prefix to generate request urls.""" self.header = header or {} """default header for requests, mostly for authentication.""" self._resolver = DottedNameResolver() def post_resource(self, path: str, iresource: IInterface, cstruct: dict) -> TestResponse: """Build and post request to create a new resource.""" url = self._build_url(path) props = self._build_post_body(iresource, cstruct) resp = self.app.post_json(url, props, headers=self.header, expect_errors=True) return resp def put(self, path: str, cstruct: dict={}) -> TestResponse: """Put request to modify a resource.""" url = self._build_url(path) resp = self.app.put_json(url, cstruct, headers=self.header, expect_errors=True) return resp def post(self, path: str, cstruct: dict={}) -> TestResponse: """Post request to create a new resource.""" url = self._build_url(path) resp = self.app.post_json(url, cstruct, headers=self.header, expect_errors=True) return resp def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict: return {'content_type': iresource.__identifier__, 'data': cstruct} def _build_url(self, path: str) -> str: if path.startswith('http'): return path return self.rest_url + self.base_path + path def batch(self, subrequests: list): """Build and post batch request to the backend rest server.""" resp = self.app.post_json(batch_url, subrequests, headers=self.header, expect_errors=True) return resp def get(self, path: str, params={}) -> TestResponse: """Send get request to the backend rest server.""" url = self._build_url(path) resp = self.app.get(url, headers=self.header, params=params, expect_errors=True) return resp def options(self, path: str) -> TestResponse: """Send options request to the backend rest server.""" url = self._build_url(path) resp = self.app.options(url, headers=self.header, expect_errors=True) return resp def get_postable_types(self, path: str) -> []: """Send options request and return the postable content types.""" resp = self.options(path) if 'POST' not in resp.json: return [] post_request_body = resp.json['POST']['request_body'] type_names = sorted([r['content_type'] for r in post_request_body]) iresources = [self._resolver.resolve(t) for t in type_names] return iresources
def test_cerberus(): class User: def __init__(self, name=None, age=None): self.name = name self.age = age user_schema = { "name": { "type": "string", "minlength": 3, "required": True }, "age": { "type": "integer", "min": 10, "required": True }, } class App(CerberusApp): pass user = User() @App.path(model=User, path="/") def get_user(): return user @App.json(model=User, request_method="POST", load=loader(user_schema)) def user_post(self, request, json): for key, value in json.items(): setattr(self, key, value) @App.json(model=User, request_method="PUT", load=loader(user_schema)) def user_put(self, request, json): for key, value in json.items(): setattr(self, key, value) c = Client(App()) c.post_json("/", {"name": "Somebody", "age": 22}) assert user.name == "Somebody" assert user.age == 22 r = c.post_json("/", {"name": "Another"}, status=422) assert r.json == {"age": ["required field"]} c.put_json("/", {"name": "Another"}) assert user.name == "Another" assert user.age == 22 r = c.put_json("/", {"age": 8}, status=422) assert r.json == {"age": ["min value is 10"]} r = c.put_json("/", {"name": "An", "age": 8}, status=422) assert r.json == {"name": ["min length is 3"], "age": ["min value is 10"]} r = c.put_json("/", {"name": 5, "age": "8"}, status=422) assert r.json == { "name": ["must be of string type"], "age": ["must be of integer type"], }
class TestShield(Test): def test_shields(self): @register class MyAuth(Authentication): expiration_time = 5 @classmethod def salt_key(cls): return 'ray_salt_key' @classmethod def authenticate(cls, login_data): if login_data['password'] == '123': return {'username': '******'} @endpoint('/person', authentication=MyAuth) class PersonModel(ModelInterface): def __init__(self, *a, **k): self.login = None super(PersonModel, self).__init__(*a, **k) @classmethod def columns(cls): return ['id'] class PersonShield(Shield): __model__ = PersonModel def get(self, user_data, person_id, parameters): return user_data['username'] == 'felipe' def put(self, user_data, person_id, parameters): assert person_id == '1' assert parameters == {'any': '*****@*****.**'} return True global global_person_id 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 = FakeApp(application) response = self.app.post_json('/api/_login', { "username": "******", 'password': '******' }) self.assertEqual(200, response.status_int) global global_parameters self.app.put_json('/api/person/1/', {'any': '*****@*****.**'}) self.assertEqual(200, response.status_int) self.app = FakeApp(application) response = self.app.get('/api/person', expect_errors=True) self.assertEquals(401, response.status_int) self.app = FakeApp(application) response = self.app.post('/api/person/', expect_errors=True) self.assertIsNot(401, response.status_int) self.app = FakeApp(application) response = self.app.put('/api/person/', expect_errors=True) self.assertIsNot(404, response.status_int) self.app = FakeApp(application) response = self.app.delete('/api/person/', expect_errors=True) self.assertIsNot(404, response.status_int)
class FlaskAdapterTests(unittest.TestCase): def setUp(self): from tests.example_app.flask_app import create_pale_flask_app self.flask_app = create_pale_flask_app() self.app = TestApp(self.flask_app) def assertExpectedFields(self, returned_dict, expected_fields): d = returned_dict.copy() # don't clobber the input for f in expected_fields: self.assertIn(f, d) val = d.pop(f) # don't check the val for now # make sure there's nothing extraneous left in the dict self.assertEqual(len(d.keys()), 0) return def test_successful_get_with_route_args(self): now = datetime.datetime.utcnow() resp = self.app.get('/api/arg_test/arg-a/arg-b') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.json, { "arg_a": "arg-a", "arg_b": "arg-b", }) def test_successful_get_without_params(self): now = datetime.datetime.utcnow() resp = self.app.get('/api/time/current') self.assertEqual(resp.status_code, 200) # Test _after_response_handlers self.assertIn("After-Response", resp.headers) self.assertEqual(resp.headers["After-Response"], 'OK') # Test CORS self.assertIn("Access-Control-Allow-Origin", resp.headers) self.assertEqual(resp.headers["Access-Control-Allow-Origin"], '*') # the 'time' value was set in the endpoint handler self.assertIn('time', resp.json_body) # the returned time value should match the resource defined # in tests.example_app.api.resources.py returned_time = resp.json_body['time'] # the endpoint specifies `fields=DateTimeResource._all_fields()` # so, we should expect to find all of them expected_fields = DateTimeResource._all_fields() self.assertExpectedFields(returned_time, expected_fields) self.assertEqual(returned_time['eurodate'], now.strftime("%d.%m.%Y")) def test_successful_post_with_required_params(self): # month is required in the endpoint definition, so we must pass # it in here resp = self.app.post('/api/time/parse', {'month': 2}) self.assertEqual(resp.status_code, 200) self.assertIn('time', resp.json_body) returned_time = resp.json_body['time'] # we didn't specify any other fields in the endpoint definition, # so this one should only get the defaults expected_fields = DateTimeResource._default_fields self.assertExpectedFields(returned_time, expected_fields) self.assertIn('Cache-Control', resp.headers) self.assertEqual('max-age=3', resp.headers['Cache-Control']) def test_successful_json_post_with_required_params(self): # this is the same as the above post, but passes json in the # request body, instead of x-www-form-urlencoded resp = self.app.post_json('/api/time/parse', {'month': 2}) self.assertEqual(resp.status_code, 200) self.assertIn('time', resp.json_body) returned_time = resp.json_body['time'] # we didn't specify any other fields in the endpoint definition, # so this one should only get the defaults expected_fields = DateTimeResource._default_fields self.assertExpectedFields(returned_time, expected_fields) def test_unsuccessful_post_missing_required_params(self): resp = self.app.post('/api/time/parse', status=422) self.assertIn('error', resp.json_body) def test_getting_with_nested_resources(self): test_duration = 60 * 1000 # one minute in milliseconds resp = self.app.get('/api/time/range', {'duration': test_duration}) self.assertEqual(resp.status_code, 200) self.assertIn('range', resp.json_body) returned_range = resp.json_body['range'] self.assertEqual(returned_range['duration_microseconds'], test_duration * 1000) # start has default fields start = returned_range['start'] expected_fields = DateTimeResource._default_fields self.assertExpectedFields(start, expected_fields) # end has all of them end = returned_range['end'] expected_fields = DateTimeResource._all_fields() self.assertExpectedFields(end, expected_fields) def test_resource(self): # Start by resetting the resource. # (multiple test runs from the same process will fail otherwise) resp = self.app.post('/api/resource/reset') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value'}) # Test creating a new resource resp = self.app.put_json('/api/resource', {'key': 'boop'}, headers={'Content-Type': 'application/json'}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'boop'}) # Test retrieving the resource. resp = self.app.get('/api/resource') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'boop'}) # Test patching the resource. # Without the correct Content-Type, we expect a 415 error. self.assertRaises(AppError, self.app.patch_json, '/api/resource', {'key': 'value2'}) resp = self.app.patch_json( '/api/resource', {'key': 'value2'}, headers={'Content-Type': 'application/merge-patch+json'}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value2'}) # Test get to ensure the resource persists. resp = self.app.get('/api/resource') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.json, {'key': 'value2'}) # A NoContentResource shouldn't have a Content-Type header (no content!) resp = self.app.post('/api/blank') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content_type, None)
class WsgiInterfaceTests(base.BaseWSGITest): @classmethod def setUpClass(cls): super(WsgiInterfaceTests, cls).setUpClass() def setUp(self): super(WsgiInterfaceTests, self).setUp() self.app = TestApp(app.setup_app()) self.fixture = { 'cluster_id': 1 } def tearDown(self): super(WsgiInterfaceTests, self).tearDown() def test_get_all_tests(self): self.app.get('/v1/tests/{0}' .format(self.fixture['cluster_id'])) def test_get_all_testsets(self): self.app.get('/v1/testsets/{0}' .format(self.fixture['cluster_id'])) def test_get_one_testruns(self): self.app.get('/v1/testruns/1') def test_get_all_testruns(self): self.app.get('/v1/testruns') @patch('fuel_plugin.ostf_adapter.wsgi.controllers.models') def test_post_testruns(self, models): testruns = [ { 'testset': 'test_simple', 'metadata': {'cluster_id': 3} }, { 'testset': 'test_simple', 'metadata': {'cluster_id': 4} } ] self.request_mock.body = json.dumps(testruns) models.TestRun.start.return_value = {} self.app.post_json('/v1/testruns', testruns) def test_put_testruns(self): testruns = [ { 'id': 2, 'metadata': {'cluster_id': 3}, 'status': 'non_exist' }, { 'id': 1, 'metadata': {'cluster_id': 4}, 'status': 'non_exist' } ] self.request_mock.body = json.dumps(testruns) self.request_mock.storage.get_test_run.return_value = \ MagicMock(frontend={}) self.app.put_json('/v1/testruns', testruns) def test_get_last_testruns(self): self.app.get('/v1/testruns/last/{0}' .format(self.fixture['cluster_id']))
class BasicTest(unittest.TestCase): @classmethod def setUpClass(cls): renki.app.catchall = False def setUp(self): """ Initialize database and create tables, relations, indexes etc. """ connection.session.rollback() self.app = TestApp(renki.app) connection.conn.create_tables() connection.session.commit() self._users = {} # Create permissions for permission in permissions.PERMISSIONS: if not auth_db.Permissions.query().filter( auth_db.Permissions.name == permission).all(): p = auth_db.Permissions() p.name = permission p.save() def tearDown(self): """ Destroy tables, indexes and relations. """ try: connection.session.rollback() connection.conn.drop_tables() connection.session.commit() connection.session.flush() connection.session.session().close() except: connection.session.rollback() raise def _get_error(self, item): error = None try: if 'error' in item.json: error = item.json['error'] except (AttributeError, KeyError): pass return error def auth(self, user, password): """ Authenticate user and return authentiction key """ args = {'username': user, 'password': password} s = self.app.post('/login', params=args, status="*") self.assertStatus(s, STATUS_OK) return s.json['apikey'] def user(self, name, perms=[]): """ Create user with name `name` and permissions `permissins` return authenticated session """ if name not in self._users: pw = utils.generate_key() user = auth_db.Users() user.id = len(self._users) + 1 user.name = name user.set_password(pw) user.firstnames = 'test' user.lastname = 'test' user.save() connection.session.commit() for perm_name in perms: perm = auth_db.Permissions.query().filter( auth_db.Permissions.name == perm_name).one() user.permissions.append(perm) connection.session.commit() sessionkey = self.auth(user=name, password=pw) u = TestUser(name=name, password=pw, sessionkey=sessionkey, user=user) self._users[name] = u return self._users[name] def q(self, route, user, method='GET', args={}): """ Query route using `method` with args `args` as `user` returns response object """ if user: args['apikey'] = user.sessionkey elif 'apikey' in args: del args['apikey'] if method.upper() == 'GET': return self.app.get(route, params=args, status="*") elif method.upper() == 'POST': return self.app.post_json(route, params=args, status="*") elif method.upper() == 'PUT': return self.app.put_json(route, params=args, status="*") elif method.upper() == 'DELETE': if 'apikey' in args: route = "%s?apikey=%s" % (route, args['apikey']) return self.app.delete(route, params=args, status="*") self.fail("Method %s not implemented" % method) def assertContainsOne(self, database, cls=None): query = database.query() if cls is not None: query = query.filter(cls) self.assertEqual(query.count(), 1) def assertContainsMany(self, database, cls=None): query = database.query() if cls is not None: query = query.filter(cls) self.assertTrue(query.count() > 1) def assertContainsNone(self, database, cls=None): query = database.query() if cls is not None: query = query.filter(cls) self.assertEqual(query.count(), 0) def assertStatus(self, response, status): """ Assert that response status is `status` """ self.assertEqual( response.json['status'], status.JSON_STATUS, "Wrong JSON status code %s, excepted %s, error: %s" % (response.json['status'], status.JSON_STATUS, self._get_error(response))) self.assertEqual( response.status_int, status.HTTP_STATUS, "Wrong HTTP status code %s, excepted %s" % (response.status_int, status.HTTP_STATUS)) def assertValidResponse(self, item, schema=[]): """ Validates that response is valid json response @param schema: optional json schema. """ if not schema: schema = [] else: # Copy schema schema = [i for i in schema] schema.append(JSONString('status', required=True)) d = { 'type': 'object', 'properties': {}, "additionalProperties": False, "required": [] } for i in schema: d['properties'][i.name] = i.as_property() for req in i.as_required(): if req not in d["required"]: d["required"].append(req) try: jsonschema_validate(item.json, schema=d) except JSONValidationError: self.fail("Response JSON is not valid") def assertQ(self, route, user, method='GET', args={}, status=None, schema=None): """ Sortcut to execute query and validate status and response schema. """ args = args.copy() if not schema and status and status != STATUS_OK: schema = status.FIELDS elif status and status != STATUS_OK: schema += status.FIELDS q = self.q(route=route, user=user, method=method, args=args) if status is not None: self.assertStatus(q, status) if schema: self.assertValidResponse(q, schema=schema)
class TestApiViews(unittest.TestCase): """ Tests the ApiViews class. """ def setUp(self): my_settings = { 'sqlalchemy.url': 'sqlite:///:memory:', 'api_auth_token': u"SECRETAUTHTOKEN", } self.config = testing.setUp() app = main({}, **my_settings) # set up the database engine = engine_from_config(my_settings) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: member1 = C3sMember( # german firstname=u'SomeFirstnäme', lastname=u'SomeLastnäme', email=u'*****@*****.**', address1=u"addr one", address2=u"addr two", postcode=u"12345", city=u"Footown Mäh", country=u"Foocountry", locale=u"de", date_of_birth=date.today(), email_is_confirmed=False, email_confirm_code=u'ABCDEFGFOO', password=u'arandompassword', date_of_submission=date.today(), membership_type=u'normal', member_of_colsoc=True, name_of_colsoc=u"GEMA", num_shares=u'23', ) # pylint: disable=no-member DBSession.add(member1) member1.email_invite_token_bcgv18 = u'MEMBERS_TOKEN' # pylint: disable=no-member DBSession.flush() self.testapp = TestApp(app) def tearDown(self): testing.tearDown() # pylint: disable=no-member DBSession.close() DBSession.remove() def test_api_userinfo(self): """ Test the api_userinfo service. * must be a PUT, not a GET request * the auth header must be present * returns None if members refcode does not match * returns firstname, lastname, email, membership type """ # try a GET -- must fail res = self.testapp.get('/lm', status=405) self.assertTrue('405 Method Not Allowed' in res.body) self.assertTrue('The method GET is not allowed for this resource.' in res.body) # try a PUT -- fails under certain conditions with self.assertRaises(ValueError): res = self.testapp.put('/lm', status=200) # ValueError: No JSON object could be decoded # try a PUT -- fails under certain conditions with self.assertRaises(KeyError): res = self.testapp.put_json( '/lm', dict(id=1)) # status=200) # KeyError: 'token' # missing auth token -- must fail with self.assertRaises(KeyError): res = self.testapp.put_json( '/lm', dict(token=1)) # status=200) # KeyError: 'HTTP_X_MESSAGING_TOKEN' # try false auth token -- must fail: 401 unauthorized _headers = {'X-messaging-token': 'bar'} res = self.testapp.put_json( '/lm', dict(token=1), headers=_headers, status=401) # now use the correct auth token _auth_info = {'X-messaging-token': 'SECRETAUTHTOKEN'} # ..but a non-existing refcode (email_invite_token_bcgv18) # returns no user (None) res = self.testapp.put_json( '/lm', dict(token='foo'), headers=_auth_info, status=200) # body: {"lastname": "None", "firstname": "None"} self.assertTrue(json.loads(res.body)['firstname'], "None") self.assertTrue(json.loads(res.body)['lastname'], "None") self.testapp.reset() member1 = C3sMember.get_by_id(1) # load member from DB for crosscheck # now try a valid refcode (email_invite_token_bcgv18) res2 = self.testapp.put_json( '/lm', dict(token=member1.email_invite_token_bcgv18), headers=_auth_info, status=200) self.assertTrue(json.loads(res2.body)['firstname'], member1.firstname) self.assertTrue(json.loads(res2.body)['lastname'], member1.lastname) self.assertTrue(json.loads(res2.body)['email'], member1.email) self.assertTrue(json.loads(res2.body)['mtype'], member1.membership_type)
class TestApiViews(unittest.TestCase): """ Tests the ApiViews class. """ def setUp(self): my_settings = { 'sqlalchemy.url': 'sqlite:///:memory:', 'api_auth_token': u"SECRETAUTHTOKEN", } self.config = testing.setUp() app = main({}, **my_settings) # set up the database engine = engine_from_config(my_settings) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: member1 = C3sMember( # german firstname=u'SomeFirstnäme', lastname=u'SomeLastnäme', email=u'*****@*****.**', address1=u"addr one", address2=u"addr two", postcode=u"12345", city=u"Footown Mäh", country=u"Foocountry", locale=u"de", date_of_birth=date.today(), email_is_confirmed=False, email_confirm_code=u'ABCDEFGFOO', password=u'arandompassword', date_of_submission=date.today(), membership_type=u'normal', member_of_colsoc=True, name_of_colsoc=u"GEMA", num_shares=u'23', ) member1.membership_number = 'M1' # pylint: disable=no-member DBSession.add(member1) GeneralAssemblyRepository.invite_member( member1.membership_number, GENERAL_ASSEMBLY, u'MEMBERS_TOKEN') # pylint: disable=no-member DBSession.flush() self.testapp = TestApp(app) def tearDown(self): testing.tearDown() # pylint: disable=no-member DBSession.close() DBSession.remove() def test_api_userinfo(self): """ Test the api_userinfo service. * must be a PUT, not a GET request * the auth header must be present * returns None if members refcode does not match * returns firstname, lastname, email, membership type """ # try a GET -- must fail res = self.testapp.get('/lm', status=405) self.assertTrue('405 Method Not Allowed' in res.body) self.assertTrue('The method GET is not allowed for this resource.' in res.body) # try a PUT -- fails under certain conditions with self.assertRaises(ValueError): res = self.testapp.put('/lm', status=200) # ValueError: No JSON object could be decoded # try a PUT -- fails under certain conditions with self.assertRaises(KeyError): res = self.testapp.put_json( '/lm', dict(id=1)) # status=200) # KeyError: 'token' # missing auth token -- must fail with self.assertRaises(KeyError): res = self.testapp.put_json( '/lm', dict(token=1)) # status=200) # KeyError: 'HTTP_X_MESSAGING_TOKEN' # try false auth token -- must fail: 401 unauthorized _headers = {'X-messaging-token': 'bar'} res = self.testapp.put_json( '/lm', dict(token=1), headers=_headers, status=401) # now use the correct auth token _auth_info = {'X-messaging-token': 'SECRETAUTHTOKEN'} # ..but a non-existing refcode # returns no user (None) res = self.testapp.put_json( '/lm', dict(token='foo'), headers=_auth_info, status=200) # body: {"lastname": "None", "firstname": "None"} self.assertTrue(json.loads(res.body)['firstname'], "None") self.assertTrue(json.loads(res.body)['lastname'], "None") self.testapp.reset() member1 = C3sMember.get_by_id(1) # load member from DB for crosscheck # now try a valid refcode res2 = self.testapp.put_json( '/lm', dict(token='MEMBERS_TOKEN'), headers=_auth_info, status=200) self.assertTrue(json.loads(res2.body)['firstname'], member1.firstname) self.assertTrue(json.loads(res2.body)['lastname'], member1.lastname) self.assertTrue(json.loads(res2.body)['email'], member1.email) self.assertTrue( json.loads(res2.body)['mtype'], member1.membership_type)
class AppUser: """:class:`webtest.TestApp` wrapper for backend functional testing.""" def __init__(self, app_router: Router, rest_url: str='http://localhost', base_path: str='/', header: dict=None, user_path: str='', user_login: str='', user_password: str='', ): """Initialize self.""" self.app_router = app_router """The adhocracy wsgi application""" self.app = TestApp(app_router) """:class:`webtest.TestApp`to send requests to the backend server.""" self.rest_url = rest_url """backend server url to generate request urls.""" self.base_path = base_path """path prefix to generate request urls.""" self.header = header or {} """default header for requests, mostly for authentication. If not set, `user_login` and `user_password` is used to login, the new authentication header is stored in `header`. """ if user_password and user_login and not header: token, user_path = self._get_token_and_user_path(user_login, user_password) self.header = {UserTokenHeader: token} self.user_password = user_password """password for authenticated user.""" self.user_login = user_login """login name for authenticated user.""" self.user_path = user_path """path for authenticated user.""" self._resolver = DottedNameResolver() def _get_token_and_user_path(self, login: str, password: str) -> tuple: login_page = self.rest_url + '/login_username' data = {'name': login, 'password': password} resp = self.app.post_json(login_page, data).json return resp['user_token'], resp['user_path'] def post_resource(self, path: str, iresource: IInterface, cstruct: dict) -> TestResponse: """Build and post request to create a new resource.""" url = self._build_url(path) props = self._build_post_body(iresource, cstruct) resp = self.app.post_json(url, props, headers=self.header, expect_errors=True) return resp def put(self, path: str, cstruct: dict={}, upload_files: [(str, str, bytes)]=None, ) -> TestResponse: """Put request to modify a resource.""" url = self._build_url(path) kwargs = {'headers': self.header, 'expect_errors': True, } if upload_files: kwargs['upload_files'] = upload_files resp = self.app.put(url, cstruct, **kwargs) else: resp = self.app.put_json(url, cstruct, **kwargs) return resp def post(self, path: str, cstruct: dict={}, upload_files: [(str, str, bytes)]=None, ) -> TestResponse: """Post request to create a new resource.""" url = self._build_url(path) kwargs = {'headers': self.header, 'expect_errors': True, } if upload_files: kwargs['upload_files'] = upload_files resp = self.app.post(url, cstruct, **kwargs) else: resp = self.app.post_json(url, cstruct, **kwargs) return resp def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict: return {'content_type': iresource.__identifier__, 'data': cstruct} def _build_url(self, path: str) -> str: if path.startswith('http'): return path return self.rest_url + self.base_path + path def batch(self, subrequests: list): """Build and post batch request to the backend rest server.""" resp = self.app.post_json(batch_url, subrequests, headers=self.header, expect_errors=True) return resp def get(self, path: str, params={}) -> TestResponse: """Send get request to the backend rest server.""" url = self._build_url(path) resp = self.app.get(url, headers=self.header, params=params, expect_errors=True) return resp def delete(self, path: str) -> TestResponse: """Send delete request to the backend rest server.""" url = self._build_url(path) resp = self.app.delete(url, headers=self.header, expect_errors=True) return resp def options(self, path: str) -> TestResponse: """Send options request to the backend rest server.""" url = self._build_url(path) resp = self.app.options(url, headers=self.header, expect_errors=True) return resp def get_postable_types(self, path: str) -> []: """Send options request and return the postable content types.""" resp = self.options(path) if 'POST' not in resp.json: return [] post_request_body = resp.json['POST']['request_body'] type_names = sorted([r['content_type'] for r in post_request_body]) iresources = [self._resolver.resolve(t) for t in type_names] return iresources
class UserServiceRestIntegrationTest(unittest.TestCase): """ Integration tests for UserServiceRest """ @classmethod def tearDownClass(cls): os.remove(db_filename) def setUp(self): create_db_tables(db_filename) self.populate_db_tables() settings = {'sqlalchemy.url': 'sqlite:///' + db_filename} app = main(None, **settings) self.testapp = TestApp(app) def tearDown(self): drop_db_tables(db_filename) def test_get_user_found(self): url = 'http://*****:*****@jazz.com' headers = {'Accept': 'application/json; charset=utf8'} res = self.testapp.get(url, headers=headers, status=200) res_dict = json.loads(str(res.body, 'utf-8')) self.assertEqual('*****@*****.**', res_dict['email']) self.assertEqual('Coltrane', res_dict['last_name']) self.assertEqual('34568', res_dict['address']['post_code']) def test_get_user_not_found(self): url = 'http://*****:*****@nowhere.com' headers = {'Accept': 'application/json; charset=utf8'} res = self.testapp.get(url, headers=headers, status=404) def test_add_user_ok(self): url = 'http://*****:*****@jazz.com", "middles": None, "address": { "country": "USA", "street": "5311 E 1st St", "city": "New York", "post_code": "10012", "state": "NY" }, "first_name": "Miles", "last_name": "Davis" } res = self.testapp.post_json(url, post_body, status=201) rows = execute_select( db_filename, "select * from people where email = '*****@*****.**'") self.assertEqual("Miles", rows[0][7]) def test_update_user_ok(self): url = 'http://*****:*****@jazz.com", "middles": "William", "address": { "country": "USA", "street": "123 Cool St", "city": "Chicago", "post_code": "34568", "state": "IL" }, "first_name": "John", "last_name": "Coltrance" } res = self.testapp.put_json(url, put_body, status=202) rows = execute_select( db_filename, "select * from people where email = '*****@*****.**'") self.assertEqual("John", rows[0][7]) self.assertEqual("William", rows[0][9]) def test_delete_user_found(self): url = 'http://*****:*****@jazz.com' self.testapp.delete(url, status=202) def test_delete_user_not_found(self): url = 'http://*****:*****@nowhere.com' res = self.testapp.delete(url, headers=headers, status=404) def populate_db_tables(self): execute_insert(db_filename, 'people', (123, 'Chicago', 'USA', '34568', 'IL', '123 Cool St', '*****@*****.**', 'John', 'Coltrane', ''), (124, 'New Paltz', 'USA', '12345', 'NY', '123 Main St', '*****@*****.**', 'Mike', 'Woinoski', ''))
class AutohubAPITests(unittest.TestCase): def setUp(self): app = main({"DB_NAME":"test.db"}) from webtest import TestApp self.testapp = TestApp(app) self.maxDiff = None self.kermit_car = { "id": 1, "owner": "Kermit the Frog", "name": "Silver Spur", "brand": "Rolls-Royce", "year": 1980, "engine": 6.75, "description": "This car can travel by map!", "picture": "http://localhost:6547/cars/1/File:Kermit%27s_car_hood_ornament.jpg" } self.count_car = { "id": 2, "owner": "Count von Count", "name": "Steamer", "brand": "Stanley Motor", "year": -1, "engine": -1.0, "description": "Can hold up to 99 bats!", "picture": "" } def tearDown(self): delete_db("test.db") def test_add_car_simple(self): input_car = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(res.json, self.kermit_car) def test_add_car_non_json(self): res = self.testapp.post('/api/cars', {"some":"stuff"}, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Body should be JSON"}) def test_add_car_invalid_json(self): res = self.testapp.post_json('/api/cars', '{"hello":"there"]', status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Problems parsing JSON"}) def test_add_car_missing_essential_fields(self): input_car = { "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Missing field", "field": "name"}) input_car["name"] = "Silver Spur" res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Missing field", "field": "owner"}) def test_add_car_missing_nonessential_fields(self): input_car = { "name": "Silver Spur", "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", } res = self.testapp.post_json('/api/cars', input_car) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.status_code, 200) self.assertEqual(res.json["description"], "") self.assertEqual(res.json["engine"], -1) self.assertEqual(res.json["picture"], "") def test_add_car_non_unique_owner_name(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Silver Spur", "owner": "Kermit the Frog", } res = self.testapp.post_json('/api/cars', input_car1, status=200) res = self.testapp.post_json('/api/cars', input_car2, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Already existing car"}) def test_add_car_invalid_fields(self): input_car = { "name": "Silver Spur", "owner": "Kermit the Frog", "description": 1, "engine": "6.75", "brand": "Rolls-Royce", "year": 1980, } res = self.testapp.post_json('/api/cars', input_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Invalid field format", "field": "engine"}) def test_list_cars_simple(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Steamer", "owner": "Count von Count", "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.post_json('/api/cars', input_car2) res = self.testapp.get('/api/cars') self.assertEqual(res.content_type, 'application/json') self.assertEqual(len(res.json), 2) self.assertEqual(res.json[0], self.kermit_car) self.assertEqual(res.json[1], self.count_car) def test_list_car_empty(self): res = self.testapp.get('/api/cars') self.assertEqual(res.content_type, 'application/json') self.assertEqual(len(res.json), 0) self.assertEqual(res.json, []) def test_list_car_simple(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.get('/api/cars/1') self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, self.kermit_car) def test_list_car_not_there(self): res = self.testapp.get('/api/cars/1', status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"}) def test_update_car(self): input_car = { "name": "Steamer", "owner": "Count von Count", } mod_car = { "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.post_json('/api/cars', input_car) res = self.testapp.put_json('/api/cars/{}'.format(res.json["id"]), mod_car) self.assertEqual(res.content_type, 'application/json') self.count_car["id"] = 1 self.assertEqual(res.json, self.count_car) def test_update_car_not_there(self): mod_car = { "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } res = self.testapp.put_json('/api/cars/{}'.format(1), mod_car, status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"}) def test_update_car_not_unique(self): input_car1 = { "name": "Silver Spur", "description": "This car can travel by map!", "engine": 6.75, "brand": "Rolls-Royce", "year": 1980, "owner": "Kermit the Frog", "picture": "http://muppet.wikia.com/wiki/File:Kermit%27s_car_hood_ornament.jpg" } input_car2 = { "name": "Steamer", "owner": "Count von Count", "brand": "Stanley Motor", "description": "Can hold up to 99 bats!", } mod_car = { "name": "Steamer", "owner": "Count von Count", } res = self.testapp.post_json('/api/cars', input_car1) res = self.testapp.post_json('/api/cars', input_car2) res = self.testapp.put_json('/api/cars/1', mod_car, status=400) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Already existing car"}) def test_delete_car_simple(self): input_car = { "name": "Steamer", "owner": "Count von Count", } res = self.testapp.post_json('/api/cars', input_car) res = self.testapp.delete('/api/cars/1', status=200) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"Message": "Deleted car 1"}) res = self.testapp.get('/api/cars/1', status=404) def test_delete_car_not_there(self): res = self.testapp.delete('/api/cars/1', status=404) self.assertEqual(res.content_type, 'application/json') self.assertEqual(res.json, {"error": "Car not found"})