class RackspaceTests(unittest2.TestCase): def setUp(self): self.client = Client(LibcloudRestApp(), BaseResponse) self.fixtures = ComputeFixtures('rackspace') self.headers = {'x-auth-user': '******', 'x-api-key': 'key'} self.url_tmpl = rest_versions[libcloud.__version__] +\ '/compute/RACKSPACE/%s?test=1' OpenStackMockHttp.type = None def test_create_node(self): url = self.url_tmpl % ('nodes') test_request = self.fixtures.load('create_node_request.json') test_request_json = json.loads(test_request) resp = self.client.post(url, headers=self.headers, data=json.dumps(test_request_json), content_type='application/json') node = json.loads(resp.data) self.assertEqual(resp.status_code, httplib.CREATED) self.assertEqual(resp.headers.get('Location'), '72258') self.assertEqual(node['name'], 'racktest') def test_create_node_ex_shared_ip_group(self): OpenStackMockHttp.type = 'EX_SHARED_IP_GROUP' url = self.url_tmpl % ('nodes') test_request = self.fixtures.load('create_node_shared_ip.json') test_request_json = json.loads(test_request) resp = self.client.post(url, headers=self.headers, data=json.dumps(test_request_json), content_type='application/json') node = json.loads(resp.data) self.assertEqual(resp.status_code, httplib.CREATED) self.assertEqual(resp.headers.get('Location'), '72258') self.assertEqual(node['name'], 'racktest')
def test_base_request(): """Base request behavior""" client = Client(request_demo_app, RequestTestResponse) # get requests response = client.get('/?foo=bar&foo=hehe') assert response['args'] == MultiDict([('foo', 'bar'), ('foo', 'hehe')]) assert response['args_as_list'] == [('foo', ['bar', 'hehe'])] assert response['form'] == MultiDict() assert response['form_as_list'] == [] assert response['data'] == '' assert_environ(response['environ'], 'GET') # post requests with form data response = client.post('/?blub=blah', data='foo=blub+hehe&blah=42', content_type='application/x-www-form-urlencoded') assert response['args'] == MultiDict([('blub', 'blah')]) assert response['args_as_list'] == [('blub', ['blah'])] assert response['form'] == MultiDict([('foo', 'blub hehe'), ('blah', '42')]) assert response['data'] == '' # currently we do not guarantee that the values are ordered correctly # for post data. ## assert response['form_as_list'] == [('foo', ['blub hehe']), ('blah', ['42'])] assert_environ(response['environ'], 'POST') # post requests with json data json = '{"foo": "bar", "blub": "blah"}' response = client.post('/?a=b', data=json, content_type='application/json') assert response['data'] == json assert response['args'] == MultiDict([('a', 'b')]) assert response['form'] == MultiDict()
def test_request(): client = Client(request_test_app, RequestTestResponse) # get requests response = client.get('/?foo=bar&foo=hehe') assert response['args'] == MultiDict([('foo', 'bar'), ('foo', 'hehe')]) assert response['args_as_list'] == [('foo', ['bar', 'hehe'])] assert response['form'] == MultiDict() assert response['form_as_list'] == [] assert response['data'] == '' assert_request_test_environ(response['environ'], 'GET') # post requests with form data response = client.post('/?blub=blah', data='foo=blub+hehe&blah=42', content_type='application/x-www-form-urlencoded') assert response['args'] == MultiDict([('blub', 'blah')]) assert response['args_as_list'] == [('blub', ['blah'])] assert response['form'] == MultiDict([('foo', 'blub hehe'), ('blah', '42')]) assert response['data'] == '' # currently we do not guarantee that the values are ordered correctly # for post data. ## assert response['form_as_list'] == [('foo', ['blub hehe']), ('blah', ['42'])] assert_request_test_environ(response['environ'], 'POST') # post requests with json data json = '{"foo": "bar", "blub": "blah"}' response = client.post('/?a=b', data=json, content_type='application/json') assert response['data'] == json assert response['args'] == MultiDict([('a', 'b')]) assert response['form'] == MultiDict()
class TestAccountServer(BaseTestCase): def setUp(self): super(TestAccountServer, self).setUp() _, _, self.redis_host, self.redis_port = self.get_service('redis') conf = {'redis_host': self.redis_host, 'redis_port': self.redis_port} self.account_id = 'test' self.app = Client(create_app(conf), BaseResponse) self._create_account() def _create_account(self): self.app.put('/v1.0/account/create', query_string={"id": self.account_id}) def test_status(self): resp = self.app.get('/status') self.assertEqual(resp.status_code, 200) status = json.loads(resp.data) self.assertTrue(status['account_count'] > 0) def test_account_info(self): resp = self.app.get('/v1.0/account/show', query_string={"id": self.account_id}) self.assertEqual(resp.status_code, 200) data = json.loads(resp.data) for f in ["ctime", "objects", "bytes", "containers", "metadata"]: self.assertTrue(f in data) self.assertTrue(data['objects'] >= 0) self.assertTrue(data['containers'] >= 0) self.assertTrue(data['bytes'] >= 0) def test_account_update(self): data = {'metadata': {'foo': 'bar'}, 'to_delete': []} data = json.dumps(data) resp = self.app.post('/v1.0/account/update', data=data, query_string={'id': self.account_id}) self.assertEqual(resp.status_code, 204) def test_account_container_update(self): data = {'name': 'foo', 'mtime': 0, 'objects': 0, 'bytes': 0} data = json.dumps(data) resp = self.app.post('/v1.0/account/container/update', data=data, query_string={'id': self.account_id}) self.assertEqual(resp.status_code, 200) def test_account_containers(self): args = {'id': self.account_id} resp = self.app.post('/v1.0/account/containers', query_string=args) self.assertEqual(resp.status_code, 200) data = json.loads(resp.data) for f in ["ctime", "objects", "bytes", "listing", "containers", "metadata"]: self.assertTrue(f in data) self.assertTrue(data['objects'] >= 0) self.assertTrue(data['containers'] >= 0) self.assertTrue(data['bytes'] >= 0)
def test_multi_value_submit(): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = {"field": ["val1", "val2"]} resp = c.post("/", data=data) strict_eq(resp.status_code, 200) c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({"field": ["val1", "val2"]}) resp = c.post("/", data=data) strict_eq(resp.status_code, 200)
def session(): client = Client(App(), Response) client.post('/session') body = client.get('/session').data.strip() assert body == '[1, 2, 3]' body = client.get('/session').data.strip() assert body == '[1, 2, 3, 4]' body = client.get('/session').data.strip() assert body == '[1, 2, 3, 4, 5]'
def test_multi_value_submit(self): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = {'field': ['val1', 'val2']} resp = c.post('/', data=data) assert resp.status_code == 200 c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({'field': ['val1', 'val2']}) resp = c.post('/', data=data) assert resp.status_code == 200
def test_create(self): client = Client(ApiApp(), response_wrapper=BaseResponse) resp = client.post("/address/", data=json.dumps({'name': 'bob', 'age': 34})) self.assertEqual(resp.status_code, 201) self.assertEqual(resp.headers['Location'], "http://localhost/100") resp = client.post("/address/", data={"test": datetime.datetime.now()}) self.assertEqual(resp.status_code, 400)
def test_get_partial_sql_raise(self): client = Client(WSGIDispatcher([PartialSQLApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({"name": "bob", "age": 34})) response = client.get("/address/?fields=wrongkey") self.assertEqual(response.status_code, 400) os.remove("test.db")
def test_multi_value_submit(): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = {'field': ['val1', 'val2']} resp = c.post('/', data=data) strict_eq(resp.status_code, 200) c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({'field': ['val1', 'val2']}) resp = c.post('/', data=data) strict_eq(resp.status_code, 200)
def test_base_pagination_count(self): client = Client(WSGIDispatcher([SQLiteApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({"name": "bob", "age": 34})) resp = client.get("/address/?count=2") self.assertEqual(len(json.loads(resp.data)), 2) os.remove("test.db")
def test_multi_value_submit(): c = Client(multi_value_post_app) data = {"field": ["val1", "val2"]} resp = c.post("/", data=data) assert resp.status_code == 200 c = Client(multi_value_post_app) data = MultiDict({"field": ["val1", "val2"]}) resp = c.post("/", data=data) assert resp.status_code == 200
def test_post_with_file_descriptor(tmpdir): c = Client(Response()) f = tmpdir.join("some-file.txt") f.write("foo") with open(f.strpath, mode="rt") as data: resp = c.post("/", data=data) assert resp.status_code == 200 with open(f.strpath, mode="rb") as data: resp = c.post("/", data=data) assert resp.status_code == 200
def test_post_with_file_descriptor(tmpdir): c = Client(Response(), response_wrapper=Response) f = tmpdir.join("some-file.txt") f.write("foo") with open(f.strpath, mode="rt") as data: resp = c.post("/", data=data) strict_eq(resp.status_code, 200) with open(f.strpath, mode="rb") as data: resp = c.post("/", data=data) strict_eq(resp.status_code, 200)
def test_post_with_file_descriptor(tmpdir): c = Client(Response(), response_wrapper=Response) f = tmpdir.join('some-file.txt') f.write('foo') with open(f.strpath, mode='rt') as data: resp = c.post('/', data=data) strict_eq(resp.status_code, 200) with open(f.strpath, mode='rb') as data: resp = c.post('/', data=data) strict_eq(resp.status_code, 200)
def test_base_request(self): client = Client(request_demo_app, RequestTestResponse) # get requests response = client.get('/?foo=bar&foo=hehe') self.assert_strict_equal( response['args'], MultiDict([('foo', u'bar'), ('foo', u'hehe')])) self.assert_strict_equal(response['args_as_list'], [('foo', [u'bar', u'hehe'])]) self.assert_strict_equal(response['form'], MultiDict()) self.assert_strict_equal(response['form_as_list'], []) self.assert_strict_equal(response['data'], b'') self.assert_environ(response['environ'], 'GET') # post requests with form data response = client.post( '/?blub=blah', data='foo=blub+hehe&blah=42', content_type='application/x-www-form-urlencoded') self.assert_strict_equal(response['args'], MultiDict([('blub', u'blah')])) self.assert_strict_equal(response['args_as_list'], [('blub', [u'blah'])]) self.assert_strict_equal( response['form'], MultiDict([('foo', u'blub hehe'), ('blah', u'42')])) self.assert_strict_equal(response['data'], b'') # currently we do not guarantee that the values are ordered correctly # for post data. ## self.assert_strict_equal(response['form_as_list'], [('foo', ['blub hehe']), ('blah', ['42'])]) self.assert_environ(response['environ'], 'POST') # patch requests with form data response = client.patch( '/?blub=blah', data='foo=blub+hehe&blah=42', content_type='application/x-www-form-urlencoded') self.assert_strict_equal(response['args'], MultiDict([('blub', u'blah')])) self.assert_strict_equal(response['args_as_list'], [('blub', [u'blah'])]) self.assert_strict_equal( response['form'], MultiDict([('foo', u'blub hehe'), ('blah', u'42')])) self.assert_strict_equal(response['data'], b'') self.assert_environ(response['environ'], 'PATCH') # post requests with json data json = b'{"foo": "bar", "blub": "blah"}' response = client.post('/?a=b', data=json, content_type='application/json') self.assert_strict_equal(response['data'], json) self.assert_strict_equal(response['args'], MultiDict([('a', u'b')])) self.assert_strict_equal(response['form'], MultiDict())
def testDeleteAndCreateByDifferentUsersButSamePostId(self): mallory = Client(self.app, Response) mallory.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Foo'})) mallory.delete('/id/1') bob = Client(self.app, Response) bob.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Bar'})) assert mallory.delete('/id/1').status_code == 403 assert bob.delete('/id/1').status_code == 200
def test_basic(self): resources = join(dirname(__file__), 'multipart') client = Client(form_data_consumer, Response) repository = [ ('firefox3-2png1txt', '---------------------------186454651713519341951581030105', [ (u'anchor.png', 'file1', 'image/png', 'file1.png'), (u'application_edit.png', 'file2', 'image/png', 'file2.png') ], u'example text'), ('firefox3-2pnglongtext', '---------------------------14904044739787191031754711748', [ (u'accept.png', 'file1', 'image/png', 'file1.png'), (u'add.png', 'file2', 'image/png', 'file2.png') ], u'--long text\r\n--with boundary\r\n--lookalikes--'), ('opera8-2png1txt', '----------zEO9jQKmLc2Cq88c23Dx19', [ (u'arrow_branch.png', 'file1', 'image/png', 'file1.png'), (u'award_star_bronze_1.png', 'file2', 'image/png', 'file2.png') ], u'blafasel öäü'), ('webkit3-2png1txt', '----WebKitFormBoundaryjdSFhcARk8fyGNy6', [ (u'gtk-apply.png', 'file1', 'image/png', 'file1.png'), (u'gtk-no.png', 'file2', 'image/png', 'file2.png') ], u'this is another text with ümläüts'), ('ie6-2png1txt', '---------------------------7d91b03a20128', [ (u'file1.png', 'file1', 'image/x-png', 'file1.png'), (u'file2.png', 'file2', 'image/x-png', 'file2.png') ], u'ie6 sucks :-/') ] for name, boundary, files, text in repository: folder = join(resources, name) data = get_contents(join(folder, 'request.txt')) for filename, field, content_type, fsname in files: response = client.post( '/?object=' + field, data=data, content_type='multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) lines = response.get_data().split(b'\n', 3) self.assert_strict_equal(lines[0], repr(filename).encode('ascii')) self.assert_strict_equal(lines[1], repr(field).encode('ascii')) self.assert_strict_equal(lines[2], repr(content_type).encode('ascii')) self.assert_strict_equal(lines[3], get_contents(join(folder, fsname))) response = client.post( '/?object=text', data=data, content_type='multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) self.assert_strict_equal(response.get_data(), repr(text).encode('utf-8'))
def test_base_pagination_offset(self): client = Client(WSGIDispatcher([SQLiteApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({"name": "bob", "age": 34})) resp = client.get("/address/?offset=2") self.assertEqual(json.loads(resp.data)["object_list"][0]['id'], 2)
def test_wsgi_app_make_response_arity_check(arity): class ExtendedWsgiApp(WsgiApp): def make_response(self, status_code, headers, content): return (status_code, headers, content, None)[:arity] wsgi_app = ExtendedWsgiApp(MusicServiceImpl()) client = Client(wsgi_app, Response) with raises(TypeError) as e: client.post('/?method=get_music_by_artist_name', data=json.dumps({'artist_name': u'damien rice'})) assert str(e.value).startswith('make_response() must return a triple of ' '(status_code, headers, content), not ')
def test_environ_builder_json(): @Request.application def app(request): assert request.content_type == "application/json" return Response(json.loads(request.get_data(as_text=True))["foo"]) c = Client(app) response = c.post("/", json={"foo": "bar"}) assert response.data == b"bar" with pytest.raises(TypeError): c.post("/", json={"foo": "bar"}, data={"baz": "qux"})
def test_environ_builder_json(): @Request.application def app(request): assert request.content_type == "application/json" return Response(json.loads(request.get_data(as_text=True))["foo"]) c = Client(app, Response) response = c.post("/", json={"foo": "bar"}) assert response.data == b"bar" with pytest.raises(TypeError): c.post("/", json={"foo": "bar"}, data={"baz": "qux"})
def test_multi_value_submit(self): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = { 'field': ['val1','val2'] } resp = c.post('/', data=data) self.assert_strict_equal(resp.status_code, 200) c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({ 'field': ['val1', 'val2'] }) resp = c.post('/', data=data) self.assert_strict_equal(resp.status_code, 200)
def test_get_partial_sql(self): client = Client(WSGIDispatcher([PartialSQLApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({"name": "bob", "age": 34})) resp = client.get("/address/?fields=age") # we only want "age". get_list add id, JsonResponse add ressource_uri self.assertEqual(len(json.loads(resp.data)["object_list"][0].keys()), 3) resp = client.get("/address/") self.assertEqual(resp.status_code, 200) os.remove("test.db")
def test_base_pagination_count(self): client = Client(WSGIDispatcher([SQLiteApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({ "name": "bob", "age": 34 })) resp = client.get("/address/?count=2") self.assertEqual(len(json.loads(resp.data)), 2)
def testDeleteWithMultipleReferences(self): """ [ comment 1 ] | --- [ comment 2, ref 1 ] | --- [ comment 3, ref 2 ] | --- [ comment 4, ref 2 ] [ comment 5 ] """ client = Client(self.app, Response) client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'First'})) client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Second', 'parent': 1})) client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Third 1', 'parent': 2})) client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': 'Third 2', 'parent': 2})) client.post('/new?uri=%2Fpath%2F', data=json.dumps({'text': '...'})) client.delete('/id/1') assert self.get('/?uri=%2Fpath%2F').status_code == 200 client.delete('/id/2') assert self.get('/?uri=%2Fpath%2F').status_code == 200 client.delete('/id/3') assert self.get('/?uri=%2Fpath%2F').status_code == 200 client.delete('/id/4') assert self.get('/?uri=%2Fpath%2F').status_code == 200 client.delete('/id/5') assert self.get('/?uri=%2Fpath%2F').status_code == 404
def test_talk_anonymization(client: Client, user: User, send_mail: Mock) -> None: user.site_admin = True db.session.add(user) talk = Talk( title="Alice's Identifying Talk", description="This talk is by Alice", outline="Alice!", take_aways="Alice's point.", length=25, ) talk.add_speaker(user, InvitationStatus.CONFIRMED) db.session.add(talk) db.session.commit() db.session.refresh(talk) client.get("/test-login/{}".format(user.user_id), follow_redirects=True) resp = client.get(f"/manage/anonymize/{talk.talk_id}") assert_html_response_contains(resp, "Alice's Identifying Talk") postdata = { "title": "(Speaker name redacted)'s Identifying Talk", "description": "This talk is by (Speaker name redacted)", "outline": "(Speaker name redacted)!", "take_aways": "(The speaker's) point.", "csrf_token": extract_csrf_from(resp), } client.post(f"/manage/anonymize/{talk.talk_id}", data=postdata) talk = Talk.query.get(talk.talk_id) assert talk.is_anonymized is True assert talk.has_anonymization_changes is True assert talk.anonymized_title == "(Speaker name redacted)'s Identifying Talk" assert talk.anonymized_description == "This talk is by (Speaker name redacted)" assert talk.anonymized_outline == "(Speaker name redacted)!" assert talk.anonymized_take_aways == "(The speaker's) point." assert talk.title == "Alice's Identifying Talk" assert talk.description == "This talk is by Alice" assert talk.outline == "Alice!" assert talk.take_aways == "Alice's point." send_mail.assert_called_once_with( to=[user.email], template="email/talk-anonymized", talk_id=talk.talk_id, title=talk.title, # the original title )
def test_base_pagination_offset(self): client = Client(WSGIDispatcher([SQLiteApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({ "name": "bob", "age": 34 })) resp = client.get("/address/?offset=2") self.assertEqual(json.loads(resp.data)["object_list"][0]['id'], 2) os.remove("test.db")
def test_create(self): client = Client(WSGIDispatcher([ApiApp]), response_wrapper=BaseResponse) resp = client.post("/address/", data=json.dumps({ 'name': 'bob', 'age': 34 })) self.assertEqual(resp.status_code, 201) self.assertEqual(resp.headers['Location'], "http://localhost/address/101/") resp = client.post("/address/", data={"test": datetime.datetime.now()}) self.assertEqual(resp.status_code, 400)
def test_method_rewrite_middleware(): def test_app(environ, start_response): start_response(b'200 OK', [(b'Content-Type', b'text/plain')]) return [environ['REQUEST_METHOD'].upper()] client = Client(MethodRewriteMiddleware(test_app), Response) response = client.get('/') assert response.data == b'GET' response = client.get('/?_method=PUT') assert response.data == b'GET' response = client.post('/') assert response.data == b'POST' response = client.post('/?_method=PUT') assert response.data == b'PUT' response = client.post('/?_method=DELETE') assert response.data == b'DELETE'
def test_get_partial_sql(self): client = Client(WSGIDispatcher([PartialSQLApp]), response_wrapper=BaseResponse) for i in range(100): client.post("/address/", data=json.dumps({"name": "bob", "age": 34})) resp = client.get("/address/?fields=age") # we only want "age". get_list add id, JsonResponse add ressource_uri self.assertEqual( len(json.loads(resp.data)["object_list"][0].keys()), 3) resp = client.get("/address/") self.assertEqual(resp.status_code, 200) os.remove("test.db")
def test_get_all(self, raven_mock, riemann_mock): with closing(TestDatabase()) as test_db: test_db.use_table('users') with unittest.mock.patch( 'microservice.components.get_psql') as db_mock: db_mock.return_value = test_db.connection json_rpc = { "jsonrpc": "2.0", "id": 1, "method": "get_users", "params": [] } client = Client(main.application, BaseResponse) response = client.post(data=json.dumps(json_rpc)) json_rpc_result = { "jsonrpc": "2.0", "result": ["user_A", "user_B", "user_C"], "id": 1 } json_rpc_response = response.get_data(as_text=True) self.assertDictEqual(json_rpc_result, json.loads(json_rpc_response))
def test_post_auth(self): """ Test a read only api. GET should be ok, POST and PUT should not """ from rest_api_framework.pagination import Pagination ressources = [{"id": "azerty"}] authentication = ApiKeyAuthentication( PythonListDataStore(ressources, ApiModel)) class ApiAppAuth(ApiApp): controller = { "list_verbs": ["GET"], "unique_verbs": ["GET"], "options": { "pagination": Pagination(20), "authentication": authentication, "authorization": ApiKeyAuthorization } } client = Client(WSGIDispatcher([ApiAppAuth]), response_wrapper=BaseResponse) resp = client.get("/address/1/?apikey=azerty") self.assertEqual(resp.status_code, 200) resp = client.post("/address/?apikey=azerty", data=json.dumps({ 'name': 'bob', 'age': 34 })) self.assertEqual(resp.status_code, 405)
class TestModeratedComments(unittest.TestCase): def setUp(self): fd, self.path = tempfile.mkstemp() conf = core.Config.load(None) conf.set("general", "dbpath", self.path) conf.set("moderation", "enabled", "true") conf.set("guard", "enabled", "off") class App(Isso, core.Mixin): pass self.app = App(conf) self.app.wsgi_app = FakeIP(self.app.wsgi_app) self.client = Client(self.app, Response) def tearDown(self): os.unlink(self.path) def testAddComment(self): rv = self.client.post('/new?uri=test', data=json.dumps({"text": "..."})) assert rv.status_code == 202 assert self.client.get('/id/1').status_code == 200 assert self.client.get('/?uri=test').status_code == 404 self.app.db.comments.activate(1) assert self.client.get('/?uri=test').status_code == 200
def test_message_action_on_test_message(client: Client, queue: MagicMock, slack_api_call: MagicMock): with get_mock_data( "interactive/message_action_on_test_message.json") as json_data: resp: Response = client.post( _ENDPOINT, data=json.loads(json_data.read()), content_type="application/x-www-form-urlencoded", ) assert resp.status_code == 200 assert resp.json["response_type"] == "in_channel" queue.assert_not_called() slack_api_call.assert_called_once_with( "dialog.open", dialog={ "title": "Echo dialog", "submit_label": "submit", "callback_id": "echo_dialog_1", "elements": [{ "type": "text", "label": "Echo this text", "name": "echo_element" }], }, trigger_id="TEST_TRIGGER_ID", )
def test_readable_error_when_null_returned_from_null_disallowed_method(caplog): """Even if the method implementation returns None (FYI Python functions return None when it lacks return statement so that service methods are prone to return None by mistake) the error message should be readable and helpful for debugging. """ expected_message = '''The return type of null-disallowed-method() method \ is not optional (i.e., no trailing question mark), but its server-side \ implementation has tried to return nothing (i.e., null, nil, None). \ It is an internal server error and should be fixed by server-side.''' app = WsgiApp(NullDisallowedMethodServiceImpl(None)) client = Client(app, Response) caplog.handler.records = [] # Clear log records response = client.post('/?method=null_disallowed_method', data=json.dumps({}), content_type='application/json') assert caplog.record_tuples and caplog.record_tuples[-1] == ( '{0}.null_disallowed_method'.format( typing._type_repr(NullDisallowedMethodServiceImpl)), logging.ERROR, '''None is an invalid return value for the return type of {0}.\ null_disallowed_method() method.'''.format( typing._type_repr(NullDisallowedMethodServiceImpl)), ) assert response.status_code == 500, response.get_data(as_text=True) actual = json.loads(response.get_data(as_text=True)) assert actual == { '_type': 'error', '_tag': 'internal_server_error', 'message': expected_message, }
def test_demo_plugin(): with_plugin_cfg = CertomancerConfig.from_file('tests/data/with-plugin.yml', 'tests/data') with_plugin_app = Animator(AnimatorArchStore(with_plugin_cfg.pki_archs), with_web_ui=False) client = Client(with_plugin_app, Response) # make the endpoint encrypt something endpoint = '/testing-ca/plugin/encrypt-echo/test-endpoint' payload = b'test test test' response = client.post(endpoint, data=payload) # decrypt it env_data = cms.ContentInfo.load(response.data)['content'] arch = with_plugin_cfg.get_pki_arch(ArchLabel('testing-ca')) key = arch.key_set.get_private_key(KeyLabel('signer1')) ktri = env_data['recipient_infos'][0].chosen encrypted_key = ktri['encrypted_key'].native decrypted_key = asymmetric.rsa_pkcs1v15_decrypt( asymmetric.load_private_key(key.dump()), encrypted_key) eci = env_data['encrypted_content_info'] cea = eci['content_encryption_algorithm'] assert cea['algorithm'].native == 'aes256_cbc' iv = cea['parameters'].native encrypted_content_bytes = eci['encrypted_content'].native decrypted_payload = symmetric.aes_cbc_pkcs7_decrypt( decrypted_key, encrypted_content_bytes, iv) assert decrypted_payload == payload
def test_inviting_a_speaker_adds_the_speaker(client: Client, user: User, send_mail: Mock) -> None: talk = Talk(title="My Talk", length=25) talk.add_speaker(user, InvitationStatus.CONFIRMED) db.session.add(talk) alice = User(email="*****@*****.**", fullname="Alice Example") db.session.add(alice) db.session.commit() # reload from DB to avoid "not attached to session" error talk = Talk.query.filter_by(title="My Talk").one() client.get("/test-login/{}".format(user.user_id)) resp = client.get("/talks/{}/speakers".format(talk.talk_id)) assert_html_response(resp) csrf_token = extract_csrf_from(resp) postdata = {"email": "*****@*****.**", "csrf_token": csrf_token} resp = client.post("/talks/{}/speakers".format(talk.talk_id), data=postdata, follow_redirects=True) assert_html_response_contains(resp, "Alice Example") send_mail.assert_called_once_with(to=["*****@*****.**"], template="email/co-presenter-invite", talk=ANY) _, kwargs = send_mail.call_args assert kwargs["talk"].talk_id == talk.talk_id assert_talk_has_speakers(talk, ["*****@*****.**"])
def test_inviting_a_speaker_emails_the_speaker(client: Client, user: User, send_mail: Mock) -> None: talk = Talk(title="My Talk", length=25) talk.add_speaker(user, InvitationStatus.CONFIRMED) db.session.add(talk) db.session.commit() assert User.query.filter_by( email="*****@*****.**").one_or_none() is None # reload from DB to avoid "not attached to session" error talk = Talk.query.filter_by(title="My Talk").one() client.get("/test-login/{}".format(user.user_id)) resp = client.get("/talks/{}/speakers".format(talk.talk_id)) assert_html_response(resp) csrf_token = extract_csrf_from(resp) # this speaker doesn't exist, but we should still send the email postdata = {"email": "*****@*****.**", "csrf_token": csrf_token} resp = client.post("/talks/{}/speakers".format(talk.talk_id), data=postdata, follow_redirects=True) assert_html_response_contains(resp, "*****@*****.**") send_mail.assert_called_once_with(to=["*****@*****.**"], template="email/co-presenter-invite", talk=ANY) _, kwargs = send_mail.call_args assert kwargs["talk"].talk_id == talk.talk_id # this also implies a user with that email was created assert_talk_has_speakers(talk, ["*****@*****.**"])
def test_follow_redirect_body(code, keep): @Request.application def app(request): if request.url == "http://localhost/some/redirect/": assert request.method == "POST" if keep else "GET" assert request.headers["X-Foo"] == "bar" if keep: assert request.form["foo"] == "bar" else: assert not request.form return Response("current url: %s" % request.url) return redirect("http://localhost/some/redirect/", code=code) c = Client(app, response_wrapper=BaseResponse) response = c.post( "/", follow_redirects=True, data={"foo": "bar"}, headers={"X-Foo": "bar"}, ) assert response.status_code == 200 assert response.data == b"current url: http://localhost/some/redirect/"