def test_workflow_no_enriched_data(tmpdir, mock_env_home, set_workflow_config): """ Test confirms that if workflow produces no enriched data that no output file is created """ # Create source and destination configurations source = set_workflow_config[1] destination = set_workflow_config[2] test_dir = tmpdir.mkdir("tmp_test_workflow") input_path = str(test_dir.join("person.csv")) input_df.to_csv(input_path, index=False) output_path = str(test_dir.join("output_empty.csv")) source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations test_workflow = spy( TestWorkflowImpl(source=source, destination=destination, name="test-workflow-no-data", custom_workflow_param="test_param")) io_writer = spy(test_workflow._io_writer) # Return empty dataframe when workflow runs when(test_workflow).workflow(...).thenReturn(DataFrame()) # Verify io_writer does not write data verify(io_writer, times=0).write_data(...) # Verify that no output file created. assert not os.path.exists(output_path)
def setUp(self) -> None: self._model = SimpleNet() self._criterion_mock = spy(nn.CrossEntropyLoss()) self._optimizer_mock = spy(SGD(self._model.parameters(), lr=0.001)) self._scheduler_mock = mock(lr_scheduler) self._accuracy_computer_mock = spy(Accuracy()) self._recall_computer_mock = spy(Recall()) self._gradient_clipping_strategy = None self._model_trainer = ModelTrainer( self.MODEL_NAME_1, self._model, {self.LOSS_NAME: self._criterion_mock}, self._optimizer_mock, self._scheduler_mock, { "Accuracy": self._accuracy_computer_mock, "Recall": self._recall_computer_mock }, self._gradient_clipping_strategy) self._model_trainer_2 = ModelTrainer( self.MODEL_NAME_2, self._model, {self.LOSS_NAME: self._criterion_mock}, self._optimizer_mock, self._scheduler_mock, { "Accuracy": self._accuracy_computer_mock, "Recall": self._recall_computer_mock }, self._gradient_clipping_strategy) self._model_trainer_list = ModelTrainerList( [self._model_trainer, self._model_trainer_2])
def testRaisesAttributeErrorIfNoSuchMethod(self): dummy = spy(Dummy()) try: dummy.lol() self.fail("Should fail if no such method.") except AttributeError as e: self.assertEquals("You tried to call method 'lol' which 'Dummy' instance does not have.", str(e))
def testModuleFunction(self): import time dummy = spy(time) assert dummy.time() is not None verify(dummy).time()
def test_benchmark_decorator(tmpdir, mock_env_home, set_workflow_config): # Dummy function def func(self): return DataFrame() benchmarked_func = Workflow.benchmark(func) source = set_workflow_config[1] destination = set_workflow_config[2] test_dir = tmpdir.mkdir("tmp_test_workflow") input_path = str(test_dir.join("person.csv")) input_df.to_csv(input_path, index=False) output_path = str(test_dir.join("output_benchmark.csv")) source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations tb = spy( TestWorkflowImpl(source=source, destination=destination, name="test-workflow")) benchmarked_func(tb.run_workflow) # Verify that run_workflow was not called, instead expect that benchmark wrapper function will be called verify(tb, times=0).run_workflow(...)
def test_workflow_no_data(tmpdir, mock_env_home, set_workflow_config): """ Test confirms that workflow is not run and output not written if no data is returned from the workflow io_reader """ # Create source and destination configurations source = set_workflow_config[1] destination = set_workflow_config[2] test_dir = tmpdir.mkdir("tmp_test_workflow") input_path = str(test_dir.join("input_empty.csv")) empty_df.to_csv(input_path) output_path = str(test_dir.join("output_empty.csv")) source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations test_workflow = spy( TestWorkflowImpl(source=source, destination=destination, name="test-workflow-no-data", custom_workflow_param="test_param")) test_workflow.run_workflow() # Verify workflow not run verify(test_workflow, times=0).workflow(...) # Verify that no output file created. assert not os.path.exists(output_path)
def test_firmware_volume(): TEST_NAME = b'FirmwareVolume' enable_trace = True ql = Qiling( ['./bin/EfiFuzzTests.efi'], ".", # rootfs console=True if enable_trace else False, stdout=1 if enable_trace else None, stderr=1 if enable_trace else None, output='debug') # NVRAM environment. ql.env.update({'TestName': TEST_NAME}) rom.install(ql, "./res/$0AGD000.FL1") def validate_read_section(ql, address, params): buffer_size = read_int64(ql, params['BufferSize']) buffer = ql.mem.read(read_int64(ql, params['Buffer']), buffer_size) assert buffer.decode('utf-16').strip('\x00') == 'DxeMain.efi' return (address, params) # Hook ReadSection() to check the taint on the buffer. read_section_spy = mockito.spy(validate_read_section) ql.set_api("ReadSection", read_section_spy, QL_INTERCEPT.EXIT) # okay, ready to roll. ql.run() # Make sure that ReadSection() was intercepted once. mockito.verify(read_section_spy, times=1).__call__(*mockito.ARGS)
def test_should_not_save_model_with_higher_valid_losses( self, model_state_mock, optimizer_states_mock): model_state_mock.return_value = dict() optimizer_states_mock.return_value = list(dict()) moment = Moment(200, Frequency.EPOCH, Phase.VALIDATION) handler_mock = mockito.spy( Checkpoint(self.SAVE_PATH, self.MODEL_NAME, ["MSELoss", "L1Loss"], 0.01, MonitorMode.MIN)) monitors = { self.MODEL_NAME: { Phase.TRAINING: { Monitor.METRICS: {}, Monitor.LOSS: {} }, Phase.VALIDATION: { Monitor.METRICS: {}, Monitor.LOSS: { "MSELoss": torch.tensor([0.5]), "L1Loss": torch.tensor([0.5]) } }, Phase.TEST: { Monitor.METRICS: {}, Monitor.LOSS: {} } } } handler_mock(TemporalEvent(Event.ON_EPOCH_END, moment), monitors, self._trainer_mock) monitors = { self.MODEL_NAME: { Phase.TRAINING: { Monitor.METRICS: {}, Monitor.LOSS: {} }, Phase.VALIDATION: { Monitor.METRICS: {}, Monitor.LOSS: { "MSELoss": torch.tensor([0.5]), "L1Loss": torch.tensor([0.6]) } }, Phase.TEST: { Monitor.METRICS: {}, Monitor.LOSS: {} } } } handler_mock(TemporalEvent(Event.ON_EPOCH_END, moment), monitors, self._trainer_mock) assert_that(not os.path.exists( os.path.join(self.SAVE_PATH, self.MODEL_NAME, self.MODEL_NAME + ".tar")))
def testRaisesAttributeErrorIfNoSuchMethod(self): dummy = spy(Dummy()) try: dummy.lol() self.fail("Should fail if no such method.") except AttributeError as e: self.assertEqual("You tried to call method 'lol' which 'Dummy' instance does not have.", str(e))
def testDemo(self): demoMock = spy(Demo()) when(demoMock).method2().thenReturn('mockedmethod2') self.assertEqual(demoMock.method1(), 'method1') self.assertEqual(demoMock.method2(), 'mockedmethod2') verify(demoMock).method1() verify(demoMock).method2()
def testRaisesAttributeErrorIfNoSuchMethod(self): original = Dummy() dummy = spy(original) try: dummy.lol() self.fail("Should fail if no such method.") except AttributeError as e: self.assertEqual("You tried to call method 'lol' which '%s' " "instance does not have." % original, str(e))
def setUp(self) -> None: self._model_mock = mock(nn.Module) self._criterion_mock = spy(nn.CrossEntropyLoss()) self._optimizer_mock = mock(Optimizer) self._scheduler_mock = mock(lr_scheduler) self._accuracy_computer_mock = spy(Accuracy()) self._recall_computer_mock = spy(Recall()) self._gradient_clipping_strategy = mock(GradientClippingStrategy) self._training_data_loader_mock = mock(DataLoader) self._valid_data_loader_mock = mock(DataLoader) self._test_data_loader_mock = mock(DataLoader) self._model_trainer = ModelTrainer( self.MODEL_NAME, self._model_mock, self._criterion_mock, self._optimizer_mock, self._scheduler_mock, { "Accuracy": self._accuracy_computer_mock, "Recall": self._recall_computer_mock }, self._gradient_clipping_strategy)
def testRaisesAttributeErrorIfNoSuchMethod(self): original = Dummy() dummy = spy(original) try: dummy.lol() self.fail("Should fail if no such method.") except AttributeError as e: self.assertEquals( "You tried to call method 'lol' which '%s' " "instance does not have." % original, str(e))
def service(): api_service = spy(ApiService()) mock_tags = load_mock_data('tags.json') mock_tag = load_mock_data('tag.json') mock_statuses = load_mock_data('statuses.json') when(api_service).get_url_json(tag_url).thenReturn(mock_tags) when(api_service).get_url_json(tag_url, {'id': 22}).thenReturn(mock_tag) when(api_service).get_url_json(status_url, {'tag_id': 22}).thenReturn(mock_statuses) return api_service
def test_state_processed(self): """method tests job records in STATE_PROCESSED state""" pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_PROCESSED, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=0). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str)) verify(self.time_table_mocked, times=0).get_tree(any(str))
def test_state_embryo(self): """ method tests timetable records in STATE_EMBRYO state""" self.pipeline_real.insert_uow = then_return_uow pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_EMBRYO, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str))
def test_duplicatekeyerror_state_embryo(self): """ method tests job records in STATE_EMBRYO state""" self.pipeline_real.compute_scope_of_processing = then_raise pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_EMBRYO, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=0). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str))
def test_workflow_no_enriched_data(mock_env_home, set_workflow_config, input_path, output_path): """ Test confirms that if workflow produces no enriched data that no output file is created """ # Create source and destination configurations source = set_workflow_config[1] destination = set_workflow_config[2] source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations test_workflow = spy(TestWorkflowImpl( source=source, destination=destination, name="test-workflow-no-data", custom_workflow_param="test_param" )) io_writer = spy(test_workflow._io_writer) # Return empty dataframe when workflow runs when(test_workflow).workflow(...).thenReturn(DataFrame()) # Verify io_writer does not write data verify(io_writer, times=0).write_data(...) # Verify that no output file created. assert os.path.exists(output_path) == False
def test_setup_job_handler(self, root_chain, child_chain): (when('plasma_cash.operator_cron_job.__main__.container'). get_child_chain().thenReturn(child_chain)) (when('plasma_cash.operator_cron_job.__main__.container'). get_root_chain().thenReturn(root_chain)) job_handler = spy(JobHandler()) job_handler = setup_job_handler(job_handler) verify(job_handler).add_job(ANY(SubmitBlockJob), time_interval=SUBMIT_BLOCK_INTERVAL) verify(job_handler).add_job(ANY(ApplyDepositJob), time_interval=APPLY_DEPOSIT_INTERVAL)
def test_future_timeperiod_state_in_progress(self): """ method tests timetable records in STATE_IN_PROGRESS state""" when(self.time_table_mocked).can_finalize_job_record(any(str), any(Job)).thenReturn(True) uow_dao_mock = mock(UnitOfWorkDao) when(uow_dao_mock).get_one(any()).thenReturn(create_unit_of_work(PROCESS_UNIT_TEST, 0, 1, None)) self.pipeline_real.uow_dao = uow_dao_mock self.pipeline_real.insert_uow = then_raise pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_FUTURE_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=0). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str))
def test_cancelled_state_final_run(self): """method tests job records in STATE_FINAL_RUN state""" uow_dao_mock = mock(UnitOfWorkDao) when(uow_dao_mock).get_one(any()).thenReturn( create_unit_of_work(PROCESS_UNIT_TEST, 1, 1, None, unit_of_work.STATE_CANCELED)) self.pipeline_real.uow_dao = uow_dao_mock pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_FINAL_RUN, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=1). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str)) verify(self.time_table_mocked, times=0).get_tree(any(str))
def test_smi_dispatching(): TEST_NAME = b'SmiDispatching' enable_trace = True ql = Qiling( ['./bin/EfiFuzzTests.efi'], ".", # rootfs console=True if enable_trace else False, stdout=1 if enable_trace else None, stderr=1 if enable_trace else None, output='debug', profile='../smm/smm.ini') # NVRAM environment. ql.env.update({'TestName': TEST_NAME}) # Init SMM callbacks.init_callbacks(ql) smm.init(ql, in_smm=True) def smi_intercept(ql): # Validate EFI_SMM_SW_REGISTER_CONTEXT register_context = EFI_SMM_SW_REGISTER_CONTEXT.loadFrom(ql, ql.reg.rdx) assert register_context.SwSmiInputValue == 0x9F # Validate EFI_SMM_SW_CONTEXT sw_context = EFI_SMM_SW_CONTEXT.loadFrom(ql, ql.reg.r8) assert sw_context.SwSmiCpuIndex == 0 assert sw_context.DataPort == 0 assert sw_context.CommandPort == 0x9F smi_intercept = mockito.spy(smi_intercept) def hook_smi(ql, address, params): # Hook the SMI handler. ql.hook_address(smi_intercept, params['DispatchFunction']) return (address, params) # Hook ReadSection() to check the taint on the buffer. ql.set_api("SMM_SW_DISPATCH2_Register", hook_smi, QL_INTERCEPT.EXIT) # okay, ready to roll. ql.run() # Make sure that the SMI handler was intercepted once. mockito.verify(smi_intercept, times=1).__call__(*mockito.ARGS)
def setUp(self): self.start_date = str_to_date("2018-02-04") self.msft_contract = Contract(self.MSFT_TICKER_STR, security_type='SEK', exchange='TEST') self.msft_ticker = BloombergTicker(self.MSFT_TICKER_STR) self.contracts_to_tickers_mapper = DummyBloombergContractTickerMapper() timer = SettableTimer(initial_time=self.start_date) self.data_handler = mock(strict=True) self.scheduler = mock() self.commission_model = FixedCommissionModel(commission=0.0) self.monitor = _MonitorMock() self.spied_monitor = spy(self.monitor) self.portfolio = mock() slippage_model = PriceBasedSlippage(0.0) self.exec_hanlder = SimulatedExecutionHandler( self.data_handler, timer, self.scheduler, self.spied_monitor, self.commission_model, self.contracts_to_tickers_mapper, self.portfolio, slippage_model) self._set_current_msft_price(100.0) self.stop_loss_order_1 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(95.0), time_in_force=TimeInForce.GTC) self.stop_loss_order_2 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(90.0), time_in_force=TimeInForce.GTC) self.stop_loss_order_3 = Order(self.msft_contract, quantity=-1, execution_style=StopOrder(50.0), time_in_force=TimeInForce.DAY) self.exec_hanlder.accept_orders([ self.stop_loss_order_1, self.stop_loss_order_2, self.stop_loss_order_3 ])
def test_retry_state_in_progress(self): """ method tests timetable records in STATE_IN_PROGRESS state""" when(self.time_table_mocked).can_finalize_job_record(any(str), any(Job)).thenReturn(True) uow_dao_mock = mock(UnitOfWorkDao) when(uow_dao_mock).get_one(any()).thenReturn( create_unit_of_work(PROCESS_UNIT_TEST, 1, 1, None, unit_of_work.STATE_PROCESSED)) self.pipeline_real.uow_dao = uow_dao_mock self.pipeline_real.insert_uow = then_raise self.pipeline_real.recover_from_duplicatekeyerror = override_recover_function pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=1). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str))
def test_transfer_to_final_timeperiod_state_in_progress(self): """ method tests job records in STATE_IN_PROGRESS state""" when(self.time_table_mocked).can_finalize_job_record(any(str), any(Job)).thenReturn(True) uow_dao_mock = mock(UnitOfWorkDao) when(uow_dao_mock).get_one(any()). \ thenReturn(create_unit_of_work(PROCESS_UNIT_TEST, 1, 1, None, unit_of_work.STATE_REQUESTED)). \ thenReturn(create_unit_of_work(PROCESS_UNIT_TEST, 1, 1, None, unit_of_work.STATE_PROCESSED)) self.pipeline_real.uow_dao = uow_dao_mock self.pipeline_real.compute_scope_of_processing = then_raise pipeline = spy(self.pipeline_real) job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY) pipeline.manage_pipeline_for_process(job_record.process_name, job_record) verify(self.time_table_mocked, times=1). \ update_job_record(any(str), any(Job), any(UnitOfWork), any(str))
def test_smm_save_state(): TEST_NAME = b'SmmSaveState' enable_trace = True ql = Qiling( ['./bin/EfiFuzzTests.efi'], ".", # rootfs console=True if enable_trace else False, stdout=1 if enable_trace else None, stderr=1 if enable_trace else None, output='debug', profile='../smm/smm.ini') # NVRAM environment. ql.env.update({'TestName': TEST_NAME}) # Init SMM callbacks.init_callbacks(ql) smm.init(ql, in_smm=True) def validate_smm_read_save_state(ql, address, params): assert params['Width'] == 0x4 assert params['Register'] == EFI_SMM_SAVE_STATE_REGISTER.RAX.value assert params['CpuIndex'] == 0x0 data = int.from_bytes(ql.mem.read(params['Buffer'], params['Width']), 'little') assert data == 0xbadcafe return (address, params) # Hook ReadSaveState(). validate_smm_read_save_state = mockito.spy(validate_smm_read_save_state) ql.set_api("SmmReadSaveState", validate_smm_read_save_state, QL_INTERCEPT.EXIT) # okay, ready to roll. ql.os.smm.swsmi_args = {'rax': 0xdeadbeef_0badcafe.to_bytes(8, 'little')} ql.run() # Make sure that the SMI handler was intercepted once. mockito.verify(validate_smm_read_save_state, times=1).__call__(*mockito.ARGS)
def test_workflow_no_data(mock_env_home, set_workflow_config, input_path, output_path): """ Test confirms that workflow is not run and output not written if no data is returned from the workflow io_reader """ # Create source and destination configurations source = set_workflow_config[1] destination = set_workflow_config[2] source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations test_workflow = spy(TestWorkflowImpl( source=source, destination=destination, name="test-workflow-no-data", custom_workflow_param="test_param" )) test_workflow.run_workflow() # Verify workflow not run verify(test_workflow, times=0).workflow(...) # Verify that no output file created. assert os.path.exists(output_path) == False
def test_benchmark_decorator( mock_env_home, set_workflow_config, input_path, output_path ): # Dummy function def func(self): return DataFrame() benchmarked_func = Workflow.benchmark(func) source = set_workflow_config[1] destination = set_workflow_config[2] source["input_path"] = input_path destination["output_path"] = output_path # Create new workflow with source and destination configurations tb = spy( TestWorkflowImpl(source=source, destination=destination, name="test-workflow") ) benchmarked_func(tb.run_workflow) # Verify that run_workflow was not called, instead expect that benchmark wrapper function will be called verify(tb, times=0).run_workflow(...)
def test_uninitialized_memory_tracker(): TEST_NAME = b'UninitializedMemoryTracker' enable_trace = True ql = Qiling( ['./bin/EfiFuzzTests.efi'], ".", # rootfs console=True if enable_trace else False, stdout=1 if enable_trace else None, stderr=1 if enable_trace else None, output='debug') # NVRAM environment. ql.env.update({'TestName': TEST_NAME, 'foo': b'\xde\xad\xbe\xef'}) def validate_taint_set_variable(ql, address, params): assert params['VariableName'] == 'bar' and params['DataSize'] == 0x14 begin = params['Data'] end = params['Data'] + params['DataSize'] tainted_bytes = ql.tainters['uninitialized'].get_taint_range( begin, end) assert tainted_bytes == [ True, True, True, True, True, True, False, False, False, False, True, True, True, True, True, True, True, False, True, True ] # Un-taint to avoid crashing the process. ql.tainters['uninitialized'].set_taint_range(begin, end, False) return (address, params) # Hook SetVariable() to check the taint on the buffer. set_variable_spy = mockito.spy(validate_taint_set_variable) ql.set_api("SetVariable", set_variable_spy, QL_INTERCEPT.ENTER) # okay, ready to roll. taint.tracker.enable(ql, ['uninitialized']) ql.run() # Make sure that SetVariable() was intercepted once. mockito.verify(set_variable_spy, times=1).__call__(*mockito.ARGS)
def test_confirm_mock_of_specific_value(self): print("Test confirm_mock_of_specific_value " + self.__DATE) # create an instance of the mock of the class RobCountsLine rob_counts_line = spy(RobCountsLine()) rcl = 6847180 # define the mocking rule when(rob_counts_line).count_line_number().thenReturn(rcl) # try to run the method countLineNumber which should be mocked bt rcl line = rob_counts_line.count_line_number() self.assertEqual(rcl, line) # return to the original unMocked method unstub(rob_counts_line) # try to run the method countLineNumber which should be back to original line = rob_counts_line.count_line_number() self.assertEqual(7, line)
def testVerifyZeroInteractionsWorks(self): dummy = spy(Dummy()) verifyZeroInteractions(dummy)
def testIsVerifiable(self): dummy = spy(Dummy()) dummy.foo() verify(dummy).foo() self.assertRaises(VerificationError, verify(dummy).bar)
def testPassesArgumentsCorrectly(self): dummy = spy(Dummy()) self.assertEqual((('foo', 1), {'bar': 'baz'}), dummy.return_args('foo', 1, bar='baz'))
def testPreservesSideEffects(self): dummy = spy(Dummy()) self.assertRaises(TypeError, dummy.bar)
def testCallClassmethod(self): dummy = spy(Dummy) assert dummy.class_method('foo') == 'foo' verify(dummy).class_method('foo')
def testCantCallInstanceMethodWhenSpyingClass(self): dummy = spy(Dummy) with pytest.raises(TypeError): dummy.return_args('foo')
def transport(self): return m.spy(TestTransport())
def test_valid_and_stale_uow(self): self.worker.uow_dao.update = assume_uow_is_cancelled spy_worker = spy(self.worker) spy_worker._process_single_document(get_valid_and_stale_uow()) verify(self.publisher, times=0).publish(any(dict))
def testIsInstanceFakesOriginalClass(self): dummy = spy(Dummy()) assert isinstance(dummy, Dummy)
def testHasNiceRepr(self): dummy = spy(Dummy()) assert repr(dummy) == "<SpiedDummy id=%s>" % id(dummy)
def testPreservesReturnValues(self): dummy = Dummy() spiedDummy = spy(dummy) self.assertEqual(dummy.foo(), spiedDummy.foo())
def should_compute_hash(): track = spy(_.track) track.update_hash() verify(_.track._hasher).hash("filename.mp3")
def testPreservesReturnValues(self): dummy = Dummy() spiedDummy = spy(dummy) self.assertEquals(dummy.foo(), spiedDummy.foo())
def testPassesArgumentsCorrectly(self): dummy = spy(Dummy()) self.assertEquals((('foo', 1), { 'bar': 'baz' }), dummy.return_args('foo', 1, bar='baz'))
def test_invalid_and_fresh_uow(self): self.worker.uow_dao.update = assume_uow_is_requested spy_worker = spy(self.worker) spy_worker._process_single_document(get_invalid_and_fresh_uow()) verify(self.publisher, times=1).publish(any(dict))