class TestRingBuffer(TestCase): maxlen = 3 def setUp(self): self.callback = MagicMock() self.instance = RingBufferWithCallback(maxlen=self.maxlen, callback=self.callback) def test_add_one_item(self): self.instance.append(1) self.callback.assert_not_called() def test_add_three_items(self): self.instance.append(1) self.instance.append(2) self.instance.append(3) self.callback.assert_not_called() def test_add_four_items(self): self.test_add_three_items() self.instance.append(4) self.callback.assert_called_with(1) def test_add_five_items(self): self.test_add_four_items() self.instance.append(5) self.callback.assert_called_with(2)
def test_args__version__overrides_default(self): mock_scan = MagicMock(return_value=([], 0)) with patch("doc8.main.scan", mock_scan), patch("argparse._sys.argv", ["doc8", "--version"]): state = main() self.assertEqual(state, 0) mock_scan.assert_not_called()
def test_handle_request_happy_path_no_failures( self, mock_store_validation_results: MagicMock, mock_fetch_validations: MagicMock, mock_run_job: MagicMock, mock_emit_failures: MagicMock, mock_rematerialize_views: MagicMock, ) -> None: mock_fetch_validations.return_value = self._TEST_VALIDATIONS mock_run_job.return_value = DataValidationJobResult( validation_job=self._TEST_VALIDATIONS[0], result_details=FakeValidationResultDetails(passed=True), ) headers = {"X-Appengine-Cron": "test-cron"} response = self.client.get("/validate", headers=headers) self.assertEqual(200, response.status_code) self.assertEqual(_API_RESPONSE_IF_NO_FAILURES, response.get_data().decode()) self.assertEqual(4, mock_run_job.call_count) for job in self._TEST_VALIDATIONS: mock_run_job.assert_any_call(job) mock_rematerialize_views.assert_called() mock_emit_failures.assert_not_called() mock_store_validation_results.assert_called_once() ((results,), _kwargs) = mock_store_validation_results.call_args self.assertEqual(4, len(results))
def test_network_multiple(test): """ test the network_running function with several names """ with patch.dict(virt_utils.__opts__, {"test": test}): start_mock = MagicMock(return_value=True) with patch.dict( virt_utils.__salt__, { "virt.network_info": MagicMock(return_value=TEST_NETS), "virt.network_start": start_mock, }, ): ret = virt_utils.network_running( name="the-state-id", networks=["net0", "net1", "net2", "net3"]) if test: assert ret["result"] is None start_mock.assert_not_called() else: assert ret["result"] assert start_mock.mock_calls == [ call("net2"), call("net3"), ] assert ret["comment"] == "net2, net3 networks have been started" assert ret["changes"] == {"net2": "started", "net3": "started"}
def test_skip_send_after_void(self, mock_rabbit_worker_class): collection = Collection.objects.create( collection_set=self.collection_set, credential=self.credential, harvest_type=Collection.TWITTER_SAMPLE, name="test_collection", harvest_options=json.dumps(self.harvest_options), is_on=True) Harvest.objects.create( collection=collection, historical_collection=collection.history.all()[0], historical_credential=self.credential.history.all()[0], status=Harvest.VOIDED) mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] collection_harvest(collection.id) # Last harvest voided, so this one should be sent. # Harvest start message sent mock_rabbit_worker.assert_not_called() # Harvest start message sent name, args, kwargs = mock_rabbit_worker.mock_calls[0] self.assertEqual("send_message", name) message = args[0] # Harvest model object created harvest = Harvest.objects.get(harvest_id=message["id"]) self.assertEqual(Harvest.REQUESTED, harvest.status)
def test_ensure_webhook_notouch(self): testee = self.get_testee() dest=MagicMock() def replacement_api(path,form_data={},method=None,request_type=None): if path.endswith('/hooks') and (method=='GET' or method is None): return [ { "id": 1, "url": "https://api.github.com/repos/octocat/Hello-World/hooks/1", "test_url": "https://api.github.com/repos/octocat/Hello-World/hooks/1/test", "ping_url": "https://api.github.com/repos/octocat/Hello-World/hooks/1/pings", "name": "web", "events": [ "push", "issue_comment" ], "active": True, "config": { "url": "http://me.com", "content_type": "json" }, "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z" } ] else: return dest(path,form_data=form_data,method=method,request_type=request_type) testee.api = replacement_api testee.ensure_webhook('octocat','Hello-World','http://me.com') dest.assert_not_called()
def OnCompleteDone_NoActionIfNotDone_test( *args ): request = CompletionRequest( None ) request.Done = MagicMock( return_value = False ) action = MagicMock() request._complete_done_hooks[ 'ycmtest' ] = action request.OnCompleteDone() action.assert_not_called()
def test_construction( # pylint: disable=too-many-arguments self, mock_restoration, mock_notebook, mock_set_status, mock_status, mock_set_menu, mock_menu, ): mock_holder = MagicMock() mock_holder.attach_mock(mock_menu, 'ConfigFrameMenuBar') mock_holder.attach_mock(mock_set_menu, 'SetMenuBar') mock_holder.attach_mock(mock_status, 'ConfigFrameStatusBar') mock_holder.attach_mock(mock_set_status, 'SetStatusBar') mock_holder.attach_mock(mock_notebook, 'construct_notebook') mock_holder.attach_mock(mock_restoration, 'toggle_restoration') mock_holder.assert_not_called() self.frame.construct_gui() print(mock_holder.mock_calls) mock_holder.assert_has_calls( [ call.ConfigFrameMenuBar(), call.SetMenuBar(self.MENU_BAR), call.ConfigFrameStatusBar(self.frame), call.SetStatusBar(self.STATUS_BAR), call.construct_notebook(), call.toggle_restoration() ], True )
def test_main(self): init1_call = MagicMock() init2_call = MagicMock() class SomeClass(object): __metaclass__ = MutexInitMeta @subinit def init1(self, param1, param2): init1_call() @subinit def init2(self, param2, param3): init2_call() obj = SomeClass(param1=0, param2=0) init1_call.assert_called_once_with() init2_call.assert_not_called() obj = SomeClass(param2=0, param3=0) init1_call.assert_called_once_with() # This is the previous call init2_call.assert_called_once_with() self.assertRaises(AttributeError, SomeClass, blablabla=0) init1_call.assert_called_once_with() # This is the previous call again init2_call.assert_called_once_with() # This is the previous call self.assertRaises(AttributeError, SomeClass, param1=None, param2=0) init1_call.assert_called_once_with() # This is the previous call init2_call.assert_called_once_with() # This is the previous call
def test_init( self, async_used: bool, caplog: LogCaptureFixture, fx_deployments: YamlLoaderDeployment, mocker: MockerFixture, runway_context: MockRunwayContext, ) -> None: """Test init.""" caplog.set_level(logging.INFO, logger="runway") mock_async = MagicMock() mocker.patch.object(Deployment, "_Deployment__async", mock_async) mock_sync = MagicMock() mocker.patch.object(Deployment, "_Deployment__sync", mock_sync) runway_context._use_concurrent = async_used obj = Deployment( context=runway_context, definition=fx_deployments.load("simple_parallel_regions"), ) assert obj.init() if async_used: mock_async.assert_called_once_with("init") mock_sync.assert_not_called() else: mock_async.assert_not_called() mock_sync.assert_called_once_with("init")
def test_disabled(self, mock_django_timezone: mock.MagicMock, mock_queue_digest_recipient: mock.MagicMock) -> None: cutoff = timezone_now() # A Tuesday mock_django_timezone.return_value = datetime.datetime(year=2016, month=1, day=5) enqueue_emails(cutoff) mock_queue_digest_recipient.assert_not_called()
class RedirectFileDescriptorsUnitTests(DaemonTestCase): def setUp(self): DaemonTestCase.setUp(self) dup2_patcher = patch('py_rofi_bus.components.daemon.dup2') self.mock_dup2 = dup2_patcher.start() self.addCleanup(dup2_patcher.stop) self.mock_stdout_flush = MagicMock() self.mock_stderr_flush = MagicMock() stdin_patcher = patch('py_rofi_bus.components.daemon.stdin') self.mock_stdin = stdin_patcher.start() self.addCleanup(stdin_patcher.stop) stdout_patcher = patch( 'py_rofi_bus.components.daemon.stdout', return_value=MagicMock( flush=self.mock_stdout_flush, ), ) self.mock_stdout = stdout_patcher.start() self.addCleanup(stdout_patcher.stop) stderr_patcher = patch( 'py_rofi_bus.components.daemon.stderr', return_value=MagicMock( flush=self.mock_stderr_flush, ), ) self.mock_stderr = stderr_patcher.start() self.addCleanup(stderr_patcher.stop) def test_flush_calls(self): self.mock_stdout_flush.assert_not_called() self.mock_stderr_flush.assert_not_called() self.daemon.redirect_file_descriptors()
def test_send_event_sends_overlapped_events(self, device_transport): fake_msg_1 = create_fake_message() fake_msg_2 = Message(fake_event_2) mock_mqtt_provider = device_transport._pipeline.provider # connect device_transport.connect() mock_mqtt_provider.on_mqtt_connected() # send an event callback_1 = MagicMock() device_transport.send_event(fake_msg_1, callback_1) mock_mqtt_provider.publish.assert_called_once_with( topic=encoded_fake_topic, payload=fake_msg_1.data, callback=ANY) # while we're waiting for that send to complete, send another event callback_2 = MagicMock() device_transport.send_event(fake_msg_2, callback_2) # verify that we've called publish twice and verify that neither send_event # has completed (because we didn't do anything here to complete it). assert mock_mqtt_provider.publish.call_count == 2 callback_1.assert_not_called() callback_2.assert_not_called()
class TestRequest(unittest.TestCase): def setUp(self): self.callback = MagicMock() self.o = Request(32, self.callback) def test_init(self): assert self.o.id == 32 assert self.o.callback == self.callback def test_respond_with_return(self): cb, response = self.o.return_response(value=5) assert cb == self.callback assert response == Return(id=32, value=5) def test_respond_with_error(self): cb, response = self.o.error_response( exception=ValueError("Test Error")) assert cb == self.callback assert response == Error(id=32, message="ValueError: Test Error") def test_setters(self): self.o.set_id(123) assert 123 == self.o.id self.o.set_callback(None) self.o.callback(888) self.callback.assert_not_called()
def test_handle_request_happy_path_should_update_views( self, mock_store_validation_results: MagicMock, mock_fetch_validations: MagicMock, mock_run_job: MagicMock, mock_emit_failures: MagicMock, mock_rematerialize_views: MagicMock, ) -> None: mock_fetch_validations.return_value = [] headers = {"X-Appengine-Cron": "test-cron"} response = self.client.get("/validate", headers=headers) self.assertEqual(200, response.status_code) self.assertEqual(_API_RESPONSE_IF_NO_FAILURES, response.get_data().decode()) mock_run_job.assert_not_called() mock_emit_failures.assert_not_called() self.maxDiff = None expected_update_calls = [ call( view_source_table_datasets=VIEW_SOURCE_TABLE_DATASETS, views_to_update_builders=DEPLOYED_VIEW_BUILDERS, all_view_builders=DEPLOYED_VIEW_BUILDERS, ), ] self.assertEqual( len(mock_rematerialize_views.call_args_list), len(expected_update_calls) ) mock_store_validation_results.assert_called_once() ((results,), _kwargs) = mock_store_validation_results.call_args self.assertEqual(0, len(results))
def test_handle_backend_no_handler( self, caplog: LogCaptureFixture, mocker: MockerFixture, runway_context: MockRunwayContext, tmp_path: Path, ) -> None: """Test handle_backend with no handler.""" caplog.set_level(LogLevels.DEBUG, logger=MODULE) mock_get_full_configuration = MagicMock(return_value={}) backend: Dict[str, Union[Dict[str, Any], str]] = { "type": "unsupported", "config": {}, } obj = Terraform(runway_context, module_root=tmp_path) mocker.patch.object(obj, "tfenv", MagicMock(backend=backend)) mocker.patch.object( obj.options.backend_config, "get_full_configuration", mock_get_full_configuration, ) assert not obj.handle_backend() mock_get_full_configuration.assert_not_called() assert 'backed "unsupported" does not require special handling' in "\n".join( caplog.messages)
def test_destroy( self, async_used: bool, fx_deployments: YamlLoaderDeployment, mocker: MockerFixture, runway_context: MockRunwayContext, ) -> None: """Test destroy.""" mock_async = MagicMock() mocker.patch.object(Deployment, "_Deployment__async", mock_async) mock_sync = MagicMock() mocker.patch.object(Deployment, "_Deployment__sync", mock_sync) runway_context._use_concurrent = async_used obj = Deployment( context=runway_context, definition=fx_deployments.load("simple_parallel_regions"), ) assert obj.destroy() if async_used: mock_async.assert_called_once_with("destroy") mock_sync.assert_not_called() else: mock_async.assert_not_called() mock_sync.assert_called_once_with("destroy")
def test(use_gloo, use_mpi, use_js, gloo_is_built, mpi_is_built, lsf_exists, jsrun_installed, expected, exception): gloo_run = MagicMock() mpi_run = MagicMock() js_run = MagicMock() with is_built(gloo_is_built, mpi_is_built): with lsf_and_jsrun(lsf_exists, jsrun_installed): if exception is not None: with pytest.raises(ValueError, match=exception) as e: run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) return run_controller(use_gloo, gloo_run, use_mpi, mpi_run, use_js, js_run, verbosity=2) if expected == "gloo": gloo_run.assert_called_once() mpi_run.assert_not_called() js_run.assert_not_called() elif expected == "mpi": gloo_run.assert_not_called() mpi_run.assert_called_once() js_run.assert_not_called() elif expected == "js": gloo_run.assert_not_called() mpi_run.assert_not_called() js_run.assert_called_once() else: raise ValueError("unsupported framework: {}".format(expected))
def test_plan( self, async_used: bool, caplog: LogCaptureFixture, fx_deployments: YamlLoaderDeployment, mocker: MockerFixture, runway_context: MockRunwayContext, ) -> None: """Test plan.""" caplog.set_level(logging.INFO, logger="runway") mock_async = MagicMock() mocker.patch.object(Deployment, "_Deployment__async", mock_async) mock_sync = MagicMock() mocker.patch.object(Deployment, "_Deployment__sync", mock_sync) runway_context._use_concurrent = async_used obj = Deployment( context=runway_context, definition=fx_deployments.load("simple_parallel_regions"), ) assert obj.plan() if async_used: assert ("unnamed_deployment:processing of regions will be done in " "parallel during deploy/destroy" in caplog.messages) mock_async.assert_not_called() mock_sync.assert_called_once_with("plan")
def test_aws_relationship_external(self): fake_class_instance = MagicMock() FakeClass = MagicMock(return_value=fake_class_instance) mock_func = MagicMock() @decorators.aws_relationship(class_decl=FakeClass) def test_with_mock(*args, **kwargs): mock_func(*args, **kwargs) _ctx = self._gen_decorators_realation_context(test_properties={ 'use_external_resource': True }) test_with_mock(ctx=_ctx) mock_func.assert_not_called() # force run test_with_mock(ctx=_ctx, force_operation=True) mock_func.assert_called_with( ctx=_ctx, iface=fake_class_instance, resource_config={}, force_operation=True, resource_type='AWS Resource')
def test_cache_file_not_existing(self, timer: MagicMock, getmtime: MagicMock, exists: MagicMock): exists.return_value = False f = create_facility() f._download = download = MagicMock() download.return_value = "downloaded data" f._write_cache_file = write_cache_file = MagicMock() f._read_cache_file = read_cache_file = MagicMock() f._process = process = MagicMock() f._unzip = unzip = MagicMock() timer.return_value = timer_instance = MagicMock() f._run() download.assert_called() process.assert_called() unzip.assert_called() getmtime.assert_not_called() write_cache_file.assert_called_once_with("downloaded data") read_cache_file.assert_not_called() timer.assert_called_once_with(CHECK_INTERVAL, f._run) timer_instance.start.assert_called()
def test_skip_send(self, mock_rabbit_worker_class): collection = Collection.objects.create( collection_set=self.collection_set, credential=self.credential, harvest_type=Collection.TWITTER_SAMPLE, name="test_collection", harvest_options=json.dumps(self.harvest_options), is_active=True, ) Harvest.objects.create( collection=collection, historical_collection=collection.history.all()[0], historical_credential=self.credential.history.all()[0], ) mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] collection_harvest(collection.id) # Last harvest isn't done, so skip this harvest. # Harvest start message not sent mock_rabbit_worker.assert_not_called() # Harvest model object created harvest = collection.last_harvest(include_skipped=True) self.assertEqual(Harvest.SKIPPED, harvest.status)
def test_skip_send(self, mock_rabbit_worker_class): collection = Collection.objects.create( collection_set=self.collection_set, credential=self.credential, harvest_type=Collection.TWITTER_SAMPLE, name="test_collection", harvest_options=json.dumps(self.harvest_options), is_on=True) Harvest.objects.create( collection=collection, historical_collection=collection.history.all()[0], historical_credential=self.credential.history.all()[0]) mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] collection_harvest(collection.id) # Last harvest isn't done, so skip this harvest. # Harvest start message not sent mock_rabbit_worker.assert_not_called() # Harvest model object created harvest = collection.last_harvest(include_skipped=True) self.assertEqual(Harvest.SKIPPED, harvest.status)
def test_skip_send_after_void(self, mock_rabbit_worker_class): collection = Collection.objects.create( collection_set=self.collection_set, credential=self.credential, harvest_type=Collection.TWITTER_SAMPLE, name="test_collection", harvest_options=json.dumps(self.harvest_options), is_active=True, ) Harvest.objects.create( collection=collection, historical_collection=collection.history.all()[0], historical_credential=self.credential.history.all()[0], status=Harvest.VOIDED, ) mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] collection_harvest(collection.id) # Last harvest voided, so this one should be sent. # Harvest start message sent mock_rabbit_worker.assert_not_called() # Harvest start message sent name, args, kwargs = mock_rabbit_worker.mock_calls[0] self.assertEqual("send_message", name) message = args[0] # Harvest model object created harvest = Harvest.objects.get(harvest_id=message["id"]) self.assertEqual(Harvest.REQUESTED, harvest.status)
def test_missing_collection(self, mock_rabbit_worker_class): mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] # Error should be logged and nothing happens collection_stop(1234567) mock_rabbit_worker.assert_not_called()
def test_should_not_use_crf_when_dataset_with_no_slots(self): # Given dataset = { "language": "en", "intents": { "intent1": { "utterances": [{ "data": [{ "text": "This is an utterance without " "slots" }] }] } }, "entities": {} } slot_filler = CRFSlotFiller(**self.get_shared_data(dataset)) mock_compute_features = MagicMock() slot_filler.compute_features = mock_compute_features # When slot_filler.fit(dataset, "intent1") slots = slot_filler.get_slots("This is an utterance without slots") # Then mock_compute_features.assert_not_called() self.assertListEqual([], slots)
def test_should_raise_exception_if_stack_creation_lasts_longer_than_timeout( self): stack_name = 'test-stack' stack_version = 'test-version' image_version = '0.0.0' timeout = 0 senza_wrapper = SenzaWrapper(TEST_CONFIG) senza_wrapper.set_stack_creation_retry_timeout(timeout) create_mock = MagicMock(return_value=0) subprocess.call = create_mock events_mock = MagicMock() subprocess.check_output = events_mock with self.assertRaisesRegex( Exception, 'Timeout while creating new stack version'): senza_wrapper.create_stack(stack_name, stack_version, image_version) create_mock.assert_called_once_with([ 'senza', 'create', '--region', 'eu-west-1', '--disable-rollback', TEST_CONFIG, stack_version, 'ImageVersion=' + image_version ]) events_mock.assert_not_called()
def test_missing_collection_harvest(self, mock_rabbit_worker_class): mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] # Error should be logged and nothing happens collection_harvest(1234567) mock_rabbit_worker.assert_not_called()
def test_pool_running(test): """ test the pool_running function with only one name """ with patch.dict(virt_utils.__opts__, {"test": test}): start_mock = MagicMock(return_value=True) refresh_mock = MagicMock(return_value=True) with patch.dict( virt_utils.__salt__, { "virt.pool_info": MagicMock(return_value=TEST_POOLS), "virt.pool_start": start_mock, "virt.pool_refresh": refresh_mock, }, ): ret = virt_utils.pool_running(name="pool2") if test: assert ret["result"] is None start_mock.assert_not_called() else: assert ret["result"] start_mock.assert_called_with("pool2") refresh_mock.assert_not_called() assert ret["comment"] == "pool2 pool has been started" assert ret["changes"] == {"pool2": "started"}
def test_packet_action(self): # Callback must be callable with self.assertRaises(TypeError): self.environment.add_packet_action("waypoint_add", "no_function") mock_callback = MagicMock() self.environment.add_packet_action("waypoint_add", mock_callback) # Not allowed to add more than one callback for a packet specification. with self.assertRaises(KeyError): self.environment.add_packet_action("waypoint_add", MagicMock()) # Callback is called for correct specification. packet = Packet() packet.set("specification", "waypoint_add") packet.set("latitude", 12.345) packet.set("longitude", 32.109) packet.set("to_id", 1) self.environment.receive_packet(packet) mock_callback.assert_called_once_with(packet) # Callback is not called for another specification. mock_callback.reset_mock() packet = Packet() packet.set("specification", "waypoint_clear") packet.set("to_id", 1) self.environment.receive_packet(packet) mock_callback.assert_not_called()
class TestLocalFileSystem(LogTestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.first_receiver = MagicMock(spec=ActorRef) self.second_receiver = MagicMock(spec=ActorRef) self.lfs = LocalFileSystem.start([self.first_receiver, self.second_receiver], self.tmpdir, TEST_RELOAD_LOCAL_FILES_SEC) def tearDown(self): self.lfs.stop() shutil.rmtree(self.tmpdir) def addFile(self, filenames): for filename in filenames: with open(self.tmpdir + "/" + filename, "w") as f: f.write("FOOBAR") def test_add_one_file_in_folder(self): self.first_receiver.assert_not_called() self.second_receiver.assert_not_called() new_file = ['some_file_test1.txt'] self.addFile(new_file) sleep(TEST_WAIT) self.first_receiver.tell.assert_called_once_with(local_files_message(new_file)) self.second_receiver.tell.assert_called_once_with(local_files_message(new_file)) def test_add_three_files_in_folder(self): new_files = ['some_file_test2.txt', 'some_file2_test2.txt', 'some_file3_test2.txt'] self.addFile(new_files) sleep(TEST_WAIT) self.first_receiver.tell.assert_called_with(local_files_message(AllItemsIn(new_files))) self.second_receiver.tell.assert_called_with(local_files_message(AllItemsIn(new_files)))
class TestRequest(unittest.TestCase): def setUp(self): self.callback = MagicMock() self.o = Request(32) self.o.set_callback(self.callback) def test_init(self): assert self.o.id == 32 assert self.o.callback == self.callback def test_respond_with_return(self): cb, response = self.o.return_response(value=5) assert cb == self.callback assert response.to_dict() == Return(id=32, value=5).to_dict() def test_respond_with_error(self): cb, response = self.o.error_response( exception=ValueError("Test Error")) assert cb == self.callback assert response.to_dict() == Error(id=32, message=ANY).to_dict() assert str(response.message) == "Test Error" def test_setters(self): self.o.set_callback(MagicMock()) self.o.callback(888) self.callback.assert_not_called()
def test_check_jobs(jobResetAgent): """Test for checkJobs function.""" jobIDs = [1, 2] dummy_treatJobWithNoReq = MagicMock() dummy_treatJobWithReq = MagicMock() # if the readRequestsForJobs func returns error than checkJobs should exit and return an error jobResetAgent.reqClient.readRequestsForJobs.return_value = S_ERROR() res = jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) assert not res["OK"] # test if correct treatment functions are called jobResetAgent.reqClient.readRequestsForJobs.return_value = S_OK({'Successful': {}, 'Failed': {jobIDs[0]: 'Request not found'}}) jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) dummy_treatJobWithNoReq.assert_has_calls([call(jobIDs[0]), call(jobIDs[1])]) dummy_treatJobWithReq.assert_not_called() dummy_treatJobWithNoReq.reset_mock() req1 = Request({"RequestID": 1}) req2 = Request({"RequestID": 2}) jobResetAgent.reqClient.readRequestsForJobs.return_value = S_OK({'Successful': {jobIDs[0]: req1, jobIDs[1]: req2}, 'Failed': {}}) jobResetAgent.checkJobs(jobIDs, treatJobWithNoReq=dummy_treatJobWithNoReq, treatJobWithReq=dummy_treatJobWithReq) dummy_treatJobWithNoReq.assert_not_called() dummy_treatJobWithReq.assert_has_calls([call(jobIDs[0], req1), call(jobIDs[1], req2)])
class PrintAllHelpUnitTests(ApplicationTestCase): def setUp(self): ApplicationTestCase.setUp(self) self.mock_parser_help = MagicMock() self.mock_subparser_help = MagicMock() self.parser = MagicMock( print_help=self.mock_parser_help, _subparsers=MagicMock(_actions=[ MagicMock(choices={ 'any': MagicMock(print_help=self.mock_subparser_help) }) ])) sys_exit_patcher = patch('gitflow_easyrelease.application.sys_exit') self.mock_sys_exit = sys_exit_patcher.start() self.addCleanup(sys_exit_patcher.stop) def test_exit(self): self.mock_sys_exit.assert_not_called() Application.print_all_help(self.parser) self.mock_sys_exit.assert_called_once_with(0) def test_main_help(self): self.mock_parser_help.assert_not_called() Application.print_all_help(self.parser) self.mock_parser_help.assert_called_with() def test_subparser_help(self): self.mock_subparser_help.assert_not_called() Application.print_all_help(self.parser) self.mock_subparser_help.assert_called_with()
class AttachVersionArgumentUnitTests(SubcommandTestCase): COLOR = MagicMock() def setUp(self): SubcommandTestCase.setUp(self) color_output_patcher = patch( 'gitflow_easyrelease.subcommand.ColorOutput', return_value=self.COLOR ) self.mock_color_output = color_output_patcher.start() self.addCleanup(color_output_patcher.stop) self.mock_add = MagicMock() self.parser = MagicMock(add_argument=self.mock_add) def test_color_output(self): self.mock_color_output.assert_not_called() Subcommand.attach_version_argument( self.parser, self.subcommand.version_optional ) self.mock_color_output.assert_called_once_with() def test_add_call(self): self.mock_add.assert_not_called() Subcommand.attach_version_argument( self.parser, self.subcommand.version_optional ) self.mock_add.assert_called_once()
def test_aws_relationship_external(self): fake_class_instance = MagicMock() FakeClass = MagicMock(return_value=fake_class_instance) mock_func = MagicMock() @decorators.aws_relationship(class_decl=FakeClass) def test_with_mock(*args, **kwargs): mock_func(*args, **kwargs) _ctx = self._gen_decorators_realation_context( test_properties={'use_external_resource': True}) test_with_mock(ctx=_ctx) mock_func.assert_not_called() # force run test_with_mock(ctx=_ctx, force_operation=True) mock_func.assert_called_with(ctx=_ctx, iface=fake_class_instance, resource_config={}, force_operation=True, resource_type='AWS Resource')
def test_discover(self, bind_mock): bind_mock.configure_mock(side_effect=socket.error(errno.EADDRINUSE, "port in use")) callback_mock = MagicMock() self.rf_sensor.discover(callback_mock) bind_calls = bind_mock.call_args_list callback_calls = callback_mock.call_args_list self.assertEqual(len(bind_calls), self.rf_sensor.number_of_sensors) self.assertEqual(len(callback_calls), self.rf_sensor.number_of_sensors) # Each vehicle must be checked whether its port is in use, and # successfully report the identity of its RF sensor in order. for vehicle_id in xrange(1, self.rf_sensor.number_of_sensors + 1): expected_address = (self.rf_sensor._ip, self.rf_sensor._port + vehicle_id) address = bind_calls.pop(0)[0][0] self.assertEqual(address, expected_address) response = callback_calls.pop(0)[0][0] self.assertEqual(response, { "id": vehicle_id, "address": "{}:{}".format(*expected_address) }) callback_mock.reset_mock() bind_mock.reset_mock() bind_mock.configure_mock(side_effect=None) self.rf_sensor.discover(callback_mock, required_sensors=set([1])) bind_mock.assert_called_once_with((self.rf_sensor._ip, self.rf_sensor._port + 1)) callback_mock.assert_not_called()
def test_stop_bofore_execute(self): execute_mock = MagicMock() self.trackers_manager.execute = execute_mock self.create_runner() self.stop_runner() execute_mock.assert_not_called()
def test_add_exists_without_force(): fs = test_add_success() dummy_uploader = MagicMock(return_value=MagicMock(ids=hashIds2, size=327)) adder = add.AddController(fs, dummy_uploader) with assert_raises(add.FileExistsError): adder("Movies/midsummer.mp4", mtime=0) dummy_uploader.assert_not_called() assert_equal(adder.added, set())
def test_composite_calls_rest(): warmup_steps = np.random.randint(50, 101) warm = MagicMock() warm.warmup_steps = warmup_steps rest = MagicMock() lr = CompositeLRScheduler(warm=warm, rest=rest) step = np.random.randint(warmup_steps + 1, six.MAXSIZE) _ = lr(step) warm.assert_not_called() rest.assert_called_once_with(step - warmup_steps)
def test_check_fail_get_cache(): checker = MagicMock(return_value=False) with patch.object(cache, 'get') as cache_get_mock: cache_get_mock.return_value = 'dead' check_db(checker, 'default', 10) cache_get_mock.assert_called_once_with('%s:MagicMock:default' % hostname) checker.assert_not_called()
def test_stop_bofore_execute(self): execute_mock = MagicMock() self.trackers_manager.execute = execute_mock clients_manager = ClientsManager({}) engine_runner = EngineRunner(Logger(), self.trackers_manager, clients_manager, interval=0.1) engine_runner.stop() engine_runner.join(1) self.assertFalse(engine_runner.is_alive()) execute_mock.assert_not_called()
def test_find_torrent_false(self): find_torrent_mock1 = MagicMock(return_value=None) find_torrent_mock2 = MagicMock(return_value=None) self.client1.find_torrent = find_torrent_mock1 self.client2.find_torrent = find_torrent_mock2 torrent_hash = 'hash' self.assertFalse(self.clients_manager.find_torrent(torrent_hash)) find_torrent_mock1.assert_called_once_with(torrent_hash) find_torrent_mock2.assert_not_called()
def test_remove_torrent_false(self): remove_torrent_mock1 = MagicMock(return_value=False) remove_torrent_mock2 = MagicMock(return_value=False) self.client1.remove_torrent = remove_torrent_mock1 self.client2.remove_torrent = remove_torrent_mock2 torrent_hash = 'hash' self.assertFalse(self.clients_manager.remove_torrent(torrent_hash)) remove_torrent_mock1.assert_called_once_with(torrent_hash) remove_torrent_mock2.assert_not_called()
def test_add_torrent_false(self): add_torrent_mock1 = MagicMock(return_value=False) add_torrent_mock2 = MagicMock(return_value=False) self.client1.add_torrent = add_torrent_mock1 self.client2.add_torrent = add_torrent_mock2 torrent = b'!torrent_file' self.assertFalse(self.clients_manager.add_torrent(torrent)) add_torrent_mock1.assert_called_once_with(torrent) add_torrent_mock2.assert_not_called()
def test_find_torrent_true(self): result = {'name': 'movie.torrent'} find_torrent_mock1 = MagicMock(return_value=result) find_torrent_mock2 = MagicMock(return_value=None) self.client1.find_torrent = find_torrent_mock1 self.client2.find_torrent = find_torrent_mock2 torrent_hash = 'hash' self.assertEqual(result, self.clients_manager.find_torrent(torrent_hash)) find_torrent_mock1.assert_called_once_with(torrent_hash) find_torrent_mock2.assert_not_called()
def test_set_settings(self): settings = {'login': '******', 'password': '******'} set_settings1_mock = MagicMock(return_value=True) set_settings2_mock = MagicMock(return_value=True) self.client1.set_settings = set_settings1_mock self.client2.set_settings = set_settings2_mock self.assertTrue(self.clients_manager.set_settings(self.CLIENT1_NAME, settings)) set_settings1_mock.assert_called_with(settings) set_settings2_mock.assert_not_called()
def test_remove_torrent_true_default_client2(self): remove_torrent_mock1 = MagicMock(return_value=False) remove_torrent_mock2 = MagicMock(return_value=True) self.client1.remove_torrent = remove_torrent_mock1 self.client2.remove_torrent = remove_torrent_mock2 torrent_hash = 'hash' self.clients_manager.set_default(self.CLIENT2_NAME) self.assertTrue(self.clients_manager.remove_torrent(torrent_hash)) remove_torrent_mock1.assert_not_called() remove_torrent_mock2.assert_called_once_with(torrent_hash)
def test_add_torrent_true_default_client2(self): add_torrent_mock1 = MagicMock(return_value=False) add_torrent_mock2 = MagicMock(return_value=True) self.client1.add_torrent = add_torrent_mock1 self.client2.add_torrent = add_torrent_mock2 torrent = '!torrent_file' self.clients_manager.set_default(self.CLIENT2_NAME) self.assertTrue(self.clients_manager.add_torrent(torrent)) add_torrent_mock1.assert_not_called() add_torrent_mock2.assert_called_once_with(torrent)
def test_handle_lirc_code(self): # Test normal event callback. self.infrared_sensor.register("start", self.mock_callback) self.infrared_sensor._handle_lirc_code(None) self.mock_callback.assert_not_called() self.infrared_sensor._handle_lirc_code(['start']) self.mock_callback.assert_called_once_with() # Test additional release callback. self.mock_callback.reset_mock() mock_stop_callback = MagicMock() mock_stop_release_callback = MagicMock() self.infrared_sensor.register("stop", mock_stop_callback, mock_stop_release_callback) self.infrared_sensor._handle_lirc_code(None) mock_stop_callback.assert_not_called() mock_stop_release_callback.assert_not_called() self.infrared_sensor._handle_lirc_code(['stop']) mock_stop_callback.assert_called_once_with() mock_stop_release_callback.assert_not_called() # The release callback is called once the stop code is not provided. # The normal callback is not called. Another non-code does not call the # release callback again. mock_stop_callback.reset_mock() self.infrared_sensor._handle_lirc_code(None) self.infrared_sensor._handle_lirc_code(None) mock_stop_callback.assert_not_called() mock_stop_release_callback.assert_called_once_with() # Start button was not pressed, so its callback is not called. self.mock_callback.assert_not_called()
class TestContext(unittest.TestCase): def setUp(self): self.target_method1 = MagicMock() self.target_method2 = MagicMock() self.context = Context() def test_append_one_handler_to_one_control(self): control_name = 'test' self.context.add_app_handler('ActionEvent', control_name, self.target_method1) event_arg = ActionEvent(control_name) self.context.invoke(event_arg) self.target_method1.assert_called_with(event_arg) def test_append_two_handlers_to_one_control(self): control_name = 'test' self.context.add_app_handler('ActionEvent', control_name, self.target_method1) self.context.add_app_handler('ActionEvent', control_name, self.target_method2) event_arg = ActionEvent(control_name) self.context.invoke(event_arg) self.target_method1.assert_called_with(event_arg) self.target_method2.assert_called_with(event_arg) def test_append_handler_to_two_controls_and_invoke_one_crontrol(self): control_name1 = 'test1' control_name2 = 'test2' self.context.add_app_handler('ActionEvent', control_name1, self.target_method1) self.context.add_app_handler('ActionEvent', control_name2, self.target_method2) event_arg = ActionEvent(control_name1) self.context.invoke(event_arg) self.target_method1.assert_called_with(event_arg) self.target_method2.assert_not_called() def test_append_two_command_types(self): control_name = 'test' self.context.add_app_handler('ActionEvent', control_name, self.target_method1) self.context.add_app_handler('OpenEvent', control_name, self.target_method2) event_arg = ActionEvent(control_name) self.context.invoke(event_arg) self.target_method1.assert_called_with(event_arg) self.target_method2.assert_not_called()
def test_send_test_message(self): notify1 = MagicMock() notify2 = MagicMock() self.notifier1.notify = notify1 self.notifier2.notify = notify2 self.notifier_manager.send_test_message(self.NOTIFIER1_NAME) notify1.assert_called_once_with("Test Message", "This is monitorrent test message", "https://github.com/werwolfby/monitorrent") notify2.assert_not_called() self.notifier_manager.send_test_message(self.NOTIFIER2_NAME) notify2.assert_called_once_with("Test Message", "This is monitorrent test message", "https://github.com/werwolfby/monitorrent")
def test_get_settings(self): settings1 = {'login': '******', 'password': '******'} settings2 = {'login': '******', 'password': '******'} get_settings1_mock = MagicMock(return_value=settings1) get_settings2_mock = MagicMock(return_value=settings2) self.client1.get_settings = get_settings1_mock self.client2.get_settings = get_settings2_mock settings = self.clients_manager.get_settings(self.CLIENT1_NAME) self.assertEqual(settings1, settings) get_settings1_mock.assert_called_with() get_settings2_mock.assert_not_called()
def test_missing_seeds(self, mock_rabbit_worker_class): collection = Collection.objects.create( collection_set=self.collection_set, credential=self.credential, harvest_type=Collection.TWITTER_USER_TIMELINE, name="test_collection", harvest_options=json.dumps(self.harvest_options), is_active=True, ) mock_rabbit_worker = MagicMock(spec=RabbitWorker) mock_rabbit_worker_class.side_effect = [mock_rabbit_worker] # Error should be logged and nothing happens collection_harvest(collection.id) mock_rabbit_worker.assert_not_called()