Exemplo n.º 1
0
 def test_install_glob(self):
     stdout, _, _ = self.run_setup('install',
                                   '--root',
                                   self.temp_dir + 'installed',
                                   allow_fail=False)
     self.expectThat(stdout, matchers.Contains('copying data_files/a.txt'))
     self.expectThat(stdout, matchers.Contains('copying data_files/b.txt'))
Exemplo n.º 2
0
    def test_version_data_basics(self):
        examples = {
            'keystone': V3_VERSION_LIST,
            'cinder': CINDER_EXAMPLES,
            'glance': GLANCE_EXAMPLES
        }

        for path, data in examples.items():
            url = "%s%s" % (BASE_URL, path)

            mock = self.requests_mock.get(url, status_code=300, json=data)

            disc = discover.Discover(self.session, url)
            raw_data = disc.raw_version_data()
            clean_data = disc.version_data()

            for v in raw_data:
                for n in ('id', 'status', 'links'):
                    msg = '%s missing from %s version data' % (n, path)
                    self.assertThat(
                        v, matchers.Annotate(msg, matchers.Contains(n)))

            for v in clean_data:
                for n in ('version', 'url', 'raw_status'):
                    msg = '%s missing from %s version data' % (n, path)
                    self.assertThat(
                        v, matchers.Annotate(msg, matchers.Contains(n)))

            self.assertTrue(mock.called_once)
Exemplo n.º 3
0
 def test_body(self):
     data = "BODY DATA"
     self.request(response=data,
                  headers={'Content-Type': 'application/json'})
     logger_message = self.logger_message.getvalue()
     self.assertThat(logger_message, matchers.Contains('BODY:'))
     self.assertThat(logger_message, matchers.Contains(data))
Exemplo n.º 4
0
    def test_logfile_contains_finish(self):
        """Confirm that logger calls in 'finish' phase recorded

        Repository layout being checked

          B---C             local/master
         /
        A---D---E           upstream/master

        """
        tree = [
            ('A', []),
            ('B', ['A']),
            ('C', ['B']),
            ('D', ['A']),
            ('E', ['D']),
        ]

        branches = {
            'head': ('master', 'C'),
            'upstream': ('upstream/master', 'E'),
        }

        self.gittree = base.BuildTree(self.testrepo, tree, branches.values())

        cmdline = self.parser.get_default('script_cmdline')

        tfile = None
        try:
            tfile = tempfile.NamedTemporaryFile(delete=False)
            # need to close to allow reopen to write
            tfile.close()

            cmdline.extend([
                '-v', '--log-file', tfile.name, '--log-level', 'debug',
                'import', '--into', 'master', 'upstream/master'
            ])
            try:
                output = subprocess.check_output(cmdline,
                                                 stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as cpe:
                self.addDetail(
                    'subprocess-output',
                    content.text_content(cpe.output.decode('utf-8')))
                raise
            self.addDetail('subprocess-output',
                           content.text_content(output.decode('utf-8')))

            logfile_contents = open(tfile.name, 'r').read()
        finally:
            if tfile and os.path.exists(tfile.name):
                os.remove(tfile.name)

        self.assertThat(
            logfile_contents,
            matchers.Contains("Merging by inverting the 'ours' strategy"))
        self.assertThat(
            logfile_contents,
            matchers.Contains("Replacing tree contents with those from"))
Exemplo n.º 5
0
 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'))
Exemplo n.º 6
0
    def test_no_required_attributes_present(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/')
        resp = req.get_response(app)

        ex = self.assertRaises(exception.ValidationError,
                               app.assert_attributes, resp.body,
                               ['missing_attribute1', 'missing_attribute2'])
        self.assertThat(ex.message, matchers.Contains('missing_attribute1'))
        self.assertThat(ex.message, matchers.Contains('missing_attribute2'))
Exemplo n.º 7
0
    def test_check_immutable_params_fail(self):
        """Pass invalid parameter to the method and expect failure."""
        ref = dict([(uuid.uuid4().hex, uuid.uuid4().hex) for _ in range(3)])

        ex = self.assertRaises(exception.ImmutableAttributeError,
                               self.api.check_immutable_params, ref)
        ex_msg = six.text_type(ex)
        self.assertThat(ex_msg, matchers.Contains(self.api.__class__.__name__))
        for key in ref.keys():
            self.assertThat(ex_msg, matchers.Contains(key))
Exemplo n.º 8
0
    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')),
            ))
Exemplo n.º 9
0
 def verify_cert_instance(self, cert):
     self.assertIsInstance(cert, _cert.Certificate)
     self.assertEqual("5b8f908b5495452aa13beede0afc5d99", cert.id)
     self.assertEqual("cert-bky", cert.name)
     self.assertEqual("certificate", cert.description)
     self.assertEqual("2016-06-27 08:14:42", cert.create_time)
     self.assertEqual("2016-06-27 08:14:42", cert.update_time)
     self.assertThat(cert.certificate,
                     matchers.Contains("BEGIN CERTIFICATE"))
     self.assertThat(cert.private_key,
                     matchers.Contains("BEGIN RSA PRIVATE KEY"))
Exemplo n.º 10
0
    def test_xdelta3_logs(self):
        self.generate_snap_pair()
        base_delta = deltas.XDelta3Generator(source_path=self.source_file,
                                             target_path=self.target_file)
        base_delta.make_delta(is_for_test=True)

        self.assertThat(
            self.fake_logger.output,
            m.Contains('Generating xdelta3 delta for {}'.format(
                os.path.basename(base_delta.target_path))))
        self.assertThat(self.fake_logger.output,
                        m.Contains('xdelta3 delta diff generation'))
Exemplo n.º 11
0
 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')))
Exemplo n.º 12
0
 def test_logs_warning(self):
     req = webob.Request.blank('/')
     self.middleware(req.environ, self.start_fake_response)
     self.assertEqual(self.response_status, 200)
     log = "Use of the auth_uri option was deprecated in the Queens " \
         "release in favor of www_authenticate_uri."
     self.assertThat(self.logger.output, matchers.Contains(log))
Exemplo n.º 13
0
 def test_get_users(self):
     # Get a list of users and find the test user
     self.data.setup_test_user()
     users = self.client.get_users()
     self.assertThat([u['name'] for u in users],
                     matchers.Contains(self.data.test_user),
                     "Could not find %s" % self.data.test_user)
Exemplo n.º 14
0
    def test_basic_params(self):
        method = 'GET'
        response = 'Test Response'
        status = 200

        self.request(method=method, status=status, response=response)

        self.assertEqual(httpretty.last_request().method, method)

        self.assertThat(self.logger.debug_log, matchers.Contains('curl'))
        self.assertThat(self.logger.debug_log, matchers.Contains('-X %s' %
                                                                 method))
        self.assertThat(self.logger.debug_log, matchers.Contains(self.url))

        self.assertThat(self.logger.debug_log, matchers.Contains(str(status)))
        self.assertThat(self.logger.debug_log, matchers.Contains(response))
Exemplo n.º 15
0
    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'])
Exemplo n.º 16
0
    def test_freeze_smoke(self):
        # Use an arbitrary python, but make sure it has the venv standard lib.
        versions = ['/usr/bin/python3.%(v)s' % dict(v=v) for v in range(5, 10)]
        found = [v for v in versions if os.path.exists(v)]
        found_with_venv = []
        for py in found:
            output = str(
                subprocess.check_output([
                    py, '-c',
                    'import pkgutil; [print(x) for x in pkgutil.iter_modules()]'
                ]))
            # Needs both venv and ensurepip
            if 'venv' in output and 'ensurepip' in output:
                found_with_venv.append(py)

        if len(found_with_venv) == 0:
            self.skipTest('Unable to find python that includes venv module')

        # Grab the latest version available as that is the most likely to
        # break.
        pyversion = found_with_venv[-1]
        req = self.useFixture(fixtures.TempDir()).path + '/r.txt'
        with open(req, 'wt') as output:
            output.write('fixtures==2.0.0')
        frozen = generate._freeze(req, pyversion)
        expected_version = pyversion[-3:]
        self.expectThat(frozen, matchers.HasLength(2))
        self.expectThat(frozen[0], matchers.Equals(expected_version))
        # There are multiple items in the dependency tree of fixtures.
        # Since this is a smoke test, just ensure fixtures is there.
        self.expectThat(frozen[1], matchers.Contains(('fixtures', '2.0.0')))
    def _validate_policygroup(self, topology, pg_name=None):
        if self.is_dhcp_agent_present():
            expected_pgs = 2
        else:
            expected_pgs = 1
        self.assertThat(topology.vsd_policygroups,
                        matchers.HasLength(expected_pgs),
                        message="Unexpected amount of PGs found")
        for vsd_policygroup in topology.vsd_policygroups:
            self.assertThat(vsd_policygroup['type'],
                            matchers.Equals('SOFTWARE'))
            if pg_name:
                self.assertThat(vsd_policygroup['name'],
                                matchers.Contains(pg_name))

            vsd_pg_vports = self.vsd_client.get_vport(constants.POLICYGROUP,
                                                      vsd_policygroup['ID'])
            self.assertThat(vsd_pg_vports,
                            matchers.HasLength(1),
                            message="Expected to find exactly 1 vport in PG")
            if topology.subnet['id'] in vsd_pg_vports[0]['externalID']:
                self.assertThat(vsd_pg_vports[0]['ID'],
                                matchers.Equals(
                                    topology.vsd_switchdev_vport['ID']),
                                message="Vport should be part of PG")
Exemplo n.º 18
0
 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')))
Exemplo n.º 19
0
 def test_get_users(self):
     # Get a list of users and find the test user
     user = self.setup_test_user()
     users = self.users_client.list_users()['users']
     self.assertThat([u['name'] for u in users],
                     matchers.Contains(user['name']),
                     "Could not find %s" % user['name'])
Exemplo n.º 20
0
    def test_get_localized_response(self):
        # If the request has the Accept-Language set to a supported language
        # and an exception is raised by the application that is translatable
        # then the response will have the translated message.

        language = uuid.uuid4().hex

        self._set_expected_languages(all_locales=[language])

        # The arguments for the xlated message format have to match the args
        # for the chosen exception (exception.NotFound)
        xlated_msg_fmt = "Xlated NotFound, %(target)s."

        # Fake out gettext.translation() to return a translator for our
        # expected language and a passthrough translator for other langs.

        def fake_translation(*args, **kwargs):
            class IdentityTranslator(object):
                def ugettext(self, msgid):
                    return msgid

                gettext = ugettext

            class LangTranslator(object):
                def ugettext(self, msgid):
                    if msgid == exception.NotFound.message_format:
                        return xlated_msg_fmt
                    return msgid

                gettext = ugettext

            if language in kwargs.get('languages', []):
                return LangTranslator()
            return IdentityTranslator()

        with mock.patch.object(gettext,
                               'translation',
                               side_effect=fake_translation) as xlation_mock:
            target = uuid.uuid4().hex

            # Fake app raises NotFound exception to simulate Keystone raising.

            class FakeApp(wsgi.Application):
                def index(self, context):
                    raise exception.NotFound(target=target)

            # Make the request with Accept-Language on the app, expect an error
            # response with the translated message.

            req = webob.Request.blank('/')
            args = {'action': 'index', 'controller': None}
            req.environ['wsgiorg.routing_args'] = [None, args]
            req.headers['Accept-Language'] = language
            resp = req.get_response(FakeApp())

            # Assert that the translated message appears in the response.

            exp_msg = xlated_msg_fmt % dict(target=target)
            self.assertThat(resp.body, matchers.Contains(exp_msg))
            self.assertThat(xlation_mock.called, matchers.Equals(True))
Exemplo n.º 21
0
    def test_raises_AssertionError_when_test_passes(self):

        @utils.wip('waiting on bug #000000')
        def test():
            pass  # literally

        e = self.assertRaises(AssertionError, test)
        self.assertThat(str(e), matchers.Contains('#000000'))
Exemplo n.º 22
0
    def test_basic_params(self):
        method = 'GET'
        response = 'Test Response'
        status = 200

        self.request(method=method, status_code=status, response=response)

        self.assertEqual(self.requests.last_request.method, method)

        logger_message = self.logger_message.getvalue()

        self.assertThat(logger_message, matchers.Contains('curl'))
        self.assertThat(logger_message, matchers.Contains('-X %s' % method))
        self.assertThat(logger_message, matchers.Contains(self.url))

        self.assertThat(logger_message, matchers.Contains(str(status)))
        self.assertThat(logger_message, matchers.Contains(response))
Exemplo n.º 23
0
 def test_attribute_missing_from_request(self):
     app = FakeAttributeCheckerApp()
     req = self._make_request(url='/?a=1&b=2')
     resp = req.get_response(app)
     ex = self.assertRaises(exception.ValidationError,
                            app.assert_attributes, resp.body,
                            ['a', 'missing_attribute'])
     self.assertThat(ex.message, matchers.Contains('missing_attribute'))
Exemplo n.º 24
0
    def test_raises_SkipError_when_broken_test_fails(self):

        @utils.wip('waiting on bug #000000')
        def test():
            raise Exception('i expected a failure - this is a WIP')

        e = self.assertRaises(testcase.TestSkipped, test)
        self.assertThat(str(e), matchers.Contains('#000000'))
Exemplo n.º 25
0
    def test_discover_forwards_original_ip(self):
        self.requests_mock.get(BASE_URL, status_code=300, text=V3_VERSION_LIST)

        ip = '192.168.1.1'
        self.assertCreatesV3(auth_url=BASE_URL, original_ip=ip)

        self.assertThat(self.requests_mock.last_request.headers['forwarded'],
                        matchers.Contains(ip))
Exemplo n.º 26
0
    def test_finder_ignores_files(self, mock_walk):
        mock_walk.return_value = [
            ['.', [], ['file.txt', 'keystone.conf', 'keystone.domain0.conf']],
        ]

        domain_configs = list(cli._domain_config_finder('.'))

        expected_domain_configs = [('./keystone.domain0.conf', 'domain0')]
        self.assertThat(domain_configs,
                        matchers.Equals(expected_domain_configs))

        expected_msg_template = ('Ignoring file (%s) while scanning '
                                 'domain config directory')
        self.assertThat(self.logging.output,
                        matchers.Contains(expected_msg_template % 'file.txt'))
        self.assertThat(
            self.logging.output,
            matchers.Contains(expected_msg_template % 'keystone.conf'))
    def test_discover_forwards_original_ip(self):
        httpretty.register_uri(httpretty.GET, BASE_URL, status=300,
                               body=V3_VERSION_LIST)

        ip = '192.168.1.1'
        self.assertCreatesV3(auth_url=BASE_URL, original_ip=ip)

        self.assertThat(httpretty.last_request().headers['forwarded'],
                        matchers.Contains(ip))
Exemplo n.º 28
0
    def test_uploading_all_from_an_empty_directory(self):
        CONF(args=['domain_config_upload', '--all'],
             project='keystone',
             default_config_files=[])
        cli.DomainConfigUpload.main()

        expected_msg = ('No domain configs uploaded from %r' %
                        CONF.identity.domain_config_dir)
        self.assertThat(self.logging.output, matchers.Contains(expected_msg))
Exemplo n.º 29
0
 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:])
Exemplo n.º 30
0
    def test_basic_params(self):
        method = 'GET'
        response = 'Test Response'
        status = 200

        self.request(method=method, status_code=status, response=response,
                     headers={'Content-Type': 'application/json'})

        self.assertEqual(self.requests_mock.last_request.method, method)

        logger_message = self.logger_message.getvalue()

        self.assertThat(logger_message, matchers.Contains('curl'))
        self.assertThat(logger_message, matchers.Contains('-X %s' %
                                                          method))
        self.assertThat(logger_message, matchers.Contains(self.url))

        self.assertThat(logger_message, matchers.Contains(str(status)))
        self.assertThat(logger_message, matchers.Contains(response))