コード例 #1
0
    def test_deserialize_binary_to_str(self):
        """Ensures that bytes deserialization works"""
        response_types_mixed = (str, )

        # sample from http://www.jtricks.com/download-text
        HTTPResponse = namedtuple(
            'urllib3_response_HTTPResponse',
            ['status', 'reason', 'data', 'getheaders', 'getheader'])
        headers = {}

        def get_headers():
            return headers

        def get_header(name, default=None):
            return headers.get(name, default)

        data = "str"

        http_response = HTTPResponse(status=200,
                                     reason='OK',
                                     data=json.dumps(data).encode("utf-8")
                                     if six.PY3 else json.dumps(data),
                                     getheaders=get_headers,
                                     getheader=get_header)

        mock_response = RESTResponse(http_response)

        result = self.deserialize(mock_response, response_types_mixed, True)
        self.assertEqual(isinstance(result, str), True)
        self.assertEqual(result, data)
コード例 #2
0
 def mock_response(body_value):
     http_response = HTTPResponse(
         status=200,
         reason='OK',
         data=json.dumps(body_value).encode('utf-8'),
         getheaders=get_headers,
         getheader=get_header)
     return RESTResponse(http_response)
コード例 #3
0
    def test_upload_file(self):
        # uploads a file
        test_file_dir = os.path.realpath(
            os.path.join(os.path.dirname(__file__), "..", "testfiles"))
        file_path1 = os.path.join(test_file_dir, "1px_pic1.png")

        headers = {}
        def get_headers():
            return headers
        def get_header(name, default=None):
            return headers.get(name, default)
        api_respponse = {
            'code': 200,
            'type': 'blah',
            'message': 'file upload succeeded'
        }
        http_response = HTTPResponse(
            status=200,
            reason='OK',
            data=json.dumps(api_respponse).encode('utf-8'),
            getheaders=get_headers,
            getheader=get_header
        )
        mock_response = RESTResponse(http_response)
        file1 = open(file_path1, "rb")
        try:
            with patch.object(RESTClientObject, 'request') as mock_method:
                mock_method.return_value = mock_response
                res = self.api.upload_file(
                    file=file1)
                body = None
                post_params=[
                    ('file', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')),
                ]
                self.assert_request_called_with(
                    mock_method,
                    'http://petstore.swagger.io:80/v2/fake/uploadFile',
                    body=body, post_params=post_params, content_type='multipart/form-data'
                )
        except petstore_api.ApiException as e:
            self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
        finally:
            file1.close()

        # passing in an array of files to when file only allows one
        # raises an exceptions
        try:
            file = open(file_path1, "rb")
            with self.assertRaises(petstore_api.ApiTypeError) as exc:
                self.api.upload_file(file=[file])
        finally:
            file.close()

        # passing in a closed file raises an exception
        with self.assertRaises(petstore_api.ApiValueError) as exc:
            file = open(file_path1, "rb")
            file.close()
            self.api.upload_file(file=file)
コード例 #4
0
    def test_download_attachment(self):
        """Ensures that file deserialization works"""

        # sample from http://www.jtricks.com/download-text
        file_name = 'content.txt'
        headers_dict = {
            'with_filename': {
                'Content-Disposition':
                'attachment; filename={}'.format(file_name),
                'Content-Type': 'text/plain'
            },
            'no_filename': {
                'Content-Disposition': 'attachment;',
                'Content-Type': 'text/plain'
            }
        }

        def get_headers(*args):
            return args

        file_data = (
            "You are reading text file that was supposed to be downloaded\r\n"
            "to your hard disk. If your browser offered to save you the file,"
            "\r\nthen it handled the Content-Disposition header correctly.")
        for key, headers in headers_dict.items():

            def get_header(name, default=None):
                return headers_dict[key].get(name, default)

            http_response = HTTPResponse(status=200,
                                         reason='OK',
                                         data=file_data,
                                         getheaders=get_headers(headers),
                                         getheader=get_header)
            # deserialize response to a file
            mock_response = RESTResponse(http_response)
            with patch.object(RESTClientObject, 'request') as mock_method:
                mock_method.return_value = mock_response
                try:
                    file_object = self.api.download_attachment(
                        file_name='download-text')
                    self.assert_request_called_with(
                        mock_method,
                        'http://www.jtricks.com/download-text',
                        http_method='GET',
                        accept='text/plain',
                        content_type=None,
                    )
                    self.assertTrue(isinstance(file_object, file_type))
                    self.assertFalse(file_object.closed)
                    self.assertEqual(file_object.read(),
                                     file_data.encode('utf-8'))
                finally:
                    file_object.close()
                    os.unlink(file_object.name)
コード例 #5
0
    def test_upload_download_file(self):
        test_file_dir = os.path.realpath(
            os.path.join(os.path.dirname(__file__), "..", "testfiles"))
        file_path1 = os.path.join(test_file_dir, "1px_pic1.png")

        with open(file_path1, "rb") as f:
            expected_file_data = f.read()

        headers = {'Content-Type': 'application/octet-stream'}

        def get_headers():
            return headers

        def get_header(name, default=None):
            return headers.get(name, default)

        http_response = HTTPResponse(status=200,
                                     reason='OK',
                                     data=expected_file_data,
                                     getheaders=get_headers,
                                     getheader=get_header)
        mock_response = RESTResponse(http_response)
        file1 = open(file_path1, "rb")
        try:
            with patch.object(RESTClientObject, 'request') as mock_method:
                mock_method.return_value = mock_response
                downloaded_file = self.api.upload_download_file(body=file1)
                self.assert_request_called_with(
                    mock_method,
                    'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile',
                    body=expected_file_data,
                    content_type='application/octet-stream',
                    accept='application/octet-stream')

                self.assertTrue(isinstance(downloaded_file, file_type))
                self.assertFalse(downloaded_file.closed)
                self.assertEqual(downloaded_file.read(), expected_file_data)
        except petstore_api.ApiException as e:
            self.fail("upload_download_file() raised {0} unexpectedly".format(
                type(e)))
        finally:
            file1.close()
            downloaded_file.close()
            os.unlink(downloaded_file.name)
コード例 #6
0
    def test_deserialize_file(self):
        """Ensures that file deserialization works"""
        response_types_mixed = (file_type,)

        # sample from http://www.jtricks.com/download-text
        HTTPResponse = namedtuple(
            'urllib3_response_HTTPResponse',
            ['status', 'reason', 'data', 'getheaders', 'getheader']
        )
        headers = {'Content-Disposition': 'attachment; filename=content.txt'}
        def get_headers():
            return headers
        def get_header(name, default=None):
            return headers.get(name, default)
        file_data = (
            "You are reading text file that was supposed to be downloaded\r\n"
            "to your hard disk. If your browser offered to save you the file,"
            "\r\nthen it handled the Content-Disposition header correctly."
        )
        http_response = HTTPResponse(
            status=200,
            reason='OK',
            data=file_data,
            getheaders=get_headers,
            getheader=get_header
        )
        # response which is deserialized to a file
        mock_response = RESTResponse(http_response)
        file_path = None
        try:
            file_object = self.deserialize(
                mock_response, response_types_mixed, True)
            self.assertTrue(isinstance(file_object, file_type))
            file_path = file_object.name
            self.assertFalse(file_object.closed)
            file_object.close()
            if six.PY3:
                file_data = file_data.encode('utf-8')
            with open(file_path, 'rb') as other_file_object:
                self.assertEqual(other_file_object.read(), file_data)
        finally:
            os.unlink(file_path)
コード例 #7
0
    def test_upload_file(self):
        # upload file with form parameter
        file_path1 = os.path.join(self.test_file_dir, "1px_pic1.png")
        file_path2 = os.path.join(self.test_file_dir, "1px_pic2.png")
        try:
            file = open(file_path1, "rb")
            additional_metadata = "special"
            self.pet_api.upload_file(pet_id=self.pet.id,
                                     additional_metadata=additional_metadata,
                                     file=file)
        except ApiException as e:
            self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
        finally:
            file.close()

        # upload only one file
        try:
            file = open(file_path1, "rb")
            self.pet_api.upload_file(pet_id=self.pet.id, file=file)
        except ApiException as e:
            self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
        finally:
            file.close()

        # upload multiple files
        HTTPResponse = namedtuple(
            'urllib3_response_HTTPResponse',
            ['status', 'reason', 'data', 'getheaders', 'getheader'])
        headers = {}

        def get_headers():
            return headers

        def get_header(name, default=None):
            return headers.get(name, default)

        api_respponse = {
            'code': 200,
            'type': 'blah',
            'message': 'file upload succeeded'
        }
        http_response = HTTPResponse(
            status=200,
            reason='OK',
            data=json.dumps(api_respponse).encode('utf-8'),
            getheaders=get_headers,
            getheader=get_header)
        mock_response = RESTResponse(http_response)
        try:
            file1 = open(file_path1, "rb")
            file2 = open(file_path2, "rb")
            with patch.object(RESTClientObject, 'request') as mock_method:
                mock_method.return_value = mock_response
                res = self.pet_api.upload_file(pet_id=684696917,
                                               files=[file1, file2])
                mock_method.assert_called_with(
                    'POST',
                    'http://localhost/v2/pet/684696917/uploadImage',
                    _preload_content=True,
                    _request_timeout=None,
                    body=None,
                    headers={
                        'Accept': 'application/json',
                        'Content-Type': 'multipart/form-data',
                        'User-Agent': 'OpenAPI-Generator/1.0.0/python',
                        'Authorization': 'Bearer ACCESS_TOKEN'
                    },
                    post_params=
                    [('files',
                      ('1px_pic1.png',
                       b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82',
                       'image/png')),
                     ('files',
                      ('1px_pic2.png',
                       b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82',
                       'image/png'))],
                    query_params=[])
        except ApiException as e:
            self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
        finally:
            file1.close()
            file2.close()

        # passing in an array of files to when file only allows one
        # raises an exceptions
        try:
            file = open(file_path1, "rb")
            with self.assertRaises(ApiTypeError) as exc:
                self.pet_api.upload_file(pet_id=self.pet.id, file=[file])
        finally:
            file.close()

        # passing in a single file when an array of file is required
        # raises an exception
        try:
            file = open(file_path1, "rb")
            with self.assertRaises(ApiTypeError) as exc:
                self.pet_api.upload_file(pet_id=self.pet.id, files=file)
        finally:
            file.close()

        # passing in a closed file raises an exception
        with self.assertRaises(ApiValueError) as exc:
            file = open(file_path1, "rb")
            file.close()
            self.pet_api.upload_file(pet_id=self.pet.id, file=file)