コード例 #1
0
 def test_simple_response(self):
     content_json = b'"this is content"'
     content_str = "this is content"
     response = HttpResponse(status_code=http_client.OK,
                             headers={},
                             content=content_json)
     assert content_str == response.json()
コード例 #2
0
    def test_retry_update_attributes(self, openshift, status_codes,
                                     should_raise, update_or_set, attr_type,
                                     object_type):
        try:
            fn = getattr(
                openshift,
                "{update}_{attr}_on_{object}".format(update=update_or_set,
                                                     attr=attr_type,
                                                     object=object_type))
        except AttributeError:
            return  # not every combination is implemented

        get_expectation = (flexmock(openshift).should_receive('_get').times(
            len(status_codes)))
        put_expectation = (flexmock(openshift).should_receive('_put').times(
            len(status_codes)))
        for status_code in status_codes:
            get_response = HttpResponse(httplib.OK,
                                        headers={},
                                        content='{"metadata": {}}')
            put_response = HttpResponse(status_code, headers={}, content='')
            get_expectation = get_expectation.and_return(get_response)
            put_expectation = put_expectation.and_return(put_response)

        (flexmock(time).should_receive('sleep').with_args(0.5))

        args = ('any-object-id', {'key': 'value'})
        if should_raise:
            with pytest.raises(OsbsResponseException):
                fn(*args)
        else:
            fn(*args)
コード例 #3
0
 def test_bad_coding_guess(self):
     bad_json = b'[\"cat\", \"dog\"][\"cat\", \"dog\"]'
     response = HttpResponse(status_code=http_client.OK,
                             headers={},
                             content=bad_json)
     with pytest.raises(OsbsResponseException) as exc_info:
         response.json()
     assert 'HtttpResponse has corrupt json' in exc_info.value.message
コード例 #4
0
    def test_retry_ensure_image_stream_tag(self, openshift,
                                           status_codes, should_raise):
        get_expectation = (flexmock(openshift)
                           .should_receive('_get')
                           .times(len(status_codes)))
        put_expectation = (flexmock(openshift)
                           .should_receive('_put')
                           .times(len(status_codes)))
        for status_code in status_codes:
            get_response = HttpResponse(http_client.NOT_FOUND,
                                        headers={},
                                        content=b'')
            put_response = HttpResponse(status_code,
                                        headers={},
                                        content=b'')
            get_expectation = get_expectation.and_return(get_response)
            put_expectation = put_expectation.and_return(put_response)

        (flexmock(time)
            .should_receive('sleep')
            .and_return(None))

        fn = openshift.ensure_image_stream_tag
        args = (
            {
                'kind': 'ImageStream',
                'metadata': {
                    'name': 'imagestream',
                },
                'spec': {
                    'dockerImageRepository': 'registry.example.com/repo',
                },
            },
            'tag',
            {
                'kind': 'ImageStreamTag',
                'metadata': {
                    'name': 'imagestream:tag',
                },
                'tag': {
                    'name': 'tag',
                    'from': {
                        'kind': 'DockerImage',
                        'name': 'registry.example.com/repo:tag',
                    },
                    'importPolicy': {},
                },
            })

        if should_raise:
            with pytest.raises(OsbsResponseException):
                fn(*args)
        else:
            fn(*args)
コード例 #5
0
 def test_get_missing_build_config(self, openshift):  # noqa
     build_config_name = 'some-build-config-name'
     expected_url = openshift._build_url(
         "build.openshift.io/v1", "buildconfigs/%s/" % build_config_name)
     (flexmock(openshift).should_receive("_get").with_args(
         expected_url).once().and_return(HttpResponse(404, {}, b'')))
     with pytest.raises(OsbsResponseException):
         openshift.get_build_config(build_config_name)
コード例 #6
0
 def test_get_build_config(self, openshift):
     mock_response = {"spam": "maps"}
     build_config_name = 'some-build-config-name'
     expected_url = openshift._build_url("buildconfigs/%s/" %
                                         build_config_name)
     (flexmock(openshift).should_receive("_get").with_args(
         expected_url).once().and_return(
             HttpResponse(200, {}, json.dumps(mock_response))))
     response = openshift.get_build_config(build_config_name)
     assert response['spam'] == 'maps'
コード例 #7
0
    def test_import_image_retry(self, openshift, image_status, expect_retry):
        imagestream_name = TEST_IMAGESTREAM

        # Load example API response
        this_file = inspect.getfile(TestCheckResponse)
        this_dir = os.path.dirname(this_file)
        json_path = os.path.join(this_dir, "mock_jsons",
                                 openshift._con.version,
                                 'imagestreamimport.json')
        with open(json_path) as f:
            content_json = json.load(f)

        # Assume mocked data contains a good response
        good_resp = HttpResponse(
            200, {}, content=json.dumps(content_json).encode('utf-8'))

        # Create a bad response by marking the first image as failed
        for key in ('status', 'code', 'reason'):
            content_json['status']['images'][0]['status'][key] = image_status[
                key]
        bad_resp = HttpResponse(
            200, {}, content=json.dumps(content_json).encode('utf-8'))

        # Make time go faster
        flexmock(time).should_receive('sleep')

        stream_import = {'metadata': {'name': 'FOO'}, 'spec': {'images': []}}
        tags = ['7.2.username-66', '7.2.username-67']

        if expect_retry:
            (flexmock(openshift).should_receive('_post').times(3).and_return(
                bad_resp).and_return(bad_resp).and_return(good_resp))
            assert openshift.import_image(
                imagestream_name, stream_import, tags=tags) is True
        else:
            (flexmock(openshift).should_receive('_post').once().and_return(
                bad_resp))
            with pytest.raises(ImportImageFailed):
                openshift.import_image(imagestream_name,
                                       stream_import,
                                       tags=tags)
コード例 #8
0
 def test_get_build_config_by_labels(self, openshift):
     mock_response = {"items": [{"spam": "maps"}]}
     build_config_name = 'some-build-config-name'
     label_selectors = (
         ('label-1', 'value-1'),
         ('label-2', 'value-2'),
     )
     expected_url = openshift._build_url(
         "buildconfigs/?labelSelector=label-1%3Dvalue-1%2Clabel-2%3Dvalue-2"
     )
     (flexmock(openshift).should_receive("_get").with_args(
         expected_url).once().and_return(
             HttpResponse(200, {}, json.dumps(mock_response))))
     response = openshift.get_build_config_by_labels(label_selectors)
     assert response['spam'] == 'maps'
コード例 #9
0
        def verify_image_stream_tag(*args, **kwargs):
            data = json.loads(kwargs['data'])

            assert (bool(data['tag']['importPolicy'].get('insecure')) ==
                    expected_insecure)
            assert (bool(data['tag']['importPolicy'].get('scheduled')) ==
                    expected_scheduled)

            # Also verify new image stream tags are created properly.
            if status_code == 404:
                assert data['metadata']['name'] == tag_id
                assert data['tag']['name'] == tag_name
                assert (data['tag']['from']['name'] == '{0}:{1}'.format(
                    stream_repo, tag_name))

            return HttpResponse(200, {}, json.dumps('{}'))
コード例 #10
0
    def test_get_multiple_build_config_by_labels(self, openshift):
        mock_response = {"items": [{"spam": "maps"}, {"eggs": "sgge"}]}
        build_config_name = 'some-build-config-name'
        label_selectors = (
            ('label-1', 'value-1'),
            ('label-2', 'value-2'),
        )
        expected_url = openshift._build_url(
            "buildconfigs/?labelSelector=label-1%3Dvalue-1%2Clabel-2%3Dvalue-2"
        )
        (flexmock(openshift).should_receive("_get").with_args(
            expected_url).once().and_return(
                HttpResponse(200, {}, json.dumps(mock_response))))

        with pytest.raises(OsbsException) as exc:
            openshift.get_build_config_by_labels(label_selectors)
        assert str(exc.value).startswith('More than one build config found')
コード例 #11
0
    def test_put_image_stream_tag(self, openshift):
        tag_name = 'spam'
        tag_id = 'maps:' + tag_name
        mock_data = {
            'kind': 'ImageStreamTag',
            'apiVersion': 'v1',
            'tag': {
                'name': tag_name
            }
        }

        expected_url = openshift._build_url('imagestreamtags/' + tag_id)
        (flexmock(openshift).should_receive("_put").with_args(
            expected_url,
            data=json.dumps(mock_data),
            headers={
                "Content-Type": "application/json"
            }).once().and_return(HttpResponse(200, {}, json.dumps(mock_data))))

        openshift.put_image_stream_tag(tag_id, mock_data)
コード例 #12
0
    def test_import_image_tags(self, openshift, tags, imagestream_name,
                               expect_update, insecure, remove_tags):
        """
        tests that import_image return True
        regardless if tags were changed
        """
        this_file = inspect.getfile(TestCheckResponse)
        this_dir = os.path.dirname(this_file)

        json_path = os.path.join(this_dir, "mock_jsons",
                                 openshift._con.version, 'imagestream.json')
        with open(json_path) as f:
            template_resource_json = json.load(f)

        modified_resource_json = deepcopy(template_resource_json)
        for annotation in ANNOTATION_SOURCE_REPO, ANNOTATION_INSECURE_REPO:
            modified_resource_json['metadata']['annotations'].pop(
                annotation, None)

        source_repo = None
        if modified_resource_json['spec'].get('dockerImageRepository'):
            source_repo = modified_resource_json['spec'].pop(
                'dockerImageRepository')
        else:
            source_repo = modified_resource_json['status'].get(
                'dockerImageRepository')
            modified_resource_json['spec'][
                'dockerImageRepository'] = source_repo
        if modified_resource_json['metadata']['annotations'].get(
                ANNOTATION_SOURCE_REPO):
            modified_resource_json['metadata']['annotations'][
                ANNOTATION_SOURCE_REPO] = source_repo

        if remove_tags:
            modified_resource_json['spec']['tags'] = []
        expect_import = False
        if tags:
            expect_import = True

        stream_import = {'metadata': {'name': 'FOO'}, 'spec': {'images': []}}
        stream_import_json = deepcopy(stream_import)
        stream_import_json['metadata']['name'] = imagestream_name

        if tags:
            for tag in set(tags):
                image_import = {
                    'from': {
                        "kind": "DockerImage",
                        "name": '{}:{}'.format(source_repo, tag)
                    },
                    'to': {
                        'name': tag
                    },
                    'importPolicy': {
                        'insecure': insecure
                    },
                }
                stream_import_json['spec']['images'].append(image_import)

        put_url = openshift._build_url("image.openshift.io/v1",
                                       "imagestreams/%s" % imagestream_name)
        (flexmock(openshift).should_call('_put').times(
            1 if expect_update else 0).with_args(
                put_url,
                data=JsonMatcher(modified_resource_json),
                use_json=True))

        # Load example API response
        this_file = inspect.getfile(TestCheckResponse)
        this_dir = os.path.dirname(this_file)
        json_path = os.path.join(this_dir, "mock_jsons",
                                 openshift._con.version,
                                 'imagestreamimport.json')
        with open(json_path) as f:
            content_json = json.load(f)
        good_resp = HttpResponse(
            200, {}, content=json.dumps(content_json).encode('utf-8'))
        image_status = {'status': 'Failure', 'code': 504, 'reason': 'TimeOut'}
        # Create a bad response by marking the first image as failed
        for key in ('status', 'code', 'reason'):
            content_json['status']['images'][0]['status'][key] = image_status[
                key]
        bad_resp = HttpResponse(
            504, {}, content=json.dumps(content_json).encode('utf-8'))

        post_url = openshift._build_url("image.openshift.io/v1",
                                        "imagestreamimports/")
        if expect_import:
            (flexmock(openshift).should_receive('_post').times(2).with_args(
                post_url, data=JsonMatcher(stream_import_json),
                use_json=True).and_return(bad_resp).and_return(good_resp))
        else:
            (flexmock(openshift).should_call('_post').times(0).with_args(
                post_url, data=JsonMatcher(stream_import_json), use_json=True))

        assert openshift.import_image_tags(imagestream_name, stream_import,
                                           tags, source_repo,
                                           insecure) is expect_import
コード例 #13
0
    def test_ensure_image_stream_tag(self, existing_scheduled,
                                     existing_insecure, expected_scheduled,
                                     s_annotations, status_code, repository,
                                     insecure, openshift):
        stream_name = 'spam'
        dockerImage_stream_repo = 'repo_from_dockerImageR.com/spam'
        stream_repo = dockerImage_stream_repo
        if repository:
            stream_repo = repository
        elif s_annotations and ANNOTATION_SOURCE_REPO in s_annotations:
            stream_repo = s_annotations[ANNOTATION_SOURCE_REPO]

        expected_insecure = False
        if repository:
            if insecure is not None:
                expected_insecure = insecure
        elif s_annotations:
            expected_insecure = s_annotations.get(
                ANNOTATION_INSECURE_REPO) == 'true'

        stream = {
            'metadata': {
                'name': stream_name
            },
            'spec': {
                'dockerImageRepository': dockerImage_stream_repo
            }
        }
        if s_annotations is not None:
            stream['metadata']['annotations'] = s_annotations

        tag_name = 'maps'
        tag_id = '{}:{}'.format(stream_name, tag_name)

        expected_url = openshift._build_url("image.openshift.io/v1",
                                            'imagestreamtags/' + tag_id)

        def verify_image_stream_tag(*args, **kwargs):
            data = json.loads(kwargs['data'])

            assert (bool(data['tag']['importPolicy'].get('insecure')) ==
                    expected_insecure)
            assert (bool(data['tag']['importPolicy'].get('scheduled')) ==
                    expected_scheduled)

            # Also verify new image stream tags are created properly.
            if status_code == 404:
                assert data['metadata']['name'] == tag_id
                assert data['tag']['name'] == tag_name
                assert (data['tag']['from']['name'] == '{}:{}'.format(
                    stream_repo, tag_name))

            return make_json_response({})

        expected_change = False
        expected_error = status_code == 500

        mock_response = {}

        expectation = (flexmock(openshift).should_receive("_get").with_args(
            expected_url).once())

        if status_code == 200:
            existing_image_stream_tag = {'tag': {'importPolicy': {}}}

            if existing_insecure is not None:
                existing_image_stream_tag['tag']['importPolicy']['insecure'] = \
                    existing_insecure

            if existing_scheduled is not None:
                existing_image_stream_tag['tag']['importPolicy']['scheduled'] = \
                    existing_scheduled

            mock_response = existing_image_stream_tag

            if expected_insecure != bool(existing_insecure) or \
               expected_scheduled != bool(existing_scheduled):
                expected_change = True

            expectation.and_return(make_json_response(mock_response))

        else:
            expectation.and_return(
                HttpResponse(status_code, headers={}, content=b''))

        if status_code == 404:
            expected_change = True

        if expected_change:
            (flexmock(openshift).should_receive("_put").with_args(
                expected_url,
                data=str,
                headers={
                    "Content-Type": "application/json"
                }).replace_with(verify_image_stream_tag).once())

        kwargs = {}
        if repository:
            kwargs['repository'] = repository
        if insecure:
            kwargs['insecure'] = insecure
        if expected_error:
            with pytest.raises(OsbsResponseException):
                openshift.ensure_image_stream_tag(stream, tag_name,
                                                  self._make_tag_template(),
                                                  expected_scheduled, **kwargs)

        else:
            assert (openshift.ensure_image_stream_tag(
                stream, tag_name, self._make_tag_template(),
                expected_scheduled, **kwargs) == expected_change)
コード例 #14
0
def make_json_response(obj):
    return HttpResponse(200,
                        headers={"Content-Type": "application/json"},
                        content=json.dumps(obj).encode('utf-8'))
コード例 #15
0
ファイル: conftest.py プロジェクト: ssalatsk/osbs-client
 def response(status_code=200, content=b'', headers=None):
     return HttpResponse(status_code, headers or {}, content=content)
コード例 #16
0
    def test_ensure_image_stream_tag(self, existing_scheduled,
                                     existing_insecure, expected_scheduled,
                                     s_annotations, expected_insecure,
                                     status_code, openshift):
        stream_name = 'spam'
        stream_repo = 'some.registry.com/spam'
        stream = {
            'metadata': {
                'name': stream_name
            },
            'spec': {
                'dockerImageRepository': stream_repo
            }
        }
        if s_annotations is not None:
            stream['metadata']['annotations'] = s_annotations

        tag_name = 'maps'
        tag_id = '{0}:{1}'.format(stream_name, tag_name)

        expected_url = openshift._build_url('imagestreamtags/' + tag_id)

        def verify_image_stream_tag(*args, **kwargs):
            data = json.loads(kwargs['data'])

            assert (bool(data['tag']['importPolicy'].get('insecure')) ==
                    expected_insecure)
            assert (bool(data['tag']['importPolicy'].get('scheduled')) ==
                    expected_scheduled)

            # Also verify new image stream tags are created properly.
            if status_code == 404:
                assert data['metadata']['name'] == tag_id
                assert data['tag']['name'] == tag_name
                assert (data['tag']['from']['name'] == '{0}:{1}'.format(
                    stream_repo, tag_name))

            return HttpResponse(200, {}, json.dumps('{}'))

        expected_change = False
        expected_error = status_code == 500

        mock_response = '{}'

        if status_code == 200:
            existing_image_stream_tag = {'tag': {'importPolicy': {}}}

            if existing_insecure is not None:
                existing_image_stream_tag['tag']['importPolicy']['insecure'] = \
                    existing_insecure

            if existing_scheduled is not None:
                existing_image_stream_tag['tag']['importPolicy']['scheduled'] = \
                    existing_scheduled

            mock_response = json.dumps(existing_image_stream_tag)

            if expected_insecure != bool(existing_insecure) or \
               expected_scheduled != bool(existing_scheduled):
                expected_change = True

        elif status_code == 404:
            expected_change = True

        (flexmock(openshift).should_receive("_get").with_args(
            expected_url).once().and_return(
                HttpResponse(status_code, {}, mock_response)))

        if expected_change:
            (flexmock(openshift).should_receive("_put").with_args(
                expected_url,
                data=str,
                headers={
                    "Content-Type": "application/json"
                }).replace_with(verify_image_stream_tag).once())

        if expected_error:
            with pytest.raises(OsbsResponseException):
                openshift.ensure_image_stream_tag(stream, tag_name,
                                                  self._make_tag_template(),
                                                  expected_scheduled)

        else:
            assert (openshift.ensure_image_stream_tag(
                stream, tag_name, self._make_tag_template(),
                expected_scheduled) == expected_change)