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_snmp_v2_recording_custom_oids(self, open_mock, snmp_v2_params, snmp_orch_mock): # Setup recorder = self.get_recorder(self.REC_All) snmp_community = "test_public" oids_list = ["test", "test"] create_recording_mock = MagicMock() snmp_orch_mock.return_value.create_recording = create_recording_mock open_mock.return_value.__enter__.return_value.read.return_value.split.return_value = oids_list # Act recorder._new_snmp_recording(snmp_community=snmp_community, snmp_record="template:.\\path_to_file") # Assert snmp_v2_params.assert_called_once_with(self.IP, snmp_community=snmp_community, is_ipv6=False, port=self.PORT, timeout=2000, retry_count=2, get_bulk_flag=False, get_bulk_repetitions=25, continue_on_errors=0, v3_context_engine_id=None, v3_context='') snmp_orch_mock.assert_called_once_with(snmp_v2_params.return_value, auto_detect_vendor=False, template_oid_list=oids_list) create_recording_mock.assert_called_once()
def test_on_menu_action_previously_generated_games(default_main_window, mocker, os_type, throw_exception, monkeypatch): mock_start_file = MagicMock() mock_subprocess_run = MagicMock() monkeypatch.setattr(os, "startfile", mock_start_file, raising=False) monkeypatch.setattr(subprocess, "run", mock_subprocess_run, raising=False) mocker.patch("platform.system", return_value=os_type) mock_message_box = mocker.patch("PySide2.QtWidgets.QMessageBox") # Run if throw_exception: if os_type == "Windows": mock_start_file.side_effect = OSError() else: mock_subprocess_run.side_effect = OSError() default_main_window._on_menu_action_previously_generated_games() # Assert if throw_exception: mock_message_box.return_value.show.assert_called_once() else: if os_type == "Windows": mock_start_file.assert_called_once() mock_message_box.return_value.show.assert_not_called() else: mock_subprocess_run.assert_called_once() mock_message_box.return_value.show.assert_not_called()
def test_supports_listeners(): class TestObject(object): def __init__(self, prop): self.prop = prop @supports_listeners def test_method(self): self.test_method.event.emit(self.prop) return self.prop object1 = TestObject(1) object2 = TestObject(2) # assert object1.test_method is object1.test_method assert object1.test_method.event is object1.test_method.event assert object1.test_method.event is not object2.test_method.event callback = MagicMock() object1.test_method.event.add_listener(callback) assert object1.test_method.event is not object2.test_method.event assert object1.test_method.event is object1.test_method.event assert object1.test_method() == 1 assert object2.test_method() == 2 callback.assert_called_once()
def test_show_notification(): """tests the functionality of showing notifications""" # creating mock ipc object rpc_mock = MagicMock() cc.ipc_gui.rpc_object = rpc_mock title = 'title' description = 'description' path_to_image = ['path', 'to', 'image.png'] path_to_action = ['path', 'to', 'action'] cc.ipc_gui.displayNotification(title, description, path_to_image, path_to_action) args = { 'title': title, 'description': description, 'imagePath': path_to_image, 'actionPath': path_to_action } sleep(3) # checking call rpc_mock.assert_called_once() _, kwargs = rpc_mock.call_args assert kwargs['method'] == 'displayNotification' # checking arguments arguments = kwargs['args'][0][0] assert arguments == args
def test_it_delegates_all_remove_vlan_calls_to_supplied_callback(self): unique_message = 'Unique Result' remove_vlan_function = MagicMock( side_effect=lambda action: ConnectivitySuccessResponse( action, unique_message)) # Arrange remove_vlan_action = self._stub_remove_vlan_action( full_address='192.1.3.4/1', full_name='res1/port1', vlan_id='200') server_request = DriverRequest() server_request.actions = [remove_vlan_action] request_json = jsonpickle.encode( DriverRequestSimulation(server_request), unpicklable=False) # Act result = apply_connectivity_changes( request=request_json, logger=self.logger, add_vlan_action={}, remove_vlan_action=remove_vlan_function) # Assert remove_vlan_function.assert_called_once() response = result.driverResponse """:type : DriverResponse """ action_results = response.actionResults """:type : list[ConnectivityActionResult] """ # We validate that the action was delegated by looking for th eunique value we returned self.assertEqual(action_results[0].infoMessage, unique_message)
def test_inspire_filter_factory(inspire_app, override_config): index_name = "test_facet_aggs" mock_filter = MagicMock() mock_filter_wrapper = MagicMock() mock_filter_wrapper.return_value = mock_filter mock_post_filter = MagicMock() mock_post_filter_wrapper = MagicMock() mock_post_filter_wrapper.return_value = mock_post_filter facets_filter = { "filters": { "type": mock_filter("type") }, "post_filters": { "type": mock_post_filter("type") }, } config = {"RECORDS_REST_FACETS": {index_name: facets_filter}} with override_config(**config): with current_app.test_request_context("?type=FOO&q=BAR"): search = Search() search, urlwargs = inspire_filter_factory(search, index_name) mock_filter.assert_called_once() mock_post_filter.assert_called_once()
def test_with_metaclass(): import momox.compat mc_new_called = MagicMock() class Meta(type): def __new__(mcls, name, bases, attrs): mc_new_called.assert_not_called() mc_new_called() assert name == 'TestClass' assert bases == (object,) assert attrs['testprop'] == 'hello' assert '__init__' in attrs new_attrs = attrs.copy() new_attrs['added_prop'] = 'world' return type.__new__(mcls, name, bases, new_attrs) class TestClass(momox.compat.with_metaclass(Meta, object)): testprop = 'hello' def __init__(self, var): self.var = var tc = TestClass(42) assert tc.var == 42 assert tc.testprop == 'hello' assert tc.added_prop == 'world' tc2 = TestClass(45) mc_new_called.assert_called_once()
def test_trace_flask_propagate(monkeypatch): app = get_flask_app() recorder = get_recorder() propagated_span = MagicMock() propagated_span.context.trace_id = 123 propagated_span.context.span_id = 123456 extract = MagicMock() extract.return_value = propagated_span monkeypatch.setattr('opentracing.tracer.extract', extract) trace_flask(app) with app.app_context(): client = app.test_client() r = client.get('/') assert b'Hello Test' in r.data assert len(recorder.spans) == 1 assert recorder.spans[ 0].context.trace_id == propagated_span.context.trace_id assert recorder.spans[0].parent_id == propagated_span.context.span_id assert recorder.spans[0].tags[ot_tags.COMPONENT] == 'flask' assert recorder.spans[0].tags[ot_tags.HTTP_URL] == 'http://localhost/' assert recorder.spans[0].tags[ot_tags.HTTP_METHOD] == 'GET' assert recorder.spans[0].tags[ot_tags.HTTP_STATUS_CODE] == '200' extract.assert_called_once()
def test_plan( self, mock_action: MagicMock, cfngin_fixtures: Path, tmp_path: Path, patch_safehaven: MagicMock, ) -> None: """Test plan.""" mock_instance = self.configure_mock_action_instance(mock_action) copy_basic_fixtures(cfngin_fixtures, tmp_path) context = self.get_context() cfngin = CFNgin(ctx=context, sys_path=tmp_path) cfngin.plan() mock_action.assert_called_once() mock_instance.execute.assert_called_once_with() patch_safehaven.assert_has_calls( [ call(environ=context.env.vars), call.__enter__(), call(), call.__enter__(), call.__exit__(None, None, None), call.__exit__(None, None, None), ] )
def test_check_argument_count(): do_f1 = MagicMock() do_f2 = MagicMock() do_f1.__name__ = 'do_f1' do_f2.__name__ = 'do_f2' class DerivedWSCli(SwitchboardWSCli): def __init__(self): self.test_func_1_arg = SwitchboardWSCli.check_argument_count(1)( do_f1) self.test_func_2_or_3_args = SwitchboardWSCli.check_argument_count( 2, 3)(do_f2) cli = DerivedWSCli() # Test incorrect number of arguments cli.test_func_1_arg(cli, '') cli.test_func_1_arg(cli, 'arg1 arg2') cli.test_func_2_or_3_args(cli, 'arg1') cli.test_func_2_or_3_args(cli, 'arg1 arg2 arg3 arg4') do_f1.assert_not_called() do_f2.assert_not_called() # Now test with correct number of arguments and make sure the functions have been called cli.test_func_1_arg(cli, 'arg1') cli.test_func_2_or_3_args(cli, 'arg1 arg2') cli.test_func_2_or_3_args(cli, 'arg1 arg2 arg3') do_f1.assert_called_once() do_f2.call_count == 2
def test_process_msg(self): correlate_func = MagicMock() with patch( 'meniscus.correlation.correlator.' 'correlate_syslog_message', correlate_func): self.server.process_msg() correlate_func.assert_called_once()
def test_extract_intents(self): user_intents = MagicMock() nlp = MagicMock() research_question = MagicMock() model_locator = MagicMock() extractor = UserIntentsExtractor(user_intents, nlp, research_question, model_locator) extractor.post_process = Mock() extractor.post_process.return_value = True query = UserQuery(id='query-id', user_id='user-1', query_type='package_search', query_text='Some text') result = extractor.extract_intents(query) assert_true(result is not None) assert_true(result.get('transactional') is not None) assert_true(result.get('informational') is not None) assert_true(result.get('navigational') is not None) user_intents.assert_called_once() user_intents.add_user_intent.assert_called_once extractor.post_process.assert_called_once()
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 assert_task_core_call( task_core: MagicMock, taskname: str, doer: DoerType, *doer_args: Any, test_guest_logger: Optional[str] = None ) -> None: """ Test properties of a mock representing :py:func:`tft.artemis.task.task_core`. The helper verifies several properties of the mock, assuming it has been used to dispatch a task doer. """ # Right, should have been called already. task_core.assert_called_once() # We can't use `assert_called_once_with()` because we have no access to objects passed to the `task_core()` call. # Therefore unpacking the store call information, and testing call properties "manually". _, args, kwargs = task_core.mock_calls[0] # There's one positional argument only, and that's the given doer. assert args == (doer,) # Its arguments are given as a keyword argument... assert kwargs.get('doer_args', tuple()) == doer_args # ... and then there's a task logger object. assert isinstance(kwargs['logger'], TaskLogger) assert kwargs['logger'].taskname == taskname # Some tasks go even beyond task logger by creating a guest logger. If we were given a task name, # let's verify guest logger has been created correctly. if test_guest_logger: assert isinstance(kwargs['logger']._logger, tft.artemis.guest.GuestLogger) assert kwargs['logger']._logger.guestname == test_guest_logger
def test_update_wim_account(self): # Given a WIM account connecting a tenant and a WIM exists self.populate() with self.engine.threads_running(): num_threads = len(self.engine.threads) thread = self.engine.threads[uuid('wim-account00')] reload = MagicMock(wraps=thread.reload) with patch.object(thread, 'reload', reload): # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.put_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim0')), {'wim_account': { 'name': 'account888', 'user': '******' }}) num_threads_after = len(self.engine.threads) # then the wim thread should be restarted reload.assert_called_once() # and no thread should be added or removed self.assertEqual(num_threads_after, num_threads) # and the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(response.json['wim_account']['name'], 'account888') self.assertEqual(response.json['wim_account']['user'], 'user888')
def testUpdateFTB(self): atem = MagicMock() atem.getFadeToBlackState.return_value = { 'full_black': True, 'in_transition': False } atem.getFadeToBlackProperties.return_value = {'rate': 17} ss = SwitcherState(atem) atem.getFadeToBlackState.assert_called_once() atem.getFadeToBlackProperties.assert_called_once() self.assertEqual(17, ss.ftb.rate) self.assertTrue(ss.ftb.active) aHandler = MagicMock() ss.ftb.activeChanged.connect(aHandler) ss.handleMessage(MessageTypes.FTB_CHANGED, {0: { 'full_black': False, 'in_transition': False }}) aHandler.assert_called_once() self.assertFalse(ss.ftb.active) rHandler = MagicMock() ss.ftb.rateChanged.connect(rHandler) ss.handleMessage(MessageTypes.FTB_RATE_CHANGED, {0: 42}) rHandler.assert_called_once_with(42) self.assertEqual(42, ss.ftb.rate)
def test_it_delegates_all_remove_vlan_calls_to_supplied_callback(self): unique_message = 'Unique Result' remove_vlan_function = MagicMock(side_effect=lambda action: ConnectivitySuccessResponse(action, unique_message)) # Arrange remove_vlan_action = self._stub_remove_vlan_action(full_address='192.1.3.4/1', full_name='res1/port1', vlan_id='200') server_request = DriverRequest() server_request.actions = [remove_vlan_action] request_json = jsonpickle.encode(DriverRequestSimulation(server_request), unpicklable=False) # Act result = apply_connectivity_changes(request=request_json, logger=self.logger, add_vlan_action={}, remove_vlan_action= remove_vlan_function) # Assert remove_vlan_function.assert_called_once() response = result.driverResponse """:type : DriverResponse """ action_results = response.actionResults """:type : list[ConnectivityActionResult] """ # We validate that the action was delegated by looking for th eunique value we returned self.assertEqual(action_results[0].infoMessage, unique_message)
def test_that_record_success_metric_if_there_is_no_error( self, mock_record_success: mock.MagicMock, mock_record_realtime: mock.MagicMock): self.event.record({"status": True}, start_time=time.time()) mock_record_realtime.assert_called_once() mock_record_success.assert_called_once()
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_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_delete_wim_account(self): # Given a WIM account exists and it is connected to a tenant self.populate() num_accounts_before = self.count('wim_accounts') with self.engine.threads_running(): thread = self.engine.threads[uuid('wim-account00')] exit = MagicMock(wraps=thread.exit) num_threads = len(self.engine.threads) with patch.object(thread, 'exit', exit): # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.delete_json('/{}/wims/{}'.format( uuid('tenant0'), uuid('wim0'))) num_threads_after = len(self.engine.threads) # then the wim thread should exit self.assertEqual(num_threads_after, num_threads - 1) exit.assert_called_once() # and the request should be well succeeded self.assertEqual(response.status_code, OK) response.mustcontain('account `wim-account00` deleted') # and the number of wim_accounts should decrease num_accounts_after = self.count('wim_accounts') self.assertEqual(num_accounts_after, num_accounts_before - 1)
def test_that_raises_error_file_not_found_when_blob_object_is_not_existed( self, mock_object: mock.MagicMock): mock_object.side_effect = StorageError.FileNotFound with self.assertRaises(StorageError.FileNotFound): self.blob.is_existed() mock_object.assert_called_once()
def test_visit_should_call_drop(self): stmt = MagicMock(spec=DropTableStatement) convertor = StatementToPlanConvertor() mock = MagicMock() convertor.visit_drop = mock convertor.visit(stmt) mock.assert_called_once() mock.assert_called_with(stmt)
def test_that_raises_can_not_delete_when_file_is_not_existed( self, mock_object: mock.MagicMock): mock_object.side_effect = exceptions.NotFound("") with self.assertRaises(StorageError.FileNotFound): self.blob.delete(self.remote_file_path) mock_object.assert_called_once()
def test_integrate2d_with_different_detector_and_image_shape(self): self.calibration_model.load_detector('Pilatus CdTe 1M') self.calibration_model.load(os.path.join(data_path, 'CeO2_Pilatus1M.poni')) self.img_model.load(os.path.join(data_path, 'LaB6_40keV_MarCCD.tif')) callback_function = MagicMock() self.calibration_model.detector_reset.connect(callback_function) self.calibration_model.integrate_2d() callback_function.assert_called_once()
def test_that_raises_error_when_it_can_not_find_bucket( self, mock_storage_client: mock.MagicMock): mock_storage_client.side_effect = exceptions.NotFound("") with self.assertRaises(StorageError.BucketNotFound): self.request.upload(self.remote_file_path, self.local_file_path) mock_storage_client.assert_called_once()
def test_function_with_one_parameter(self): async_scheduler = AsyncScheduler(1) foo = MagicMock() foo_param = 'param' async_scheduler.schedule(1, foo, foo_param) async_scheduler.run() foo.assert_called_once() foo.assert_called_with(foo_param)
def test_that_record_failure_metric_if_error_occurs( self, mock_record_failure: mock.MagicMock, mock_record_realtime: mock.MagicMock): with self.assertRaises(ValueError): self.event.record({"error": ValueError}, start_time=time.time()) mock_record_realtime.assert_called_once() mock_record_failure.assert_called_once()
def test_migrate_command(): TESTED_ACTIONS.append('migrate') mock_action = MagicMock() with patch.dict('foolscap.actor.FUNCTION_MAP', {'migrate': mock_action}): expected = call() actor.action('migrate', None) mock_action.assert_called_once() assert mock_action.call_args == expected
def test_instance(self, run: MagicMock): with patch('locast2dvr.locast.fcc.Facilities.__init__') as init: init.return_value = None first = Facilities.instance() second = Facilities.instance() self.assertEqual(first, second) run.assert_called_once()
def test_correlate_message(self): get_validated_tenant_func = MagicMock() add_correlation_func = MagicMock() with patch.object(correlator.TenantIdentification, 'get_validated_tenant', get_validated_tenant_func), \ patch('meniscus.api.correlation.zmq.correlator.' 'add_correlation_info_to_message', add_correlation_func): zmq._correlate_src_message(self.src_msg) get_validated_tenant_func.assert_called_once() add_correlation_func.assert_called_once()
def test_correlate_message(self): syslog_message = self.syslog_message_head.as_dict() syslog_message["message"] = (self.message_part_1 + self.message_part_2 + self.message_part_3).decode("utf-8") get_validated_tenant_func = MagicMock() add_correlation_func = MagicMock() with patch.object(correlator.TenantIdentification, "get_validated_tenant", get_validated_tenant_func), patch( "meniscus.api.correlation.syslog.correlator." "add_correlation_info_to_message", add_correlation_func ): syslog._correlate_syslog_message(syslog_message) get_validated_tenant_func.assert_called_once() add_correlation_func.assert_called_once()
def test_get_event_type__mapped(self, mock_mappings): """Test where an event mapping of the specified name exists.""" mock_name = MagicMock(spec=str) mock_return = MagicMock(spec=ht.events.event.HoudiniEvent) mock_mappings.return_value = {mock_name: mock_return} result = ht.events.event.HoudiniEventFactory.get_event_type(mock_name) self.assertEqual(result, mock_return.return_value) mock_return.assert_called_once()
def test_trigger_job_error(self): check_call = MagicMock() check_call.side_effect = subprocess.CalledProcessError( 99, ['launchpadTrigger.py']) logging_error = MagicMock() trigger = {'name': 'foo-ci', 'branch': 'lp:foo', 'options': ['--trigger-ci']} plugin_path = '/iSCSI/jenkins/plugin' with patch('subprocess.check_call', check_call): with patch("logging.error", logging_error): self.jt.trigger_job(plugin_path, trigger, 'lock') logging_error.assert_called_once()
def test_success_step(self): entered = MagicMock() exited = MagicMock() self.my_task.steps['say_hello'].entered_handler = entered self.my_task.steps['say_hello'].exited_handler = exited self.client.succeed_step(EmptyRequest()) self.assertEqual(self.my_task.current_step.name, 'say_hello') entered.assert_called_once() self.client.succeed_step(EmptyRequest()) exited.assert_called_once()
def test_exit_without_active_connection(executor): quit_handler = MagicMock() pgspecial = PGSpecial() pgspecial.register(quit_handler, '\\q', '\\q', 'Quit pgcli.', arg_type=NO_QUERY, case_sensitive=True, aliases=(':q',)) with patch.object(executor, "conn", BrokenConnection()): # we should be able to quit the app, even without active connection run(executor, "\\q", pgspecial=pgspecial) quit_handler.assert_called_once() # an exception should be raised when running a query without active connection with pytest.raises(psycopg2.InterfaceError): run(executor, "select 1", pgspecial=pgspecial)
def testCallsOnMove(self): camera = MagicMock() cja = CameraJoystickAdapter(None) cja.set_camera(camera) on_move = MagicMock() cja.set_on_move(on_move) cja._handle_axis(0, -16535) cja._update_camera() cja._handle_axis(0, 0) cja._update_camera() on_move.assert_called_once()
def test_exception_on_broadcast(self): msg, handler, subscriber = self.get_subscription() error_handler = MagicMock() self.hub.subscribe(subscriber, msg, handler) self.hub.subscribe(subscriber, ErrorMessage, error_handler) test_exception = Exception("Test") handler.side_effect = test_exception msg_instance = msg("Test") self.hub.broadcast(msg_instance) error_handler.assert_called_once() err_msg = error_handler.call_args[0][0] assert err_msg.tag == "%s" % test_exception
def test_returns_202_for_non_durable_message(self): correlate_http_msg_func = MagicMock() with patch('dreadfort.correlation.correlator.correlate_http_message', correlate_http_msg_func): self.simulate_request( self.test_route, method='POST', headers={ 'content-type': 'application/json', MESSAGE_TOKEN: self.token }, body=jsonutils.dumps(self.message)) correlate_http_msg_func.assert_called_once() self.assertEquals(falcon.HTTP_202, self.srmock.status)
class AttachBaseArgumentUnitTests(SubcommandTestCase): def setUp(self): SubcommandTestCase.setUp(self) self.mock_add = MagicMock() self.parser = MagicMock(add_argument=self.mock_add) @patch( 'gitflow_easyrelease.subcommand.RepoInfo.get_branches', return_value=[] ) def test_add_call(self, mock_branches): mock_branches.assert_not_called() self.mock_add.assert_not_called() Subcommand.attach_base_argument(self.parser) self.mock_add.assert_called_once() mock_branches.assert_called_once_with()
def assertUploadFileToRemotePath(self, remote_path, renaming_to=None, target_type=None, raising=None): expected_target = remote_path if renaming_to is None else renaming_to listing_of_target_type = MagicMock() listing_of_target_type.path_type = MagicMock(return_value=target_type) self.client.list_path = MagicMock(return_value=listing_of_target_type) with TempDirectory() as local_dir: with open(local_dir.write('file.txt', 'contents'), 'rb') as fd: if raising is None: target_path = self.instance.upload_file(fd, remote_path) self.assertEquals(target_path, expected_target) self.client.put_file.assert_called_once_with( fd, expected_target) else: self.assertRaises(raising, self.instance.upload_file, fd, remote_path) self.client.list_path.assert_called_once_with(remote_path) listing_of_target_type.assert_called_once()
def test_retry_failure_reduced_set(self): sleep = MagicMock() self.patch(time, "sleep", sleep) method = MagicMock() method.side_effect = [ {"FailedResourcesMap": {"arn:abc": {"ErrorCode": "ThrottlingException"}}}, {"Result": 32}, ] self.assertEqual( universal_retry(method, ["arn:abc", "arn:def"]), {"Result": 32} ) sleep.assert_called_once() self.assertTrue( method.call_args_list == [ call(ResourceARNList=["arn:abc", "arn:def"]), call(ResourceARNList=["arn:abc"]), ] )
def test_vim_client_errback(self, connect_mock, host_mock): callback = MagicMock() vim_client = VimClient("esx.local", "root", "password", auto_sync=False, errback=callback) host_mock.side_effect = vim.fault.NotAuthenticated vim_client.host_system callback.assert_called_once() host_mock.side_effect = vim.fault.HostConnectFault vim_client.host_system assert_that(callback.call_count, is_(2)) host_mock.side_effect = vim.fault.InvalidLogin vim_client.host_system assert_that(callback.call_count, is_(3)) host_mock.side_effect = AcquireCredentialsException vim_client.host_system assert_that(callback.call_count, is_(4))
class WhenTestingBroadcasterProcess(unittest.TestCase): def setUp(self): self.resource = BroadcasterProcess() self.conf = MagicMock() self.conf.broadcast_settings.broadcast_message_interval = 1 self.target_list = [ 'http://hostname1.domain:8080/callback', 'http://hostname2.domain:8080/callback', 'http://hostname3.domain:8080/callback', 'http://hostname4.domain:8080/callback' ] self.get_targets = MagicMock(return_value=self.target_list) self.delete_message = MagicMock() self.resp = requests.Response() self.http_request = MagicMock(return_value=self.resp) def test_kill_terminates_sub_process(self): with patch.object( BroadcastCache, 'get_targets', self.get_targets), patch( 'meniscus.personas.broadcaster.broadcaster_process.' 'http_request', self.http_request): self.resource.run() sleep(1) self.assertTrue(self.resource.process.is_alive()) self.resource.kill() sleep(1) self.assertFalse(self.resource.process.is_alive()) def test_http_request_called(self): with patch.object( BroadcastCache, 'get_targets', self.get_targets), patch( 'meniscus.personas.broadcaster.broadcaster_process.' 'http_request', self.http_request), patch.object( BroadcastCache, 'delete_message', self.delete_message): self.resource.run_once = True self.resource._broadcast_route_messages(1) self.http_request.assert_called_once() self.delete_message.assert_called_once_with('ROUTES')
class AllHelpProgHeaderUnitTests(ApplicationTestCase): RESULT = 'qqq' def setUp(self): ApplicationTestCase.setUp(self) self.mock_color = MagicMock(return_value=self.RESULT) color_output_patcher = patch( 'gitflow_easyrelease.application.ColorOutput', return_value=self.mock_color ) self.mock_color_output = color_output_patcher.start() self.addCleanup(color_output_patcher.stop) def test_call(self): self.mock_color_output.assert_not_called() self.mock_color.assert_not_called() self.assertEqual( Application.all_help_prog_header(self.parser), self.RESULT ) self.mock_color_output.assert_called_once() self.mock_color.assert_called_once()
def testUpdateFTB(self): atem = MagicMock() atem.getFadeToBlackState.return_value = {'full_black': True, 'in_transition': False} atem.getFadeToBlackProperties.return_value = {'rate': 17} ss = SwitcherState(atem) atem.getFadeToBlackState.assert_called_once() atem.getFadeToBlackProperties.assert_called_once() self.assertEqual(17, ss.ftb.rate) self.assertTrue(ss.ftb.active) aHandler = MagicMock() ss.ftb.activeChanged.connect(aHandler) ss.handleMessage(MessageTypes.FTB_CHANGED, {0: {'full_black': False, 'in_transition': False}}) aHandler.assert_called_once() self.assertFalse(ss.ftb.active) rHandler = MagicMock() ss.ftb.rateChanged.connect(rHandler) ss.handleMessage(MessageTypes.FTB_RATE_CHANGED, {0: 42}) rHandler.assert_called_once_with(42) self.assertEqual(42, ss.ftb.rate)
def nest_action_load(self): # todo: fix this test """test load an action.""" COMP = [dict(AM), dict(L0)] [i.update(o_place=None) for i in COMP] def eff(**kwargs): cmpr = COMP.pop() assert kwargs == cmpr, 'but action were %s -AND- %s' % (kwargs, cmpr) self._action_load() print('self.control', self.control) self.employ.side_effect = eff self.employ.assert_called_once() #assert self.gui['adm1n']["o_Id"] == "o1_jeppeto/ampu.png", 'no admin in %s' % self.gui['adm1n'] things = {'o1_jeppeto/ampu.png', 'o1_EICA/1_1c.jpg', 'o1_o1_EICA/1_1c.jpg'} assert things <= set(self.control.ALL_THINGS.keys()), self.control.ALL_THINGS.keys() assert len(self.control.items) == 1, 'Not one member in items %s' % self.control.items assert self.control.current.o_Id == 'o1_EICA/1_1c.jpg', 'Not current locus %s' % self.control.current.o_Id register_value = MagicMock(side_effect=lambda **k: eff(**k)) #COMP = AM self.control.deploy(register_value) register_value.assert_called_once() pass
def test_timeout(self): entered = MagicMock() exited = MagicMock() self.my_task.steps['timed'].entered_handler = entered self.my_task.steps['timed'].exited_handler = exited rospy.wait_for_service("mytask_step") proxy = rospy.ServiceProxy( "mytask_step", StepTask ) response = proxy(name='timed') self.assertEqual(self.my_task.current_step.name, 'timed') entered.assert_called_once() rospy.sleep(0.2) self.assertEqual(self.my_task.current_step.name, 'say_hello') exited.assert_called_once() # Test that the timer does in fact reset rospy.sleep(0.2) self.assertEqual(self.my_task.current_step.name, 'say_hello')
class AttachSubparserUnitTests(SubcommandTestCase): def setUp(self): SubcommandTestCase.setUp(self) self.subcommand.has_version = False self.subcommand.version_optional = True self.subcommand.has_base = False self.parser = MagicMock() self.mock_add = MagicMock(return_value=self.parser) self.subparsers = MagicMock(add_parser=self.mock_add) attach_version_argument_patcher = patch.object( Subcommand, 'attach_version_argument' ) self.mock_attach_version_argument = attach_version_argument_patcher.start() self.addCleanup(attach_version_argument_patcher.stop) attach_base_argument_patcher = patch.object( Subcommand, 'attach_base_argument' ) self.mock_attach_base_argument = attach_base_argument_patcher.start() self.addCleanup(attach_base_argument_patcher.stop) def test_parser_only(self): self.mock_add.assert_not_called() self.mock_attach_version_argument.assert_not_called() self.mock_attach_base_argument.assert_not_called() self.subcommand.attach_subparser(self.subparsers) self.mock_add.assert_called_once() self.mock_attach_version_argument.assert_not_called() self.mock_attach_base_argument.assert_not_called() def test_version(self): self.subcommand.has_version = True self.subcommand.version_optional = True self.mock_add.assert_not_called() self.mock_attach_version_argument.assert_not_called() self.mock_attach_base_argument.assert_not_called() self.subcommand.attach_subparser(self.subparsers) self.mock_add.assert_called_once() self.mock_attach_version_argument.assert_called_once_with( self.parser, True ) self.mock_attach_base_argument.assert_not_called() def test_base(self): self.subcommand.has_base = True self.mock_add.assert_not_called() self.mock_attach_version_argument.assert_not_called() self.mock_attach_base_argument.assert_not_called() self.subcommand.attach_subparser(self.subparsers) self.mock_add.assert_called_once() self.mock_attach_version_argument.assert_not_called() self.mock_attach_base_argument.assert_called_once_with(self.parser)
def test_failure_step(self): hello_entered = MagicMock() hello_exited = MagicMock() load_entered = MagicMock() self.my_task.steps['load'].entered_handler = load_entered self.my_task.steps['say_hello'].entered_handler = hello_entered self.my_task.steps['say_hello'].exited_handler = hello_exited self.client.succeed_step(EmptyRequest()) self.assertEqual(self.my_task.current_step.name, 'say_hello') self.client.fail_step(EmptyRequest()) hello_entered.assert_called_once() hello_exited.assert_called_once() load_entered.assert_called_once()
def test_retry_no_error(self): mock = MagicMock() mock.side_effect = [{"Result": 42}] self.assertEqual(universal_retry(mock, []), {"Result": 42}) mock.assert_called_once()
class TestModuleScanctrl(TestCase): def setUp(self): self.old_File = module.File self.old_Scan = module.Scan self.old_build_sha256_path = module.build_sha256_path self.old_celery_brain = module.celery_brain self.File = MagicMock() self.Scan = MagicMock() self.build_sha256_path = MagicMock() self.celery_brain = MagicMock() module.File = self.File module.Scan = self.Scan module.build_sha256_path = self.build_sha256_path module.celery_brain = self.celery_brain def tearDown(self): module.File = self.old_File module.Scan = self.old_Scan module.build_sha256_path = self.old_build_sha256_path module.celery_brain = self.old_celery_brain del self.File del self.Scan del self.build_sha256_path del self.celery_brain def test001_add_files(self): fobj = TemporaryFile() filename = "n_test" scan, session = MagicMock(), MagicMock() function = "frontend.controllers.scanctrl.IrmaScanStatus.filter_status" with patch(function) as mock: scan.status = IrmaScanStatus.empty module.add_files(scan, {filename: fobj}, session) self.assertTrue(mock.called) self.assertEqual(mock.call_args, ((scan.status, IrmaScanStatus.empty, IrmaScanStatus.ready),)) self.File.load_from_sha256.assert_called_once() self.build_sha256_path.assert_called_once() fobj.close() def test002_check_probe(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.ready probelist = ['probe1', 'probe2'] all_probelist = ['probe1', 'probe2', 'probe3'] scan.set_probelist.return_value = None self.celery_brain.probe_list.return_value = all_probelist module.check_probe(scan, probelist, session) self.assertTrue(scan.set_probelist.called) scan.set_probelist.assert_called_once_with(probelist) def test003_check_probe_None(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.ready probelist = None all_probelist = ['probe1', 'probe2', 'probe3'] scan.set_probelist.return_value = None self.celery_brain.probe_list.return_value = all_probelist module.check_probe(scan, probelist, session) self.assertTrue(scan.set_probelist.called) scan.set_probelist.assert_called_once_with(all_probelist) def test004_check_probe_unknown_probe(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.ready probelist = ['probe1', 'probe2', 'probe6'] all_probelist = ['probe1', 'probe2', 'probe3'] scan.set_probelist.return_value = None self.celery_brain.probe_list.return_value = all_probelist with self.assertRaises(IrmaValueError) as context: module.check_probe(scan, probelist, session) self.assertFalse(scan.set_probelist.called) self.assertEquals(str(context.exception), "probe probe6 unknown") def test005_cancel_status_empty(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.empty res = module.cancel(scan, session) self.assertIsNone(res) scan.set_status.assert_called_once_with(IrmaScanStatus.cancelled) def test006_cancel_status_ready(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.ready res = module.cancel(scan, session) self.assertIsNone(res) scan.set_status.assert_called_once_with(IrmaScanStatus.cancelled) def test007_cancel_status_uploaded(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.uploaded label = IrmaScanStatus.label[scan.status] expected = "can not cancel scan in {} status".format(label) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), expected) def test008_cancel_status_launched_ok(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.launched retcode = IrmaReturnCode.success cancel_res = {'cancel_details': "details"} self.celery_brain.scan_cancel.return_value = (retcode, cancel_res) res = module.cancel(scan, session) self.assertEqual(res, cancel_res['cancel_details']) scan.set_status.assert_called_once_with(IrmaScanStatus.cancelled) def test008_cancel_status_launched_status_processed(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.launched retcode = IrmaReturnCode.success status = IrmaScanStatus.label[IrmaScanStatus.processed] cancel_res = {'status': status} self.celery_brain.scan_cancel.return_value = (retcode, cancel_res) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), "can not cancel scan in {0} status".format(status)) scan.set_status.assert_called_once_with(IrmaScanStatus.processed) def test008_cancel_status_launched_status_error(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.error_ftp_upload res = module.cancel(scan, session) self.assertIsNone(res) scan.set_status.assert_not_called() def test008_cancel_status_launched_brain_error(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.launched retcode = IrmaReturnCode.error ret_val = "reason" self.celery_brain.scan_cancel.return_value = (retcode, ret_val) with self.assertRaises(IrmaTaskError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), ret_val) scan.set_status.assert_not_called() def test009_cancel_status_processed(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.processed label = IrmaScanStatus.label[scan.status] expected = "can not cancel scan in {} status".format(label) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), expected) def test010_cancel_status_flushed(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.flushed label = IrmaScanStatus.label[scan.status] expected = "can not cancel scan in {} status".format(label) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), expected) def test011_cancel_status_cancelling(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.cancelling label = IrmaScanStatus.label[scan.status] expected = "can not cancel scan in {} status".format(label) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), expected) def test012_cancel_status_cancelled(self): scan, session = MagicMock(), MagicMock() scan.status = IrmaScanStatus.cancelled label = IrmaScanStatus.label[scan.status] expected = "can not cancel scan in {} status".format(label) with self.assertRaises(IrmaValueError) as context: module.cancel(scan, session) self.assertEqual(str(context.exception), expected) def test013_set_launched_status_uploaded(self): scan = MagicMock() scan.status = IrmaScanStatus.uploaded self.Scan.load_from_ext_id.return_value = scan module.set_launched("whatever", "whatever") scan.set_status.assert_called_with(IrmaScanStatus.launched) def test014_set_launched_status_not_uploaded(self): scan = MagicMock() scan.status = IrmaScanStatus.finished self.Scan.load_from_ext_id.return_value = scan module.set_launched("whatever", "whatever") self.assertEqual(scan.status, IrmaScanStatus.finished) @patch("frontend.controllers.scanctrl.sha256sum") def test015_new_file_existing(self, m_sha256sum): m_file = MagicMock() m_file.path = "whatever" self.File.load_from_sha256.return_value = m_file fobj, session = MagicMock(), MagicMock() res = module._new_file(fobj, session) self.assertEqual(res, m_file) @patch("frontend.controllers.scanctrl.sha256sum") @patch("frontend.controllers.scanctrl.save_to_file") def test016_new_file_existing_deleted(self, m_save_to_file, m_sha256sum): m_file = MagicMock() self.File.load_from_sha256.return_value = m_file fobj, session = MagicMock(), MagicMock() path = "testpath" self.build_sha256_path.return_value = path m_file.path = None module._new_file(fobj, session) m_save_to_file.assert_called_once_with(fobj, path) @patch("frontend.controllers.scanctrl.md5sum") @patch("frontend.controllers.scanctrl.sha1sum") @patch("frontend.controllers.scanctrl.sha256sum") @patch("frontend.controllers.scanctrl.Magic") @patch("frontend.controllers.scanctrl.save_to_file") def test017_new_file_not_existing(self, m_save_to_file, m_magic, m_sha256sum, m_sha1sum, m_md5sum): self.File.load_from_sha256.side_effect = IrmaDatabaseResultNotFound fobj, session = MagicMock(), MagicMock() path = "testpath" self.build_sha256_path.return_value = path module._new_file(fobj, session) m_md5sum.assert_called_once_with(fobj) m_sha1sum.assert_called_once_with(fobj) m_sha256sum.assert_called_once_with(fobj) m_magic.assert_called() self.File.assert_called() def test018_update_ref_no_prev(self): m_fw, m_file, m_pr = MagicMock(), MagicMock(), MagicMock() m_probe = MagicMock() probe = MagicMock() probename = "probe1" probe.name = probename m_probe.name = probe m_file.ref_results = [] m_pr.name = "probe2" module._update_ref_results(m_fw, m_file, m_pr) self.assertItemsEqual(m_file.ref_results, [m_pr]) def test019_update_ref_prev(self): m_fw, m_file = MagicMock(), MagicMock() m_pr_new, m_pr_old = MagicMock(), MagicMock() m_probe = MagicMock() probe = MagicMock() probename = "probe1" probe.name = probename m_probe.name = probe m_pr_old.name = "probe1" m_pr_new.name = "probe1" m_file.ref_results = [m_pr_old] module._update_ref_results(m_fw, m_file, m_pr_new) self.assertItemsEqual(m_file.ref_results, [m_pr_new]) @patch("frontend.controllers.scanctrl.log") def test020_update_ref_error(self, m_log): m_fw, m_file, m_pr = MagicMock(), MagicMock(), MagicMock() m_probe = MagicMock() probe = MagicMock() probename = "probe1" probe.name = probename m_probe.name = probe m_pr.name = "probe1" m_file.ref_results = [m_pr, m_pr] module._update_ref_results(m_fw, m_file, m_pr) self.assertItemsEqual(m_file.ref_results, [m_pr, m_pr]) m_log.error.called_once() def test021_fetch_probe_results(self): m_fw, m_pr = MagicMock(), MagicMock() probename = "probe1" m_pr.name = probename m_fw.probe_results = [m_pr] res = module._fetch_probe_result(m_fw, probename) self.assertEqual(res, m_pr) @patch("frontend.controllers.scanctrl.log") def test022_resubmit_new_files_error(self, m_log): m_scan, m_parent_file = MagicMock(), MagicMock() m_resubmit_fws, m_session = MagicMock(), MagicMock() hash_uploaded = "whatever" m_parent_file.files_web = [] module._resubmit_files(m_scan, m_parent_file, m_resubmit_fws, hash_uploaded, m_session) m_log.error.assert_called_once() self.celery_brain.scan_launch.assert_not_called() @patch("frontend.controllers.scanctrl.log") def test023_resubmit_new_files_no_new_file(self, m_log): m_scan, m_parent_file = MagicMock(), MagicMock() m_session = MagicMock() m_fw = MagicMock() hash_uploaded = ["whatever"] m_fw.file.sha256 = hash_uploaded[0] m_resubmit_fws = [m_fw] m_parent_file.files_web = [m_fw] module._resubmit_files(m_scan, m_parent_file, m_resubmit_fws, hash_uploaded, m_session) self.celery_brain.scan_launch.assert_not_called() @patch("frontend.controllers.scanctrl.log") def test024_resubmit_new_files_new_file(self, m_log): m_scan, m_parent_file = MagicMock(), MagicMock() m_session = MagicMock() m_fw = MagicMock() hash_uploaded = ["whatever"] m_fw.file.sha256 = "anotherthing" m_resubmit_fws = [m_fw] m_parent_file.files_web = [m_fw] module._resubmit_files(m_scan, m_parent_file, m_resubmit_fws, hash_uploaded, m_session) self.celery_brain.scan_launch.assert_called() @patch("frontend.controllers.scanctrl._new_fileweb") @patch("frontend.controllers.scanctrl.ftp_ctrl") def test025_append_new_files(self, m_ftpctrl, m_new_fw): m_scan, m_session = MagicMock(), MagicMock() filename = "filename" filehash = "filehash" uploaded_files = {filename: filehash} m_fobj = MagicMock() m_ftpctrl.download_file_data.return_value = m_fobj module._append_new_files_to_scan(m_scan, uploaded_files, m_session) m_download = m_ftpctrl.download_file_data m_download.assert_called_once_with(m_scan.external_id, filehash) m_new_fw.assert_called_once_with(m_scan, filename, m_fobj, m_session) def test026_sanitize_res(self): pattern = u"\u0000test" + "\x00" pattern_expected = "test" dic_key = "te.st$key" dic_expected = "te_stkey" dic = {'unicode': unicode(pattern), 'list': [pattern], 'dict': {dic_key: pattern}, 'else': "else"} expected = {'unicode': pattern_expected, 'list': [pattern_expected], 'dict': {dic_expected: pattern_expected}, 'else': "else"} res = module._sanitize_res(dic) self.assertItemsEqual(res.values(), expected.values()) def test027_add_empty_result_refresult(self): fw, scan, session = MagicMock(), MagicMock(), MagicMock() pr1, pr2 = MagicMock(), MagicMock() probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] pr1.name = probe1 pr2.name = probe2 scan.force = False fw.file.ref_results = [pr1, pr2] fw.probe_results = [] module._add_empty_result(fw, probelist, scan, session) self.assertItemsEqual(fw.probe_results, [pr1, pr2]) @patch("frontend.controllers.scanctrl._fetch_known_results") def test027_add_empty_result_knownresult(self, m_fetch_known_results): fw, scan, session = MagicMock(), MagicMock(), MagicMock() pr1, pr2 = MagicMock(), MagicMock() probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] pr1.name = probe1 pr2.name = probe2 scan.force = True m_fetch_known_results.return_value = [pr1, pr2] fw.probe_results = [] module._add_empty_result(fw, probelist, scan, session) self.assertItemsEqual(fw.probe_results, [pr1, pr2]) @patch("frontend.controllers.scanctrl.ProbeResult") def test028_add_empty_result_noresult(self, m_ProbeResult): fw, scan, session = MagicMock(), MagicMock(), MagicMock() probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] scan.force = True fw.probe_results = [] res = module._add_empty_result(fw, probelist, scan, session) self.assertItemsEqual(res, probelist) @patch("frontend.controllers.scanctrl.FileWeb") def test029_fetch_known_results(self, m_FileWeb): m_scan, m_file, m_session = MagicMock(), MagicMock(), MagicMock() m_scan.id = "scanid" m_file.id = "fileid" fw1 = MagicMock() m_FileWeb.load_by_scanid_fileid.return_value = [fw1, fw1] res = module._fetch_known_results(m_file, m_scan, m_session) self.assertItemsEqual(res, fw1.probe_results) @patch("frontend.controllers.scanctrl.braintasks") @patch("frontend.controllers.scanctrl._add_empty_result") def test030_add_empty_results(self, m_add_empty_result, m_braintasks): m_scan, m_session = MagicMock(), MagicMock() fw1, fw2 = MagicMock(), MagicMock() fw1.file.sha256 = "sha256file1" fw1.file.mimetype = "mimetypefile1" fw2.file.sha256 = "sha256file2" fw2.file.mimetype = "mimetypefile2" fw_list = [fw1, fw2] probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] m_add_empty_result.return_value = probelist m_braintasks.mimetype_filter_scan_request = lambda x: x scan_request = module._create_scan_request(fw_list, probelist, True) res = module._add_empty_results(fw_list, scan_request, m_scan, m_session) self.assertItemsEqual(res.to_dict().values(), scan_request.to_dict().values()) @patch("frontend.controllers.scanctrl.log") def test031_fetch_probe_results_error(self, m_log): fw, pr = MagicMock(), MagicMock() pr.name = "Probe1" fw.probe_results = [pr, pr] module._fetch_probe_result(fw, pr.name) m_log.error.assert_called_once() @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test032_launch_asynchronous_nothing_to_do(self, m_session_transaction, m_Scan): m_session, m_scan = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session m_scan.status = IrmaScanStatus.ready m_Scan.load_from_ext_id.return_value = m_scan module.launch_asynchronous("whatever") m_scan.set_status.assert_called_once_with(IrmaScanStatus.finished) @patch("frontend.controllers.scanctrl._add_empty_result") @patch("frontend.controllers.scanctrl.ftp_ctrl") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test033_launch_asynchronous(self, m_session_transaction, m_Scan, m_ftp_ctrl, m_add_empty_result): m_scan, m_session = MagicMock(), MagicMock() fw1, fw2 = MagicMock(), MagicMock() file1, file2 = MagicMock(), MagicMock() pathf1, pathf2 = 'path-file1', 'path-file2' file1.path = pathf1 file2.path = pathf2 fw1.file.sha256 = "sha256file1" fw1.file.mimetype = "mimetypefile1" fw2.file.sha256 = "sha256file2" fw2.file.mimetype = "mimetypefile2" m_scan.files_web = [fw1, fw2] m_scan.files = [file1, file2] probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] m_scan.get_probe_list.return_value = probelist m_add_empty_result.return_value = probelist m_session_transaction().__enter__.return_value = m_session m_scan.status = IrmaScanStatus.ready m_scan.mimetype_filtering = False m_Scan.load_from_ext_id.return_value = m_scan scanid = "scanid" module.launch_asynchronous(scanid) m_ftp_ctrl.upload_scan.assert_called_with(scanid, [pathf1, pathf2]) m_scan.set_status.assert_called_once_with(IrmaScanStatus.uploaded) @patch("frontend.controllers.scanctrl._add_empty_result") @patch("frontend.controllers.scanctrl.ftp_ctrl") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test034_launch_asynchronous_ftp_error(self, m_session_transaction, m_Scan, m_ftp_ctrl, m_add_empty_result): m_scan, m_session = MagicMock(), MagicMock() fw1, fw2 = MagicMock(), MagicMock() file1, file2 = MagicMock(), MagicMock() pathf1, pathf2 = 'path-file1', 'path-file2' file1.path = pathf1 file2.path = pathf2 fw1.file.sha256 = "sha256file1" fw1.file.mimetype = "mimetypefile1" fw2.file.sha256 = "sha256file2" fw2.file.mimetype = "mimetypefile2" m_scan.files_web = [fw1, fw2] m_scan.files = [file1, file2] probe1, probe2 = "Probe1", "Probe2" probelist = [probe1, probe2] m_scan.get_probe_list.return_value = probelist m_add_empty_result.return_value = probelist m_session_transaction().__enter__.return_value = m_session m_scan.status = IrmaScanStatus.ready m_scan.mimetype_filtering = False m_Scan.load_from_ext_id.return_value = m_scan scanid = "scanid" m_ftp_ctrl.upload_scan.side_effect = IrmaFtpError() module.launch_asynchronous(scanid) expected = IrmaScanStatus.error_ftp_upload m_scan.set_status.assert_called_once_with(expected) @patch("frontend.controllers.scanctrl.log") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test035_set_result_fw_not_found(self, m_session_transaction, m_Scan, m_log): m_scan, m_session = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session m_scan.get_filewebs_by_sha256.return_value = [] m_Scan.load_from_ext_id.return_value = m_scan module.set_result("scanid", "filehash", "probe", "result") m_log.error.assert_called_once() @patch("frontend.controllers.scanctrl._update_ref_results") @patch("frontend.controllers.scanctrl._fetch_probe_result") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test036_set_result(self, m_session_transaction, m_Scan, m_fetch_pr, m_update_ref_res): scanid = "scanid" filehash = "filehash" probe = "probe" m_scan, m_session = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session fw1, pr1 = MagicMock(), MagicMock() pr1.doc = "ProbeResult" file1 = MagicMock() fw1.file = file1 fw1.probe_results = [pr1] m_scan.get_filewebs_by_sha256.return_value = [fw1] m_Scan.load_from_ext_id.return_value = m_scan result = {'status': 1, 'type': "something"} m_fetch_pr.return_value = pr1 module.set_result(scanid, filehash, probe, result) m_fetch_pr.assert_called_once_with(fw1, probe) m_update_ref_res.assert_called_once_with(fw1, file1, pr1) m_Scan.load_from_ext_id.assert_called_with(scanid, session=m_session) @patch("frontend.controllers.scanctrl.File") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test037_handle_output_files_no_resubmit(self, m_session_transaction, m_Scan, m_File): m_scan, m_session = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session m_scan.resubmit_files = True m_Scan.load_from_ext_id.return_value = m_scan result = {} module.handle_output_files("scanid", "parent_file_hash", "probe", result) m_Scan.load_from_ext_id.assert_called_once_with("scanid", session=m_session) @patch("frontend.controllers.scanctrl.File") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test038_handle_output_files_resubmit_False(self, m_session_transaction, m_Scan, m_File): m_scan, m_session = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session m_scan.resubmit_files = False m_Scan.load_from_ext_id.return_value = m_scan result = {'uploaded_files': []} module.handle_output_files("scanid", "parent_file_hash", "probe", result) m_Scan.load_from_ext_id.assert_called_once_with("scanid", session=m_session) @patch("frontend.controllers.scanctrl._append_new_files_to_scan") @patch("frontend.controllers.scanctrl.File") @patch("frontend.controllers.scanctrl.Scan") @patch("frontend.controllers.scanctrl.session_transaction") def test039_handle_output_files_resubmit(self, m_session_transaction, m_Scan, m_File, m_append_new_files_to_scan): m_scan, m_session = MagicMock(), MagicMock() m_session_transaction().__enter__.return_value = m_session m_scan.resubmit_files = True m_Scan.load_from_ext_id.return_value = m_scan uploaded_files = {} result = {'uploaded_files': uploaded_files} fw1 = MagicMock() m_append_new_files_to_scan.return_value = [fw1] m_parentfile = MagicMock() m_parentfile.children = [] m_File.load_from_sha256.return_value = m_parentfile module.handle_output_files("scanid", "parent_file_hash", "probe", result) m_Scan.load_from_ext_id.assert_called_once_with("scanid", session=m_session) m_append_new_files_to_scan.assert_called_once_with(m_scan, uploaded_files, m_session) self.assertItemsEqual(m_parentfile.children, [fw1])
class TestPyndoramaControl(unittest.TestCase): def setUp(self): class Brython(dict): def __init__(self): dict.__init__({}) self.DOC, self.SVG, self.HTML, self.AJAX = [self]*4 self.doc = dict(base=self) self['base'] = self['book'] = self self.cookie = '_xsrf=123456; ' self.WIN, self.STORAGE, self.JSON, self.TIME = [self]*4 self.__getitem__ = self.DIV = self.div = self.IMG = self.nop self.div = self.img = self.deploy = self.employ = self.nop self.show_front_menu = self.screen_context = self.nop self.aler = self.prom = self.conf = self.nop self.offsetLeft = self.offsetTop = self.menuX = self.menuY = 1 self.Id = self.search = '' self.location = self.target = self self.aargs = self.items = self.evs = [] def __le__(self, other): """ shades brython append operator """ pass def activate(self, **kwargs): self.aargs = kwargs def bind(self, ev, hook): self.evs.append(hook) return self def nop(self, *args, **kwargs): return self def __call__(self, *args, **kwargs): return self class _Gui(dict): def employ(self, **kwargs): print('setUp employ') #self['adm1n'].update(kwargs) return 'adm1n', 1 self.control = model.init() self.br = Brython() self.br.dumps = json.dumps self.br.loads = json.loads self.app = Gui(self.br) self.app._locate = self.app._filter = MagicMock(name='locate') self.app.menuX = self.app.menuY = 1 self.builder = Builder(self.br, self.control) self.builder.build_all(self.app) self.gui = _Gui() self.gui['adm1n'] = {} Gui.REV = {} self.control.ALL_THINGS = model.Thing.ALL_THINGS = {} self.control.items = [] def _action_load(self): """load an action.""" self.employ = MagicMock() self.control.activate(self.employ, **L0) self.control.activate(self.employ, **AM) #self.gui['adm1n'] = {} #self.control.activate(self.employ, **JEP0["JAC"]) def _add_locus(self): """ adds a new locus.""" self.br.id, self.app.game = 'idEica01', '_JPT_g0' self.app.storage = dict(_JPT__JPT_g0=json.dumps([LR])) def eff(**kw): assert 2424 in kw, 'but not in %s' % kw self.br.DIV = MagicMock(name='div', side_effect=eff) self.builder.jenu.ad_cenario(self.br, self.br) def _add_baloon(self): """ adds a new baloon.""" mock_prop = self.mp = MagicMock(name='prop') mock_prop.bind = MagicMock(name='prop_bind', side_effect=lambda ev, hook: hook(mock_prop)) self.control.current = self.control # MagicMock(name='curr') # self.br mock_shape = self.app.shape = MagicMock(name='shape') self.mc_doc = self.app.doc = MagicMock(name='doc') # self.br #mc_doc.__getitem__ = MagicMock(name='doc_set', return_value=mock_prop) self.app.doc.__getitem__ = MagicMock(name='doc_set', side_effect=lambda x: self.mp) mock_store = self.app.storage = MagicMock(name='store') mock_store_get = self.app.storage.__getitem__ = MagicMock(name='store_get', return_value="[]") mock_store_set = self.app.storage.__setitem__ = MagicMock(name='store_set') self.br.id, self.br.o_Id, self.app.game = 'idEica01', 'idEica01', '_JPT_g0' self.the_div = MagicMock(name='div') self.the_div.html = "Lorem isum" self.app.div = MagicMock(name='div_call', side_effect=lambda *a, **x: self.the_div) # , side_effect=eff) #activate, self.app.control.activate = self.app.control.activate, MagicMock(name='act', side_effect=eff) def _result_test(self, the_item, container=None, app_op=None, item_id='o1_balao', savdict=ED, extra=EL): container = container or self.control.items assert len(container) >= 1, 'but ALL_THINGS is %s ' % container assert item_id in the_item.o_Id, 'but item id is %s but given is %s ' % (the_item.o_Id, item_id) #assert self.app.control.activate.assert_any_called() app_op = app_op or self.app.div if savdict != {}: app_op.assert_any_called() bv, ks = set(savdict.values()), set(app_op.call_args[1].values()) assert bv < ks, 'but %s not in %s' % (bv, ks) #container = self.app.control.items self.app.doc.__getitem__.assert_any_called() self.app.storage.__getitem__.assert_any_call('_JPT__JPT_g0') self.app.storage.__setitem__.assert_any_call('_JPT__JPT_g0', ANY) bv, ks = set(list(savdict.values())+extra), self.app.storage.__setitem__.call_args[0][1] assert bv < set(json.loads(ks)[0].values()), 'but %s not in %s' % (bv, set(json.loads(ks)[0].values())) #assert False, 'but mc was %s' % self.mp.mock_calls savargs = {} saver = MagicMock(name='saver', side_effect=lambda **kw: savargs.update(kw)) the_item.deploy(saver) bv, ks = set(savdict.values()), set(savargs.values()) assert bv < ks, 'but %s not in %s' % (bv, savargs) def test_add_baloon(self): """test adds a new baloon.""" self._add_baloon() self.builder.mmenu.menu_balao(self.br, self.br) self.mp.bind.assert_called_once_with('click', ANY) self._result_test(the_item=self.app.control.items[0], savdict=BALSAV) def test_add_jump(self): """test adds a jump action.""" self._add_baloon() self._action_load() self.app.obj_id = 'o1_EICA/1_1c.jpg' self.app.act = MagicMock(name='mock_act') self.builder.mmenu.pular(self.br, self.br) #self.app.act.assert_any_call() item_id = 'o1_o1_EICA/1_1c.jpg' jump = self.control.ALL_THINGS[item_id] self._result_test(the_item=jump, container=model.Thing.ALL_THINGS, app_op=self.app.act, item_id=item_id, savdict=JUMP) def test_add_hide(self): """test adds a hide action.""" self._add_baloon() self._action_load() self.app.obj_id = 'o1_EICA/1_1c.jpg' self.app.shape = MagicMock(name='mock_act') self.builder.mmenu.menu_esconder(self.br, self.br) #self.app.act.assert_any_call() item_id = 'o1_jeppeto/ampu.png' #assert False, 'items %s things %s' % (self.control.items[0].items[0], self.control.ALL_THINGS) jump = self.control.items[0].items[0] self._result_test(the_item=jump, container=model.Thing.ALL_THINGS, app_op=self.app.shape, item_id=item_id, extra=['o1_EICA/1_1c.jpg', '0.1', 'Holder', 'jeppeto/ampu.png', 'shape', 'absolute', 'DoShape', 'o1_jeppeto/ampu.png']) def test_save_action(self): """test saves a jump action.""" self._add_baloon() self._action_load() #assert False,'self.control.ALL_THINGS.keys() %s' % self.control.ALL_THINGS.keys() place = 'o1_jeppeto/ampu.png' self.app.obj_id = place #self.app.obj_id = 'o1_pl_Eica01' self.app.act = MagicMock(name='mock_act') self.app.save = MagicMock(name='mock_save') self.builder.mmenu.pular(self.br, self.br) #self.app.act.assert_any_call() #jump = self.control.ALL_THINGS['o1_Eica01'] calls = [{'o1_'+place}, {'o1_jeppeto/ampu.png'}, {'o1_EICA/1_1c.jpg'}] def save(o_Id='', **kwargs): _id = calls.pop() assert _id == {o_Id}, 'but id %s was not %s' % (_id, {o_Id}) employ = MagicMock(name='mock_save', side_effect=save) self.control.deploy(employ) #employ.assert_any_call(ANY) employ_calls = employ.call_args_list #self.app.act.assert_any_call() #self.app.save.assert_called_once_with() assert self.control.current.o_Id == 'o1_EICA/1_1c.jpg', 'but current id was %s' % self.control.current.o_Id #assert employ_calls == '', 'but employ_calls was %s' % str(employ_calls) def test_edit_baloon(self): """test edit an existing baloon.""" self._add_baloon() self.the_div.html = "Sic Amet" self.builder.mmenu.menu_balao(self.br, self.br) self.mp = MagicMock(name='edit_prop') self.mp.html = "Sic Amet" self.mp.id = 'o1_balao' self.builder.mmenu.menu_editar(self.br, self.br) self.mp.bind.assert_called_once_with('click', ANY) baloon = self.app.control.items[0] self._result_test(the_item=baloon, container=self.app.control.items, item_id='o1_balao', savdict=BALSAV, extra=["Sic Amet"]) def test_add_locus(self): """test adds a new locus.""" self._add_locus() assert 'o1_Eica01' in self.br.DIV.call_args[1]['Id'], self.br.DIV.call_args[1]['Id'] loci = self.control.items assert len(loci) == 1, 'but items was %s' % loci assert loci[0].o_Id == 'o1_Eica01', 'but id was %s' % loci[0].o_Id def _add_object(self): """adds a new holder object.""" self._add_locus() self.br.id, self.app.game = 'idEica01', '_JPT_g0' self.app.storage = dict(_JPT__JPT_g0=json.dumps([LR])) def eff(**kw): assert 2424 in kw, 'but not in %s' % kw self.br.IMG = MagicMock(name='img', side_effect=eff) act, self.control.activate = self.control.activate, MagicMock(name='act') self.control.activate.side_effect = lambda **kw: act(**kw) self.builder.jenu.ad_objeto(self.br, self.br) def test_add_object(self): """test adds a new holder object.""" self._add_object() self.control.activate.assert_called_any() #self.br.IMG.assert_called_once_with() loci = self.control.items assert len(loci) == 1, 'but items was %s' % loci assert loci[0].o_Id == 'o1_Eica01', 'but id was %s' % loci[0].o_Id assert loci[0].items[0].o_Id == 'o2_Eica01', 'but id was %s' % loci[0].items[0].o_Id assert 'o2_Eica01' in self.br.IMG.call_args[1]['Id'], 'but call id was %s' % self.br.IMG.call_args[1]['Id'] def nest_action_load(self): # todo: fix this test """test load an action.""" COMP = [dict(AM), dict(L0)] [i.update(o_place=None) for i in COMP] def eff(**kwargs): cmpr = COMP.pop() assert kwargs == cmpr, 'but action were %s -AND- %s' % (kwargs, cmpr) self._action_load() print('self.control', self.control) self.employ.side_effect = eff self.employ.assert_called_once() #assert self.gui['adm1n']["o_Id"] == "o1_jeppeto/ampu.png", 'no admin in %s' % self.gui['adm1n'] things = {'o1_jeppeto/ampu.png', 'o1_EICA/1_1c.jpg', 'o1_o1_EICA/1_1c.jpg'} assert things <= set(self.control.ALL_THINGS.keys()), self.control.ALL_THINGS.keys() assert len(self.control.items) == 1, 'Not one member in items %s' % self.control.items assert self.control.current.o_Id == 'o1_EICA/1_1c.jpg', 'Not current locus %s' % self.control.current.o_Id register_value = MagicMock(side_effect=lambda **k: eff(**k)) #COMP = AM self.control.deploy(register_value) register_value.assert_called_once() pass def _remote_load(self): """fixture for loading from remote server.""" self.br.on_complete = lambda x: None self.br.text = '{"status": 0, "value": "[\"GamesInteligentesII\",\"Jeppeto_1\",\"Jeppeto_0\"]"}' def do_call(): self.br.on_complete(self.br) self.br.set_timeout = self.br.set_header = MagicMock() self.br.open = MagicMock(name='open') self.br.send = MagicMock(name='send', side_effect=lambda x: do_call()) self.app.ajax = lambda: self.br # MagicMock() def test_remove_game(self): """remove a game locally and from remote server.""" self.app.alert = MagicMock(name='alert') self.app.confirm = MagicMock(name='confirm', return_value=True) self.app.send = MagicMock(name='send', side_effect=lambda a, b, c, d, e: b('1 2 3')) self.app.remote_games = 'Jeppeto_0 Jeppeto_1 Jeppeto_2'.split() self.app.game = 'Jeppeto_0' self.builder.mmenu.menu_apagar_jogo(self.br, self.br) #self.app.remote_delete('Jeppeto_0') self.app.confirm.assert_called_once_with('Tem certeza que quer remover completamente Jeppeto_0 ?') self.app.send.assert_called_once_with(SAVEGAMELIST, ANY, ANY, ANY, 'POST') self.app.alert.assert_called_once_with('Arquivo Jeppeto_0 completamente removido com sucesso') bv, ks = {'Jeppeto_1', 'Jeppeto_2'}, json.loads(self.app.send.call_args[0][3]['value']) assert bv == set(ks), 'but %s not same as %s' % (bv, ks) self.app.confirm = MagicMock(name='newconfirm') self.app.remote_delete('NoNo') self.app.confirm.assert_called_once_with('Tem certeza que quer remover completamente NoNo ?') self.app.alert.assert_called_once_with('Arquivo Jeppeto_0 completamente removido com sucesso') def test_remote_load(self): """test load from remote server.""" def store(x, y): assert x == '_JPT_Jeppeto_1', 'but storage was %s %s' % (x, y) self._remote_load() self.br.status, self.br.text = 200, json.dumps(dict(status=0, value=JP0)) #self.app.load('_JPT_g0') self.app.storage = MagicMock(name="storage") self.app.storage.__setitem__ = MagicMock(name="setitem") # , side_effect=store) self.app.storage.__getitem__ = MagicMock(name="setitem", return_value="[\"Jeppeto_0\"]") self.br['_JPT_Jeppeto_1'] = JP0 self.app.load('Jeppeto_1') assert self.br.on_complete self.br.open.assert_called_once_with('GET', LOAD, True) self.br.send.assert_called_once_with({}) assert self.app.remote_games == [], 'but remote_games was %s' % self.app.remote_games self.app.storage.__setitem__.assert_called_with(JEPPETO, '["Jeppeto_1", "Jeppeto_0"]') self.app.storage.__setitem__.assert_any_call('_JPT_Jeppeto_1', ANY) def test_no_remote_local_load(self): """test load from local on remote server denial.""" self._remote_load() self.app.storage = dict(_JPT_Jeppeto_1=json.dumps([LR])) self.br.status, self.br.text = 404, json.dumps(dict(status=0, value=[LR])) self.app.load('Jeppeto_1') assert self.br.on_complete self.br.open.assert_called_once_with('GET', LOAD, True) self.br.send.assert_called_once_with({}) def nest_action_execute(self): # todo: fix this test """test execute an action.""" self._action_load() self.gui['adm1n'] = {} self.control.activate(o_emp=self.gui.employ, o_Id="o1_jeppeto/ampu.png", o_cmd='DoExecute') #assert False, 'no admin in %s' % self.gui['adm1n'] assert self.gui['adm1n']["o_Id"] == "o1_EICA/1_1c.jpg", 'no admin in %s' % self.gui['adm1n'] assert self.gui['adm1n']["o_gcomp"] == "up", 'no admin in %s' % self.gui['adm1n'] def test_save_remote(self): """test save remote.""" #Url = 'https://activufrj.nce.ufrj.br/storage/jeppeto/_JPT_Jeppeto_0/__persist__' Urle = SAVEPAGE % ('jeppeto', '_JPT_Jeppeto_0') # '/rest/wiki/edit/jeppeto/_JPT_Jeppeto_0' Url = GAMELIST # '/rest/wiki/edit/activlets/__J_E_P_P_E_T_O__' conts = ['', '[]', '["Jeppeto_0"]'] urls = [Urle, NEWPAGE % ('jeppeto', '_JPT_Jeppeto_0'), Url] # '/wiki/newpage/jeppeto?folder=', Url] import json def store_effect(key, value): assert 'o_gcomp' in value, 'but value was %s' % value def send_effect(url, func, funcb, value, tx=0): expected = urls.pop() assert expected == url, 'but url was %s against %s' % (url, expected) val = [L0, AM] expect_cont = conts.pop() if len(value['value']) > 20: value = json.loads(value['value']) #assert False, 'val, value %s %s' % (value, val) assert val[0] == value[0], 'but value was %s -AND- %s' % (value, val[0]) else: assert value['value'] == expect_cont, \ 'but value conteudo was %s against %s' % (value['value'], conts) func('um texto') self._action_load() self.app.game = "Jeppeto_0" self.app.games = ["Jeppeto_1"] self.app.json = self.br self.br.dumps = lambda x: json.dumps(x) self.app.storage = MagicMock(name='store', side_effect=store_effect) send = self.app.send = MagicMock(name='send', side_effect=send_effect) self.app.remote_save() send.assert_any_call(ANY, ANY, ANY, ANY, "POST") self.app.storage.__setitem__.assert_any_call(ANY, ANY) expected_count = 2 assert send.call_count == expected_count, 'but send count was %s' % send.call_count def test_Menu_cenario(self): """test add a new scene.""" #Url = 'https://activufrj.nce.ufrj.br/storage/jeppeto/_JPT_Jeppeto_0/__persist__' import json self.app.json = self.br self.br.id = 'jeppeto/thing' self.br.dumps = MagicMock(name='dumps') # lambda x: json.dumps(x) self.br.loads = lambda x: json.loads(x) self.app.game = "jeppeto_0" self.app.storage = MagicMock(name='store') self.app.storage.__getitem__ = MagicMock(name='storeget', return_value="[]") self.builder.jenu.ad_cenario(self.br, None) self.br.dumps.assert_called_once() # _with(0) assert self.control.items[0].o_gcomp == 'div', 'but items gcomp was %s' % self.control.items[0].o_gcomp def test_game_start(self): """test show start screen.""" event = MagicMock(name='event') div_eff = MagicMock(name='div_effect') self.br = MagicMock(name='gui') self.br.__le__ = MagicMock() self.br.JSON.loads = lambda x=0: ['a_game'] self.app = Gui(self.br) ids = [ 0, '__ROOT__', 'ad_objeto', 'ad_cenario', 'navegar', 'pular', 'mostrar', 'ob_ctx', 'tx_ctx', 'jeppeto', 'wiki', '_JPT_a_game', '_JPT_jpt_0', '_JPT_g' ] def side_effect(a, b, c, d, e): assert a == GAMELIST, 'but url was %s' % a assert e == "GET" assert d == {'_xsrf': '', 'value': []}, 'but data was %s' % d #assert d == {'_xsrf': '', 'conteudo': '[]'}, 'but data was %s' % d self.app.games = ['jpt_0', 'g'] def div_effect(a=0, b=0, c=0, s_top=0, s_display=0, s_left=0, s_width=0, s_position=0, s_border=0, o_Id=0, s_color=0, s_fontSize=0, s_fontFamily=0): assert o_Id in ids, 'but id was %s' % o_Id return div_eff #self.app._remote_load = MagicMock(name='rl', side_effect=side_effect) self.app.send = MagicMock(name='send', side_effect=side_effect) self.app.div = MagicMock(name='div', side_effect=div_effect) self.app.img = MagicMock(name='img') self.builder = Builder(self.br, self.control) self.builder.build_all(self.app) self.app.start(event) self.app.send.assert_called_once() self.app.div.assert_called_any()
def test_process_msg(self): correlate_func = MagicMock() with patch('dreadfort.correlation.correlator.' 'correlate_syslog_message', correlate_func): self.server.process_msg() correlate_func.assert_called_once()