def test_urlLookup200ResponseAllow(): with Client(app) as client: app.log.info( "Printing response body from test test_urlLookup200ResponseAllow") response = client.http.get('/urlLookUp?url=http://www.google.com/news') app.log.info(response.body) assert response.status_code == 200
def test_post_add_transactions_invalid_data_types3(): with Client(app) as client: request_body = [ { "payer": "DANNON", "points": -200, "timestamp": 20201101 }, { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z", }, { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }, ] response = client.http.post( "/transactions", headers={"content-type": "application/json"}, body=json.dumps(request_body), ) assert response.status_code == 400 assert response.json_body == { "Code": "BadRequestError", "Message": "BadRequestError: Transaction records must contain valid data types: payer (string), points (integer), timestamp (string as YYYY-MM-DDT00:00:00Z)", }
def test_urlLookupWithMalformedURI(): with Client(app) as client: app.log.info( "Printing response body from test_urlLookupWithMalformedURI") response = client.http.get('/urlLookUp?url=www.google.co.in/news') app.log.info(response.body) assert response.status_code == 400
def test_graphiql_mutation(): with Client(app) as client: headers = {"Accept": "application/json", "Content-Type": "application/json"} query = {"query": """mutation EchoMutation { echo(stringToEcho: "mark")} """} response = client.http.post("/graphql", headers=headers, body=json.dumps(query)) assert response.status_code == HTTPStatus.OK assert "mark" == response.json_body["data"]["echo"]
def test_one_light_command(): lightId = str(uuid.uuid4()) topic = '{}/command'.format(lightId) iot_data_stub = Stubber(app.iot_data) iot_data_stub.add_response( 'publish', expected_params={ 'topic': topic, 'qos': 1, 'payload': json.dumps({ "power": True }).encode('utf-8') }, service_response={} ) with iot_data_stub: with Client(app.app) as client: response = client.http.post('/light/{}/command/on'.format(lightId)) assert response.json_body == { "id": lightId, "topic": "{}/command".format(lightId), "command": { "power": True } } # 同じテストで、対応していないコマンドがちゃんと400に確認する response = client.http.post('/light/{}/command/TESTME'.format(lightId)) assert response.status_code == 400
def test_audit_controller(): with Client(app) as client: response = client.http.get('/auditcontroller') assert response.json_body == {'audit': 'controller'} response = client.http.get('/api/audit/user/randomid', headers=headers) assert response.status_code == 400 response = client.http.get('/api/audit/session/randomid', headers=headers) assert response.status_code == 400 response = client.http.post('/api/audit/session', body=json.dumps({}), headers=headers) assert response.status_code == 422 # response = client.http.post('/api/audit/session', body=json.dumps({"status":"COMPLETED"}), headers=headers) # assert response.status_code == 200 # assert response.json_body == {"message": "updated"} # response = client.http.post('/api/audit/user', body=json.dumps({}), headers=headers) assert response.status_code == 422
def test_post_add_transactions_invalid_record_keys2(): with Client(app) as client: request_body = [ { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }, { "payer": "DANNON", "points": 300 }, ] response = client.http.post( "/transactions", headers={"content-type": "application/json"}, body=json.dumps(request_body), ) assert response.status_code == 400 assert response.json_body == { "Code": "BadRequestError", "Message": "BadRequestError: Transaction records must only contain payer, points, and timestamp keys", }
def test_can_mix_pure_lambda_and_event_handlers(): app = Chalice('lambda-only') @app.on_sns_message(topic='mytopic') def foo(event): return {'message': event.message, 'subject': event.subject} @app.lambda_function() def bar(event, context): return {'event': event} @app.route('/') def index(): return {'hello': 'restapi'} with Client(app) as client: assert client.lambda_.invoke( 'foo', client.events.generate_sns_event(message='my message', subject='hello')).payload == { 'message': 'my message', 'subject': 'hello' } assert client.lambda_.invoke('bar', { 'hello': 'world' }).payload == { 'event': { 'hello': 'world' } } assert client.http.get('/').json_body == {'hello': 'restapi'}
def test_create_folder(): with Client(app) as client: response = client.http.post( '/create-directory', headers={'Content-Type': 'application/json'}, body=json.dumps({'platform_name': 'test-platform'})) assert response.status_code == 200 assert response.json_body[ 'message'] == 'Platform folder created successfully' assert response.json_body['status'] == 'success' print(response.json_body['data']) assert response.json_body['data'].startswith('test-platform') assert response.json_body['data'].endswith('-images') assert len(response.json_body['data']) > 30 # def test_generate_folder(): # with Client(app, stage_name='dev') as client: # response = client.http.post('/uploads/generate-link', headers={ 'Content-Type': 'application/json' }, body= json.dumps({'platform_name': 'test-platform', 'filename': 'image1.jpg', 'content_type':'jpg'})) # print(response.status_code) # print(response.body) # assert response.status_code == 200 # assert response.json_body['message'] == 'Upload policy generated successfully' # assert response.json_body['status'] == 'success' # assert response.json_body['data']['fields']['Content-Type'] == 'jpg' # def test_create_folder(): # with Client(app) as client: # response = client.http.get('/create-directory') # assert response.json_body == {'hello': 'world'}
def test_can_access_env_vars_in_rest_api(sample_app, tmpdir): fake_config = { "version": "2.0", "app_name": "testenv", "stages": { "prod": { "api_gateway_stage": "api", "environment_variables": { "MY_ENV_VAR": "TOP LEVEL" }, } } } tmpdir.mkdir('.chalice').join('config.json').write( json.dumps(fake_config).encode('utf-8')) project_dir = str(tmpdir) os.environ.pop('MY_ENV_VAR', None) @sample_app.route('/env') def env_vars(): return {'value': os.environ.get('MY_ENV_VAR')} with Client(sample_app, project_dir=project_dir, stage_name='prod') as client: response = client.http.get('/env') assert response.json_body == {'value': 'TOP LEVEL'}
def test_challenge_actual(day, challenge, expected): input = load_test_data_relative(f'actual_inputs/day{day}.txt') with Client(app) as client: response = client.http.post(f'/day/{day}/challenge/{challenge}', body=input) answer = response.json_body['answer'] assert answer == expected
def test_list_books_timeout(mock_storage): mock_storage.get_books = MagicMock( side_effect=DataServiceNotReadyException('Timeout test')) with Client(app.app) as client: response = client.http.get('/books') assert response.status_code == 408
def test_graphiql_query_with_malformed_json_gives_http_ok_and_bad_request_message(): with Client(app) as client: headers = {"Accept": "application/json", "Content-Type": "application/json"} response = client.http.post("/graphql", headers=headers, body="{invalidjson") assert response.status_code == HTTPStatus.OK assert response_is_of_error_type(response)
def test_urlLookupWithOutQueryParameters(): with Client(app) as client: app.log.info( "Printing response body from test_urlLookupWithOutQueryParameters") response = client.http.get('/urlLookUp') app.log.info(response.body) assert response.status_code == 400
def test_post_add_transactions_success_multiple(): with Client(app) as client: request_body = [ { "payer": "UNILEVER", "points": 200, "timestamp": "2020-10-31T11:00:00Z" }, { "payer": "DANNON", "points": -200, "timestamp": "2020-10-31T15:00:00Z" }, { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z", }, { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }, ] response = client.http.post( "/transactions", headers={"content-type": "application/json"}, body=json.dumps(request_body), ) assert response.status_code == 200 assert response.json_body == [ { "payer": "DANNON", "points": 1000, "timestamp": "2020-11-02T14:00:00Z" }, { "payer": "UNILEVER", "points": 200, "timestamp": "2020-10-31T11:00:00Z" }, { "payer": "DANNON", "points": -200, "timestamp": "2020-10-31T15:00:00Z" }, { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z", }, { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }, ]
def test_add_patron(mock_storage): with Client(app.app) as client: patron = {'Patrons.FirstName': 'Pierre'} response = client.http.post( '/patrons', headers={'content-type': 'application/json'}, body=json.dumps(patron)) mock_storage.add_patron.assert_called_with(patron) assert response.json_body == {'Patrons.PatronID': 'patron1'}
def test_can_provide_http_headers(sample_app): @sample_app.route('/header') def headers(): return {'value': sample_app.current_request.headers['x-my-header']} with Client(sample_app) as client: response = client.http.get('/header', headers={'x-my-header': 'foo'}) assert response.json_body == {'value': 'foo'}
def test_can_pass_http_url(sample_app): @sample_app.route('/{name}') def hello(name): return {'hello': name} with Client(sample_app) as client: response = client.http.get('/james') assert response.json_body == {'hello': 'james'}
def test_malformed_unparsable_json_query_returns_error(): with Client(app) as client: headers = {"Accept": "application/json", "Content-Type": "application/json"} # The query key in the json dict is missing query = "I am a malformed query" response = client.http.post("/graphql", headers=headers, body=json.dumps(query)) assert response_is_of_error_type(response)
def test_add_book(mock_storage): with Client(app.app) as client: test_book = {'Books.Title': 'test-book'} response = client.http.post( '/books', headers={'content-type': 'application/json'}, body=json.dumps(test_book)) mock_storage.add_book.assert_called_with(test_book) assert response.json_body == { 'Authors.AuthorID': 'author1', 'Books.BookID': 'book1'}
def test_noauth_hello_world(): with Client(app) as client: response = client.http.get('/noauth/hello/world') # app.log.info(response.json_body) assert response.status_code == 200 assert response.json_body[ 'hello'] == 'world' # response.json_body returns a `dict` assert json.loads( response.body)['hello'] == 'world' # response.body returns bytes
def test_chalice_async_http(moto_patch, region, bucket_name): session = aioboto3.Session() app.aioboto3 = session with Client(app) as client: response = client.http.get('/hello/myname') assert response.status_code == 200 assert response.json_body['hello'] == 'myname'
def test_graphiql_query(): with Client(app) as client: headers = {"Accept": "application/json", "Content-Type": "application/json"} query = {"query": "query GreetMe {greetings}"} response = client.http.post("/graphql", headers=headers, body=json.dumps(query)) assert response.status_code == HTTPStatus.OK assert not response_is_of_error_type(response) assert "hello" == response.json_body["data"]["greetings"]
def test_urlLookupWithOutURLQueryParameter(): with Client(app) as client: app.log.info( "Printing response body from test_urlLookupWithOutURLQueryParameter" ) response = client.http.get( '/urlLookUp?query1=http://www.google.co.in/news') app.log.info(response.body) assert response.status_code == 400
def test_can_invoke_pure_lambda_function(): app = Chalice('lambda-only') @app.lambda_function() def foo(event, context): return {'event': event} with Client(app) as client: response = client.lambda_.invoke('foo', {'hello': 'world'}) assert response.payload == {'event': {'hello': 'world'}}
def make_request(body): with Client(app) as client: response = client.http.post( '/webhook', headers={ 'Content-Type': 'application/json', }, body=json.dumps(body), ) return response.json_body
def test_can_return_error_message(sample_app): @sample_app.route('/error') def error(): raise BadRequestError("bad request") with Client(sample_app) as client: response = client.http.get('/error') assert response.status_code == 400 assert response.json_body['Code'] == 'BadRequestError' assert 'bad request' in response.json_body['Message']
def test_lambda_function_with_custom_name(): app = Chalice('lambda-only') @app.lambda_function(name='my-custom-name') def foo(event, context): return {'event': event} with Client(app) as client: response = client.lambda_.invoke('my-custom-name', {'hello': 'world'}) assert response.payload == {'event': {'hello': 'world'}}
def test_dont_generate_link(): with Client(app) as client: response = client.http.post( '/uploads/generate-link', headers={'Content-Type': 'application/json'}, body=json.dumps({'unkown_key': 'what_not'})) assert response.status_code == 400 assert response.json_body[ 'Message'] == 'BadRequestError: You must send a filename ,content_type ,platform_name in your request body' assert response.json_body['Code'] == 'BadRequestError'
def test_payload_not_required_for_invoke(): app = Chalice('lambda-only') @app.lambda_function() def foo(event, context): return {'event': event} with Client(app) as client: response = client.lambda_.invoke('foo') assert response.payload == {'event': {}}