def test_modes_checked(self): user = mock() user2 = mock() cli = self.createSshConnection(user=user) cli.modeList = [user, user2] cli.check_prereq(0) verify(user2).exit()
def createSshConnection(self, pexpectObject=mock(), user=mock()): cli = SshCli("0.0.0.0", user, pexpectObject=pexpectObject) cli._secure = True cli._connection = mock() user.commandLine(cli) cli.modeList = [user] return cli
def test_ProfileUploadActionRethrowsExceptions(self): storage = mock() jsonEncoder = mock() action = profile.Upload(storage, **{'name': 'ProfileName', 'profile': 'p.json'}) action.jsonEncoder = jsonEncoder when(jsonEncoder).encode('p.json').thenRaise(ValueError) self.assertRaises(ValueError, action.execute)
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 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 test_image_name(self): res = mock(requests.Response) url = 'https://example.com/scheduler/jobs/search?name=example_team-app' image_data = [{'container':{'image':'place-robot-simpleapp-2345643lkjfkdajurakdsfoweifa/v0.1.0'}}] data = {'environments':{'dev':{'chronos_endpoint':'https://example.com'}}} os.environ['ROGER_CONFIG_DIR'] = '/vagrant/config' username = '******' password = '******' config_dir = '/vagrant/config' config_file = 'test.yml' app_config_object = mock(AppConfig) when(app_config_object).getRogerEnv(config_dir).thenReturn(data) when(requests).get(url, auth=(username, password)).thenReturn(res) when(res).json().thenReturn(image_data) c = Chronos() img = c.get_image_name( username, password, 'dev', 'example_team-app', config_dir, config_file, app_config_object ) assert img == image_data[0]['container']['image']
def test_should_return_empty_running_environment_if_nothing_is_running(self): fake_boto_instance = mock() tags = { 'services' : """ apache : 80: 80""", 'credentials_name': 'test', 'env_name' : 'my_environment', 'env_def_name' : 'Single-AZ Deployment', } fake_boto_instance.tags = tags stub_region = mock() stub_region.name = 'eu-west' fake_boto_instance.region = stub_region fake_boto_instance.image_id = '1234' fake_boto_instance.instance_type = 'large' mock_connection_provider = mock() when(mock_connection_provider).ec2_connection_for_region("eu-west", None, None).thenReturn(None) when(mock_connection_provider).get_all_boto_instances(None, None).thenReturn([fake_boto_instance]) provider = AWSNodeProvider(None, None, mock_connection_provider) environment = provider.get_running_environment("test","test", all_credentials) self.assertIsNotNone(environment) self.assertEqual(0, len(environment.get_locations()))
def test_register_should_call_listener_for_each_late_combination_of_references_when_there_are_multiple_selectors(self): reference1a = 'REFERENCE1a' reference2a = 'REFERENCE2a' reference1b = 'REFERENCE1b' reference2b = 'REFERENCE2b' selection_a = mock() (when(selection_a).__iter__() .thenReturn([reference1a].__iter__()) .thenReturn([reference1a, reference2a].__iter__()) .thenReturn([reference1a, reference2a].__iter__())) when(selection_a).is_elegible(reference2a).thenReturn(True) selection_b = mock() (when(selection_b).__iter__() .thenReturn([reference1b].__iter__()) .thenReturn([reference1b].__iter__()) .thenReturn([reference1b, reference2b].__iter__())) when(selection_b).is_elegible(reference2b).thenReturn(True) self.manager.register(self.listener_callable_mock, utils.IterableMock(selection_a), utils.IterableMock(selection_b)) verify(self.listener_mock, times=1).__call__(reference1a, reference1b) verifyNoMoreInteractions(self.listener_mock) self.manager.evaluate_new_candidate(reference2a) verify(self.listener_mock, times=1).__call__(reference2a, reference1b) verifyNoMoreInteractions(self.listener_mock) self.manager.evaluate_new_candidate(reference2b) verify(self.listener_mock, times=1).__call__(reference1a, reference2b) verify(self.listener_mock, times=1).__call__(reference2a, reference2b) verifyNoMoreInteractions(self.listener_mock)
def setup(self): """ Setup the test case """ model = mock() action_factory = mock() rng = mock() self.creature1 = (CharacterBuilder() .with_tick(5) .with_speed(1) .with_name('creature 1') .build()) self.creature2 = (CharacterBuilder() .with_tick(0) .with_speed(2) .with_name('creature 2') .build()) self.creature3 = (CharacterBuilder() .with_tick(3) .with_speed(0.5) .with_name('creature 3') .build()) self.model = Model() self.model.dungeon = Dungeon() self.model.dungeon.levels = Level((20, 20), 0, 0) self.model.dungeon.levels.add_creature(self.creature1) self.model.dungeon.levels.add_creature(self.creature2) self.model.player = self.creature3 self.model.dungeon.levels.add_creature(self.creature3)
def test_find_by_name_parent_is_webelement(self): webelement = mock() when(self.finder)._is_webelement(webelement).thenReturn(True) when(self.finder)._is_webelement('name=value').thenReturn(False) when(webelement).find_elements_by_name('value').thenReturn([mock()]) self.finder.find('name=value', parent=webelement) verify(webelement).find_elements_by_name("value")
def test_find_by_xpath_parent_is_webelement(self): webelement = mock() when(self.finder)._is_webelement(webelement).thenReturn(True) when(self.finder)._is_webelement('//div').thenReturn(False) when(webelement).find_elements_by_xpath('//div').thenReturn([mock()]) self.finder.find('//div', parent=webelement) verify(webelement).find_elements_by_xpath('//div')
def test_dual_wielding(self): """ Test that character can wield two weapons """ item1 = (ItemBuilder() .with_name('dagger') .with_tag('light weapon') .with_damage(1) .build()) item2 = (ItemBuilder() .with_name('sickle') .with_tag('light weapon') .with_damage(2) .build()) assert_that(item1, is_not(is_in(self.character.weapons))) assert_that(item2, is_not(is_in(self.character.weapons))) pyherc.rules.items.wield(mock(), self.character, item1) pyherc.rules.items.wield(mock(), self.character, item2, dual_wield = True) assert_that(item1, is_in(self.character.weapons)) assert_that(item2, is_in(self.character.weapons))
def test_tranformer_shutdown_instance(self): status = rd_instance.ServiceStatuses.SHUTDOWN.api_status db_instance = self.build_db_instance(status) server = mock(Server) server.user_id = 'test_user_id' mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context, db_instance, server, None) when(Backup).running('1').thenReturn(None) self.assertThat(mgmt_instance.status, Equals('SHUTDOWN')) when(mgmtmodels).load_mgmt_instances( self.context, deleted=False, client=self.client).thenReturn( [mgmt_instance]) flavor = mock(Flavor) flavor.name = 'db.small' when(self.flavor_mgr).get('flavor_1').thenReturn(flavor) # invocation transformer = mgmtmodels.NovaNotificationTransformer( context=self.context) payloads = transformer() # assertion that SHUTDOWN instances are not reported self.assertIsNotNone(payloads) self.assertThat(len(payloads), Equals(0))
def setUp(self): self.transaction = mock() self.transaction._map = {} self.cursor = mock() self.connection = mock() self.transaction.cursor = self.cursor when(self.cursor).getconnection().thenReturn(self.connection)
def test_tranformer_flavor_cache(self): status = rd_instance.ServiceStatuses.BUILDING.api_status db_instance = MockMgmtInstanceTest.build_db_instance( status, InstanceTasks.BUILDING) server = mock(Server) server.user_id = 'test_user_id' mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context, db_instance, server, None) when(mgmtmodels).load_mgmt_instances( self.context, deleted=False, client=self.client).thenReturn( [mgmt_instance]) flavor = mock(Flavor) flavor.name = 'db.small' when(self.flavor_mgr).get('flavor_1').thenReturn(flavor) transformer = mgmtmodels.NovaNotificationTransformer( context=self.context) transformer() # call twice ensure client.flavor invoked once payloads = transformer() self.assertIsNotNone(payloads) self.assertThat(len(payloads), Equals(1)) payload = payloads[0] self.assertThat(payload['audit_period_beginning'], Not(Is(None))) self.assertThat(payload['audit_period_ending'], Not(Is(None))) self.assertThat(payload['state'], Equals(status.lower())) self.assertThat(payload['instance_type'], Equals('db.small')) self.assertThat(payload['instance_type_id'], Equals('flavor_1')) self.assertThat(payload['user_id'], Equals('test_user_id')) # ensure cache was used to get flavor second time verify(self.flavor_mgr).get('flavor_1')
def make_edge_with_mock_vehicles(self): edge, lane_1, lane_2 = self.make_edge_without_vehicles() first = mock() second = mock() lane_1.add_vehicle(first) lane_2.add_vehicle(second) return edge, first, second
def test_should_throw_exception_when_node_is_not_up_and_running(self): mock_connection_provider = mock() tags = { 'services' : """ 'apache' : 80: 80""", 'credentials_name': 'test', 'env_name' : 'test', 'env_def_name' : 'Single-AZ Deployment', } fake_boto_instance1 = mock() fake_boto_instance1.tags = tags stub_region = mock() stub_region.name = 'eu-west' fake_boto_instance1.region = stub_region fake_boto_instance1.id = 'id1234' fake_boto_instance1.ip_address = 'test_ip' fake_boto_instance1.state = 'running' fake_boto_instance1.placement='us-east-1' aws_node = AWSRunningNode(fake_boto_instance1, None, mock_connection_provider) when(mock_connection_provider).connected_to_node('test_ip', 22).thenReturn(False) with self.assertRaisesRegexp(Exception, "Node id1234 is not running"): aws_node.wait_for_ready(lambda : None, 5)
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_create_incremental(self): instance = mock(instance_models.Instance) parent = mock(models.DBBackup) when(instance_models.BuiltInstance).load(any(), any()).thenReturn( instance) when(instance).validate_can_perform_action().thenReturn(None) when(models.Backup).verify_swift_auth_token(any()).thenReturn( None) when(api.API).create_backup(any()).thenReturn(None) when(models.Backup).get_by_id(any(), any()).thenReturn( parent) incremental = models.Backup.create(self.context, self.instance_id, BACKUP_NAME, BACKUP_DESC, parent_id='parent_uuid') self.created = True db_record = models.DBBackup.find_by(id=incremental.id) self.assertEqual(incremental.id, db_record['id']) self.assertEqual(BACKUP_NAME, db_record['name']) self.assertEqual(BACKUP_DESC, db_record['description']) self.assertEqual(self.instance_id, db_record['instance_id']) self.assertEqual(models.BackupState.NEW, db_record['state']) self.assertEqual('parent_uuid', db_record['parent_id'])
def test_search_found_multiple(self): # pylint: disable=too-many-locals """Test found multiple colors.""" begin = 5 end = 15 region = NormalizedRegion(begin, end) whole_region = mock() when(sublime).Region(begin, end).thenReturn(whole_region) color_region1 = mock() when(sublime).Region(begin + 1, begin + 4).thenReturn(color_region1) color_region2 = mock() when(sublime).Region(end - 4, end - 1).thenReturn(color_region2) view = mock() test_color_text1 = "#FA" test_color_text2 = "#E5" when(view).substr(whole_region).thenReturn(" %s %s " % (test_color_text1, test_color_text2)) when(view).substr(color_region1).thenReturn(test_color_text1) when(view).substr(color_region2).thenReturn(test_color_text2) test_color1 = "#FB" test_color2 = "#DB" test_group = "test_group" color_converter = mock() when(color_converter).to_color({test_group: test_color_text1}).thenReturn(test_color1) when(color_converter).to_color({test_group: test_color_text2}).thenReturn(test_color2) color_searcher = ColorSearcher(re.compile("(?P<%s>#[0-9a-fA-F]{2})" % test_group), color_converter) results = [result for result in color_searcher.search(view, region)] self.assertEqual( [(NormalizedRegion(begin + 1, begin + 4), test_color1, {test_group: test_color_text1}), (NormalizedRegion(end - 4, end - 1), test_color2, {test_group: test_color_text2})], results)
def test_roger_push_env_from_ROGER_ENV_VAR(self): settings = mock(Settings) appConfig = mock(AppConfig) roger_push = RogerPush() marathon = mock(Marathon) mockedHooks = mock(Hooks) roger_env = self.roger_env config = self.config frameworkUtils = mock(FrameworkUtils) when(settings).getConfigDir().thenReturn(self.configs_dir) when(mockedHooks).run_hook(any(), any(), any()).thenReturn(0) when(appConfig).getRogerEnv(self.configs_dir).thenReturn(roger_env) when(appConfig).getConfig(any(), any()).thenReturn(config) args = self.args args.env = None args.secrets_file = "" args.skip_push = True args.app_name = 'grafana_test_app' args.config_file = 'test.json' roger_env = appConfig.getRogerEnv(self.configs_dir) roger_env["default_environment"] = None # Setting ROGER_ENV to specific value os.environ["ROGER_ENV"] = "test_env" with self.assertRaises(ValueError): roger_push.main(settings, appConfig, frameworkUtils, mockedHooks, args)
def test_processingtask_factory_should_return_processing_task(self): instance = mock() dependencies = mock() registration = mock() result = task.factory(instance, registration, dependencies) assert isinstance(result, task.DataFrameDatasourceTask)
def test_tranformer_shutdown_instance(self): status = ServiceStatuses.SHUTDOWN.api_status db_instance = DBInstance(InstanceTasks.DELETING, 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(Backup).running('1').thenReturn(None) self.assertThat(mgmt_instance.status, Equals('SHUTDOWN')) when(mgmtmodels).load_mgmt_instances( self.context, deleted=False, client=self.client).thenReturn( [mgmt_instance]) flavor = mock(Flavor) flavor.name = 'db.small' when(self.flavor_mgr).get('flavor_1').thenReturn(flavor) # invocation transformer = NovaNotificationTransformer(context=self.context) payloads = transformer() # assertion that SHUTDOWN instances are not reported self.assertIsNotNone(payloads) self.assertThat(len(payloads), Equals(0))
def test_process_should_receive_dependencies_process_results_as_context(self): registration = mock() symbol = 'symbol' start = None end = None expected_a = pandas.DataFrame([1, 2, 3]) expected_b = pandas.DataFrame([9, 8, 7]) class DatasourceMock(): def evaluate(self, context, s, ds, de): assert isinstance(context, task.DatasourceContext) deps = context.dependencies() assert isinstance(deps, dict) assert len(deps) is 2 assert (deps['a'].values == expected_a.values).all() assert (deps['b'].values == expected_b.values).all() assert s == symbol assert ds == start assert de == end dependencies = { 'a': mock(task.DataFrameDatasourceTask), 'b': mock(task.DataFrameDatasourceTask), } when(dependencies['a']).process(symbol, start, end).thenReturn(expected_a) when(dependencies['b']).process(symbol, start, end).thenReturn(expected_b) task.DataFrameDatasourceTask(DatasourceMock(), registration, dependencies).process(symbol, start, end)
def test_should_execute_test_function_when_running_test(self): test_definition_mock = mock(TestDefinition) when(self.injector_mock).execute_test(test_definition_mock).thenReturn(mock(TestResult)) self.test_runner.run_test([test_definition_mock]) when(self.injector_mock).execute_test(test_definition_mock)
def start_client(self): soledad_test_folder = self._generate_soledad_test_folder_name() SearchEngine.DEFAULT_INDEX_HOME = soledad_test_folder self.cleanup = lambda: shutil.rmtree(soledad_test_folder) self.soledad = yield initialize_soledad(tempdir=soledad_test_folder) self.keymanager = mock() self.search_engine = SearchEngine(self.INDEX_KEY, agent_home=soledad_test_folder) self.mail_sender = self._create_mail_sender() self.mail_store = SearchableMailStore(LeapMailStore(self.soledad), self.search_engine) account_ready_cb = defer.Deferred() self.account = IMAPAccount(self.ACCOUNT, self.soledad, account_ready_cb) yield account_ready_cb self.draft_service = DraftService(self.mail_store) self.leap_session = mock() self.feedback_service = FeedbackService(self.leap_session) self.mail_service = self._create_mail_service(self.mail_sender, self.mail_store, self.search_engine) mails = yield self.mail_service.all_mails() self.search_engine.index_mails(mails) self.resource = RootResource() self.resource.initialize( self.keymanager, self.search_engine, self.mail_service, self.draft_service, self.feedback_service )
def test_level_generator_is_created(self): """ Test that portal adder has level generator set to it """ portal_config = [PortalAdderConfiguration(icons = (1, 2), level_type = 'catacombs', location_type = 'room', chance = 100, new_level = 'upper crypt', unique = False)] level_generator_factory = mock(LevelGeneratorFactory) level_generator = mock(LevelGenerator) when(level_generator_factory).get_generator(any()).thenReturn(level_generator) factory = PortalAdderFactory(portal_config, self.rng) factory.level_generator_factory = level_generator_factory portal_adders = factory.create_portal_adders('catacombs') portal_adder = portal_adders[0] assert_that(portal_adder.level_generator, is_(same_instance(level_generator)))
def test_dual_wielding_two_handed_weapons(self): #pylint: disable=C0103 """ Test that character can not dual wield two-handed weapon """ item1 = (ItemBuilder() .with_name('longspear') .with_tag('two-handed weapon') .with_tag('weapon') .build()) item2 = (ItemBuilder() .with_name('sickle') .with_tag('light weapon') .with_tag('weapon') .build()) assert_that(item1, is_not(is_in(self.character.weapons))) assert_that(item2, is_not(is_in(self.character.weapons))) pyherc.rules.items.wield(mock(), self.character, item2) pyherc.rules.items.wield(mock(), self.character, item1, dual_wield = True) assert_that(item1, is_not(is_in(self.character.weapons))) assert_that(item2, is_in(self.character.weapons))
def __init__(self): """ Default constructor """ super(CharacterBuilder, self).__init__() self.hit_points = 10 self.max_hp = 10 self.model = mock() self.action_factory = mock() self.rng = Random() self.speed = 1 self.tick = 0 self.attack = 1 self.body = 1 self.mind = 1 self.name = 'prototype' self.level = None self.location = () self.effect_handles = [] self.effects = [] self.effects_collection = EffectsCollection() self.player_character = False self.listeners = []
def testShouldScreamWhenCallingUnexpectedMethod(self): action = mock(Action) with pytest.raises(AttributeError): action.run(11)
def testShouldScreamWhenCallingUnknownMethod(self): action = mock(Action) with pytest.raises(AttributeError): action.unknownMethod()
def testWithConflictingNames(self): theMock = mock(IWithGet) when(theMock).get('d').thenReturn(0) when(theMock).names().thenReturn(0)
def root_chain(self): root_chain = mock() root_chain.functions = mock() return root_chain
def mock_file_detector(creator): file_detector = mock() when(creator)._get_sl_file_detector().thenReturn(file_detector) return file_detector
def testShouldPassIsInstanceChecks(self): action = mock(Action) assert isinstance(action, Action)
def testPreconfigureWithFunctionThatTakesNoArgs(self): action = mock({'no_arg': lambda: 12}, spec=Action) assert action.no_arg() == 12 verify(action).no_arg()
def get_db(*args): db_mock = mockito.mock(Database) mockito.when(db_mock).documents().thenReturn([]) return db_mock
def finder(): ctx = mock() ctx.driver = mock() return ElementFinder(ctx)
def setUp(self): ctx = mock() ctx.event_firing_webdriver = None ctx._browser = mock() ctx._drivers = mock() self.brorser = BrowserManagementKeywords(ctx)
def setUp(self): self.ctx = mock() self.ctx.driver = self.driver = mock() self.finder = ExtendedElementFinder(self.ctx)
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 box_api_mocker(uri): response = mock({'status_code': 200, 'text': 'Ok'}) when(requests).get(uri).thenReturn(response) requests.get(uri) unstub()
def testPreconfigureMockWithAttributes(self): action = mock({'foo': 'bar'}, spec=Action) assert action.foo == 'bar' with pytest.raises(InvocationError): when(action).remember()
def testPreconfigureWithFunction(self): action = mock({'run': lambda _: 12}, spec=Action) assert action.run(11) == 12 verify(action).run(11)
# -*- coding:utf-8 -*- import unittest from mockito import when, mock, unstub, verify,times import test_data import simplejson as sjson from util import log_utils import datetime from core import database from cache import rediscache when(database).db_session().thenReturn(mock()) from cache import api_mongo from cache.api_mongo import ApiMongo # from cache.api_rcms import ApiRCMS # from cache.api_portal import ApiPortal class ApiMongoTest(unittest.TestCase): def setUp(self): api_mongo.ApiRCMS=mock() api_mongo.ApiPortal=mock() api_mongo.rediscache=mock() # self.ApiRCMS=mock() # self.ApiPortal=mock() dbsession=mock() dbsession.statistical=mock() when(database).db_session().thenReturn(dbsession) dbsession.cache_user_channels=mock() when(dbsession.cache_user_channels).create_index('username').thenReturn('username')
def testShouldScreamOnUnknownAttribute(self): action = mock(Action) with pytest.raises(AttributeError): action.cam
def testHasANiceName(self): action = mock(Action) assert repr(action) == "<DummyAction id=%s>" % id(action)
def _execute_rename_resource(self, new_basename, boolean_variable): self.res_controller.remove_from_filesystem = mock() self.res_controller.save = mock() self.res_controller.execute(RenameResourceFile(new_basename, lambda : boolean_variable))
def testFails(self): theMock = mock() theMock.foo() self.assertRaises(VerificationError, verifyNoMoreInteractions, theMock)
def testPrintsNicely(self): theMock = mock() try: verify(theMock).foo() except VerificationError, e: self.assertEquals("\nWanted but not invoked: foo()", str(e))
def testVerifies(self): theMock = mock() verifyZeroInteractions(theMock) theMock.foo() self.assertRaises(VerificationError, verifyNoMoreInteractions, theMock)
def testInheritedInterface(self): theMock = mock(ISuper) when(theMock).simple('a', 'b', 'c').thenReturn(0) when(theMock).complex('d').thenReturn(0)
def setUp(self): self.mock = mock()
def testReturnNoneForEveryMethod(self): action = mock(Action, strict=False) assert action.unknownMethod() is None assert action.run(11) is None
def testNamedParam(self): theMock = mock(ITest) when(theMock).simple_with_names_params('d', 'e', any(), d=1).thenReturn(0)
def testStubCallAndVerify(self): action = mock(Action) when(action).run(11).thenReturn(12) assert action.run(11) == 12 verify(action).run(11)
def testShouldScreamWhenStubbingUnknownMethod(self): action = mock(Action) with pytest.raises(InvocationError): when(action).unknownMethod()
def child_chain(self): return mock()
def setUp(self): self._mappers_manager = managers.mapper_manager.MapperManager() self._persistence_manager = NullPersistenceManager() self._mappers_manager.createMappers(self._persistence_manager) self.model_controller = model.controller.ModelController( mock(), self._mappers_manager)