def assert_no_request(self, path, method='GET', query=None, body=None, json=None): try: results = self.requests_matching(path, method) except AssertionError: return if query: query_matcher = has_entry('query', has_entries(query)) else: query_matcher = anything() if body: body_matcher = has_entry('body', equal_to(body)) else: body_matcher = anything() if json: json_matcher = has_entry('json', equal_to(json)) else: json_matcher = anything() assert_that( results, not (has_item(all_of(query_matcher, body_matcher, json_matcher), pformat(results))), )
def test_collect_works(self): obs = position.collect( from_iterable([ IbApiMessage(type=IbApiMessageType.POSITION, payload=('DU123', test_utils.appl_contract(), 100.0, 123.45)), IbApiMessage(type=IbApiMessageType.POSITION, payload=('DU123', test_utils.ibkr_contract(), 1.0, 45.6789)), ])) # TODO: for now, Contract, etc cannot be tested naively as they do not have __eq__ defined. assert_that( obs.run(), contains_exactly( all_of( has_property('account', equal_to('DU123')), has_property('contract', anything()), has_property('size', equal_to(100.0)), has_property('average_cost', equal_to(123.45)), ), all_of( has_property('account', equal_to('DU123')), has_property('contract', anything()), has_property('size', equal_to(1.0)), has_property('average_cost', equal_to(45.6789)), )))
def has_attachment(attach_type=None, name=None): return has_entry( 'attachments', has_item( all_of( has_entry('source', anything()), has_entry('type', attach_type) if attach_type else anything(), has_entry('name', name) if name else anything())))
def has_attachment(attach_type=None, name=None): return has_entry('attachments', has_item( all_of( has_entry('source', anything()), has_entry('type', attach_type) if attach_type else anything(), has_entry('name', name) if name else anything() ) ))
def calls_are_bridged(): host_call1 = self.calld_client.calls.get_call(host_call1_id) assert_that(host_call1, has_entries({ 'talking_to': has_entries({ participant1_call_id: anything(), participant2_call_id: anything(), }) })) assert_that(host_call2_id, self.c.is_hungup())
def has_label(test_name, label_name=anything(), label_value=anything()): return has_property('{}test-cases', has_property('test-case', has_item( has_properties({'name': equal_to(test_name), 'labels': has_property('label', has_item( has_property('attrib', equal_to( {'name': label_name, 'value': label_value}))))}))))
def test_load_dataset_forced_fallback(self, api_client, dw, dataset_key): when(api_client).download_datapackage(equal_to(dataset_key), anything()).raises(RestApiError) # Forced update dataset = dw.load_dataset(dataset_key, force_update=True) assert_that( api_client.download_datapackage, called().times(1).with_args(equal_to(dataset_key), anything())) assert_that(dataset.raw_data, has_length(3))
def test_processor_init_3x3_operands_in_3x3_processors(self): # given nprocs = 9 procs = [Spy(Cannon.Processor) for i in range(nprocs)] frontend = FrontendI(procs) # when frontend.init_processors() # then assert_that(procs[0].init, called().with_args(0, 3, procs[6], procs[2], anything())) assert_that(procs[1].init, called().with_args(1, 3, procs[7], procs[0], anything())) assert_that(procs[2].init, called().with_args(2, 3, procs[8], procs[1], anything())) assert_that(procs[3].init, called().with_args(3, 3, procs[0], procs[5], anything())) assert_that(procs[4].init, called().with_args(4, 3, procs[1], procs[3], anything())) assert_that(procs[5].init, called().with_args(5, 3, procs[2], procs[4], anything())) assert_that(procs[6].init, called().with_args(6, 3, procs[3], procs[8], anything())) assert_that(procs[7].init, called().with_args(7, 3, procs[4], procs[6], anything())) assert_that(procs[8].init, called().with_args(8, 3, procs[5], procs[7], anything()))
def api_client(self, test_datapackages_path): with Spy(RestApiClient) as client: def download_datapackage(_, dest_dir): shutil.copytree( path.join(test_datapackages_path, 'the-simpsons-by-the-data'), dest_dir) return path.join(dest_dir, 'datapackage.json') client.download_datapackage( anything(), anything()).delegates(download_datapackage) return client
def test_2x2_processors_2x2_operands(self): ''' initial shift: 1 2 1 2 5 6 5 8 3 4 < 4 3 7 8 7 6 ^ processors and collectors are distributed objects ''' P = [self.broker.add_servant(ProcessorI(), Cannon.ProcessorPrx) for i in range(4)] collector_servant = Mimic(Spy, Cannon.Collector) collector = self.broker.add_servant(collector_servant, Cannon.CollectorPrx) # by-hand shifted submatrices A0 = M1(1) A1 = M1(2) A2 = M1(4) A3 = M1(3) B0 = M1(5) B1 = M1(8) B2 = M1(7) B3 = M1(6) # by-hand processor initialization P[0].init(0, 2, P[2], P[1], collector) P[1].init(1, 2, P[3], P[0], collector) P[2].init(2, 2, P[0], P[3], collector) P[3].init(3, 2, P[1], P[2], collector) # by-hand processor loading P[0].injectA(A0, 0); P[0].injectB(B0, 0) P[1].injectA(A1, 0); P[1].injectB(B1, 0) P[2].injectA(A2, 0); P[2].injectB(B2, 0) P[3].injectA(A3, 0); P[3].injectB(B3, 0) wait_that(collector_servant.inject, called().times(4)) # expected result blocks C0 = M1(19) C1 = M1(22) C2 = M1(43) C3 = M1(50) assert_that(collector_servant.inject, called().with_args(0, C0, anything())) assert_that(collector_servant.inject, called().with_args(1, C1, anything())) assert_that(collector_servant.inject, called().with_args(2, C2, anything())) assert_that(collector_servant.inject, called().with_args(3, C3, anything()))
def test_processor_init_2x2_operands_in_2x2_processors(self): nprocs = 4 procs = [Spy(Cannon.Processor) for i in range(nprocs)] loader = OperationsI(procs) # when loader.init_processors() # then assert_that(procs[0].init, called().with_args(0, 0, procs[2], procs[1], 2, anything())) assert_that(procs[1].init, called().with_args(0, 1, procs[3], procs[0], 2, anything())) assert_that(procs[2].init, called().with_args(1, 0, procs[0], procs[3], 2, anything())) assert_that(procs[3].init, called().with_args(1, 1, procs[1], procs[2], 2, anything()))
def test_default_suite(executed_docstring_source): """ >>> def test_default_suite_example(): ... pass """ assert_that( executed_docstring_source.allure_report, has_test_case( "test_default_suite_example", has_parent_suite(anything()), # path to testdir has_suite("test_default_suite"), # created file name not_(has_sub_suite(anything()))))
def test_default_suite(executed_docstring_source): """ >>> def test_default_suite_example(): ... pass """ assert_that(executed_docstring_source.allure_report, has_test_case("test_default_suite_example", has_parent_suite(anything()), # path to testdir has_suite("test_default_suite"), # created file name not_(has_sub_suite(anything())) ) )
def test_2x2_processors_2x2_operands(self): ''' initial shift: 1 2 1 2 5 6 5 8 3 4 < 4 3 7 8 7 6 ^ processors and collector are distributed objects ''' P = [self.broker.add_servant(ProcessorI(), Cannon.ProcessorPrx) for i in range(4)] collector_servant = Mimic(Spy, Cannon.Collector) collector = self.broker.add_servant(collector_servant, Cannon.CollectorPrx) # by-hand shifted submatrices A00 = M1(1) A01 = M1(2) A10 = M1(4) A11 = M1(3) B00 = M1(5) B01 = M1(8) B10 = M1(7) B11 = M1(6) # by-hand processor initialization P[0].init(0, 0, P[2], P[1], 2, collector) P[1].init(0, 1, P[3], P[0], 2, collector) P[2].init(1, 0, P[0], P[3], 2, collector) P[3].init(1, 1, P[1], P[2], 2, collector) # by-hand processor loading P[0].injectFirst(A00, 0); P[0].injectSecond(B00, 0) P[1].injectFirst(A01, 0); P[1].injectSecond(B01, 0) P[2].injectFirst(A10, 0); P[2].injectSecond(B10, 0) P[3].injectFirst(A11, 0); P[3].injectSecond(B11, 0) wait_that(collector_servant.injectSubmatrix, called().times(4)) # expected result blocks C00 = M1(19) C01 = M1(22) C10 = M1(43) C11 = M1(50) assert_that(collector_servant.injectSubmatrix, called().with_args(C00, 0, 0, anything())) assert_that(collector_servant.injectSubmatrix, called().with_args(C01, 0, 1, anything())) assert_that(collector_servant.injectSubmatrix, called().with_args(C10, 1, 0, anything())) assert_that(collector_servant.injectSubmatrix, called().with_args(C11, 1, 1, anything()))
def test_2x2_processors_1x1_blocks_with_collector_injection(self): ''' A = (1, 2, 3, 4) B = (5, 6, 7, 8) ''' nprocs = 4 # given P = [ProcessorI() for i in range(nprocs)] collector = Spy(Cannon.Collector) # by-hand shift and split A0 = M1(1) A1 = M1(2) A2 = M1(4) A3 = M1(3) B0 = M1(5) B1 = M1(8) B2 = M1(7) B3 = M1(6) # when P[0].init(0, 0, P[2], P[1], 2, collector) P[1].init(0, 1, P[3], P[0], 2, collector) P[2].init(1, 0, P[0], P[3], 2, collector) P[3].init(1, 1, P[1], P[2], 2, collector) P[0].injectFirst(A0, 0) P[0].injectSecond(B0, 0) P[1].injectFirst(A1, 0) P[1].injectSecond(B1, 0) P[2].injectFirst(A2, 0) P[2].injectSecond(B2, 0) P[3].injectFirst(A3, 0) P[3].injectSecond(B3, 0) # then C0 = M1(19) C1 = M1(22) C2 = M1(43) C3 = M1(50) self.assert_collector_called(collector, C0, 0, 0, anything()) self.assert_collector_called(collector, C1, 0, 1, anything()) self.assert_collector_called(collector, C2, 1, 0, anything()) self.assert_collector_called(collector, C3, 1, 1, anything())
def test_processor_init_2x2_operands_in_2x2_processors(self): # given nprocs = 4 procs = [Spy(Cannon.Processor) for i in range(nprocs)] frontend = FrontendI(procs) # when frontend.init_processors() # then assert_that(procs[0].init, called().with_args(0, 2, procs[2], procs[1], anything())) assert_that(procs[1].init, called().with_args(1, 2, procs[3], procs[0], anything())) assert_that(procs[2].init, called().with_args(2, 2, procs[0], procs[3], anything())) assert_that(procs[3].init, called().with_args(3, 2, procs[1], procs[2], anything()))
def test_handles_submit_error(self): # В случае, если ejudge вернул не 0 код submit = Submit(id=1, user_id=self.users[0].id, problem_id=self.problems[0].id, create_time=datetime.datetime(2018, 3, 30, 17, 10, 11), file=self.file_mock, language_id=27, ejudge_url='ejudge_url', statement_id=self.statements[0].id) ejudge_submit_mock.return_value = { 'code': 123, 'message': 'some message', 'other': 'secrets' } assert_that( calling(submit.send), is_not(raises(anything())), ) notify_user_mock.assert_called_once_with( self.users[0].id, 'SUBMIT_ERROR', {'ejudge_error': { 'code': 123, 'message': 'some message' }}) ejudge_submit_mock.side_effect = None
def __init__(self, list, paths): self.list = list self.paths = paths self.path_matcher = contains_inanyorder(*[ contains(*path) for path in self.paths ]) if paths else anything()
def test_handles_submit_exception(self): # В случае, если функция submit бросила исключение submit = Submit( id=1, user_id=self.users[0].id, problem_id=self.problems[0].id, create_time=datetime.datetime(2018, 3, 30, 17, 10, 11), file=self.file_mock, language_id=27, ejudge_url='ejudge_url', statement_id=self.statements[0].id, ) ejudge_submit_mock.side_effect = lambda *args, **kwargs: 1 / 0 assert_that( calling(submit.send), is_not(raises(anything())), ) notify_user_mock.assert_called_once_with( self.users[0].id, 'SUBMIT_ERROR', { 'ejudge_error': { 'code': None, 'message': 'Ошибка отправки задачи' } }) ejudge_submit_mock.side_effect = None
def test_handles_submit_exception(self): # В случае, если функция submit бросила исключение run = Run( user_id=self.users[0].id, problem_id=self.ejudge_problems[0].id, statement_id=self.statements[0].id, create_time=datetime.datetime(2018, 3, 30, 16, 59, 0), ejudge_contest_id=self.ejudge_problems[0].ejudge_contest_id, ejudge_language_id=27, ejudge_status=EjudgeStatuses.COMPILING.value, ) db.session.add(run) db.session.flush() db.session.refresh(run) file = self.file_mock text = file.read() run.update_source(text) submit = Submit( id=1, run_id=run.id, ejudge_url='ejudge_url', ) ejudge_submit_mock.side_effect = lambda *args, **kwargs: 1 / 0 assert_that( calling(submit.send), is_not(raises(anything())), ) ejudge_submit_mock.side_effect = None
def test_matches_none_for_distribution(self): metric_result = _create_metric_result(EVERYTHING_DISTRIBUTION) matcher = MetricResultMatcher( namespace=is_not(equal_to('invalidNamespace')), name=is_not(equal_to('invalidName')), step=is_not(equal_to('invalidStep')), labels={ is_not(equal_to('invalidPcollection')): anything(), is_not(equal_to('invalidCustomKey')): is_not(equal_to( 'invalidCustomValue')) }, committed=is_not(DistributionMatcher( sum_value=120, count_value=50, min_value=100, max_value=60 )), attempted=is_not(DistributionMatcher( sum_value=120, count_value=50, min_value=100, max_value=60 )), ) hc_assert_that(metric_result, matcher)
def test_has_id_tag(): # Given should_match = has_id_tag("fish", has_class("banana")) should_not_match_1 = has_id_tag("fish", has_class("foo")) should_not_match_2 = has_id_tag("grrgug", anything()) assert_that(HTML, should_match) assert_that(HTML, not_(should_not_match_1)) assert_that(HTML, not_(should_not_match_2)) assert_that( should_match, has_string( matches_regexp( r"HTML with tag id=['<]fish['>] matching tag with class matching 'banana'" )), ) assert_that( should_not_match_1, mismatches_with( HTML, matches_regexp( r"""got HTML with tag id=['<]fish['>] values """ r"""\['<div class="banana grapes" id="fish"><p>Some text.</p></div>'\]""" ), ), ) assert_that( should_not_match_2, mismatches_with( HTML, matches_regexp( r"got HTML with tag id=['<]grrgug['>] values \[\]")), )
def test_user_create_adhoc_conference_participant_not_in_stasis(self): host_uuid = make_user_uuid() participant1_uuid = make_user_uuid() participant2_uuid = make_user_uuid() token = self.make_user_token(host_uuid) self.calld_client.set_token(token) host_call1_id, participant1_call_id = self.real_asterisk.given_bridged_call_not_stasis(caller_uuid=host_uuid, callee_uuid=participant1_uuid) host_call2_id, participant2_call_id = self.real_asterisk.given_bridged_call_not_stasis(caller_uuid=host_uuid, callee_uuid=participant2_uuid) adhoc_conference = self.calld_client.adhoc_conferences.create_from_user( host_call1_id, participant1_call_id, participant2_call_id, ) assert_that(adhoc_conference, has_entries({ 'conference_id': anything(), })) def calls_are_bridged(): host_call1 = self.calld_client.calls.get_call(host_call1_id) assert_that(host_call1, has_entries({ 'talking_to': has_entries({ participant1_call_id: anything(), participant2_call_id: anything(), }) })) assert_that(host_call2_id, self.c.is_hungup()) until.assert_(calls_are_bridged, timeout=10)
def test_load_dataset_existing_forced(self, api_client, dw, dataset_key): dataset = dw.load_dataset(dataset_key, force_update=True) assert_that( api_client.download_datapackage, called().times(1).with_args(equal_to(dataset_key), anything())) assert_that(dataset.raw_data, has_length(4))
def api_client(self, test_datapackages_path): with Spy(RestApiClient) as client: def download_datapackage(_, dest_dir): shutil.copytree( path.join(test_datapackages_path, 'the-simpsons-by-the-data'), dest_dir) return path.join(dest_dir, 'datapackage.json') def get_dataset(_): return {'updated': '2016-11-07T00:00:00.000Z'} client.download_datapackage( anything(), anything()).delegates(download_datapackage) client.get_dataset(anything()).delegates(get_dataset) return client
def has_failure(test_name, message=anything()): return has_property('{}test-cases', has_property('test-case', has_item( has_properties({'name': equal_to(test_name), 'failure': any_of( has_property('stack-trace', equal_to(message)), has_property('message', equal_to(message)))}))))
def has_table(table: str) -> Matcher: """TODO""" select = f"SELECT * FROM {table};" # nosec return described_as( "DB connection has table named %0", given_select_returns_rows_matching(select, anything()), table, )
def __init__(self, property_name, value=hamcrest.anything(), times=any_time): super(property_set, self).__init__() self.property_name = property_name self.value = value self._times = times
def test_2x2_processors_1x1_blocks_with_collector_injection(self): ''' A = (1, 2, 3, 4) B = (5, 6, 7, 8) ''' nprocs = 4 # given P = [ProcessorI() for i in range(nprocs)] collector = Spy(Cannon.Collector) # by-hand shift and split A0 = M1(1) A1 = M1(2) A2 = M1(4) A3 = M1(3) B0 = M1(5) B1 = M1(8) B2 = M1(7) B3 = M1(6) # when P[0].init(0, 0, P[2], P[1], 2, collector) P[1].init(0, 1, P[3], P[0], 2, collector) P[2].init(1, 0, P[0], P[3], 2, collector) P[3].init(1, 1, P[1], P[2], 2, collector) P[0].injectFirst(A0, 0); P[0].injectSecond(B0, 0) P[1].injectFirst(A1, 0); P[1].injectSecond(B1, 0) P[2].injectFirst(A2, 0); P[2].injectSecond(B2, 0) P[3].injectFirst(A3, 0); P[3].injectSecond(B3, 0) # then C0 = M1(19) C1 = M1(22) C2 = M1(43) C3 = M1(50) self.assert_collector_called(collector, C0, 0, 0, anything()) self.assert_collector_called(collector, C1, 0, 1, anything()) self.assert_collector_called(collector, C2, 1, 0, anything()) self.assert_collector_called(collector, C3, 1, 1, anything())
def assert_result(self, *matchers, **kwargs): result = kwargs.get(u'result', self.result) assert_that(result, all_of( has_property(u'exit_code', kwargs.pop(u'exit_code', 0)), has_property(u'output', kwargs.pop(u'output', anything())), has_properties(**kwargs), *matchers ))
def test_any_arg_matches_property(self): prop_stub = Spy(CollaboratorWithProperty) when(prop_stub).prop.returns(5) with Stub(Collaborator) as stub: stub.method_accepting_property(prop=anything()).returns(2) assert_that(stub.method_accepting_property(prop_stub.prop), is_(2)) assert prop_stub.prop == 5
def test_load_dataset_existing_expired_auto_update(self, monkeypatch, api_client, dw, dataset_key): monkeypatch.setattr(os.path, 'getmtime', lambda _: 1468195199) dataset = dw.load_dataset(dataset_key, auto_update=True) assert_that( api_client.download_datapackage, called().times(1).with_args(equal_to(dataset_key), anything())) assert_that(dataset.raw_data, has_length(4))
def _adapt_tuples(cls, a, b): if len(a) > len(b): return cls._adapt_tuples(b, a) if a[:-1] != ANY_ARG: raise AssertionError("Incompatible argument list: %s, %s" % (a, b)) a = a[:-1] + (hamcrest.anything(),) * (len(b) - len(a)) return a, b
def assert_deprecated(message, matcher): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") matcher(anything()).matches("", StringDescription()) assert_that( w, has_item(has_properties(category=DeprecationWarning, message=has_string(message))) )
def _adapt_tuples(cls, a, b): if len(a) > len(b): return cls._adapt_tuples(b, a) if a[:-1] != ANY_ARG: raise AssertionError("Incompatible argument list: %s, %s" % (a, b)) a = a[:-1] + (hamcrest.anything(), ) * (len(b) - len(a)) return a, b
def test_spy(self): playername = "Kawhi Leonard" year = 2017 salary = "20m" #使用with关键字和Spy()来创建free spy #设置和salaryService一样的方法 with Spy() as free_ss_spy: free_ss_spy.set_salary(salary).returns("20m") #通过SUT调用spy对象的方法 pls.playerService(playername, 2017, ds.dataService(playername), pos.profileService(playername), bs.bodyService(), free_ss_spy).set_new_salary(salary) #验证spy_ss.set_salary方法被调用过 assert_that(free_ss_spy.set_salary, called()) #使用Spy(类对象)来创建spy spy_ss = Spy(ss.salaryService) #通过SUT调用spy对象的方法 pls.playerService(playername, 2017, ds.dataService(playername), pos.profileService(playername), bs.bodyService(), spy_ss).set_new_salary(salary) #验证spy_ss.set_salary方法被调用过 assert_that(spy_ss.set_salary, called()) #Spy是Stub的扩展,所以除了记录方法被调用的情况,也可以设定返回值 with Spy(bs.bodyService) as spy_bs_as_stub: spy_bs_as_stub.get_height().returns("188cm") spy_bs_as_stub.get_weight().returns("110kg") spy_bs_as_stub.illnessHistory(2017).returns("Year 2017 no injury") spy_bs_as_stub.illnessHistory(2018).returns("Year 2017 has ankle injury") #直接调用spy对象方法 spy_bs_as_stub.get_height() spy_bs_as_stub.get_weight() spy_bs_as_stub.illnessHistory(2017) spy_bs_as_stub.illnessHistory(2018) #可以验证spy对象方法已经被调用及其参数接受情况 assert_that(spy_bs_as_stub.get_height, called()) assert_that(spy_bs_as_stub.get_weight, called()) assert_that(spy_bs_as_stub.illnessHistory, called().times(2)) #使用anything()去任意匹配 assert_that(spy_bs_as_stub.illnessHistory, called().with_args(anything())) #通过SUT调用spy对象的方法 player_service_spy_2016 = pls.playerService(playername, 2017, ds.dataService(playername), pos.profileService(playername), spy_bs_as_stub, ss.salaryService()) player_service_spy_2016.get_physical_feature(2017) #验证spy对象方法再一次被方法(SUT)调用 called验证调用与否,times验证调用次数 assert_that(spy_bs_as_stub.get_height, called().times(2)) assert_that(spy_bs_as_stub.get_weight, called().times(2)) assert_that(spy_bs_as_stub.illnessHistory, called().times(3)) #传递实例给ProxySpy() spy_pos = ProxySpy(pos.profileService(playername)) #通过SUT调用spy对象的方法 pls.playerService(playername, 2016, ds.dataService(playername), spy_pos, bs.bodyService(), ss.salaryService()).get_player_info() #验证spy对象方法被调用过 assert_that(spy_pos.get_player_team, called())
def assert_deprecated(message, matcher): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") matcher(anything()).matches("", StringDescription()) assert_that(w, has_item( has_properties( category=DeprecationWarning, message=has_string(message))))
def test_simple(self): response = self.send_request( session_user_id=self.admin_user.id, user_id=self.user.id, ) assert_that(response.status_code, equal_to(200)) assert_that( response.json, has_entries({ 'id': self.user.id, 'password': anything(), }))
def replace_ANY_ARG(self, actual): try: index = self.args.index(ANY_ARG) except ValueError: return self retval = self.copy() args = list(self.args[0:index]) args.extend([hamcrest.anything()] * (len(actual.args) - index)) retval.args = tuple(args) retval.kargs = actual.kargs.copy() return retval
def test_linked_processors(self): P0 = self.broker.add_servant(ProcessorI(), Cannon.ProcessorPrx) P1_servant = Mimic(Spy, Cannon.Processor) P1 = self.broker.add_servant(P1_servant, Cannon.ProcessorPrx) P2_servant = Mimic(Spy, Cannon.Processor) P2 = self.broker.add_servant(P2_servant, Cannon.ProcessorPrx) collector_servant = Mimic(Spy, Cannon.Collector) collector = self.broker.add_servant(collector_servant, Cannon.CollectorPrx) A00 = M1(1) B00 = M1(5) P0.init(1, 1, P2, P1, 2, collector) P0.injectFirst(A00, 0) P0.injectSecond(B00, 0) assert_that(P1_servant.injectFirst, called().asyncio(1).with_args(A00, 1, anything())) assert_that(P2_servant.injectSecond, called().asyncio(1).with_args(B00, 1, anything()))
def test_linked_processors(self): P0 = self.broker.add_servant(ProcessorI(), Cannon.ProcessorPrx) P1_servant = Mimic(Spy, Cannon.Processor) P1 = self.broker.add_servant(P1_servant, Cannon.ProcessorPrx) P2_servant = Mimic(Spy, Cannon.Processor) P2 = self.broker.add_servant(P2_servant, Cannon.ProcessorPrx) collector_servant = Mimic(Spy, Cannon.Collector) collector = self.broker.add_servant(collector_servant, Cannon.CollectorPrx) A00 = M1(1) B00 = M1(5) P0.init(1, 1, P2, P1, 2, collector) P0.injectFirst(A00, 0) P0.injectSecond(B00, 0) assert_that(P1_servant.injectFirst, called().async(1).with_args(A00, 1, anything())) assert_that(P2_servant.injectSecond, called().async(1).with_args(B00, 1, anything()))
def test_processor_init_3x3_operands_in_3x3_processors(self): nprocs = 9 procs = [Spy(Cannon.Processor) for i in range(nprocs)] loader = OperationsI(procs) # when loader.init_processors() # then assert_that(procs[0].init, called().with_args(0, 0, procs[6], procs[2], 3, anything())) assert_that(procs[1].init, called().with_args(0, 1, procs[7], procs[0], 3, anything())) assert_that(procs[2].init, called().with_args(0, 2, procs[8], procs[1], 3, anything())) assert_that(procs[3].init, called().with_args(1, 0, procs[0], procs[5], 3, anything())) assert_that(procs[4].init, called().with_args(1, 1, procs[1], procs[3], 3, anything())) assert_that(procs[5].init, called().with_args(1, 2, procs[2], procs[4], 3, anything())) assert_that(procs[6].init, called().with_args(2, 0, procs[3], procs[8], 3, anything())) assert_that(procs[7].init, called().with_args(2, 1, procs[4], procs[6], 3, anything())) assert_that(procs[8].init, called().with_args(2, 2, procs[5], procs[7], 3, anything()))
def test_upload(self): response = self.client.post( "/api/file", data=dict( file=(BytesIO(b"Hello World\n"), "hello.txt"), ), ) assert_that(response.status_code, is_(equal_to(204))) assert_that(self.controller.calls, contains( has_entries( files=contains(contains("file", anything(), "hello.txt")), extra="something", ), ))
def test_matches_none_for_counter(self): metric_result = _create_metric_result(EVERYTHING_COUNTER) matcher = MetricResultMatcher( namespace=is_not(equal_to('invalidNamespace')), name=is_not(equal_to('invalidName')), step=is_not(equal_to('invalidStep')), labels={ is_not(equal_to('invalidPcollection')): anything(), is_not(equal_to('invalidCustomKey')): is_not(equal_to( 'invalidCustomValue')) }, attempted=is_not(equal_to(1000)), committed=is_not(equal_to(1000))) hc_assert_that(metric_result, matcher)
def test_account_creation__argument_values(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', 'some')) assert_that(store.save, called().with_args('John', ANY_ARG)) assert_that(store.save, never(called().with_args('Alice', anything()))) assert_that(store.save, called().with_args(contains_string('oh'), ANY_ARG))
def add_unspecifed_args(self, context): arg_spec = context.signature.get_arg_spec() if arg_spec is None: raise WrongApiUsage( 'free spies does not support the with_some_args() matcher') if arg_spec.keywords is not None: raise WrongApiUsage( 'with_some_args() can not be applied to method %s' % self.signature) keys = arg_spec.args retval = dict((k, hamcrest.anything()) for k in keys) retval.update(context.kargs) return retval
def test_default_class_suite(executed_docstring_source): """ >>> class TestSuiteClass(object): ... def test_default_class_suite_example(self): ... pass """ assert_that(executed_docstring_source.allure_report, has_test_case("test_default_class_suite_example", has_parent_suite(anything()), # path to testdir has_suite("test_default_class_suite"), # created file name has_sub_suite("TestSuiteClass") ) )
def replace_ANY_ARG(self, actual): index = None for i, val in enumerate(self.args): if val is ANY_ARG: index = i if index is None: return self retval = self.copy() args = list(self.args[0:index]) args.extend([hamcrest.anything()] * (len(actual.args) - index)) retval.args = tuple(args) retval.kargs = actual.kargs.copy() return retval
def test_collector_called(self): # given processor = self.broker.add_servant(ProcessorI(), Cannon.ProcessorPrx) collector_servant = Mimic(Spy, Cannon.Collector) collector = self.broker.add_servant(collector_servant, Cannon.CollectorPrx) A = M2(1, 2, 3, 4) B = M2(5, 6, 7, 8) # when processor.init(1, 1, None, None, 1, collector) processor.injectFirst(A, 0) processor.injectSecond(B, 0) # then C = M2(19, 22, 43, 50) assert_that(collector_servant.injectSubmatrix, called().async(1).with_args(C, 1, 1, anything()))
def test_upload_for(self): person_id = uuid4() response = self.client.post( "/api/person/{}/file".format(person_id), data=dict( file=(BytesIO(b"Hello World\n"), "hello.txt"), ), ) assert_that(response.status_code, is_(equal_to(200))) response_data = loads(response.get_data().decode("utf-8")) assert_that(response_data, is_(equal_to(dict( id=str(person_id), )))) assert_that(self.controller.calls, contains( has_entries( files=contains(contains("file", anything(), "hello.txt")), extra="something", person_id=person_id, ), ))
def not_called(): '''Match mock that was never called''' return Called(anything(), count=0)
def test_2x2_processors_2x2_blocks_with_collector_injection(self): ''' A = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) B = (17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32) ''' nprocs = 4 # given P = [ProcessorI() for i in range(nprocs)] collector = Spy(Cannon.Collector) # by-hand shift and split A0 = M2(1, 2, 5, 6) A1 = M2(3, 4, 7, 8) A2 = M2(11, 12, 15, 16) A3 = M2(9, 10, 13, 14) B0 = M2(17, 18, 21, 22) B1 = M2(27, 28, 31, 32) B2 = M2(25, 26, 29, 30) B3 = M2(19, 20, 23, 24) # when P[0].init(0, 0, P[2], P[1], 2, collector) P[1].init(0, 1, P[3], P[0], 2, collector) P[2].init(1, 0, P[0], P[3], 2, collector) P[3].init(1, 1, P[1], P[2], 2, collector) P[0].injectFirst(A0, 0); P[0].injectSecond(B0, 0) P[1].injectFirst(A1, 0); P[1].injectSecond(B1, 0) P[2].injectFirst(A2, 0); P[2].injectSecond(B2, 0) P[3].injectFirst(A3, 0); P[3].injectSecond(B3, 0) # then C0 = M2(250, 260, 618, 644) C1 = M2(270, 280, 670, 696) C2 = M2(986, 1028, 1354, 1412) C3 = M2(1070, 1112, 1470, 1528) self.assert_collector_called(collector, C0, 0, 0, anything()) self.assert_collector_called(collector, C1, 0, 1, anything()) self.assert_collector_called(collector, C2, 1, 0, anything()) self.assert_collector_called(collector, C3, 1, 1, anything())
def called_once(): '''Match mock that was called once regardless of arguments''' return Called(anything(), count=1)
def called(): '''Match mock that was called one or more times''' return Called(anything())