def test_ornamentation_rate_can_be_controlled(self): """ There should be way to control how frequently walls are ornamented """ wall_tile(self.level, (2, 2), self.wall) wall_tile(self.level, (3, 2), self.wall) wall_tile(self.level, (4, 2), self.wall) rng = mock() when(rng).randint(any(), any()).thenReturn(0).thenReturn(100).thenReturn(0) when(rng).choice(any()).thenReturn(self.ornamentation) self.config = WallOrnamentDecoratorConfig( ['any level'], wall_tile = self.wall, ornamentation = [self.ornamentation], rng = rng, rate = 50) self.decorator = WallOrnamentDecorator(self.config) self.decorator.decorate_level(self.level) candle_count = 0 for location, tile in get_tiles(self.level): if self.ornamentation in tile['\ufdd0:ornamentation']: candle_count = candle_count + 1 assert_that(candle_count, is_(equal_to(2)))
def test_run_verify_checksum(self): """This tests that swift download cmd runs if original backup checksum matches swift object etag""" context = TroveContext() location = "/backup/location/123" is_zipped = False backup_checksum = "fake-md5-sum" swift_client = FakeSwiftConnection() when(swift).create_swift_client(context).thenReturn(swift_client) download_process = MockProcess() subprocess = mock(swift.subprocess) when(subprocess).Popen(any(), any(), any(), any()).thenReturn(download_process) when(swift.utils).raise_if_process_errored().thenReturn(None) storage_strategy = SwiftStorage(context) download_stream = storage_strategy.load(context, location, is_zipped, backup_checksum) self.assertEqual(download_stream.container, "location") self.assertEqual(download_stream.filename, "123") with download_stream as stream: print "Testing SwiftDownloadStream context manager: %s" % stream self.assertIsNotNone(download_stream.process, "SwiftDownloadStream process/cmd is supposed " "to run.") self.assertIsNotNone(download_stream.pid, "SwiftDownloadStream process/cmd is supposed " "to run.")
def test_execute_restore(self): """This test should ensure backup agent resolves backup instance determines backup/restore type transfers/downloads data and invokes the restore module reports status """ backup = mock(DBBackup) backup.location = "/backup/location/123" backup.backup_type = 'InnoBackupEx' when(utils).execute(contains('sudo rm -rf')).thenReturn(None) when(utils).clean_out(any()).thenReturn(None) when(backupagent).get_storage_strategy(any(), any()).thenReturn( MockStorage) when(backupagent).get_restore_strategy( 'InnoBackupEx', any()).thenReturn(MockRestoreRunner) when(DatabaseModelBase).find_by(id='123').thenReturn(backup) when(backup).save().thenReturn(backup) agent = backupagent.BackupAgent() bkup_info = {'id': '123', 'location': 'fake-location', 'type': 'InnoBackupEx', 'checksum': 'fake-checksum', } agent.execute_restore(TroveContext(), bkup_info, '/var/lib/mysql')
def test_ProfileRemoveAction(self): storage = mock() action = profile.Remove(storage, **{'name': 'ProfileName'}) when(storage).remove(any(str), any(str)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get() verify(storage).remove('profiles', 'ProfileName')
def test_RunlistListAction(self): storage = mock() action = runlist.List(storage) when(storage).find(any(str), any(tuple)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get() verify(storage).find('runlists', RUNLISTS_TAGS)
def mock_sql_connection(): mock_engine = mock() when(sqlalchemy).create_engine("mysql://root:@localhost:3306", echo=True).thenReturn(mock_engine) mock_conn = mock() when(dbaas.LocalSqlClient).__enter__().thenReturn(mock_conn) when(dbaas.LocalSqlClient).__exit__(any(), any(), any()).thenReturn(None) return mock_conn
def test_ProfileListAction(self): storage = mock() action = profile.List(storage) when(storage).find(any(str), any(tuple)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get(timeout=0.1) verify(storage).find('profiles', PROFILES_TAGS)
def setup(self): """ Setup the test case """ self.rng = Random() self.model = mock() self.effect_factory = mock() drink_factory = DrinkFactory(self.effect_factory) self.action_factory = ActionFactory(self.model, drink_factory) self.character = (CharacterBuilder() .with_action_factory(self.action_factory) .with_hit_points(1) .with_max_hp(5) .build()) effect = Heal(duration = 0, frequency = 0, tick = 0, healing = 5, target = self.character) when(self.effect_factory).create_effect(any(), target = any()).thenReturn(effect) self.potion = (ItemBuilder() .with_name('healing potion') .with_effect( EffectHandleBuilder() .with_trigger('on drink') .with_effect('heal')) .build()) self.character.inventory.append(self.potion)
def setUp(self): super(FreshInstanceTasksTest, self).setUp() when(taskmanager_models.FreshInstanceTasks).id().thenReturn( "instance_id") when(taskmanager_models.FreshInstanceTasks).tenant_id().thenReturn( "tenant_id") when(taskmanager_models.FreshInstanceTasks).hostname().thenReturn( "hostname") when(taskmanager_models.FreshInstanceTasks).name().thenReturn( 'name') when(datastore_models. DatastoreVersion).load(any()).thenReturn(mock()) when(datastore_models. Datastore).load(any()).thenReturn(mock()) taskmanager_models.FreshInstanceTasks.nova_client = fake_nova_client() taskmanager_models.CONF = mock() when(taskmanager_models.CONF).get(any()).thenReturn('') self.orig_ISS_find_by = InstanceServiceStatus.find_by self.orig_DBI_find_by = DBInstance.find_by self.userdata = "hello moto" self.guestconfig_content = "guest config" with NamedTemporaryFile(suffix=".cloudinit", delete=False) as f: self.cloudinit = f.name f.write(self.userdata) with NamedTemporaryFile(delete=False) as f: self.guestconfig = f.name f.write(self.guestconfig_content) self.freshinstancetasks = taskmanager_models.FreshInstanceTasks( None, mock(), None, None)
def testActivityRunnerSuccess(self): mock_activity = mock() mock_success_handler = mock() mock_failure_handler = mock() ActivityRunner(mock_activity, mock_success_handler, mock_failure_handler).run() verify(mock_success_handler).handle_success(any()) verify(mock_failure_handler, times=0).handle_failure(any(), any())
def test_CrashlogListAction(self): storage = mock() action = crashlog.List(storage, **{'name': 'CrashlogName'}) when(storage).find(any(str), any(list)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get() verify(storage).find('crashlogs', ['CrashlogName'])
def test_RunlistViewAction(self): storage = mock() action = RunlistViewAction(storage, **{'name': 'RunlistName'}) when(storage).read(any(str), any(str)).thenReturn(ChainFactory([lambda: 'Ok'])) action.execute().get() verify(storage).read('runlists', 'RunlistName')
def test_CrashlogListAction(self): storage = mock() action = CrashlogListAction(storage, **{'name': 'CrashlogName'}) when(storage).find(any(str), any(tuple)).thenReturn(ChainFactory([lambda: 'Ok'])) action.execute().get() verify(storage).find('crashlogs', ('CrashlogName', ))
def test_ProfileViewAction(self): storage = mock() action = ProfileViewAction(storage, **{'name': 'ProfileName'}) when(storage).read(any(str), any(str)).thenReturn(ChainFactory([lambda: 'Ok'])) action.execute().get() verify(storage).read('profiles', 'ProfileName')
def _when_connection_timeouts_for_first_time(self): when_connect = when(self._ssh).connect(any(), username=any(), key_filename=any(), timeout=any()) first_timeout = when_connect.thenRaise(socket.timeout) second_timeout = first_timeout.thenRaise(socket.timeout) second_timeout.thenReturn(None)
def testS3FileWriter(self): mock_s3_client = mock() writer = S3FileWriter(mock_s3_client) writer.write(mock(), {'bucket': 'test bucket', 'key': 'test key'}) verify(mock_s3_client).connect() verify(mock_s3_client).write_key(any(), any(), any(), any()) verify(mock_s3_client).disconnect()
def test_RunlistUploadActionRawRunlistProvided(self): storage = mock() action = runlist.Upload(storage, **{'name': 'RunlistName', 'runlist': '{}'}) when(storage).write(any(str), any(str), any(str), any(tuple)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get() verify(storage).write('runlists', 'RunlistName', msgpack.dumps({}), RUNLISTS_TAGS)
def _prepare_dynamic(self, device_path='/dev/vdb', is_mysql_installed=True, backup_id=None, is_root_enabled=False, overrides=None): # covering all outcomes is starting to cause trouble here COUNT = 1 if device_path else 0 backup_info = None if backup_id is not None: backup_info = {'id': backup_id, 'location': 'fake-location', 'type': 'InnoBackupEx', 'checksum': 'fake-checksum', } # TODO(juice): this should stub an instance of the MySqlAppStatus mock_status = mock() when(dbaas.MySqlAppStatus).get().thenReturn(mock_status) when(mock_status).begin_install().thenReturn(None) when(VolumeDevice).format().thenReturn(None) when(VolumeDevice).migrate_data(any()).thenReturn(None) when(VolumeDevice).mount().thenReturn(None) when(dbaas.MySqlApp).stop_db().thenReturn(None) when(dbaas.MySqlApp).start_mysql().thenReturn(None) when(dbaas.MySqlApp).install_if_needed(any()).thenReturn(None) when(backup).restore(self.context, backup_info, '/var/lib/mysql').thenReturn(None) when(dbaas.MySqlApp).secure(any()).thenReturn(None) when(dbaas.MySqlApp).secure_root(any()).thenReturn(None) (when(pkg.Package).pkg_is_installed(any()). thenReturn(is_mysql_installed)) when(dbaas.MySqlAdmin).is_root_enabled().thenReturn(is_root_enabled) when(dbaas.MySqlAdmin).create_user().thenReturn(None) when(dbaas.MySqlAdmin).create_database().thenReturn(None) when(os.path).exists(any()).thenReturn(True) # invocation self.manager.prepare(context=self.context, packages=None, memory_mb='2048', databases=None, users=None, device_path=device_path, mount_point='/var/lib/mysql', backup_info=backup_info, overrides=overrides) # verification/assertion verify(mock_status).begin_install() verify(VolumeDevice, times=COUNT).format() verify(dbaas.MySqlApp, times=COUNT).stop_db() verify(VolumeDevice, times=COUNT).migrate_data( any()) if backup_info: verify(backup).restore(self.context, backup_info, '/var/lib/mysql') verify(dbaas.MySqlApp).install_if_needed(any()) # We dont need to make sure the exact contents are there verify(dbaas.MySqlApp).secure(any(), overrides) verify(dbaas.MySqlAdmin, never).create_database() verify(dbaas.MySqlAdmin, never).create_user() verify(dbaas.MySqlApp).secure_root(secure_remote_root=any())
def test_RunlistRemoveAction(self): storage = mock() action = runlist.Remove(storage, **{'name': 'RunlistName'}) when(storage).remove(any(str), any(str)).thenReturn(Chain([lambda: 'Ok'])) action.execute().get() verify(storage).remove('runlists', 'RunlistName')
def _prepare_dynamic(self, device_path='/dev/vdb', is_redis_installed=True, backup_info=None, is_root_enabled=False): # covering all outcomes is starting to cause trouble here dev_path = 1 if device_path else 0 mock_status = mock() when(redis_service.RedisAppStatus).get().thenReturn(mock_status) when(mock_status).begin_install().thenReturn(None) when(VolumeDevice).format().thenReturn(None) when(VolumeDevice).mount().thenReturn(None) when(redis_service.RedisApp).start_redis().thenReturn(None) when(redis_service.RedisApp).install_if_needed().thenReturn(None) when(backup).restore(self.context, backup_info).thenReturn(None) when(redis_service.RedisApp).write_config(any()).thenReturn(None) when(redis_service.RedisApp).complete_install_or_restart( any()).thenReturn(None) self.manager.prepare(self.context, self.packages, None, '2048', None, device_path=device_path, mount_point='/var/lib/redis', backup_info=backup_info) verify(redis_service.RedisAppStatus, times=2).get() verify(mock_status).begin_install() verify(VolumeDevice, times=dev_path).format() verify(VolumeDevice, times=dev_path).mount(redis_system.REDIS_BASE_DIR) verify(redis_service.RedisApp).install_if_needed(self.packages) verify(redis_service.RedisApp).write_config(None) verify(redis_service.RedisApp).complete_install_or_restart()
def test_public_exists_events(self): status = ServiceStatuses.BUILDING.api_status db_instance = DBInstance( InstanceTasks.BUILDING, created="xyz", name="test_name", id="1", flavor_id="flavor_1", compute_instance_id="compute_id_1", server_id="server_id_1", tenant_id="tenant_id_1", server_status=status, ) server = mock(Server) server.user_id = "test_user_id" mgmt_instance = SimpleMgmtInstance(self.context, db_instance, server, None) when(mgmtmodels).load_mgmt_instances(self.context, deleted=False, client=self.client).thenReturn( [mgmt_instance, mgmt_instance] ) flavor = mock(Flavor) flavor.name = "db.small" when(self.flavor_mgr).get("flavor_1").thenReturn(flavor) self.assertThat(self.context.auth_token, Is("some_secret_password")) when(notifier).notify(self.context, any(str), "trove.instance.exists", "INFO", any(dict)).thenReturn(None) # invocation mgmtmodels.publish_exist_events(NovaNotificationTransformer(context=self.context), self.context) # assertion verify(notifier, times=2).notify(self.context, any(str), "trove.instance.exists", "INFO", any(dict)) self.assertThat(self.context.auth_token, Is(None))
def test_startFlatLBP(self): #given defaultClassMat,\ edgesData,\ graph,\ lbpLoops,\ lbpThreshold,\ nodeList,\ nodes,\ nrOfClasses,\ nrOfFolds,\ nrOfNodes,\ percentOfKnownNodes,\ method_type = self.prepareExperimentData() #when mockito.when(graph).nodes().thenReturn(nodes) mockito.when(graph).edges_iter(mockito.any(), data=True)\ .thenReturn(self.utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(self.utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(self.utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(self.utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(self.utils.generateEdges(10, nodeList, edgesData)) #then foldSumEstimated = self.methods.start(graph, nrOfFolds, defaultClassMat, nrOfClasses, lbpLoops, lbpThreshold, nrOfNodes, percentOfKnownNodes, method_type) mockito.verify(graph, times=5).nodes() mockito.verify(graph, times=5).edges_iter(mockito.any(), data=True) assert foldSumEstimated.__len__() == NUMBER_OF_ELEMENTS assert 0 in foldSumEstimated or 1 in foldSumEstimated assert 0.5 not in foldSumEstimated
def test_check_for_heartbeat_negative(self): # TODO (juice) maybe it would be ok to extend the test to validate # the is_active method on the heartbeat when(db_models.DatabaseModelBase).find_by( instance_id=any()).thenReturn('agent') when(agent_models.AgentHeartBeat).is_active(any()).thenReturn(False) self.assertRaises(exception.GuestTimeout, self.api._check_for_hearbeat)
def test_skip_song_if_any_filter_should_filter(self): self.create_file_in(self.SOURCE_PATH) f = mock() when(f).should_filter(any()).thenReturn(True) self.ms.filters = [f] self.ms.sync() verify(self.file_operator_mock, never).copyfile(any(), any())
def setUp(self): super(BackupTasksTest, self).setUp() self.backup = backup_models.DBBackup() self.backup.id = 'backup_id' self.backup.name = 'backup_test', self.backup.description = 'test desc' self.backup.location = 'http://xxx/z_CLOUD/12e48.xbstream.gz' self.backup.instance_id = 'instance id' self.backup.created = 'yesterday' self.backup.updated = 'today' self.backup.state = backup_models.BackupState.NEW self.container_content = (None, [{'name': 'first'}, {'name': 'second'}, {'name': 'third'}]) when(backup_models.Backup).delete(any()).thenReturn(None) when(backup_models.Backup).get_by_id( self.backup.id).thenReturn(self.backup) when(self.backup).delete(any()).thenReturn(None) self.swift_client = mock() when(remote).create_swift_client( any()).thenReturn(self.swift_client) when(self.swift_client).head_container( any()).thenRaise(ClientException("foo")) when(self.swift_client).head_object( any(), any()).thenRaise(ClientException("foo")) when(self.swift_client).get_container(any()).thenReturn( self.container_content) when(self.swift_client).delete_object(any(), any()).thenReturn(None) when(self.swift_client).delete_container(any()).thenReturn(None)
def testFtpFileWriter(self): mock_ftp_client = mock() writer = FtpFileWriter(mock_ftp_client) writer.write(mock(), {'filename': 'test'}) verify(mock_ftp_client).connect() verify(mock_ftp_client).write_file(any(), any()) verify(mock_ftp_client).disconnect()
def test_ensure_after_action_teardown_is_executed_and_suppresses(self): task = mock(name="task", dependencies=[]) when(task).execute(any(), {}).thenRaise(ValueError("simulated task error")) action_teardown1 = mock(name="action_teardown1", execute_before=[], execute_after=["task"], teardown=True, source="task") when(action_teardown1).execute({}).thenRaise(ValueError("simulated action error teardown1")) action_teardown2 = mock(name="action_teardown2", execute_before=[], execute_after=["task"], teardown=True, source="task") self.execution_manager.register_action(action_teardown1) self.execution_manager.register_action(action_teardown2) self.execution_manager.register_task(task) self.execution_manager.resolve_dependencies() try: self.execution_manager.execute_task(task) self.assertTrue(False, "should not have reached here") except Exception as e: self.assertEquals(type(e), ValueError) self.assertEquals(str(e), "simulated task error") verify(task).execute(any(), {}) verify(action_teardown1).execute({}) verify(action_teardown2).execute({}) verify(self.execution_manager.logger).error( "Executing action '%s' from '%s' resulted in an error that was suppressed:\n%s", "action_teardown1", "task", any())
def test_random_walk_classical(self): methods = RandomWalkMethods() #given graph = mockito.mock(nx.MultiGraph) edgesData, nodes, nodeList = utils.prepareNodesAndEdges() edgesList = utils.prepareEdgesList(edgesData, nodeList) class_mat = utils.prepareTestClassMatWithUnknownNodes() default_class_mat = utils.prepareTestClassMat() mockito.when(graph).edges_iter(mockito.any(), data=True)\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData)) mockito.when(graph).edges_iter(mockito.any())\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData))\ .thenReturn(utils.generateEdges(10, nodeList, edgesData)) mockito.when(graph).edges(data=True).thenReturn(edgesList) mockito.when(graph).nodes().thenReturn(nodes) result = methods.random_walk_classical(graph, default_class_mat, [1, 2], 5, 1) assert result.__len__() == 5
def test_backup_incremental_metadata(self): when(backupagent).get_storage_strategy(any(), any()).thenReturn( MockSwift) MockStorage.save_metadata = Mock() when(MockSwift).load_metadata(any(), any()).thenReturn( {'lsn': '54321'}) meta = { 'lsn': '12345', 'parent_location': 'fake', 'parent_checksum': 'md5', } when(mysql_impl.InnoBackupExIncremental).metadata().thenReturn(meta) when(mysql_impl.InnoBackupExIncremental).check_process().thenReturn( True) agent = backupagent.BackupAgent() bkup_info = {'id': '123', 'location': 'fake-location', 'type': 'InnoBackupEx', 'checksum': 'fake-checksum', 'parent': {'location': 'fake', 'checksum': 'md5'} } agent.execute_backup(TroveContext(), bkup_info, '/var/lib/mysql') self.assertTrue(MockStorage.save_metadata.called_once_with( any(), meta))
def test_getPlayerList(self): """\ Query the game server for connected players. return a dict having players' id for keys and players' data as another dict for values """ when(self.output_mock).write('status', maxRetries=any()).thenReturn("""\ map: ut4_casa num score ping name lastmsg address qport rate --- ----- ---- --------------- ------- --------------------- ----- ----- 10 0 13 snowwhite 0 192.168.1.11:51034 9992 15000 12 0 10 superman 0 192.168.1.12:53039 9993 15000 """) result = self.console.getPlayerList() verify(self.output_mock).write('status', maxRetries=any()) self.assertDictEqual({'10': {'ip': '192.168.1.11', 'last': '0', 'name': 'snowwhite', 'pbid': None, 'ping': '13', 'port': '51034', 'qport': '9992', 'rate': '15000', 'score': '0', 'slot': '10'}, '12': {'ip': '192.168.1.12', 'last': '0', 'name': 'superman', 'pbid': None, 'ping': '10', 'port': '53039', 'qport': '9993', 'rate': '15000', 'score': '0', 'slot': '12'}} , result)
def setUp(self): """Set up needed items for test.""" parameters_used = 'bcipy/parameters/parameters.json' self.window = mock() when(psychopy.visual).Window(size=any(), screen=any(), allowGUI=False, useFBO=False, fullscr=any(bool), allowStencil=False, monitor=any(str), winType='pyglet', units=any(), waitBlanking=False, color=any(str)).thenReturn(self.window) self.parameters = load_json_parameters(parameters_used, value_cast=True)
def _verify_rpc_call(self, exp_msg): verify(rpc).call(any(), any(), exp_msg, any(int))
def _mock_rpc_cast(self, exp_msg): when(rpc).cast(any(), any(), exp_msg).thenReturn(None)
def test_pkg_is_instaled_yes(self): packages = "package1=1.0 package2" when(commands).getstatusoutput(any()).thenReturn( {1: "package1=1.0\n" "package2=2.0"}) self.assertTrue(self.pkg.pkg_is_installed(packages))
def should_add_song_to_internal_playlist(): _.playlist.append(_.track) verify(_.internal_playlist).add(any())
def test_load_composite_one_workspace_two_hosts(self): doc_ws = { "type": "Workspace", "_id": "test_ws", "name": "test_ws", "description": "some description", "customer": "Infobyte", "sdate": None, "fdate": None } doc_host1 = { "type": "Host", "_id": "1234", "name": "pepito", "owned": False, "parent": "test_ws", "owner": None, "description": "some description", "metadata": None, "os": "linux", "default_gateway": None } doc_host2 = { "type": "Host", "_id": "5678", "name": "coquito", "owned": False, "parent": "test_ws", "owner": None, "description": "some description", "metadata": None, "os": "windows", "default_gateway": None } pmanager = NullPersistenceManager() when(pmanager).getDocument("test_ws").thenReturn(doc_ws) when(pmanager).getDocument("1234").thenReturn(doc_host1) when(pmanager).getDocument("5678").thenReturn(doc_host2) when(pmanager).getDocsByFilter(any, any).thenReturn([]) when(pmanager).getDocsByFilter(any(str), None).thenReturn([]) when(pmanager).getDocsByFilter(None, None).thenReturn([]) when(pmanager).getDocsByFilter("test_ws", None).thenReturn([{ '_id': "1234", 'type': "Host" }, { '_id': "5678", 'type': "Host" }]) #when(pmanager).getDocsByFilter(None, "Host").thenReturn([]) self.mapper_manager.createMappers(pmanager) ws = self.mapper_manager.find("test_ws") self.assertNotEquals(ws, None, "Existent Workspace shouldn't be None") self.assertEquals(len(ws.getHosts()), 2, "Workspace should have two hosts") hosts_ids = [host.getID() for host in ws.getHosts()] self.assertIn("1234", hosts_ids, "Host '1234' should be one of the workspace's hosts") self.assertIn("5678", hosts_ids, "Host '5678' should be one of the workspace's hosts")
def test_load_composite_one_host_one_interface_two_services(self): doc_host = { "type": "Host", "_id": "1234", "name": "pepito", "owned": False, "parent": None, "owner": None, "description": "some description", "metadata": None, "os": "linux", "default_gateway": None } doc_interface = { "type": "Interface", "_id": "5678", "name": "192.168.10.168", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "mac": "01:02:03:04:05:06", "network_segment": None, "hostnames": ["www.test.com"], "ipv4": { "address": "192.168.10.168", "mask": "255.255.255.0", "gateway": "192.168.10.1", "DNS": "192.168.10.1" }, "ipv6": {}, "ports": { "opened": 2, "closed": 3, "filtered": 4, } } doc_service1 = { "type": "Service", "_id": "abcd", "name": "http", "owned": False, "parent": "5678", "owner": None, "description": "some description", "metadata": None, "protocol": "tcp", "status": "open", "ports": [80], "version": "Apache 2.4" } doc_service2 = { "type": "Service", "_id": "efgh", "name": "ssh", "owned": False, "parent": "5678", "owner": None, "description": "some description", "metadata": None, "protocol": "tcp", "status": "open", "ports": [22], "version": "OpenSSH" } pmanager = mock(NullPersistenceManager) when(pmanager).getDocument("1234").thenReturn(doc_host) when(pmanager).getDocument("5678").thenReturn(doc_interface) when(pmanager).getDocument("abcd").thenReturn(doc_service1) when(pmanager).getDocument("efgh").thenReturn(doc_service2) when(pmanager).getChildren(any(str)).thenReturn([]) when(pmanager).getChildren("1234").thenReturn([{ '_id': "5678", 'type': "Interface" }]) when(pmanager).getChildren("5678").thenReturn([{ '_id': "abcd", 'type': "Service" }, { '_id': "efgh", 'type': "Service" }]) self.mapper_manager.createMappers(pmanager) iface = self.mapper_manager.find("5678") self.assertNotEquals(iface, None, "Existent interface shouldn't be None") # Lets make sure that the host was created host = iface.getParent() self.assertEquals(host.getID(), "1234", "Interface's parent id should be 1234") self.assertEquals( host, self.mapper_manager.find("1234"), "Interface1's parent should be equals to the host retrieved") self.assertEquals(len(iface.getAllServices()), 2, "Interface should have two services") services_ids = [srv.getID() for srv in iface.getAllServices()] self.assertIn( "abcd", services_ids, "Service 'abcd' should be one of the interface's services") self.assertIn( "efgh", services_ids, "Service 'efgh' should be one of the interface's services")
def create_file_operator_mock(self): self.file_operator_mock = mock() when(self.file_operator_mock).get_all_files_under(any(str)).thenReturn([]) when(self.file_operator_mock).exists(any(str)).thenReturn(False) when(self.file_operator_mock).getsize(any(str)).thenReturn(0)
def test_load_composite_one_host_one_note_one_vuln_one_credential(self): doc_host = { "type": "Host", "_id": "1234", "name": "pepito", "owned": False, "parent": None, "owner": None, "description": "some description", "metadata": None, "os": "linux", "default_gateway": None } doc_note = { "type": "Note", "_id": "note1", "name": "Note1", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "text": "this is a note" } doc_vuln = { "type": "Vulnerability", "_id": "vuln1", "name": "Vuln1", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "desc": "this is a vuln", "severity": "high", "refs": ["cve1", "cve2"] } doc_cred = { "type": "Cred", "_id": "cred1", "name": "Vuln1", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "username": "******", "password": "******" } pmanager = mock(NullPersistenceManager) when(pmanager).getDocument("1234").thenReturn(doc_host) when(pmanager).getDocument("note1").thenReturn(doc_note) when(pmanager).getDocument("vuln1").thenReturn(doc_vuln) when(pmanager).getDocument("cred1").thenReturn(doc_cred) when(pmanager).getChildren(any(str)).thenReturn([]) when(pmanager).getChildren("1234").thenReturn([{ '_id': "note1", 'type': "Note" }, { '_id': "vuln1", 'type': "Vulnerability" }, { '_id': "cred1", 'type': "Cred" }]) self.mapper_manager.createMappers(pmanager) host = self.mapper_manager.find("1234") self.assertNotEquals(host, None, "Existent host shouldn't be None") self.assertEquals(len(host.getNotes()), 1, "Host should have one note") self.assertEquals(len(host.getVulns()), 1, "Host should have one vuln") self.assertEquals(len(host.getCreds()), 1, "Host should have one cred")
def test_should_not_eat_first_character_of_modules_when_source_path_ends_with_slash(self): when(pybuilder.utils).discover_files_matching(any(), any()).thenReturn(['/path/to/tests/reactor_tests.py']) self.assertEquals(["reactor_tests"], discover_modules_matching("/path/to/tests/", "*"))
def setUp(self): """set up the needed path for load functions.""" self.parameters_used = 'bcipy/parameters/parameters.json' self.parameters = load_json_parameters(self.parameters_used, value_cast=True) self.display = visual.Window(size=[1, 1], screen=0, allowGUI=False, useFBO=False, fullscr=False, allowStencil=False, monitor='mainMonitor', winType='pyglet', units='norm', waitBlanking=False, color='black') self.text_mock = mock() self.image_mock = mock() self.rect_mock = mock() self.clock = core.Clock() self.visual_feedback = VisualFeedback(display=self.display, parameters=self.parameters, clock=self.clock) when(psychopy.visual).TextStim(win=self.display, font=any(), text=any(), height=any(), pos=any(), color=any()).thenReturn(self.text_mock) when(psychopy.visual).TextStim(win=self.display, font=any(), text=any(), height=any(), pos=any()).thenReturn(self.text_mock) when(psychopy.visual).ImageStim(win=self.display, image=any(), mask=None, pos=any(), ori=any()).thenReturn(self.image_mock) when(psychopy.visual).Rect(win=self.display, width=any(), height=any(), lineColor=any(), pos=any(), lineWidth=any(), ori=any()).thenReturn(self.rect_mock)
def should_detach_given_tracks_from_playlist(): _.internal_playlist.invocations = [] # cleanup invocations _.playlist.discard([_.track, _.track]) verify(_.internal_playlist, times=2).remove(any())
def should_detach_that_track_from_playlist(): _.playlist.remove(_.track) verify(_.internal_playlist).remove(any())
def should_add_all_songs_to_internal_playlist(): _.internal_playlist.invocations = [] # cleanup previous calls _.playlist.extend([_.track, _.track]) verify(_.internal_playlist, times=2).add(any())
def _verify_rpc_cast(self, exp_msg): verify(rpc).cast(any(), any(), exp_msg)
def test_skip_if_file_already_exists_in_the_same_size(self): self.create_file_in(self.TARGET_PATH) self.create_file_in(self.SOURCE_PATH) self.ms.sync() verify(self.file_operator_mock, times(0)).copyfile(any(str), any(str))
def test_check_for_heartbeat_positive(self): when(db_models.DatabaseModelBase).find_by( instance_id=any()).thenReturn('agent') when(agent_models.AgentHeartBeat).is_active('agent').thenReturn(True) self.assertTrue(self.api._check_for_hearbeat())
def test_mark_as_read(self): mail = mock() when(self.mail_service).mail(any()).thenReturn(mail) self.mail_service.mark_as_read(1) verify(mail).mark_as_read()
def test_delete_interface_from_composite_one_host_one_interface_two_services( self): doc_host = { "type": "Host", "_id": "1234", "name": "pepito", "owned": False, "parent": None, "owner": None, "description": "some description", "metadata": None, "os": "linux", "default_gateway": None } doc_interface = { "type": "Interface", "_id": "5678", "name": "192.168.10.168", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "mac": "01:02:03:04:05:06", "network_segment": None, "hostnames": ["www.test.com"], "ipv4": { "address": "192.168.10.168", "mask": "255.255.255.0", "gateway": "192.168.10.1", "DNS": "192.168.10.1" }, "ipv6": {}, "ports": { "opened": 2, "closed": 3, "filtered": 4, } } doc_service1 = { "type": "Service", "_id": "abcd", "name": "http", "owned": False, "parent": "5678", "owner": None, "description": "some description", "metadata": None, "protocol": "tcp", "status": "open", "ports": [80], "version": "Apache 2.4" } doc_service2 = { "type": "Service", "_id": "efgh", "name": "ssh", "owned": False, "parent": "5678", "owner": None, "description": "some description", "metadata": None, "protocol": "tcp", "status": "open", "ports": [22], "version": "OpenSSH" } self.pmanager = mock(NullPersistenceManager) when(self.pmanager).getDocument("1234").thenReturn(doc_host) when(self.pmanager).getDocument("5678").thenReturn(doc_interface) when(self.pmanager).getDocument("abcd").thenReturn(doc_service1) when(self.pmanager).getDocument("efgh").thenReturn(doc_service2) when(self.pmanager).getChildren(any(str)).thenReturn([]) when(self.pmanager).getChildren("1234").thenReturn([{ '_id': "5678", 'type': "Interface" }]) when(self.pmanager).getChildren("5678").thenReturn([{ '_id': "abcd", 'type': "Service" }, { '_id': "efgh", 'type': "Service" }]) self.mapper_manager.createMappers(self.pmanager) # load the host first host = self.mapper_manager.find("1234") #then remove the interface iface_id = host.getInterface("5678").getID() host.deleteChild(iface_id) def fake_remove(id): when(self.pmanager).getDocument(id).thenReturn(None) when(self.pmanager).remove("5678").thenReturn(fake_remove("5678")) when(self.pmanager).remove("abcd").thenReturn(fake_remove("abcd")) when(self.pmanager).remove("efgh").thenReturn(fake_remove("efgh")) self.mapper_manager.remove(iface_id) # now we make sure that we have removed the interface # and the services self.assertEquals(len(host.getAllInterfaces()), 0, "Host should have no interfaces") self.assertEquals(self.mapper_manager.find("5678"), None, "Service abcd shouldn't exist anymore") self.assertEquals(self.mapper_manager.find("abcd"), None, "Service abcd shouldn't exist anymore") self.assertEquals(self.mapper_manager.find("efgh"), None, "Service efgh shouldn't exist anymore")
def assert_removed_from_drafts(_): verify(self.drafts).remove(any())
def test_load_composite_one_host_two_interfaces(self): doc_host = { "type": "Host", "_id": "1234", "name": "pepito", "owned": False, "parent": None, "owner": None, "description": "some description", "metadata": None, "os": "linux", "default_gateway": None } doc_interface1 = { "type": "Interface", "_id": "5678", "name": "192.168.10.168", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "mac": "01:02:03:04:05:06", "network_segment": None, "hostnames": ["www.test.com"], "ipv4": { "address": "192.168.10.168", "mask": "255.255.255.0", "gateway": "192.168.10.1", "DNS": "192.168.10.1" }, "ipv6": {}, "ports": { "opened": 2, "closed": 3, "filtered": 4, } } doc_interface2 = { "type": "Interface", "_id": "6789", "name": "192.168.10.168", "owned": False, "parent": "1234", "owner": None, "description": "some description", "metadata": None, "mac": "01:02:03:04:05:06", "network_segment": None, "hostnames": ["www.test.com"], "ipv4": { "address": "192.168.10.168", "mask": "255.255.255.0", "gateway": "192.168.10.1", "DNS": "192.168.10.1" }, "ipv6": {}, "ports": { "opened": 2, "closed": 3, "filtered": 4, } } pmanager = mock(NullPersistenceManager) when(pmanager).getDocument("1234").thenReturn(doc_host) when(pmanager).getDocument("5678").thenReturn(doc_interface1) when(pmanager).getDocument("6789").thenReturn(doc_interface2) when(pmanager).getChildren(any(str)).thenReturn([]) when(pmanager).getChildren("1234").thenReturn([{ '_id': "5678", 'type': "Interface" }, { '_id': "6789", 'type': "Interface" }]) self.mapper_manager.createMappers(pmanager) host = self.mapper_manager.find("1234") self.assertNotEquals(host, None, "Existent host shouldn't be None") self.assertEquals(len(host.getAllInterfaces()), 2, "Host should have two interface") iface1 = self.mapper_manager.find("5678") self.assertNotEquals(iface1, None, "Existent interface1 shouldn't be None") self.assertEquals( host.getInterface("5678"), iface1, "Interface1 inside host should be equals to retrieved interface1") self.assertEquals(iface1.getParent(), host, "Host should be the interface1's parent") iface2 = self.mapper_manager.find("6789") self.assertNotEquals(iface2, None, "Existent interface2 shouldn't be None") self.assertEquals( host.getInterface("6789"), iface2, "Interface2 inside host should be equals to retrieved interface2") self.assertEquals(iface2.getParent(), host, "Host should be the interface2's parent")
def _verify_rpc_connection_and_cast(self, rpc, mock_conn, exp_msg): verify(rpc).create_connection(new=True) verify(mock_conn).create_consumer(self.api._get_routing_key(), None, fanout=False) verify(rpc).cast(any(), any(), exp_msg)
def setUp(self): super(BackupAgentTest, self).setUp() when(backupagent).get_auth_password().thenReturn('secret') when(backupagent).get_storage_strategy(any(), any()).thenReturn(MockSwift) when(os).statvfs(any()).thenReturn(MockStats)
def _mock_rpc_call(self, exp_msg, resp=None): rpc.common = mock() when(rpc).call(any(), any(), exp_msg, any(int)).thenReturn(resp)
def testStubsMultipleClasses(self): when(os.path).exists("test").thenReturn(True) when(os.path).dirname(any(str)).thenReturn("mocked") self.assertEqual(True, os.path.exists("test")) self.assertEqual("mocked", os.path.dirname("whoah!"))
def test_should_honor_suffix_without_stripping_it_from_module_names(self): when(pybuilder.utils).discover_files_matching(any(), any()).thenReturn(['/path/to/tests/reactor_tests.py']) self.assertEquals(["reactor_tests"], discover_modules_matching("/path/to/tests/", "*_tests"))
def should_create_new_instances(self): when(self.handler).param('field1').thenReturn("Field1 data") when(self.handler).param('field2').thenReturn("Field2 data") self.handler.post() verify(self.repository).save(any(entity))
def testStubsWithMatchers(self): theMock = mock() when(theMock).foo(any()).thenReturn(1) self.assertEquals(1, theMock.foo(1)) self.assertEquals(1, theMock.foo(100))
def testNamedParam(self): theMock = mock(ITest) when(theMock).simple_with_names_params('d', 'e', any(), d=1).thenReturn(0)
def testVerifiesUsingAnyIntMatcher(self): self.mock.foo(1, "bar") self.verification_function(self.mock).foo(any(int), "bar")