def _setUp(self): self.useFixture( MonkeyPatch('twisted.internet.defer.Deferred.debug', self._debug_setting)) self.useFixture( MonkeyPatch('twisted.internet.base.DelayedCall.debug', self._debug_setting))
def test_patch_and_restore(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.reference', 45) self.assertEqual(23, reference) fixture.setUp() try: self.assertEqual(45, reference) finally: fixture.cleanUp() self.assertEqual(23, reference)
def test_patch_missing_attribute(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.new_attr', True) self.assertFalse('new_attr' in globals()) fixture.setUp() try: self.assertEqual(True, new_attr) finally: fixture.cleanUp() self.assertFalse('new_attr' in globals())
def test_delete_existing_attribute(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.reference', MonkeyPatch.delete) self.assertEqual(23, reference) fixture.setUp() try: self.assertFalse('reference' in globals()) finally: fixture.cleanUp() self.assertEqual(23, reference)
def test_delete_missing_attribute(self): fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.new_attr', MonkeyPatch.delete) self.assertFalse('new_attr' in globals()) fixture.setUp() try: self.assertFalse('new_attr' in globals()) finally: fixture.cleanUp() self.assertFalse('new_attr' in globals())
def test_double_patch_classmethod(self): oldmethod = C.foo_cls oldmethod_inst = C().foo_cls fixture1 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', fake) fixture2 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_cls', fake2) with fixture1: with fixture2: C.foo_cls() C().foo_cls() self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, C, 'foo_cls')
def test_double_patch_instancemethod(self): oldmethod = C.foo oldmethod_inst = C().foo fixture1 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake) fixture2 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake2) with fixture1: with fixture2: C().foo() self.assertEqual(oldmethod, C.foo) # The method address changes with each instantiation of C, and method # equivalence just tests that. Compare the code objects instead. self.assertEqual(oldmethod_inst.__code__, C().foo.__code__)
def test_double_patch_staticmethod(self): oldmethod = C.foo_static oldmethod_inst = C().foo_static fixture1 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', fake_no_args) fixture2 = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo_static', fake_static) with fixture1: with fixture2: C.foo_static() C().foo_static() self._check_restored_static_or_class_method(oldmethod, oldmethod_inst, C, 'foo_static')
def setUp(self): super(FunctionalTest, self).setUp() self.test_data_dir = ''.join((os.path.abspath(os.getcwd()), '/', self.test_data_subdir)) self.maildir = TempDir() self.useFixture(self.maildir) self.fake_getmtime_val = 123456.7 self.useFixture(MonkeyPatch('os.path.getmtime', self.fake_getmtime)) config = { 'app': { 'root': 'mailase.api.controllers.root.RootController', 'modules': ['mailase.api'], }, 'mail': { 'maildirs': self.maildir.path }, 'search': { 'server_url': ['http://localhost:9200'], 'index': 'mailase_test' } } self.app = load_test_app(config) self.mailboxes = {} self.mua_subdirs = {}
def test_isolated_runs_multiple_processes(self): ui, cmd = self.get_test_ui_and_cmd(options=[('isolated', True)]) cmd.repository_factory = memory.RepositoryFactory() self.setup_repo(cmd, ui) self.set_config('[DEFAULT]\ntest_command=foo $IDLIST $LISTOPT\n' 'test_id_option=--load-list $IDFILE\n' 'test_list_option=--list\n') params, capture_ids = self.capture_ids(list_result=['ab', 'cd', 'ef']) self.useFixture( MonkeyPatch( 'testrepository.testcommand.TestCommand.get_run_command', capture_ids)) cmd_result = cmd.execute() self.assertEqual([ ('results', Wildcard), ('summary', True, 0, -3, None, None, [('id', 1, None)]), ('results', Wildcard), ('summary', True, 0, 0, None, None, [('id', 2, None)]), ('results', Wildcard), ('summary', True, 0, 0, None, None, [('id', 3, None)]), ], ui.outputs) self.assertEqual(0, cmd_result) # once to list, then 3 each executing one test. self.assertThat(params, HasLength(4)) self.assertThat(params[0][1], Equals(None)) self.assertThat(params[1][1], Equals(['ab'])) self.assertThat(params[2][1], Equals(['cd'])) self.assertThat(params[3][1], Equals(['ef']))
def _mock_list_images(self, return_value, image_name, expected_resp): mock_function = mock.Mock(return_value=return_value) func2mock = self.FAKE_CLIENT_MOCK + '.list_images' self.useFixture(MonkeyPatch(func2mock, mock_function)) resp = self.Service._find_image(image_id=None, image_name=image_name) self.assertEqual(resp, expected_resp)
def test_correct_opal_keygen_command_executed(self): # Check that calling generateOpalKeys() will generate the # expected command. self.setUpPPA() self.setUpOpalKeys(create=False) fake_call = FakeMethod(result=0) self.useFixture(MonkeyPatch("subprocess.call", fake_call)) upload = SigningUpload() upload.setTargetDirectory(self.archive, "test_1.0_amd64.tar.gz", "distroseries") upload.generateOpalKeys() self.assertEqual(2, fake_call.call_count) # Assert the actual command matches. args = fake_call.calls[0][0][0] # Sanitise the keygen tmp file. if args[11].endswith('.keygen'): args[11] = 'XXX.keygen' expected_cmd = [ 'openssl', 'req', '-new', '-nodes', '-utf8', '-sha512', '-days', '3650', '-batch', '-x509', '-config', 'XXX.keygen', '-outform', 'PEM', '-out', self.opal_pem, '-keyout', self.opal_pem ] self.assertEqual(expected_cmd, args) args = fake_call.calls[1][0][0] expected_cmd = [ 'openssl', 'x509', '-in', self.opal_pem, '-outform', 'DER', '-out', self.opal_x509 ] self.assertEqual(expected_cmd, args)
def test_correct_uefi_keygen_command_executed(self): # Check that calling generateUefiKeys() will generate the # expected command. self.setUpPPA() self.setUpUefiKeys(create=False) fake_call = FakeMethod(result=0) self.useFixture(MonkeyPatch("subprocess.call", fake_call)) upload = SigningUpload() upload.setTargetDirectory(self.archive, "test_1.0_amd64.tar.gz", "distroseries") upload.generateUefiKeys() self.assertEqual(1, fake_call.call_count) # Assert the actual command matches. args = fake_call.calls[0][0][0] expected_cmd = [ 'openssl', 'req', '-new', '-x509', '-newkey', 'rsa:2048', '-subj', self.testcase_cn, '-keyout', self.key, '-out', self.cert, '-days', '3650', '-nodes', '-sha256', ] self.assertEqual(expected_cmd, args)
def test_empty_requirements_file(self): fixture = self.useFixture(MainFixture()) self.useFixture(MonkeyPatch('sys.argv', ['bindep'])) with open(fixture.path + '/other-requirements.txt', 'wt'): pass self.assertEqual(0, main()) self.assertEqual('', fixture.logger.output)
def test_load_list_passes_ids(self): list_file = tempfile.NamedTemporaryFile() self.addCleanup(list_file.close) expected_ids = set(['foo', 'quux', 'bar']) write_list(list_file, expected_ids) list_file.flush() ui, cmd = self.get_test_ui_and_cmd(options=[('load_list', list_file.name)]) cmd.repository_factory = memory.RepositoryFactory() self.setup_repo(cmd, ui) self.set_config( '[DEFAULT]\ntest_command=foo $IDOPTION\ntest_id_option=--load-list $IDFILE\n' ) params, capture_ids = self.capture_ids() self.useFixture( MonkeyPatch( 'testrepository.testcommand.TestCommand.get_run_command', capture_ids)) cmd_result = cmd.execute() self.assertEqual( [('results', Wildcard), ('summary', True, 0, -3, None, None, [('id', 1, None)])], ui.outputs) self.assertEqual(0, cmd_result) self.assertEqual([[Wildcard, expected_ids, [], None]], params)
def _test_create_flavor(self, no_rng=False): return_value = {"flavor": {"id": "MyFakeID", "name": "MyID"}} self.Service.flavor_list = [] client = self.CLIENT_MOCK mock_function = mock.Mock(return_value=return_value) self.useFixture(MonkeyPatch(client + '.create_flavor', mock_function)) mock_function = mock.Mock(return_value={}) self.useFixture( MonkeyPatch(client + '.set_flavor_extra_spec', mock_function)) resp = self.Service.create_flavor("MyID", C.DEFAULT_FLAVOR_RAM, C.DEFAULT_FLAVOR_VCPUS, C.DEFAULT_FLAVOR_DISK, no_rng=no_rng) self.assertEqual(resp, return_value['flavor']['id']) return mock_function
def test_patch_boundmethod_with_classmethod(self): oldmethod = INST_C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', D.bar_cls) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo)
def test_missing_default_requirements_file(self): fixture = self.useFixture(MainFixture()) self.useFixture(MonkeyPatch('sys.argv', ['bindep'])) self.assertEqual(1, main()) self.assertEqual( 'Neither file bindep.txt nor file other-requirements.txt exist.\n', fixture.logger.output)
def test_patch_staticmethod(self): oldfoo = C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', bar) with fixture: pass self.assertEqual(oldfoo, C.foo)
def test_find_image_by_id(self): expected_resp = {"id": "001", "status": "active", "name": "ImageName"} mock_function = mock.Mock(return_value=expected_resp) func2mock = self.FAKE_CLIENT_MOCK + '.show_image' self.useFixture(MonkeyPatch(func2mock, mock_function)) resp = self.Service._find_image(image_id="001", image_name="cirros") self.assertEqual(resp, expected_resp)
def test_regex_test_filter_with_explicit_ids(self): ui, cmd = self.get_test_ui_and_cmd(args=('g1', '--', 'bar', 'quux'), options=[('failing', True)]) cmd.repository_factory = memory.RepositoryFactory() self.setup_repo(cmd, ui) self.set_config('[DEFAULT]\ntest_command=foo $IDLIST $LISTOPT\n' 'test_id_option=--load-list $IDFILE\n' 'test_list_option=--list\n') params, capture_ids = self.capture_ids() self.useFixture( MonkeyPatch( 'testrepository.testcommand.TestCommand.get_run_command', capture_ids)) cmd_result = cmd.execute() self.assertEqual( [('results', Wildcard), ('summary', True, 0, -3, None, None, [('id', 1, None)])], ui.outputs) self.assertEqual(0, cmd_result) self.assertThat(params[0][1], Equals(['failing1', 'failing2'])) self.assertThat(params[0][2], MatchesListwise([Equals('bar'), Equals('quux')])) self.assertThat(params[0][3], MatchesListwise([Equals('g1')])) self.assertThat(params, HasLength(1))
def test_missing_specific_requirements_file(self): fixture = self.useFixture(MainFixture()) self.useFixture( MonkeyPatch('sys.argv', ['bindep', '--file', 'alternative-requirements.txt'])) self.assertEqual(1, main()) self.assertEqual('Error reading file alternative-requirements.txt.\n', fixture.logger.output)
def test_patch_function_with_boundmethod(self): oldmethod = fake_no_args fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', D().bar) with fixture: fake_no_args() self.assertEqual(oldmethod, fake_no_args)
def test_patch_boundmethod_with_function(self): oldmethod = INST_C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.INST_C.foo', fake_no_args) with fixture: INST_C.foo() self.assertEqual(oldmethod, INST_C.foo)
def test_urlfetch_no_proxy_by_default(self): """urlfetch does not use a proxy by default.""" self.pushConfig('launchpad', http_proxy='http://proxy.example:3128/') fake_send = FakeMethod(result=Response()) self.useFixture( MonkeyPatch('requests.adapters.HTTPAdapter.send', fake_send)) urlfetch('http://example.com/') self.assertEqual({}, fake_send.calls[0][1]['proxies'])
def test_patch_function_with_partial(self): oldmethod = fake_no_args fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.fake_no_args', functools.partial(fake, 1)) with fixture: (ret, ) = fake_no_args() self.assertEqual(1, ret) self.assertEqual(oldmethod, fake_no_args)
def setUp(self): super(MainFixture, self).setUp() self.logger = self.useFixture(FakeLogger()) self.path = self.useFixture(TempDir()).path self.addCleanup(os.chdir, self.path) os.chdir(self.path) fake_lsb = b'Ubuntu\n14.04\nTrusty' self.useFixture( MonkeyPatch('subprocess.check_output', lambda *a, **k: fake_lsb))
def test_specific_requirements_file(self): fixture = self.useFixture(MainFixture()) self.useFixture( MonkeyPatch('sys.argv', ['bindep', '--file', 'alternative-requirements.txt'])) with open(fixture.path + '/alternative-requirements.txt', 'wt'): pass self.assertEqual(0, main()) self.assertEqual('', fixture.logger.output)
def setUp(self): super(TestFlavors, self).setUp() self.conf = self._get_conf("v2.0", "v3") self.client = self._get_clients(self.conf).flavors return_value = {"flavors": [{"id": "MyFakeID", "name": "MyID"}]} mock_function = mock.Mock(return_value=return_value) self.useFixture( MonkeyPatch(self.CLIENT_MOCK + '.list_flavors', mock_function)) self.Service = Flavors(self.client, True, self.conf, 64, 1)
def _get_creds(self, conf, admin=False, v2=False): # We return creds configured to v2 or v3 func2mock = 'config_tempest.credentials.Credentials._list_versions' return_value = self.FAKE_V3_VERSIONS if v2: return_value = self.FAKE_V2_VERSIONS mock_function = mock.Mock(return_value=return_value) self.useFixture(MonkeyPatch(func2mock, mock_function)) return Credentials(conf, admin)
def test_get_auth_provider_keystone_v3(self): # check if method returns KeystoneV3AuthProvider # make isinstance return True mockIsInstance = mock.Mock(return_value=True) self.useFixture( MonkeyPatch('config_tempest.credentials.isinstance', mockIsInstance)) mock_function = mock.Mock() # mock V3Provider, if other provider is called, it fails func2mock = 'config_tempest.credentials.auth.KeystoneV3AuthProvider' self.useFixture(MonkeyPatch(func2mock, mock_function)) resp = self.creds.get_auth_provider() self.assertEqual(resp, mock_function()) # check parameters of returned function self.creds.get_auth_provider() mock_function.assert_called_with(self.creds.tempest_creds, 'http://172.16.52.151:5000/v3', 'true', None)
def test_find_flavor_by_name(self): return_value = {"flavors": self.FLAVORS_LIST} mock_function = mock.Mock(return_value=return_value) self.useFixture( MonkeyPatch(self.CLIENT_MOCK + '.list_flavors', mock_function)) resp = self.Service.find_flavor_by_name("MyID") self.assertEqual(resp, "MyFakeID") # test no flavor found case resp = self.Service.find_flavor_by_name("NotExist") self.assertEqual(resp, None)
def test_patch_unboundmethod_with_function(self): oldmethod = C.foo fixture = MonkeyPatch( 'fixtures.tests._fixtures.test_monkeypatch.C.foo', fake) with fixture: c = C() target_self, arg = c.foo(1) self.expectThat(target_self, Is(c)) self.assertTrue(1, arg) self.assertEqual(oldmethod, C.foo)
def test_init_manager_as_admin(self): self.creds = self._get_creds(self.conf, True) mock_function = mock.Mock(return_value={"id": "my_fake_id"}) func2mock = ('config_tempest.clients.ProjectsClient.' 'get_project_by_name') self.useFixture(MonkeyPatch(func2mock, mock_function)) ClientManager(self.conf, self.creds) # check if admin project id was set admin_project_id = self.conf.get("auth", "admin_project_id") self.assertEqual(admin_project_id, "my_fake_id")