Beispiel #1
0
 def test_one_container(self):
     """
     tests to ensure behavior is normal with one container
     """
     # setup expectation
     swift_stub = SwiftClientStub()
     swift_stub.with_account('123223')
     cont_name = 'a-container-name'
     swift_stub.with_container(cont_name)
     # interact
     conn = swiftclient.client.Connection()
     conn.get_auth()
     conn.put_container(cont_name)
     # get headers plus container metadata
     self.assertThat(len(conn.get_account()), matchers.Is(2))
     # verify container details
     account_containers = conn.get_account()[1]
     self.assertThat(len(account_containers), matchers.Is(1))
     self.assertThat(account_containers[0],
                     matchers.KeysEqual('count', 'bytes', 'name'))
     self.assertThat(account_containers[0]['name'], matchers.Is(cont_name))
     # get container details
     cont_info = conn.get_container(cont_name)
     self.assertIsNotNone(cont_info)
     self.assertThat(cont_info[0], matchers.KeysEqual('content-length',
                     'x-container-object-count', 'accept-ranges',
                     'x-container-bytes-used', 'x-timestamp',
                     'x-trans-id', 'date', 'content-type'))
     self.assertThat(len(cont_info[1]), matchers.Equals(0))
     # remove container
     swift_stub.without_container(cont_name)
     with testtools.ExpectedException(swiftclient.ClientException):
         conn.get_container(cont_name)
         # ensure there are no more containers in account
     self.assertThat(len(conn.get_account()[1]), matchers.Is(0))
Beispiel #2
0
 def test_non_verbose(self):
     stdout = io.StringIO()
     root = self.useFixture(fixtures.TempDir()).path
     proj = {'root': root}
     actions = [project.Verbose(u'fred')]
     project.write(proj, actions, stdout, False)
     self.expectThat(stdout.getvalue(), matchers.Equals(''))
Beispiel #3
0
    def match(self, actual):
        response_data = actual.json

        if u"links" in response_data:
            del response_data[u"links"]

        return matchers.Equals(self.expected_data).match(response_data)
Beispiel #4
0
 def test_prepare_request_body(self):
     body = {
         'fake': {
             'name': 'terminator',
             'model': 'T-800',
         }
     }
     params = [
         {
             'param-name': 'name',
             'required': True
         },
         {
             'param-name': 'model',
             'required': True
         },
         {
             'param-name': 'quote',
             'required': False,
             'default-value': "i'll be back"
         },
     ]
     expect = {
         'fake': {
             'name': 'terminator',
             'model': 'T-800',
             'quote': "i'll be back",
         }
     }
     actual = self.controller._prepare_request_body(body, params)
     self.assertThat(expect, matchers.Equals(actual))
Beispiel #5
0
    def test_translate_urls(self):
        href_rel = self.getUniqueString()
        href = self.getUniqueString()
        href_template_rel = self.getUniqueString()
        href_template = self.getUniqueString()
        href_vars = {self.getUniqueString(): self.getUniqueString()}
        original_json_home = {
            'resources': {
                href_rel: {
                    'href': href
                },
                href_template_rel: {
                    'href-template': href_template,
                    'href-vars': href_vars
                }
            }
        }

        new_json_home = copy.deepcopy(original_json_home)
        new_prefix = self.getUniqueString()
        json_home.translate_urls(new_json_home, new_prefix)

        exp_json_home = {
            'resources': {
                href_rel: {
                    'href': new_prefix + href
                },
                href_template_rel: {
                    'href-template': new_prefix + href_template,
                    'href-vars': href_vars
                }
            }
        }

        self.assertThat(new_json_home, matchers.Equals(exp_json_home))
Beispiel #6
0
 def test_list_projects_search_compat_v3(self):
     project_data = self._get_project_data(
         description=self.getUniqueString('projectDesc'))
     self.register_uris([
         dict(method='GET',
              uri=self.get_mock_url(resource=('projects?domain_id=%s' %
                                              project_data.domain_id)),
              status_code=200,
              json={'projects': [project_data.json_response['project']]})
     ])
     projects = self.op_cloud.search_projects(
         domain_id=project_data.domain_id)
     self.assertThat(len(projects), matchers.Equals(1))
     self.assertThat(projects[0].id,
                     matchers.Equals(project_data.project_id))
     self.assert_calls()
    def test_suffix(self, mock_isdir):
        def check_params(root, source, suffix, softupdate, hacking, stdout,
                         verbose, non_std_reqs):
            self.expectThat(suffix, matchers.Equals('global'))

        update.main(['-o', 'global', '/dev/zero'], _worker=check_params)
        self.expectThat(mock_isdir.called, matchers.Equals(True))
 def test_build_v3_parameter_relation(self):
     parameter_name = self.getUniqueString()
     relation = json_home.build_v3_parameter_relation(parameter_name)
     exp_relation = (
         'http://docs.openstack.org/api/openstack-identity/3/param/%s' %
         parameter_name)
     self.assertThat(relation, matchers.Equals(exp_relation))
Beispiel #9
0
    def test_json_home_v3(self):
        # If the request is /v3 and the Accept header is application/json-home
        # then the server responds with a JSON Home document.

        client = self.client(self.public_app)
        resp = client.get('/v3/', headers={'Accept': 'application/json-home'})

        self.assertThat(resp.status, tt_matchers.Equals('200 OK'))
        self.assertThat(resp.headers['Content-Type'],
                        tt_matchers.Equals('application/json-home'))

        exp_json_home_data = {
            'resources': V3_JSON_HOME_RESOURCES_INHERIT_ENABLED}

        self.assertThat(jsonutils.loads(resp.body),
                        tt_matchers.Equals(exp_json_home_data))
Beispiel #10
0
    def test_create_client_removes_url_path_if_version_specified(self):
        # If specifying a version on the client creation call, ensure
        # the auth_url is versionless and the version required is passed
        # into the Client() call.
        self.set_up_keystone_mocks()
        auth_kwargs, all_kwargs = self.make_auth_args()
        credential = objects.Credential("http://auth_url/v2.0", "user", "pass",
                                        "tenant")
        keystone = osclients.Keystone(credential, {}, mock.MagicMock())
        client = keystone.create_client(version="3")

        self.assertIs(client, self.ksc_client.Client())
        called_with = self.ksc_client.Client.call_args_list[0][1]
        self.expectThat(called_with["auth_url"],
                        matchers.Equals("http://auth_url/"))
        self.expectThat(called_with["version"], matchers.Equals("3"))
Beispiel #11
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))
Beispiel #12
0
 def test_ordering(self):
     ordered_versions = [
         "1.2.3.dev6",
         "1.2.3.dev7",
         "1.2.3.a4.dev12",
         "1.2.3.a4.dev13",
         "1.2.3.a4",
         "1.2.3.a5.dev1",
         "1.2.3.a5",
         "1.2.3.b3.dev1",
         "1.2.3.b3",
         "1.2.3.rc2.dev1",
         "1.2.3.rc2",
         "1.2.3.rc3.dev1",
         "1.2.3",
         "1.2.4",
         "1.3.3",
         "2.2.3",
     ]
     for v in ordered_versions:
         sv = version.SemanticVersion.from_pip_string(v)
         self.expectThat(sv, matchers.Equals(sv))
     for left, right in itertools.combinations(ordered_versions, 2):
         l_pos = ordered_versions.index(left)
         r_pos = ordered_versions.index(right)
         if l_pos < r_pos:
             m1 = matchers.LessThan
             m2 = matchers.GreaterThan
         else:
             m1 = matchers.GreaterThan
             m2 = matchers.LessThan
         left_sv = version.SemanticVersion.from_pip_string(left)
         right_sv = version.SemanticVersion.from_pip_string(right)
         self.expectThat(left_sv, m1(right_sv))
         self.expectThat(right_sv, m2(left_sv))
Beispiel #13
0
    def test_find_unique_file_name(self):
        tmp_delta = deltas.BaseDeltasGenerator(
            source_path=self.source_file,
            target_path=self.target_file,
            delta_format='xdelta3',
            delta_tool_path=self.delta_tool_path)

        unique_file_name = tmp_delta.find_unique_file_name(
            tmp_delta.source_path)
        self.assertThat(unique_file_name,
                        m.Equals(tmp_delta.source_path + '-0'))
        with open(unique_file_name, 'wb') as f:
            f.write(b'tmp file.')

        self.assertThat(tmp_delta.find_unique_file_name(tmp_delta.source_path),
                        m.Equals(tmp_delta.source_path + '-1'))
Beispiel #14
0
 def test_set_and_get_queue_metadata(self):
     # Retrieve random queue
     queue_name = self.queues[data_utils.rand_int_id(
         0,
         len(self.queues) - 1)]
     # Check the Queue has no metadata
     resp, body = self.get_queue_metadata(queue_name)
     self.assertEqual('200', resp['status'])
     self.assertThat(body, matchers.HasLength(0))
     # Create metadata
     key3 = [0, 1, 2, 3, 4]
     key2 = data_utils.rand_name('value')
     req_body1 = dict()
     req_body1[data_utils.rand_name('key3')] = key3
     req_body1[data_utils.rand_name('key2')] = key2
     req_body = dict()
     req_body[data_utils.rand_name('key1')] = req_body1
     # Set Queue Metadata
     resp, body = self.set_queue_metadata(queue_name, req_body)
     self.assertEqual('204', resp['status'])
     self.assertEqual('', body)
     # Get Queue Metadata
     resp, body = self.get_queue_metadata(queue_name)
     self.assertEqual('200', resp['status'])
     self.assertThat(body, matchers.Equals(req_body))
    def test_create_role(self):
        role_data = self._get_role_data()
        self.register_uris([
            dict(method='POST',
                 uri=self.get_mock_url(),
                 status_code=200,
                 json=role_data.json_response,
                 validate=dict(json=role_data.json_request))
        ])

        role = self.cloud.create_role(role_data.role_name)

        self.assertIsNotNone(role)
        self.assertThat(role.name, matchers.Equals(role_data.role_name))
        self.assertThat(role.id, matchers.Equals(role_data.role_id))
        self.assert_calls()
 def test_build_v3_resource_relation(self):
     resource_name = self.getUniqueString()
     relation = json_home.build_v3_resource_relation(resource_name)
     exp_relation = (
         'http://docs.openstack.org/api/openstack-identity/3/rel/%s' %
         resource_name)
     self.assertThat(relation, matchers.Equals(exp_relation))
Beispiel #17
0
 def test_stdout(self):
     stdout = io.StringIO()
     root = self.useFixture(fixtures.TempDir()).path
     proj = {'root': root}
     actions = [project.StdOut(u'fred\n')]
     project.write(proj, actions, stdout, True)
     self.expectThat(stdout.getvalue(), matchers.Equals('fred\n'))
Beispiel #18
0
    def test_json_examples_have_matching_entries(self):
        # TODO(lbragstad): Once all policies have been removed from
        # policy.v3cloudsample.json, remove this test.
        removed_policies = [
            'identity:create_credential', 'identity:get_credential',
            'identity:list_credentials', 'identity:update_credential',
            'identity:delete_credential', 'identity:create_registered_limits',
            'identity:get_registered_limit', 'identity:list_registered_limits',
            'identity:update_registered_limit',
            'identity:delete_registered_limit'
        ]
        policy_keys = self._get_default_policy_rules()
        for p in removed_policies:
            del policy_keys[p]
        cloud_policy_keys = set(
            json.load(open(unit.dirs.etc('policy.v3cloudsample.json'))))

        policy_extra_keys = [
            'admin_or_token_subject',
            'service_admin_or_token_subject',
            'token_subject',
        ]
        expected_policy_keys = list(cloud_policy_keys) + policy_extra_keys
        diffs = set(policy_keys).difference(set(expected_policy_keys))

        self.assertThat(diffs, matchers.Equals(set()))
Beispiel #19
0
    def test_two_objects(self):
        with SwiftClientStub() as swift_stub:
            swift_stub.with_account('123223')
            swift_stub.with_container('bob')
            swift_stub.with_container('bob2')
            swift_stub.with_object('bob', 'test', 'test_contents')
            swift_stub.with_object('bob', 'test2', 'test_contents2')

            conn = swiftclient.client.Connection()

            self.assertIs(len(conn.get_account()), 2)
            cont_info = conn.get_container('bob')
            self.assertIsNotNone(cont_info)
            self.assertThat(
                cont_info[0],
                matchers.KeysEqual('content-length',
                                   'x-container-object-count', 'accept-ranges',
                                   'x-container-bytes-used', 'x-timestamp',
                                   'x-trans-id', 'date', 'content-type'))
            self.assertThat(len(cont_info[1]), matchers.Equals(2))
            self.assertThat(
                cont_info[1][0],
                matchers.Equals({
                    'bytes': 13,
                    'last_modified': '2013-03-15T22:10:49.361950',
                    'hash': 'ccc55aefbf92aa66f42b638802c5e7f6',
                    'name': 'test',
                    'content_type': 'application/octet-stream',
                    'contents': 'test_contents'
                }))
            self.assertThat(
                conn.get_object('bob', 'test')[1],
                matchers.Is('test_contents'))
            self.assertThat(
                conn.get_object('bob', 'test2')[1],
                matchers.Is('test_contents2'))

            swift_stub.without_object('bob', 'test')
            with ExpectedException(swiftclient.ClientException):
                conn.delete_object('bob', 'test')
            self.assertThat(len(conn.get_container('bob')[1]), matchers.Is(1))

            swift_stub.without_container('bob')
            with ExpectedException(swiftclient.ClientException):
                conn.get_container('bob')

            self.assertThat(len(conn.get_account()), matchers.Is(2))
Beispiel #20
0
 def test_list_services(self):
     service_data = self._get_service_data()
     self.register_uris([
         dict(method='GET',
              uri=self.get_mock_url(),
              status_code=200,
              json={'services': [service_data.json_response_v3['service']]})
     ])
     services = self.cloud.list_services()
     self.assertThat(len(services), matchers.Equals(1))
     self.assertThat(services[0].id,
                     matchers.Equals(service_data.service_id))
     self.assertThat(services[0].name,
                     matchers.Equals(service_data.service_name))
     self.assertThat(services[0].type,
                     matchers.Equals(service_data.service_type))
     self.assert_calls()
Beispiel #21
0
    def test_json_examples_have_matching_entries(self):
        policy_keys = self._load_entries(tests.dirs.etc('policy.json'))
        cloud_policy_keys = self._load_entries(
            tests.dirs.etc('policy.v3cloudsample.json'))

        diffs = set(policy_keys).difference(set(cloud_policy_keys))

        self.assertThat(diffs, matchers.Equals(set()))
Beispiel #22
0
 def test_cms_hash_token_default_md5(self):
     """The default hash method is md5."""
     token = self.examples.SIGNED_TOKEN_SCOPED
     token_id_default = cms.cms_hash_token(token)
     token_id_md5 = cms.cms_hash_token(token, mode='md5')
     self.assertThat(token_id_default, matchers.Equals(token_id_md5))
     # md5 hash is 32 chars.
     self.assertThat(token_id_default, matchers.HasLength(32))
Beispiel #23
0
 def make_request(accept_types=None):
     client = TestClient(self.public_app)
     headers = None
     if accept_types:
         headers = {'Accept': accept_types}
     resp = client.get('/v3', headers=headers)
     self.assertThat(resp.status, tt_matchers.Equals('200 OK'))
     return resp.headers['Content-Type']
Beispiel #24
0
 def test_create_domain(self):
     domain_data = self._get_domain_data(description=uuid.uuid4().hex,
                                         enabled=True)
     self.register_uris([
         dict(method='POST',
              uri=self.get_mock_url(),
              status_code=200,
              json=domain_data.json_response,
              validate=dict(json=domain_data.json_request))
     ])
     domain = self.cloud.create_domain(domain_data.domain_name,
                                       domain_data.description)
     self.assertThat(domain.id, matchers.Equals(domain_data.domain_id))
     self.assertThat(domain.name, matchers.Equals(domain_data.domain_name))
     self.assertThat(domain.description,
                     matchers.Equals(domain_data.description))
     self.assert_calls()
Beispiel #25
0
 def test_create_project_v2(self):
     self.use_keystone_v2()
     project_data = self._get_project_data(v3=False)
     self.register_uris([
         dict(method='POST',
              uri=self.get_mock_url(v3=False),
              status_code=200,
              json=project_data.json_response,
              validate=dict(json=project_data.json_request))
     ])
     project = self.op_cloud.create_project(
         name=project_data.project_name,
         description=project_data.description)
     self.assertThat(project.id, matchers.Equals(project_data.project_id))
     self.assertThat(project.name,
                     matchers.Equals(project_data.project_name))
     self.assert_calls()
Beispiel #26
0
 def test_parse_single_host_new_format(self):
     """Test parse_host_config with single host new format """
     hosts = '192.168.1.10:1234'
     ret = self.parse_config_test_run(hosts, OVERRIDE_PORT)
     self.assertIsInstance(ret, tuple)
     self.assertThat(ret, matchers.Equals(
         (('192.168.1.10', 1234),)
     ))
Beispiel #27
0
 def test_errors(self):
     stdout = io.StringIO()
     root = self.useFixture(fixtures.TempDir()).path
     proj = {'root': root}
     actions = [project.Error(u'fred')]
     with testtools.ExpectedException(Exception):
         project.write(proj, actions, stdout, True)
     self.expectThat(stdout.getvalue(), matchers.Equals('fred\n'))
Beispiel #28
0
    def test_logging_options_kept(self):

        argv = ["-v", "--log-level", "debug", "import"]
        with mock.patch(
                'git_upstream.commands.GitUpstreamCommand.run') as mock_import:
            main.main(argv)
            self.assertThat(mock_import.call_args[0][0].script_cmdline[2:],
                            matchers.Equals(argv[:3]))
Beispiel #29
0
    def test_use_auto_detect_cores(self, mockCpu_count):
        @concurrent
        def parallel_test():
            return True

        result = parallel_test(concurrent=[{} for _ in range(10)], n_workers=0)
        self.assertThat(result, matchers.Equals([True for _ in range(10)]))
        mockCpu_count.assert_called_once_with()
 def test_update_domain(self):
     domain_data = self._get_domain_data(
         description=self.getUniqueString('domainDesc'))
     domain_resource_uri = self.get_mock_url(append=[domain_data.domain_id])
     self.register_uris([
         dict(method='PATCH', uri=domain_resource_uri, status_code=200,
              json=domain_data.json_response,
              validate=dict(json=domain_data.json_request))])
     domain = self.cloud.update_domain(
         domain_data.domain_id,
         name=domain_data.domain_name,
         description=domain_data.description)
     self.assertThat(domain.id, matchers.Equals(domain_data.domain_id))
     self.assertThat(domain.name, matchers.Equals(domain_data.domain_name))
     self.assertThat(
         domain.description, matchers.Equals(domain_data.description))
     self.assert_calls()