def test_build_pxe_config(self): args = { 'deployment_id': 'aaa', 'deployment_key': 'bbb', 'deployment_iscsi_iqn': 'ccc', 'deployment_aki_path': 'ddd', 'deployment_ari_path': 'eee', 'aki_path': 'fff', 'ari_path': 'ggg', } config = pxe.build_pxe_config(**args) self.assertThat(config, matchers.StartsWith('default deploy')) # deploy bits are in the deploy section start = config.index('label deploy') end = config.index('label boot') self.assertThat(config[start:end], matchers.MatchesAll( matchers.Contains('kernel ddd'), matchers.Contains('initrd=eee'), matchers.Contains('deployment_id=aaa'), matchers.Contains('deployment_key=bbb'), matchers.Contains('iscsi_target_iqn=ccc'), matchers.Not(matchers.Contains('kernel fff')), )) # boot bits are in the boot section start = config.index('label boot') self.assertThat(config[start:], matchers.MatchesAll( matchers.Contains('kernel fff'), matchers.Contains('initrd=ggg'), matchers.Not(matchers.Contains('kernel ddd')), ))
def test_replace_object(self): """ Test to ensure that if an object is updated the container object count is the same and the contents of the object are updated """ swift_stub = SwiftClientStub() swift_stub.with_account('1223df2') swift_stub.with_container('new-container') swift_stub.with_object('new-container', 'new-object', 'new-object-contents') conn = swiftclient.client.Connection() conn.put_object('new-container', 'new-object', 'new-object-contents') obj_resp = conn.get_object('new-container', 'new-object') self.assertThat(obj_resp, matchers.Not(matchers.Is(None))) self.assertThat(len(obj_resp), matchers.Is(2)) self.assertThat(obj_resp[1], matchers.Is('new-object-contents')) # set expected behavior - trivial here since it is the intended # behavior however keep in mind this is just to support testing of # trove components swift_stub.with_object('new-container', 'new-object', 'updated-object-contents') conn.put_object('new-container', 'new-object', 'updated-object-contents') obj_resp = conn.get_object('new-container', 'new-object') self.assertThat(obj_resp, matchers.Not(matchers.Is(None))) self.assertThat(len(obj_resp), matchers.Is(2)) self.assertThat(obj_resp[1], matchers.Is('updated-object-contents')) # ensure object count has not increased self.assertThat(len(conn.get_container('new-container')[1]), matchers.Is(1))
def test_execute(self): with mock.patch.object(os.path, 'isfile', return_value=True): self.assertIsNone( renamer.execute('/tmp/test_file.txt', 'Test_file.txt')) tempfile = self.create_tempfiles([('test_file', 'test data')])[0] new_file = os.path.join(os.path.dirname(tempfile), 'other_file.conf') renamer.execute(tempfile, new_file) self.assertThat(new_file, matchers.FileExists()) self.assertThat(tempfile, matchers.Not(matchers.FileExists())) tempfiles = self.create_tempfiles([('test_file', 'test data'), ('other_file', 'test data')]) self.CONF.set_override('overwrite_file_enabled', True) renamer.execute(tempfiles[0], tempfiles[1]) self.assertThat(tempfiles[1], matchers.FileExists()) self.assertThat(tempfiles[0], matchers.Not(matchers.FileExists())) tempfile = self.create_tempfiles([('my_file', 'test data')])[0] new_file = os.path.join(os.path.dirname(tempfile), 'alt_file.conf') self.CONF.set_override('dryrun', True) renamer.execute(tempfile, new_file) self.assertThat(tempfile, matchers.FileExists()) self.assertThat(new_file, matchers.Not(matchers.FileExists()))
def test_hooks_exist(self): self.assertThat(self.hooks_dir.join('no-such-hook'), matchers.Not(matchers.FileExists())) for hook in self.fake_hooks: hook_path = self.hooks_dir.join(hook) self.assertThat(hook_path, matchers.FileExists())
def test_meta(self): class Manager(periodic_task.PeriodicTasks): @periodic_task.periodic_task def foo(self): return 'foo' @periodic_task.periodic_task(spacing=4) def bar(self): return 'bar' @periodic_task.periodic_task(enabled=False) def baz(self): return 'baz' m = Manager(self.conf) self.assertThat(m._periodic_tasks, matchers.HasLength(2)) self.assertEqual(periodic_task.DEFAULT_INTERVAL, m._periodic_spacing['foo']) self.assertEqual(4, m._periodic_spacing['bar']) self.assertThat(m._periodic_spacing, matchers.Not(matchers.Contains('baz'))) @periodic_task.periodic_task def external(): return 42 m.add_periodic_task(external) self.assertThat(m._periodic_tasks, matchers.HasLength(3)) self.assertEqual(periodic_task.DEFAULT_INTERVAL, m._periodic_spacing['external'])
def test_install_no_ChangeLog(self): stdout, _, _ = self.run_setup('install', '--root', self.temp_dir + 'installed', allow_fail=False) self.expectThat( stdout, matchers.Not(matchers.Contains('Generating ChangeLog')))
def _helper_test_validate_subnet(self, option, exception): cfg.CONF.set_override(option, 0) with self.network() as network: subnet = { 'network_id': network['network']['id'], 'cidr': '10.0.2.0/24', 'ip_version': 4, 'tenant_id': network['network']['tenant_id'], 'gateway_ip': '10.0.2.1', 'dns_nameservers': ['8.8.8.8'], 'host_routes': [{ 'destination': '135.207.0.0/16', 'nexthop': '1.2.3.4' }] } error = self.assertRaises( exception, FAKE_SERVER._validate_subnet, neutron_context.get_admin_context(load_admin_roles=False), subnet) self.assertThat( str(error), matchers.Not(matchers.Contains('built-in function id')))
def _test_log_curl_request_with_certs(self, mock_log, key, cert, cacert): headers = {'header1': 'value1'} http_client_object = http.HTTPClient(self.ssl_endpoint, key_file=key, cert_file=cert, cacert=cacert, token='fake-token') http_client_object.log_curl_request('GET', '/api/v1/', headers, None, None) self.assertTrue(mock_log.called, 'LOG.debug never called') self.assertTrue(mock_log.call_args[0], 'LOG.debug called with no arguments') needles = {'key': key, 'cert': cert, 'cacert': cacert} for option, value in needles.items(): if value: regex = ".*\s--%s\s+('%s'|%s).*" % (option, value, value) self.assertThat(mock_log.call_args[0][0], matchers.MatchesRegex(regex), 'no --%s option in curl command' % option) else: regex = ".*\s--%s\s+.*" % option self.assertThat( mock_log.call_args[0][0], matchers.Not(matchers.MatchesRegex(regex)), 'unexpected --%s option in curl command' % option)
def test_pep8(self): # NOTE(jecarey): Add tests marked as off_by_default to enable testing turn_on = set(['H106']) if self.options.select: turn_on.update(self.options.select) self.options.select = tuple(turn_on) report = pep8.BaseReport(self.options) checker = pep8.Checker(filename=self.filename, lines=self.lines, options=self.options, report=report) checker.check_all() self.addDetail('doctest', content.text_content(self.raw)) if self.code == 'Okay': self.assertThat( len(report.counters), matchers.Not( matchers.GreaterThan(len(self.options.benchmark_keys))), "incorrectly found %s" % ', '.join([ key for key in report.counters if key not in self.options.benchmark_keys ])) else: self.addDetail( 'reason', content.text_content("Failed to trigger rule %s" % self.code)) self.assertIn(self.code, report.counters)
def test_manifest_exclude_honoured(self): with open(os.path.join( self.package_dir, 'pbr_testpackage.egg-info/SOURCES.txt'), 'r') as f: body = f.read() self.assertThat( body, matchers.Not(matchers.Contains('pbr_testpackage/extra.py'))) self.assertThat(body, matchers.Contains('pbr_testpackage/__init__.py'))
def test_cleanup_deleted(self): with tempfile.NamedTemporaryFile(delete=False) as f: f.write(json.dumps([self.data])) f.flush() self.env['HEAT_SHELL_CONFIG'] = f.name returncode, stdout, stderr = self.run_cmd( [self.cleanup_path], self.env) # on the first run, abcdef001.json is written out, no docker calls made configs_path = os.path.join(self.env['HEAT_DOCKER_CMD_WORKING'], 'abcdef001.json') self.assertThat(configs_path, matchers.FileExists()) self.assertThat(self.test_state_path, matchers.Not(matchers.FileExists())) # run again with empty config data with tempfile.NamedTemporaryFile(delete=False) as f: f.write(json.dumps([])) f.flush() self.env['HEAT_SHELL_CONFIG'] = f.name returncode, stdout, stderr = self.run_cmd( [self.cleanup_path], self.env) # on the second run, abcdef001.json is deleted, docker rm is run on # both containers configs_path = os.path.join(self.env['HEAT_DOCKER_CMD_WORKING'], 'abcdef001.json') self.assertThat(configs_path, matchers.Not(matchers.FileExists())) state_0 = self.json_from_file(self.test_state_path) state_1 = self.json_from_file('%s_1' % self.test_state_path) self.assertEqual([ self.fake_tool_path, 'rm', '-f', 'abcdef001__db', ], state_0['args']) self.assertEqual([ self.fake_tool_path, 'rm', '-f', 'abcdef001__web', ], state_1['args'])
def test_model_load(self): res = self._runner.testLoadCompexModel() for i in range(3): self.assertThat(res[i], matchers.Not(matchers.Contains('node'))) self.assertEqual(self._runner.root.object_id, res[3]) self.assertEqual([ 'rootNode', ['childNode1', 'childNode2', 'childNode2'], True, True, True, True, True, 'rootNode', 'childNode2', 'childNode1' ], res[4:])
def assertNotIsInstance(self, obj, cls, msg=None): """Python < v2.7 compatibility. Assert 'not isinstance(obj, cls).""" try: f = super(_BaseTestCase, self).assertNotIsInstance except AttributeError: self.assertThat(obj, matchers.Not(matchers.IsInstance(cls)), message=msg or '') else: f(obj, cls, msg=msg)
def assertGreaterEqual(self, first, second, msg=None): """Python < v2.7 compatibility. Assert 'first' >= 'second'.""" try: f = super(TestCase, self).assertGreaterEqual except AttributeError: self.assertThat(first, matchers.Not(matchers.LessThan(second)), message=msg or '') else: f(first, second, msg=msg)
def test_run_heat_config(self, mock_request): mock_request.register_uri('POST', 'mock://192.0.2.2/foo') mock_request.register_uri('POST', 'mock://192.0.2.3/foo') with self.write_config_file(self.data) as config_file: env = os.environ.copy() env.update({ 'HEAT_CONFIG_HOOKS': self.hooks_dir.join(), 'HEAT_SHELL_CONFIG': config_file.name }) returncode, stdout, stderr = self.run_cmd([self.heat_config_path], env) self.assertEqual(0, returncode, stderr) for config in self.data: hook = config['group'] hook_path = self.hooks_dir.join(hook) stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) if hook == 'no-such-hook': self.assertThat(hook_path, matchers.Not(matchers.FileExists())) self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) continue self.assertTrue(hook_path, matchers.FileExists()) self.assertTrue(stdin_path, matchers.FileExists()) self.assertTrue(stdout_path, matchers.FileExists()) # parsed stdin should match the config item self.assertEqual(config, self.json_from_file(stdin_path)) self.assertEqual(self.outputs[hook], self.json_from_file(stdout_path))
def test_log_curl_request_with_token_header(self, mock_log): fake_token = 'fake-token' headers = {'X-Auth-Token': fake_token} http_client_object = http.HTTPClient(self.endpoint, identity_headers=headers) http_client_object.log_curl_request('GET', '/api/v1/', headers, None, None) self.assertTrue(mock_log.called, 'LOG.debug never called') self.assertTrue(mock_log.call_args[0], 'LOG.debug called with no arguments') token_regex = '.*%s.*' % fake_token self.assertThat(mock_log.call_args[0][0], matchers.Not(matchers.MatchesRegex(token_regex)), 'token found in LOG.debug parameter')
def test_pep8(self): report = pep8.BaseReport(self.options) checker = pep8.Checker(lines=self.lines, options=self.options, report=report) checker.check_all() self.addDetail('doctest', content.text_content(self.raw)) if self.code == 'Okay': self.assertThat( len(report.counters), matchers.Not(matchers.GreaterThan( len(self.options.benchmark_keys))), "incorrectly found %s" % ', '.join( [key for key in report.counters if key not in self.options.benchmark_keys])) else: self.addDetail('reason', content.text_content("Failed to trigger rule %s" % self.code)) self.assertIn(self.code, report.counters)
def test_meta(self): class Manager(periodic_task.PeriodicTasks): @periodic_task.periodic_task def foo(self): return 'foo' @periodic_task.periodic_task(spacing=4) def bar(self): return 'bar' @periodic_task.periodic_task(enabled=False) def baz(self): return 'baz' m = Manager() self.assertThat(m._periodic_tasks, matchers.HasLength(2)) self.assertIsNone(m._periodic_spacing['foo']) self.assertEqual(4, m._periodic_spacing['bar']) self.assertThat(m._periodic_spacing, matchers.Not(matchers.Contains('baz')))
def test_meta(self): class Manager(object): __metaclass__ = manager.ManagerMeta @manager.periodic_task def foo(self): return 'foo' @manager.periodic_task(spacing=4) def bar(self): return 'bar' @manager.periodic_task(enabled=False) def baz(self): return 'baz' m = Manager() self.assertThat(m._periodic_tasks, matchers.HasLength(2)) self.assertEqual(None, m._periodic_spacing['foo']) self.assertEqual(4, m._periodic_spacing['bar']) self.assertThat(m._periodic_spacing, matchers.Not(matchers.Contains('baz')))
def test_empty_account(self): """ this is an account with no containers and no objects """ # setup expectation with SwiftClientStub() as swift_stub: swift_stub.with_account('123223') # interact conn = swiftclient.client.Connection() account_info = conn.get_account() self.assertThat(account_info, matchers.Not(matchers.Is(None))) self.assertThat(len(account_info), matchers.Is(2)) self.assertThat(account_info, matchers.IsInstance(tuple)) self.assertThat(account_info[0], matchers.IsInstance(dict)) self.assertThat( account_info[0], matchers.KeysEqual('content-length', 'accept-ranges', 'x-timestamp', 'x-trans-id', 'date', 'x-account-bytes-used', 'x-account-container-count', 'content-type', 'x-account-object-count')) self.assertThat(account_info[1], matchers.IsInstance(list)) self.assertThat(len(account_info[1]), matchers.Is(0))
def test_run_heat_config(self): self.run_heat_config(self.data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) deployed_file = self.deployed_dir.join('%s.json' % config['id']) if hook == 'no-such-hook': self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) continue self.assertThat(stdin_path, matchers.FileExists()) self.assertThat(stdout_path, matchers.FileExists()) # parsed stdin should match the config item self.assertEqual(config, self.json_from_file(stdin_path)) # parsed stdin should match the written deployed file self.assertEqual(config, self.json_from_file(deployed_file)) self.assertEqual(self.outputs[hook], self.json_from_file(stdout_path)) # clean up files in preperation for second run os.remove(stdin_path) os.remove(stdout_path) # run again with no changes, assert no new files self.run_heat_config(self.data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) # run again changing the puppet config data = copy.deepcopy(self.data) for config in data: if config['id'] == '4444': config['id'] = '44444444' self.run_heat_config(data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) if hook == 'puppet': self.assertThat(stdin_path, matchers.FileExists()) self.assertThat(stdout_path, matchers.FileExists()) else: self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists()))
def test_cut_list_with_large_dict_of_int(self): d = [i for i in range(65535)] s = utils.cut(d, 65535) self.assertThat(len(s), ttm.Not(ttm.GreaterThan(65535)))
def test_cut_dict_with_large_dict_of_str(self): d = {} for i in range(65535): d[str(i)] = str(i) s = utils.cut(d, 65535) self.assertThat(len(s), ttm.Not(ttm.GreaterThan(65535)))
def test_cut_dict_with_large_dict_of_dict(self): d = {} for i in range(65535): d[i] = {'value': str(i)} s = utils.cut(d, 65535) self.assertThat(len(s), ttm.Not(ttm.GreaterThan(65535)))
def test_cut_dict_for_state_info(self): d = {} for i in range(2000): d[i] = {'value': 'This is a string that exceeds 35 characters'} s = utils.cut(d, 65500) self.assertThat(len(s), ttm.Not(ttm.GreaterThan(65500)))
def test_run_heat_config(self): returncode, stdout, stderr = self.run_heat_config(self.data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) deployed_file = self.deployed_dir.join('%s.json' % config['id']) notify_file = self.deployed_dir.join('%s.notify.json' % config['id']) if hook == 'no-such-hook': self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) continue # parsed stdin should match the config item self.assertThat(stdin_path, matchers.FileExists()) self.assertEqual(config, self.json_from_file(stdin_path)) # parsed stdin should match the written deployed file self.assertEqual(config, self.json_from_file(deployed_file)) if hook != 'hook-raises': self.assertEqual(self.outputs[hook], self.json_from_file(notify_file)) self.assertEqual(self.outputs[hook], self.json_from_file(stdout_path)) self.assertThat(stdout_path, matchers.FileExists()) os.remove(stdout_path) else: notify_data = self.json_from_file(notify_file) self.assertEqual( self.outputs[hook]['deploy_status_code'], six.text_type(notify_data['deploy_status_code'])) self.assertIn(self.outputs[hook]['deploy_stderr'], notify_data['deploy_stderr']) # clean up files in preparation for second run os.remove(stdin_path) # run again with no changes, assert no new files self.run_heat_config(self.data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) # run again changing the puppet config data = copy.deepcopy(self.data) for config in data: if config['id'] == '4444': config['id'] = '44444444' self.run_heat_config(data) for config in self.data: hook = config['group'] stdin_path = self.hooks_dir.join('%s.stdin' % hook) stdout_path = self.hooks_dir.join('%s.stdout' % hook) if hook == 'puppet': self.assertThat(stdin_path, matchers.FileExists()) self.assertThat(stdout_path, matchers.FileExists()) else: self.assertThat(stdin_path, matchers.Not(matchers.FileExists())) self.assertThat(stdout_path, matchers.Not(matchers.FileExists())) # run again with a different deployed_dir old_deployed_dir = self.deployed_dir self.env['HEAT_CONFIG_DEPLOYED_OLD'] = old_deployed_dir.join() self.deployed_dir = self.useFixture(fixtures.TempDir()) # make sure the new deployed_dir doesn't exist to trigger the migration shutil.rmtree(self.deployed_dir.join()) self.run_heat_config(data) for config in self.data: hook = config['group'] if hook in ('no-such-hook', 'hook-raises'): continue deployed_file = self.deployed_dir.join('%s.json' % config['id']) old_deployed_file = old_deployed_dir.join('%s.json' % config['id']) self.assertEqual(config, self.json_from_file(deployed_file)) self.assertThat(old_deployed_file, matchers.Not(matchers.FileExists()))