Esempio n. 1
0
 def setup_client(self):
     http_client = SynchronousHttpClient()
     http_client.set_basic_auth(
         urlparse(self.http_uri).netloc.split(':')[0], self.ari_user,
         self.ari_pass)
     self.client = SwaggerClient(self.ari_url, http_client=http_client)
     logger.info('ARI client setup done.')
 def __init__(self):
     LogDefine()
     self.http_client = SynchronousHttpClient()
     # self.host
     # self.port
     # self.method
     # self.parameters
     # self.data
     self.verification = []
Esempio n. 3
0
    def test_simple_get(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        uut = SynchronousHttpClient()
        resp = uut.request('GET', "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
Esempio n. 4
0
    def test_simple_get(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        uut = SynchronousHttpClient()
        resp = uut.request('GET',
                           "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
Esempio n. 5
0
    def test_api_key(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        uut = SynchronousHttpClient()
        uut.set_api_key("swagger.py",
                        'abc123', param_name='test')
        resp = uut.request('GET', "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar'], 'test': ['abc123']},
                         httpretty.last_request().querystring)
def make_request(method, url, parameters=None, data=None):
    http_client = SynchronousHttpClient()
    """
    method = 'get'
    parameters = {
        'keywords': '刘德华',
    }
    参数根据swagger定义的参数进行传递
    """
    z = http_client.request(
        method=method, url=url, params=parameters,
        data=data)  #Request请求传入method= 'get'|'post'|'put' 等,传入url 传入请求参数
    #http_client.websockets.difference()
    return z
Esempio n. 7
0
    def test_auth_leak(self):
        httpretty.register_uri(httpretty.GET,
                               "http://hackerz.py",
                               body='expected')

        uut = SynchronousHttpClient()
        uut.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        resp = uut.request('GET', "http://hackerz.py", params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertTrue(
            httpretty.last_request().headers.get('Authorization') is None)
Esempio n. 8
0
    def test_real_post(self):
        httpretty.register_uri(
            httpretty.POST, "http://swagger.py/client-test",
            body='expected', content_type='text/json')

        uut = SynchronousHttpClient()
        resp = uut.request('POST', "http://swagger.py/client-test",
                           data={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual('application/x-www-form-urlencoded',
                         httpretty.last_request().headers['content-type'])
        self.assertEqual("foo=bar",
                         httpretty.last_request().body)
Esempio n. 9
0
    def test_auth_leak(self):
        httpretty.register_uri(
            httpretty.GET, "http://hackerz.py",
            body='expected')

        uut = SynchronousHttpClient()
        uut.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        resp = uut.request('GET', "http://hackerz.py",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertTrue(
            httpretty.last_request().headers.get('Authorization') is None)
Esempio n. 10
0
    def test_basic_auth(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        uut = SynchronousHttpClient()
        uut.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        resp = uut.request('GET', "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertEqual('Basic %s' % base64.b64encode("unit:peekaboo"),
                         httpretty.last_request().headers.get('Authorization'))
Esempio n. 11
0
    def test_real_post(self):
        httpretty.register_uri(httpretty.POST,
                               "http://swagger.py/client-test",
                               body='expected',
                               content_type='text/json')

        uut = SynchronousHttpClient()
        resp = uut.request('POST',
                           "http://swagger.py/client-test",
                           data={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual('application/x-www-form-urlencoded',
                         httpretty.last_request().headers['content-type'])
        self.assertEqual("foo=bar", httpretty.last_request().body)
Esempio n. 12
0
    def test_unicode_to_utf8_encode_params(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        client = SynchronousHttpClient()
        params = self._default_params()
        params['params'] = {'foo': u'酒場'}

        resp = client.start_request(params).wait()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': [u'酒場']},
                         httpretty.last_request().querystring)
Esempio n. 13
0
    def test_basic_auth(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        uut = SynchronousHttpClient()
        uut.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        resp = uut.request('GET',
                           "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertEqual('Basic %s' % base64.b64encode("unit:peekaboo"),
                         httpretty.last_request().headers.get('Authorization'))
Esempio n. 14
0
    def from_url(cls,
                 url,
                 http_client=None,
                 api_base_path=None,
                 request_options=None):
        """
        Build a :class:`SwaggerClient` from a url to api docs describing the
        api.

        :param url: url pointing at the swagger api docs
        :type url: str
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`swaggerpy.http_client.HttpClient`
        :param api_base_path: a url, override the path used to make api requests
        :type  api_base_path: str
        :param request_options: extra values to pass with api docs requests
        :type  request_options: dict
        """
        log.debug(u"Loading from %s" % url)
        http_client = http_client or SynchronousHttpClient()

        return cls.from_resource_listing(load_resource_listing(
            url, http_client, None, request_options),
                                         http_client=http_client,
                                         api_base_path=api_base_path,
                                         url=url)
class InterfaceModel():
    def __init__(self):
        LogDefine()
        self.http_client = SynchronousHttpClient()
        # self.host
        # self.port
        # self.method
        # self.parameters
        # self.data
        self.verification = []

    def define_request_method(self, method, url, parameters=None, data=None):
        """请求模板"""
        try:
            res = self.http_client.request(method=method,
                                           url=url,
                                           params=parameters,
                                           data=data)
            http_code = res.status_code
            if http_code == HTTP_CODE_SUCCESS:
                logging.info("if code == 200 ,request success!")
                print u"返回200,请求成功", res.url
                print res.text
                return res

            else:
                logging.error("not return code 200 ,request hava some problem")
                print res.url
                print u"响应出错 code %s" % http_code
                print res.text
        except Exception, e:
            logging.info(u"请求出问题了 %s ", e)
            print e
Esempio n. 16
0
    def from_resource_listing(cls,
                              resource_listing,
                              http_client=None,
                              api_base_path=None,
                              url=None):
        """
        Build a :class:`SwaggerClient` from swagger api docs

        :param resource_listing: a dict with a list of api definitions
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`swaggerpy.http_client.HttpClient`
        :param api_base_path: a url, override the path used to make api requests
        :type  api_base_path: str
        :param url: the url used to retrieve the resource listing
        :type  url: str
        """
        url = url or resource_listing.get(u'url')
        log.debug(u"Using resources from %s" % url)

        if url:
            url_base = "{uri.scheme}://{uri.netloc}".format(uri=urlparse(url))
        else:
            url_base = None

        resources = build_resources_from_spec(
            http_client or SynchronousHttpClient(),
            map(append_name_to_api, resource_listing['apis']), api_base_path,
            url_base)
        return cls(url, resources)
Esempio n. 17
0
 def test_headers_present_when_loading_resource_through_Synchronous(self):
     self.response['apis'] = []
     self.register_urls()
     sync_http_client = SynchronousHttpClient(headers={'foo': 'bar'})
     SwaggerClient(u'http://localhost/api-docs',
                   http_client=sync_http_client)
     self.assertEqual('bar', httpretty.last_request().headers['foo'])
Esempio n. 18
0
    def __init__(self,
                 url_or_resource,
                 http_client=None,
                 extra_processors=None):
        if not http_client:
            http_client = SynchronousHttpClient()
        self.http_client = http_client

        processors = [WebsocketProcessor(), ClientProcessor()]
        if extra_processors is not None:
            processors.extend(extra_processors)
        loader = swaggerpy.Loader(http_client, processors)

        if isinstance(url_or_resource, basestring):
            log.debug("Loading from %s" % url_or_resource)
            self.api_docs = loader.load_resource_listing(url_or_resource)
        else:
            log.debug("Loading from %s" % url_or_resource.get('basePath'))
            self.api_docs = url_or_resource
            loader.process_resource_listing(self.api_docs)

        self.resources = {
            resource['name']: Resource(resource, http_client)
            for resource in self.api_docs['apis']
        }
Esempio n. 19
0
    def from_url(
            cls,
            url,
            http_client=None,
            api_base_path=None,
            api_doc_request_headers=None):
        """
        Build a :class:`SwaggerClient` from a url to api docs describing the
        api.

        :param url: url pointing at the swagger api docs
        :type url: str
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`swaggerpy.http_client.HttpClient`
        :param api_base_path: a url, override the path used to make api requests
        :type  api_base_path: str
        :param api_doc_request_headers: Headers to pass with api docs requests
        :type  api_doc_request_headers: dict
        """
        log.debug(u"Loading from %s" % url)
        http_client = http_client or SynchronousHttpClient()

        # TODO: better way to customize the request for api-docs, so we don't
        # have to add new kwargs for everything
        loader = Loader(
            http_client,
            api_doc_request_headers=api_doc_request_headers)

        return cls.from_resource_listing(
            loader.load_resource_listing(url),
            http_client=http_client,
            api_base_path=api_base_path,
            url=url)
Esempio n. 20
0
    def test_api_key(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        uut = SynchronousHttpClient()
        uut.set_api_key("swagger.py", 'abc123', param_name='test')
        resp = uut.request('GET',
                           "http://swagger.py/client-test",
                           params={'foo': 'bar'})
        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({
            'foo': ['bar'],
            'test': ['abc123']
        },
                         httpretty.last_request().querystring)
Esempio n. 21
0
    def test_headers(self):
        self.uut = SwaggerClient(self.resource_listing,
                                 SynchronousHttpClient(headers={'foo': 'bar'}))
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/swagger-test/pet",
                               body='[]')

        self.uut.pet.listPets().result()
        self.assertEqual('bar', httpretty.last_request().headers['foo'])
Esempio n. 22
0
    def test_real_post(self):
        httpretty.register_uri(httpretty.POST,
                               "http://swagger.py/client-test",
                               body='expected',
                               content_type='text/json')

        client = SynchronousHttpClient()
        params = self._default_params()
        params['data'] = {'foo': 'bar'}
        params['method'] = 'POST'

        resp = client.start_request(params).wait()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)

        self.assertEqual('application/x-www-form-urlencoded',
                         httpretty.last_request().headers['content-type'])
        self.assertEqual("foo=bar", httpretty.last_request().body)
Esempio n. 23
0
    def test_auth_leak(self):
        httpretty.register_uri(httpretty.GET,
                               "http://hackerz.py",
                               body='expected')

        client = SynchronousHttpClient()
        client.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}
        params['url'] = 'http://hackerz.py'

        resp = client.start_request(params).wait()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertTrue(
            httpretty.last_request().headers.get('Authorization') is None)
Esempio n. 24
0
    def test_api_key(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        client = SynchronousHttpClient()
        client.set_api_key("swagger.py", 'abc123', param_name='test')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}

        resp = client.start_request(params).wait()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({
            'foo': ['bar'],
            'test': ['abc123']
        },
                         httpretty.last_request().querystring)
Esempio n. 25
0
 def resource(self, auth_type, *args):
     args_values = [getattr(self, arg) for arg in args]
     if all(args_values):
         http_client = SynchronousHttpClient(verify=self.verify)
         auth = getattr(http_client, 'set_{}'.format(auth_type))
         # auth method will be one of: set_basic_auth, set_token, set_jwt depending on params passed to
         # constructor.
         auth(*args_values)
         return SwaggerClient(self.resources,
                              http_client=http_client,
                              extra_processors=[AgaveProcessor()])
Esempio n. 26
0
    def __init__(self,
                 url_or_resource,
                 http_client=None,
                 api_base_path=None,
                 raise_with=None):
        if not http_client:
            http_client = SynchronousHttpClient()
        # Wrap http client's errors with raise_with
        http_client.raise_with = raise_with
        self._http_client = http_client

        # Load Swagger APIs always synchronously
        loader = Loader(SynchronousHttpClient(headers=http_client._headers),
                        [ClientProcessor()])

        forced_api_base_path = api_base_path is not None
        # url_or_resource can be url of type str,
        # OR a dict of resource itself.
        if isinstance(url_or_resource, (str, unicode)):
            log.debug(u"Loading from %s" % url_or_resource)
            self._api_docs = loader.load_resource_listing(url_or_resource)
            parsed_uri = urlparse(url_or_resource)
            if not api_base_path:
                api_base_path = "{uri.scheme}://{uri.netloc}".format(
                    uri=parsed_uri)
        else:
            log.debug(u"Loading from %s" % url_or_resource.get(u'url'))
            self._api_docs = url_or_resource
            loader.process_resource_listing(self._api_docs)
            if not api_base_path:
                api_base_path = url_or_resource.get(u'url')

        self._resources = {}
        for resource in self._api_docs[u'apis']:
            if forced_api_base_path and 'api_declaration' in resource:
                resource['api_declaration']['basePath'] = api_base_path
            self._resources[resource[u'name']] = Resource(
                resource, http_client, api_base_path)
            setattr(self, resource['name'],
                    self._get_resource(resource[u'name']))
Esempio n. 27
0
def load_url(url, http_client=None, **kwargs):
    """Loads a resource listing.

    :param resource_listing_url: URL for a resource listing.
    :param http_client: HTTP client interface.
    :param base_url:    Optional URL to be the base URL for finding API
                        declarations. If not specified, 'basePath' from the
                        resource listing is used.
    :return: Processed object model from
    :raise: IOError, URLError: On error reading api-docs.
    """
    http_client = http_client or SynchronousHttpClient()
    return load_resource_listing(url, http_client, **kwargs)
Esempio n. 28
0
    def __init__(self, url_or_resource, http_client=None,
                 api_base_path=None, raise_with=None):
        if not http_client:
            http_client = SynchronousHttpClient()
        # Wrap http client's errors with raise_with
        http_client.raise_with = raise_with
        self._http_client = http_client

        # Load Swagger APIs always synchronously
        loader = Loader(
            SynchronousHttpClient(headers=http_client._headers),
            [ClientProcessor()])

        forced_api_base_path = api_base_path is not None
        # url_or_resource can be url of type str,
        # OR a dict of resource itself.
        if isinstance(url_or_resource, (str, unicode)):
            log.debug(u"Loading from %s" % url_or_resource)
            self._api_docs = loader.load_resource_listing(url_or_resource)
            parsed_uri = urlparse(url_or_resource)
            if not api_base_path:
                api_base_path = "{uri.scheme}://{uri.netloc}".format(
                    uri=parsed_uri)
        else:
            log.debug(u"Loading from %s" % url_or_resource.get(u'url'))
            self._api_docs = url_or_resource
            loader.process_resource_listing(self._api_docs)
            if not api_base_path:
                api_base_path = url_or_resource.get(u'url')

        self._resources = {}
        for resource in self._api_docs[u'apis']:
            if forced_api_base_path and 'api_declaration' in resource:
                resource['api_declaration']['basePath'] = api_base_path
            self._resources[resource[u'name']] = Resource(
                resource, http_client, api_base_path)
            setattr(self, resource['name'],
                    self._get_resource(resource[u'name']))
Esempio n. 29
0
def load_json(resource_listing, http_client=None, processors=None):
    """Process a resource listing that has already been parsed.

    :param resource_listing: Parsed resource listing.
    :type  resource_listing: dict
    :param http_client:
    :param processors:
    :return: Processed resource listing.
    """
    if http_client is None:
        http_client = SynchronousHttpClient()

    loader = Loader(http_client=http_client, processors=processors)
    loader.process_resource_listing(resource_listing)
    return resource_listing
Esempio n. 30
0
    def __init__(self, url_or_resource, http_client=None):
        if not http_client:
            http_client = SynchronousHttpClient()
        self.http_client = http_client

        loader = Loader(http_client, [WebsocketProcessor(), ClientProcessor()])

        if isinstance(url_or_resource, str):
            log.debug("Loading from %s" % url_or_resource)
            self.api_docs = loader.load_resource_listing(url_or_resource)
        else:
            log.debug("Loading from %s" % url_or_resource.get('basePath'))
            self.api_docs = url_or_resource
            loader.process_resource_listing(self.api_docs)

        self.resources = {
            resource['name']: Resource(resource, http_client)
            for resource in self.api_docs['apis']
        }
Esempio n. 31
0
def load_url(resource_listing_url, http_client=None, processors=None,
             base_url=None):
    """Loads a resource listing, applying the given processors.

    :param resource_listing_url: URL for a resource listing.
    :param http_client: HTTP client interface.
    :param processors:  List of SwaggerProcessors to apply to the resulting
                        resource.
    :param base_url:    Optional URL to be the base URL for finding API
                        declarations. If not specified, 'basePath' from the
                        resource listing is used.
    :return: Processed object model from
    :raise: IOError, URLError: On error reading api-docs.
    """
    if http_client is None:
        http_client = SynchronousHttpClient()

    loader = Loader(http_client=http_client, processors=processors)
    return loader.load_resource_listing(
        resource_listing_url, base_url=base_url)
Esempio n. 32
0
#!/usr/bin/env python

import json

from swaggerpy.client import SwaggerClient
from swaggerpy.http_client import SynchronousHttpClient

http_client = SynchronousHttpClient()

bitMEX = SwaggerClient(
    "https://www.bitmex.com/api/explorer/resources",
    http_client=http_client)

res = bitMEX.trade.trade_getRecent({symbol: 'XBTP14', count: 40})

print(res)