def test_get_all_responses(self): mock = CollectorResponsesBulkListMock(total=5, collector_ids=self.collector_ids) with HTTMock(mock.bulk): responses_list = self.bulk_collector.responses() expect(responses_list).to(have_length(5)) expect(responses_list[0]).to( have_keys('analyze_url', 'response_status', 'date_modified')) expect(responses_list[0]).to( have_keys('id', 'collector_id', 'recipient_id', 'survey_id'))
def test_disabled_when_configured(self): spy = MasterSpy(EndlessFake()) self.context.inject(requests, spy) self.context.set_env(HTTPS_VERIFY_CERTS="FAlSe") HttpClient().get("http://spam") args, kwargs = spy.last_call_to("get") expect(kwargs).to(have_keys(verify=False))
def _(): upload_file_path = './tests/job-descriptions/testfile.docx' # expected_response = { # "pipelineID": "randnums", # "timestamp": "time", # "jobDescriptionID": "jobid", # "convertedLength": 12345 # } # # Stubs # utils.get_req_identity = lambda x : uuid.uuid4() # utils.create_pipeline_id = lambda x : 'pipeline' # utils.get_time_stamp = lambda : 'time' # utils.get_job_description_id = lambda : 'jobid' # utils.get_length_of_job_description = lambda x : 12345 resp = application.post('/upload-job-description-file', upload_files=[('file', upload_file_path)]) # expect({'bar': 0, 'baz': 1}).to(have_key('bar', None)) # expect({'bar': 0, 'baz': 1}).to(have_keys(bar=0, baz=1)) # expect({'bar': 0, 'baz': 1}).not_to(have_keys({'foo': 0, 'foobar': 1})) # print(resp) expect(resp.status_int).to(equal(200)) expect(resp.content_type).to(equal('application/json')) expect(resp.json).to( have_keys('pipelineID', 'convertedLength', 'fileText', 'timestamp'))
async def test_delete_handler(self, *args): with patch.object(Validate, 'validate_object_id') as validate_object_id_mock: with patch.object(DB, 'get_redis') as get_redis_mock: with patch.object(EndpointCacher, 'delete') as remove_mock: with patch.object(Error, 'handle') as handle_mock: mock_req = MagicMock() mock_req.rel_url.query.get = MagicMock() mock_req.rel_url.query.get.return_value = 'some-value' mock_ctx = {'id': 'some-value'} await delete_handler(mock_req) remove_mock.assert_called() get_redis_mock.assert_called_with(mock_req) validate_object_id_mock.assert_called_with( mock_ctx['id']) expect(remove_mock.call_args[0][0]).to( equal(mock_ctx['id'])) mock_err = Exception() remove_mock.side_effect = mock_err await delete_handler(mock_req) handle_mock.assert_called_with(mock_err) try: mock_req.rel_url.query.get.return_value = None await delete_handler(mock_req) except Exception as err: handle_mock.assert_called_with(err) expect(err.args).to( have_keys('message', 'status_code'))
def test_request_validator_schema(): expect(request_validator_schema).to( have_keys('_id', 'service_id', 'method', 'schema', 'password_field', 'password_policy', 'err_response_code')) for prop in ['_id', 'service_id', 'method', 'password_field']: expect(request_validator_schema[prop]['type']).to(equal('string')) for prop in ['schema', 'password_policy']: expect(request_validator_schema[prop]['type']).to(equal('dict')) for prop in ['err_response_code']: expect(request_validator_schema[prop]['type']).to(equal('integer')) for prop in [ 'length', 'upper_case_count', 'numbers_count', 'specials_count', 'non_letters_count', ]: expect(request_validator_schema['password_policy']['schema'][prop] ['type']).to(equal('integer')) for prop in ['strength']: expect(request_validator_schema['password_policy']['schema'][prop] ['type']).to(equal('float'))
def test_repeats_initial_request_headers(self): headers = {"spams": 22, "eggs": 7, "the-spanish-inquisition": "fang"} self.queue_response(status_code=301, location="http://ratses") self.queue_response(status_code=200) HttpClient().get("something", headers=headers) expect(self.spies.get.kwargs_from_last_call()).to( have_keys(headers=headers))
async def test_create(self, *args): with asynctest.patch.object(Service, 'check_exists') as check_exists_mock: with asynctest.patch.object(EndpointCacher, '_set_indexes') as _set_indexes_mock: mock_ctx = { 'service_id': 'some-id', 'response_codes': [200], 'timeout': 2 } mock_endpoint_cacher_db = MagicMock() mock_service_db = MagicMock() mock_sadd = CoroutineMock() mock_hmset_dict = CoroutineMock() mock_endpoint_cacher_db.sadd = mock_sadd mock_endpoint_cacher_db.hmset_dict = mock_hmset_dict await EndpointCacher.create(mock_ctx, mock_endpoint_cacher_db, mock_service_db) check_exists_mock.assert_awaited() _set_indexes_mock.assert_called() expect(mock_hmset_dict.await_args[0][1]).to( have_keys('service_id', 'response_codes', '_id')) expect(mock_hmset_dict.await_args[0][1]['service_id']).to( equal(mock_ctx['service_id'])) expect(mock_sadd.await_count).to(equal(2))
def test_successful_request_to_user_me_endpoint(self): with HTTMock(self.mocks.me): current_user = self.users.me() expect(current_user).to(have_keys('id', 'username', 'email')) expect(current_user["account_type"]).to( equal("enterprise_platinum"))
def test_sends_kwargs_as_variables(self, expected_variables): self.graph_client.execute("a not important operation", **expected_variables) formatted_data = json.loads( self.post_spy.kwargs_from_last_call()["data"]) expect(formatted_data).to(have_keys(variables=expected_variables))
async def test_enforce_policy(self, *args): with patch.object(PasswordPolicy, 'from_names') as from_names_mock: password_policy_mock = MagicMock() password_policy_mock.test.return_value = [] from_names_mock.return_value = password_policy_mock mock_password = '******' mock_policy = { 'length': 'some-value', 'upper_case_count': 'some-value', 'numbers_count': 'some-value', 'specials_count': 'some-value', 'non_letters_count': 'some-value' } await RequestValidator.enforce_policy(mock_password, mock_policy) from_names_mock.assert_called_with( length=mock_policy['length'], uppercase=mock_policy['upper_case_count'], numbers=mock_policy['numbers_count'], special=mock_policy['specials_count'], nonletters=mock_policy['non_letters_count'], ) password_policy_mock.test.assert_called_with(mock_password) try: password_policy_mock.test.return_value = [None] await RequestValidator.enforce_policy(mock_password, mock_policy) except Exception as err: expect(err.args[0]).to(have_keys('message', 'status_code'))
def test_parse_response_returns_a_dict_with_correct_keys(self): with HTTMock(UsersResponseMocks().me): response = self.session.get(URL_USER_ME) data = self.manager.parse_response(response) expect(data).to(have_keys('id', 'username', 'email')) expect(data["id"]).to(be_a( six.text_type)) # IDs from SurveyMonkey are strings
def test_health_check_endpoint(self, mocker, database, test_client): mocker.patch( 'brighthive_authlib.providers.AuthZeroProvider.validate_token', return_value=True) headers = {'Authorization': 'Bearer 1qaz2wsx3edc'} response = test_client.get('/health', headers=headers) expect(response.status_code).to(be(200)) expect(response.json).to( have_keys('api_name', 'current_time', 'current_api_version', 'api_status'))
def test_single_collector_returned_for_id(self): mock = CollectorGetMock() with HTTMock(mock.by_id): collector = self.collector.by_id(collector_id=self.collector_id) expect(collector).to(be_a(dict)) expect(collector).to(have_keys("id", "status", "type", "url"))
def test_rate_limit_entry_schema(): expect(rate_limit_entry_schema).to( have_keys('_id', 'rule_id', 'host', 'count')) for prop in ['_id', 'rule_id', 'host']: expect(rate_limit_entry_schema[prop]['type']).to(equal('string')) for prop in ['count']: expect(rate_limit_entry_schema[prop]['type']).to(equal('integer'))
def test_sends_operation_through_http_client(self, expected_operation): graph_client = GraphqlClient(http_client=self.fake_http_client, url="a real url") graph_client.execute(expected_operation) formatted_data = json.loads( self.post_spy.kwargs_from_last_call()["data"]) expect(formatted_data).to(have_keys(query=expected_operation))
def test_sends_operation_to_correct_url_through_http_client( self, expected_url): graph_client = GraphqlClient(http_client=self.fake_http_client, url=expected_url) graph_client.execute("a not important operation") expect(self.post_spy.kwargs_from_last_call()).to( have_keys(url=expected_url))
def test_event_schema(): expect(event_schema).to( have_keys('_id', 'circuit_breaker_id', 'target', 'body', 'headers')) for prop in ['_id', 'circuit_breaker_id', 'target']: expect(event_schema[prop]['type']).to(equal('string')) for prop in ['body', 'headers']: expect(event_schema[prop]['type']).to(equal('dict'))
def test_get_single_response_by_id(self): with HTTMock(self.mock.by_id): response = self.response.by_id( survey_id=self.survey_id, response_id=self.response_id ) expect(response).to(be_a(dict)) expect(response).to(have_keys('id', 'response_status', 'pages'))
def test_get_big_list_of_all_surveys(self): with HTTMock(self.mocks.surveys): survey_big_list = self.surveys.surveys() expect(survey_big_list).to(have_length(125)) for survey in survey_big_list: expect(survey).to(have_keys('href', 'id', 'title')) expect(survey["href"]).to(end_with(survey['id']))
def test_list_of_collectors_returned_for_valid_survey(self): collector = Collector(connection=self.connection) mock = CollectorsListMock(total=2, survey_id=self.survey_id) with HTTMock(mock.list): collector_list = collector.list(survey_id=self.survey_id) expect(collector_list).to(have_length(2)) expect(collector_list[0]).to(have_keys('href', 'id', 'name'))
def test_object_id(self, *args): try: with patch('bson.ObjectId.is_valid') as is_valid_mock: is_valid_mock.return_value = False mock_id = 'some-value' Validate.validate_object_id(mock_id) except Exception as err: expect(err.args[0]).to(be_a(object)) expect(err.args[0]).to(have_keys('message', 'status_code'))
def test_repeats_arbitrary_keyword_arguments(self): planted = { "slogan": "Nobody rejects the Spinach Imposition!", "weapons": ["surprise", "fear", "ruthless efficiency"], } self.queue_response(status_code=301, location="http://ratses") self.queue_response(status_code=200) HttpClient().get("something", **planted) expect(self.spies.get.kwargs_from_last_call()).to(have_keys(**planted))
async def test_check_exists(self, *args): with asynctest.patch.object(Service, 'get_by_id') as get_mock: try: mock_id = 'some-value' mock_db = MagicMock() get_mock.return_value = None await Service.check_exists(mock_id, mock_db) except Exception as err: get_mock.assert_called() expect(err.args[0]).to(have_keys('message', 'status_code'))
def test_weblink_collector_created_with_no_optional_config_values(self): config = WeblinkConfig() collector = Collector(connection=self.connection, config=config) with HTTMock(CollectorMock(config).create): new_collector = collector.create(survey_id=self.survey_id) expect(new_collector).to(be_weblink) expect(new_collector).to(be_new) expect(new_collector).to(have_keys('id', 'name', 'url'))
def test_enabled_in_session_by_default(self): requests_stub = EndlessFake() self.context.inject(requests, requests_stub) spy = MasterSpy(EndlessFake()) requests_stub.Session = lambda *a, **k: spy client = HttpClient() client.enable_cookies() client.get("http://spam") args, kwargs = spy.last_call_to("send") expect(kwargs).to(have_keys(verify=True))
def test_disabled_in_session_when_configured(self): self.context.set_env(HTTPS_VERIFY_CERTS="FAlSe") requests_stub = EndlessFake() self.context.inject(requests, requests_stub) spy = MasterSpy(EndlessFake()) requests_stub.Session = lambda *a, **k: spy client = HttpClient() client.enable_cookies() client.get("http://spam") args, kwargs = spy.last_call_to("send") expect(kwargs).to(have_keys(verify=False))
def test_endpoint_cache_schema(): expect(endpoint_cache_schema).to( have_keys('_id', 'service_id', 'timeout', 'response_codes')) for prop in ['_id', 'service_id']: expect(endpoint_cache_schema[prop]['type']).to(equal('string')) for prop in ['timeout']: expect(endpoint_cache_schema[prop]['type']).to(equal('integer')) for prop in ['response_codes']: expect(endpoint_cache_schema[prop]['type']).to(equal('list'))
def test_scheme(self, *args): mock_schema_errors = {} try: mock_ctx = {} mock_schema = MagicMock() mock_schema.errors = mock_schema_errors Validate.validate_schema(mock_ctx, mock_schema) mock_schema.validate.assert_called_with(mock_ctx) except Exception as err: expect(err.args[0]).to( have_keys('message', 'status_code', 'errors')) expect(err.args[0]['errors']).to(equal(mock_schema_errors))
def _(): request_body = {"pipelineID": str(my_pipeline_id)} expected_body = { "pipelineID": str(my_pipeline_id), # "preview": { # "hello": "world" # } } resp = application.post_json('/preview', request_body) expect(resp.status_int).to(equal(200)) expect(resp.json).to(have_keys(expected_body))
async def test_generate_token(self, *args): with asynctest.patch.object(Admin, 'update') as update_mock: with asynctest.patch.object(Token, 'generate') as generate_mock: mock_db = {} mock_token = 'some-token' mock_payload = {'_id': 'some-id', 'username': '******'} generate_mock.return_value = mock_token await Admin.generate_token(mock_payload, mock_db) expect(generate_mock.call_args[0][0]).to( have_keys('_id', 'username', 'timestamp')) update_mock.assert_called()