Esempio n. 1
0
    def test_parameter(self):
        """ Parameter -> Parameter
        """
        # body
        o = self.app.root.paths["/api/pet/{petId}"].patch
        p = [p for p in o.parameters if getattr(p, "in") == "body"][0]
        self.assertEqual(getattr(p, "in"), "body")
        self.assertEqual(p.required, True)
        self.assertEqual(getattr(p.schema, "norm_ref"), _pf("/definitions/pet!##!Pet"))

        # form
        o = self.app.root.paths["/api/pet/uploadImage"].post
        p = [p for p in o.parameters if getattr(p, "in") == "formData" and p.type == "string"][0]
        self.assertEqual(p.name, "additionalMetadata")
        self.assertEqual(p.required, False)

        # file
        o = self.app.root.paths["/api/pet/uploadImage"].post
        p = [p for p in o.parameters if getattr(p, "in") == "formData" and p.type == "file"][0]
        self.assertEqual(p.name, "file")
        self.assertEqual(p.required, False)

        # non-body can't have $ref
        try:
            SwaggerApp._create_(get_test_data_folder(version="1.2", which="upgrade_parameter"))
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ("Can't have $ref in non-body Parameters",))
        else:
            self.fail("SchemaError not raised")
Esempio n. 2
0
    def test_parameter(self):
        """ Parameter -> Parameter
        """
        # body
        o = self.app.root.paths['/api/pet/{petId}'].patch
        p = [p for p in o.parameters if getattr(p, 'in') == 'body'][0]
        self.assertEqual(getattr(p, 'in'), 'body')
        self.assertEqual(p.required, True)
        self.assertEqual(getattr(p.schema, '$ref'), _pf('/definitions/pet!##!Pet'))

        # form
        o = self.app.root.paths['/api/pet/uploadImage'].post
        p = [p for p in o.parameters if getattr(p, 'in') == 'formData' and p.type == 'string'][0]
        self.assertEqual(p.name, 'additionalMetadata')
        self.assertEqual(p.required, False)
 
        # file
        o = self.app.root.paths['/api/pet/uploadImage'].post
        p = [p for p in o.parameters if getattr(p, 'in') == 'formData' and p.type == 'file'][0]
        self.assertEqual(p.name, 'file')
        self.assertEqual(p.required, False)

        # non-body can't have $ref
        try:
            SwaggerApp._create_(get_test_data_folder(
                version='1.2',
                which='upgrade_parameter'
            ))
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ("Can't have $ref in non-body Parameters",))
        else:
            self.fail('SchemaError not raised')
Esempio n. 3
0
    def test_load(self):
        """ make sure the result of yaml and json are identical """
        app_json = SwaggerApp.load(get_test_data_folder(
            version='2.0',
            which='wordnik'
        ))
        app_yaml = SwaggerApp.load(get_test_data_folder(
            version='2.0',
            which='yaml',
            )
        )
        s = Scanner(app_yaml)
        s.scan(route=[YamlFixer()], root=app_yaml.raw, leaves=[Operation])

        self.assertEqual((True, ''), app_json.raw.compare(app_yaml.raw))
Esempio n. 4
0
    def test_v2_0(self):
        """ convert from 2.0 to 2.0 """
        path = get_test_data_folder(version="2.0", which="wordnik")
        app = SwaggerApp.create(path)

        # load swagger.json into dict
        origin = None
        with open(os.path.join(path, "swagger.json")) as r:
            origin = json.loads(r.read())

        # diff for empty list or dict is allowed
        d = app.dump()
        self.assertEqual(
            sorted(_diff_(origin, d, exclude=["$ref"])),
            sorted(
                [
                    ("paths/~1pet~1{petId}/get/security/0/api_key", "list", "NoneType"),
                    ("paths/~1store~1inventory/get/parameters", None, None),
                    ("paths/~1store~1inventory/get/security/0/api_key", "list", "NoneType"),
                    ("paths/~1user~1logout/get/parameters", None, None),
                ]
            ),
        )

        # try to load the dumped dict back, to see if anything wrong
        tmp = {"_tmp_": {}}
        with SwaggerContext(tmp, "_tmp_") as ctx:
            ctx.parse(d)
Esempio n. 5
0
    def test_primfactory(self):
        app = SwaggerApp.create(
            get_test_data_folder(version="2.0", which=os.path.join("circular", "schema")), strict=False
        )

        s = app.resolve("#/definitions/s1")
        self.assertRaises(errs.CycleDetectionError, app.prim_factory.produce, s, {})
Esempio n. 6
0
    def test_deref(self):
        app = SwaggerApp.create(
            get_test_data_folder(version="2.0", which=os.path.join("circular", "schema")), strict=False
        )

        s = app.resolve("#/definitions/s1")
        self.assertRaises(errs.CycleDetectionError, utils.deref, s)
Esempio n. 7
0
    def test_schema(self):
        folder = get_test_data_folder(version="2.0", which=os.path.join("circular", "schema"))

        def _pf(s):
            return six.moves.urllib.parse.urlunparse(("file", "", folder, "", "", s))

        app = SwaggerApp.load(folder)
        app.prepare(strict=False)

        s = Scanner(app)
        c = CycleDetector()
        s.scan(root=app.raw, route=[c])
        self.maxDiff = None
        self.assertEqual(
            sorted(c.cycles["schema"]),
            sorted(
                [
                    [_pf("/definitions/s10"), _pf("/definitions/s11"), _pf("/definitions/s9"), _pf("/definitions/s10")],
                    [_pf("/definitions/s5"), _pf("/definitions/s5")],
                    [
                        _pf("/definitions/s1"),
                        _pf("/definitions/s2"),
                        _pf("/definitions/s3"),
                        _pf("/definitions/s4"),
                        _pf("/definitions/s1"),
                    ],
                    [_pf("/definitions/s12"), _pf("/definitions/s13"), _pf("/definitions/s12")],
                    [_pf("/definitions/s6"), _pf("/definitions/s7"), _pf("/definitions/s6")],
                    [_pf("/definitions/s14"), _pf("/definitions/s15"), _pf("/definitions/s14")],
                ]
            ),
        )
Esempio n. 8
0
    def test_authorization(self):
        """
        """
        app = SwaggerApp.create(get_test_data_folder(
            version='1.2', which='simple_auth')
        )
            
        expect = {
            'type':'apiKey',
            'in':'query',
            'name':'simpleQK'
        }
        self.assertEqual(_diff_(
            expect,
            app.resolve('#/securityDefinitions/simple_key').dump()
        ), [])

        expect = {
            'type':'apiKey',
            'in':'header',
            'name':'simpleHK'
        }
        self.assertEqual(_diff_(
            expect,
            app.resolve('#/securityDefinitions/simple_key2').dump()
        ), [])


        expect = {
            'type':'basic',
        }
        self.assertEqual(_diff_(
            expect,
            app.resolve('#/securityDefinitions/simple_basic').dump()
        ), [])
Esempio n. 9
0
    def setUpClass(kls):
        global folder

        kls.app = SwaggerApp.load(
            url='file:///root/swagger.json',
            url_load_hook=_hook
        )
        kls.app.prepare()
Esempio n. 10
0
    def setUpClass(kls):
        kls.app = SwaggerApp.load(get_test_data_folder(
            version='2.0',
            which='bitbucket'
        ))

        # bypass cyclic testing
        kls.app.prepare(strict=False)
Esempio n. 11
0
    def setUpClass(kls):
        kls.app = SwaggerApp.load(get_test_data_folder(
            version='1.2', which='wordnik'), sep=':'
        )
        kls.app.prepare()

        with open('./test.json', 'w') as r:
            r.write(json.dumps(kls.app.dump(), indent=3))
Esempio n. 12
0
 def test_relative_schema(self):
     """ test case for issue#53,
     relative file, which root is a Schema Object
     """
     app = SwaggerApp.load(
         url="file:///relative/internal.yaml",
         url_load_hook=_gen_hook(get_test_data_folder(version="2.0", which="ex")),
     )
     app.prepare()
Esempio n. 13
0
    def test_item(self):
        """ make sure to raise exception for invalid item
        """
        try:
            SwaggerApp._create_(get_test_data_folder(version="1.2", which=os.path.join("upgrade_items", "with_ref")))
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ("Can't have $ref for Items",))
        else:
            self.fail("SchemaError not raised")

        try:
            SwaggerApp._create_(
                get_test_data_folder(version="1.2", which=os.path.join("upgrade_items", "invalid_primitive"))
            )
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ("Non primitive type is not allowed for Items",))
        else:
            self.fail("SchemaError not raised")
Esempio n. 14
0
    def test_model_inheritance(self):
        """
        """
        app = SwaggerApp.load(get_test_data_folder(version="1.2", which="model_subtypes"), sep=":")
        app.prepare()

        expect = {"allOf": [{"$ref": u"#/definitions/user:User"}]}

        self.assertEqual(_diff_(expect, app.resolve("#/definitions/user:UserWithInfo").dump(), include=["allOf"]), [])
Esempio n. 15
0
    def test_overwrite(self):
        """ overrite type/format handler used in pyswagger """
        m1 = self.app.resolve("#/definitions/m1")
        v = m1._prim_({"job": "man"}, self.app.prim_factory)
        # should not raise
        self.assertEqual(v.job, "man")

        app = SwaggerApp.create(get_test_data_folder(version="2.0", which=os.path.join("schema", "extension")))
        m1 = app.resolve("#/definitions/m1")
        self.assertRaises(errs.ValidationError, m1._prim_, {"job": "man"}, app.prim_factory)
Esempio n. 16
0
 def test_random_name_v1_2(self):
     """
     """
     path = get_test_data_folder(
         version='1.2',
         which='random_file_name'
     )
     path = os.path.join(path, 'test_random.json')
     # should not raise ValueError
     app = SwaggerApp.create(path)
Esempio n. 17
0
    def test_no_host_basePath(self):
        """ test case for swagger.json without
        'host' and 'basePath' defined
        """
        path = get_test_data_folder(
            version='2.0',
            which=os.path.join('patch', 'no_host_schemes')
        )
        fu = utils.normalize_url(path) # file uri version of path

        # load swagger.json from a file path
        app = SwaggerApp.create(path)
        req, _ = app.s('t1').get()
        self.assertEqual(req.url, path+'/t1')
        self.assertEqual(req.schemes, ['file'])
        req.prepare(scheme='file', handle_files=False)
        self.assertEqual(req.url, fu+'/t1')

        # load swagger.json from a file uri
        self.assertNotEqual(six.moves.urllib.parse.urlparse(fu).scheme, '')
        app = SwaggerApp.create(fu)
        req, _ = app.s('t1').get()
        self.assertEqual(req.url, path+'/t1')
        self.assertEqual(req.schemes, ['file'])
        req.prepare(scheme='file', handle_files=False)
        self.assertEqual(req.url, fu+'/t1')

        # load swagger.json from a remote uri
        def _hook(url):
            # no matter what url, return the path of local swagger.json
            return fu

        url = 'test.com/api/v1'
        app = SwaggerApp.load('https://'+url, url_load_hook=_hook)
        app.prepare()
        # try to make a SwaggerRequest and verify its url
        req, _ = app.s('t1').get()
        self.assertEqual(req.url, url+'/t1')
        self.assertEqual(req.schemes, ['https'])
        req.prepare(scheme='https', handle_files=False)
        self.assertEqual(req.url, 'https://'+url+'/t1')
Esempio n. 18
0
    def setUp(self):
        folder = get_test_data_folder(
            version='1.2',
        )

        def _hook(url):
            # a demo of hooking a remote url to local path
            p = six.moves.urllib.parse.urlparse(url)
            return utils.normalize_url(os.path.join(folder, p.path[1:]))

        self.app = SwaggerApp.load('http://petstore.io/wordnik', url_load_hook=_hook)
        self.app.prepare()
Esempio n. 19
0
    def test_local_path_with_custome_getter(self):
        """ make sure path would be assigned when
        passing a getter class
        """
        cls = UrlGetter
        path = get_test_data_folder(
            version='2.0',
            which='random_file_name'
        )
        path = os.path.join(path, 'test_random.json')

        # should not raise errors
        app = SwaggerApp.load(path, getter=cls)
Esempio n. 20
0
    def test_token_endpoint(self):
        """
        """
        app = SwaggerApp.create(get_test_data_folder(version="1.2", which="simple_auth"))

        expect = {
            "tokenUrl": "http://petstore.swagger.wordnik.com/api/oauth/token",
            "type": "oauth2",
            "flow": "access_code",
            "scopes": {"test:anything": "for testing purpose"},
        }

        self.assertEqual(_diff_(expect, app.resolve("#/securityDefinitions/oauth2").dump()), [])
Esempio n. 21
0
    def test_item(self):
        """ make sure to raise exception for invalid item
        """
        try:
            SwaggerApp._create_(get_test_data_folder(
                version='1.2',
                which=os.path.join('upgrade_items', 'with_ref')
            ))
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ('Can\'t have $ref for Items',))
        else:
            self.fail('SchemaError not raised')

        try:
            SwaggerApp._create_(get_test_data_folder(
                version='1.2',
                which=os.path.join('upgrade_items', 'invalid_primitive')
            ))
        except errs.SchemaError as e:
            self.failUnlessEqual(e.args, ('Non primitive type is not allowed for Items',))
        else:
            self.fail('SchemaError not raised')
Esempio n. 22
0
    def test_authorization(self):
        """
        """
        app = SwaggerApp.create(get_test_data_folder(version="1.2", which="simple_auth"))

        expect = {"type": "apiKey", "in": "query", "name": "simpleQK"}
        self.assertEqual(_diff_(expect, app.resolve("#/securityDefinitions/simple_key").dump()), [])

        expect = {"type": "apiKey", "in": "header", "name": "simpleHK"}
        self.assertEqual(_diff_(expect, app.resolve("#/securityDefinitions/simple_key2").dump()), [])

        expect = {"type": "basic"}
        self.assertEqual(_diff_(expect, app.resolve("#/securityDefinitions/simple_basic").dump()), [])
Esempio n. 23
0
    def test_path_item(self):
        folder = get_test_data_folder(version="2.0", which=os.path.join("circular", "path_item"))

        def _pf(s):
            return six.moves.urllib.parse.urlunparse(("file", "", folder, "", "", s))

        app = SwaggerApp.create(folder)
        s = Scanner(app)
        c = CycleDetector()
        s.scan(root=app.raw, route=[c])
        self.assertEqual(
            sorted(c.cycles["path_item"]),
            sorted(
                [[_pf("/paths/~1p1"), _pf("/paths/~1p2"), _pf("/paths/~1p3"), _pf("/paths/~1p4"), _pf("/paths/~1p1")]]
            ),
        )
Esempio n. 24
0
    def test_schema(self):
        folder = get_test_data_folder(version='2.0',
                                      which=os.path.join('circular', 'schema'))

        def _pf(s):
            return six.moves.urllib.parse.urlunparse(
                ('file', '', folder, '', '', s))

        app = SwaggerApp.load(folder)
        app.prepare(strict=False)

        s = Scanner(app)
        c = CycleDetector()
        s.scan(root=app.raw, route=[c])
        self.maxDiff = None
        self.assertEqual(
            sorted(c.cycles['schema']),
            sorted([[
                _pf('/definitions/s10'),
                _pf('/definitions/s11'),
                _pf('/definitions/s9'),
                _pf('/definitions/s10')
            ], [_pf('/definitions/s5'),
                _pf('/definitions/s5')],
                    [
                        _pf('/definitions/s1'),
                        _pf('/definitions/s2'),
                        _pf('/definitions/s3'),
                        _pf('/definitions/s4'),
                        _pf('/definitions/s1')
                    ],
                    [
                        _pf('/definitions/s12'),
                        _pf('/definitions/s13'),
                        _pf('/definitions/s12')
                    ],
                    [
                        _pf('/definitions/s6'),
                        _pf('/definitions/s7'),
                        _pf('/definitions/s6')
                    ],
                    [
                        _pf('/definitions/s14'),
                        _pf('/definitions/s15'),
                        _pf('/definitions/s14')
                    ]]))
Esempio n. 25
0
    def test_model_inheritance(self):
        """
        """
        app = SwaggerApp.load(get_test_data_folder(
            version='1.2', which='model_subtypes'
            ), sep=':')
        app.prepare()

        expect = {
            'allOf': [{'$ref': u'#/definitions/user:User'}]
        }
        
        self.assertEqual(_diff_(
            expect,
            app.resolve('#/definitions/user:UserWithInfo').dump(),
            include=['allOf']
        ), [])
Esempio n. 26
0
    def test_load_from_url_without_file(self):
        """ try to load from a url withou swagger.json """
        data = None
        with open(os.path.join(get_test_data_folder(
            version='2.0',
            which='wordnik'), 'swagger.json')) as f:
            data = f.read()

        httpretty.register_uri(
            httpretty.GET,
            'http://10.0.0.10:8080/swaggerapi/api/v1beta2',
            body=data
        )

        # no exception should be raised
        app = SwaggerApp.create('http://10.0.0.10:8080/swaggerapi/api/v1beta2')
        self.assertTrue(app.schemes, ['http'])
        self.assertTrue(isinstance(app.root, BaseObj))
Esempio n. 27
0
    def test_token_endpoint(self):
        """
        """
        app = SwaggerApp.create(
            get_test_data_folder(version='1.2', which='simple_auth'))

        expect = {
            'tokenUrl': 'http://petstore.swagger.wordnik.com/api/oauth/token',
            'type': 'oauth2',
            'flow': 'access_code',
            'scopes': {
                'test:anything': 'for testing purpose'
            }
        }

        self.assertEqual(
            _diff_(expect,
                   app.resolve('#/securityDefinitions/oauth2').dump()), [])
Esempio n. 28
0
    def test_load_from_url_without_file(self):
        """ try to load from a url withou swagger.json """
        data = None
        with open(os.path.join(get_test_data_folder(
            version='2.0',
            which='wordnik'), 'swagger.json')) as f:
            data = f.read()

        httpretty.register_uri(
            httpretty.GET,
            'http://10.0.0.10:8080/swaggerapi/api/v1beta2',
            body=data
        )

        # no exception should be raised
        app = SwaggerApp.create('http://10.0.0.10:8080/swaggerapi/api/v1beta2')
        self.assertTrue(app.schemes, ['http'])
        self.assertTrue(isinstance(app.root, BaseObj))
Esempio n. 29
0
def show_method_list(args):

    app = SwaggerApp._create_(args.spec)

    # TODO: determine url basepath from spec

    methods = []

    for method, op in app.op.items():

        query_params = []
        for p in op.parameters:
            if getattr(p, 'in') == 'query':
                query_params.append(p.name + "=" + p.type)

        path = op.path + ('?' + '&'.join(query_params)
                          if len(query_params) > 0 else '')

        methods.append((path, op))

    methods = sorted(methods, key=lambda m: m[0])

    for (path, op) in methods:

        # rows, cols = os.popen('stty size', 'r').read().split()

        if args.v:
            set_color()
            print(op.summary)
            set_color(op.method)
            print("{:<7}{:<50}".format(op.method.upper(), path))
            set_color()
            print(
                get_curl_command(urllib.parse.urljoin(args.spec, path[1:]),
                                 op.method) + '\n')
        else:
            summary = (op.summary[:15] +
                       '..') if len(op.summary) > 15 else op.summary
            # print ("{}{}{:<6}{}{}{}{} {:<50}{}{:>20}{}".format(Fore.WHITE, back_color(op.method), op.method.upper(), Style.DIM, Back.BLACK, Style.NORMAL, Fore.WHITE, path, fore_color(op.method), summary, Style.RESET_ALL))
            # set_color(op.method)
            print("{}{:<6}{} {:<50}{:>20}".format(fore_color(op.method),
                                                  op.method.upper(),
                                                  Style.RESET_ALL, path,
                                                  summary))
Esempio n. 30
0
    def test_token_endpoint(self):
        """
        """
        app = SwaggerApp.create(get_test_data_folder(
            version='1.2', which='simple_auth')
        )

        expect={
            'tokenUrl':'http://petstore.swagger.wordnik.com/api/oauth/token',
            'type':'oauth2',
            'flow':'access_code',
            'scopes': {
                'test:anything':'for testing purpose'        
            }
        }

        self.assertEqual(_diff_(
            expect,
            app.resolve('#/securityDefinitions/oauth2').dump()
        ), [])
Esempio n. 31
0
    def test_auto_schemes(self):
        """ make sure we scheme of url to access
        swagger.json as default scheme
        """
        # load swagger.json
        data = None
        with open(os.path.join(get_test_data_folder(
                version='2.0',
                which=os.path.join('schema', 'model')
                ), 'swagger.json')) as f:
            data = f.read()

        httpretty.register_uri(
            httpretty.GET,
            'http://test.com/api-doc/swagger.json',
            body=data
        )

        app = SwaggerApp._create_('http://test.com/api-doc/swagger.json')
        self.assertEqual(app.schemes, ['http'])
Esempio n. 32
0
    def test_auto_schemes(self):
        """ make sure we scheme of url to access
        swagger.json as default scheme
        """
        # load swagger.json
        data = None
        with open(os.path.join(get_test_data_folder(
                version='2.0',
                which=os.path.join('schema', 'model')
                ), 'swagger.json')) as f:
            data = f.read()

        httpretty.register_uri(
            httpretty.GET,
            'http://test.com/api-doc/swagger.json',
            body=data
        )

        app = SwaggerApp._create_('http://test.com/api-doc/swagger.json')
        self.assertEqual(app.schemes, ['http'])
Esempio n. 33
0
    def test_path_item(self):
        folder = get_test_data_folder(version='2.0',
                                      which=os.path.join(
                                          'circular', 'path_item'))

        def _pf(s):
            return six.moves.urllib.parse.urlunparse(
                ('file', '', folder, '', '', s))

        app = SwaggerApp.create(folder)
        s = Scanner(app)
        c = CycleDetector()
        s.scan(root=app.raw, route=[c])
        self.assertEqual(
            sorted(c.cycles['path_item']),
            sorted([[
                _pf('/paths/~1p1'),
                _pf('/paths/~1p2'),
                _pf('/paths/~1p3'),
                _pf('/paths/~1p4'),
                _pf('/paths/~1p1')
            ]]))
Esempio n. 34
0
def get_method_list():

    from pyswagger import SwaggerApp, SwaggerSecurity
    from pyswagger.contrib.client.requests import Client
    from pyswagger.utils import jp_compose

    app = SwaggerApp._create_(swagger_spec)
    client = Client()

    methods = list(app.op.keys())

    apis = dict()

    for m in methods:

        full_method = m.split('!##!')

        if not full_method[0] in apis:
            apis[full_method[0]] = set()

        apis[full_method[0]].add(full_method[1])

    return apis
Esempio n. 35
0
    def setUpClass(kls):
        factory = SwaggerPrimitive()

        def decode_int(obj, val, ctx):
            # minus 1
            return int(val) - 1

        def decode_str(obj, val, ctx):
            # remove the last char
            return str(val)[:-1]

        def str_no_validate(obj, val, ctx):
            # same as the one used in pyswagger, but no validation
            return str(val)

        factory.register("encoded_integer", None, decode_int)
        factory.register("string", "special_encoded", decode_str)
        factory.register("string", None, str_no_validate, _2nd_pass=None)

        kls.app = SwaggerApp.load(
            get_test_data_folder(version="2.0", which=os.path.join("schema", "extension")), prim=factory
        )
        kls.app.prepare()
Esempio n. 36
0
    def test_authorization(self):
        """
        """
        app = SwaggerApp.create(
            get_test_data_folder(version='1.2', which='simple_auth'))

        expect = {'type': 'apiKey', 'in': 'query', 'name': 'simpleQK'}
        self.assertEqual(
            _diff_(expect,
                   app.resolve('#/securityDefinitions/simple_key').dump()), [])

        expect = {'type': 'apiKey', 'in': 'header', 'name': 'simpleHK'}
        self.assertEqual(
            _diff_(expect,
                   app.resolve('#/securityDefinitions/simple_key2').dump()),
            [])

        expect = {
            'type': 'basic',
        }
        self.assertEqual(
            _diff_(expect,
                   app.resolve('#/securityDefinitions/simple_basic').dump()),
            [])
Esempio n. 37
0
 def setUp(self):
     self.app = SwaggerApp._create_(get_test_data_folder(version='1.2', which='err'))
Esempio n. 38
0
    def test_http_getter(self):
        """ make sure HTTPGetter works """

        folder = get_test_data_folder(version='1.2', which='wordnik')
        resource_list = user = pet = store = None

        with open(os.path.join(folder, 'resource_list.json')) as f:
            resource_list = f.read()

        with open(os.path.join(folder, 'user.json')) as f:
            user = f.read()

        with open(os.path.join(folder, 'pet.json')) as f:
            pet = f.read()

        with open(os.path.join(folder, 'store.json')) as f:
            store = f.read()

        httpretty.register_uri(
            httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs',
            status=200,
            body=resource_list
            )

        httpretty.register_uri(
            httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/user',
            status=200,
            body=user
            )

        httpretty.register_uri(
            httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/pet',
            status=200,
            body=pet
            )

        httpretty.register_uri(
            httpretty.GET, 'http://petstore.swagger.wordnik.com/api/api-docs/store',
            status=200,
            body=store
            )

        local_app = SwaggerApp._create_('http://petstore.swagger.wordnik.com/api/api-docs')

        self.assertEqual(sorted(local_app.schema._field_names_), sorted(['info', 'authorizations', 'apiVersion', 'swaggerVersion', 'apis']))

        op = local_app.schema.apis['pet'].apis['updatePet']
        self.assertEqual(sorted(op._field_names_), sorted([
            'authorizations',
            'consumes',
            'defaultValue',
            'deprecated',
            'enum',
            'format',
            'items',
            'maximum',
            'method',
            'minimum',
            'nickname',
            'parameters',
            'path',
            'produces',
            'ref',
            'responseMessages',
            'type',
            'uniqueItems'
        ]))

        chd = local_app.schema._children_
        self.assertEqual(len(chd), 5)
        self.assertEqual(set(['user', 'pet', 'store']), set([c[0] for c in chd if isinstance(c[1], Resource)]))
Esempio n. 39
0
    def setUpClass(kls):
        global folder

        kls.app = SwaggerApp.load(url='file:///root/swagger.json',
                                  url_load_hook=_hook)
        kls.app.prepare()
Esempio n. 40
0
from pyswagger import SwaggerApp
from .utils import get_test_data_folder
from ..primitives import Model, Array, Void
from pyswagger.io import SwaggerRequest
import unittest

app = SwaggerApp._create_(get_test_data_folder(version='1.2', which='wordnik'))


class SwaggerRequest_Pet_TestCase(unittest.TestCase):
    """ test SwaggerRequest from Operation's __call__ """
    def test_updatePet(self):
        """ Pet.updatePet """
        req, _ = app.op['updatePet'](
            body=dict(id=1, name='Mary', category=dict(id=1, name='dog')))
        req.prepare()

        self.assertEqual(req.method, 'PUT')
        self.assertEqual(req.header, {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        })
        self.assertEqual(req.url,
                         'http://petstore.swagger.wordnik.com/api/pet')
        self.assertEqual(req.query, {})

        m = req._p['body']['body']
        self.assertTrue(isinstance(m, Model))
        self.assertEqual(m.id, 1)
        self.assertEqual(m.name, 'Mary')
        self.assertTrue(isinstance(m.category, Model))
Esempio n. 41
0
from pyswagger import SwaggerApp
from .utils import get_test_data_folder
from ..primitives import Model, Array, Void
from pyswagger.io import SwaggerRequest
import unittest


app = SwaggerApp._create_(get_test_data_folder(version='1.2', which='wordnik')) 


class SwaggerRequest_Pet_TestCase(unittest.TestCase):
    """ test SwaggerRequest from Operation's __call__ """

    def test_updatePet(self):
        """ Pet.updatePet """
        req, _ = app.op['updatePet'](body=dict(id=1, name='Mary', category=dict(id=1, name='dog')))
        req.prepare()

        self.assertEqual(req.method, 'PUT')
        self.assertEqual(req.header, {'Content-Type': 'application/json', 'Accept': 'application/json'})
        self.assertEqual(req.url, 'http://petstore.swagger.wordnik.com/api/pet')
        self.assertEqual(req.query, {})

        m = req._p['body']['body']
        self.assertTrue(isinstance(m, Model))
        self.assertEqual(m.id, 1)
        self.assertEqual(m.name, 'Mary')
        self.assertTrue(isinstance(m.category, Model))
        self.assertEqual(m.category.id, 1)
        self.assertEqual(m.category.name, 'dog')
Esempio n. 42
0
 def setUpClass(kls):
     kls.app = SwaggerApp.create(get_test_data_folder(
         version='2.0',
         which=os.path.join('io', 'response')
     ))
Esempio n. 43
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(
         get_test_data_folder(version='1.2', which='model_subtypes'))
Esempio n. 44
0
 def setUpClass(kls):
     kls.app = SwaggerApp.create(get_test_data_folder(
         version='2.0',
         which=path.join('render', 'operation')
     ))
     kls.rnd = Renderer()
Esempio n. 45
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(
         get_test_data_folder(version='2.0',
                              which=os.path.join('schema', 'model')))
Esempio n. 46
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(
         get_test_data_folder(version='2.0',
                              which=os.path.join('schema',
                                                 'additionalProperties')))
Esempio n. 47
0
    def setUpClass(kls):
        kls.app = SwaggerApp.load(
            get_test_data_folder(version='2.0', which='bitbucket'))

        # bypass cyclic testing
        kls.app.prepare(strict=False)
Esempio n. 48
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(folder)
Esempio n. 49
0
 def setUpClass(kls):
     kls.app = SwaggerApp.load(
         url="file:///root/swagger.json", url_load_hook=_gen_hook(get_test_data_folder(version="2.0", which="ex"))
     )
     kls.app.prepare()
Esempio n. 50
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(
         get_test_data_folder(version='2.0',
                              which=os.path.join('resolve', 'deref')))
Esempio n. 51
0
from pyswagger import SwaggerApp
from pyswagger.contrib.client.requests import Client
from pyswagger.primitives import Model
from ..utils import get_test_data_folder
import unittest
import httpretty
import json
import pytest
import sys

app = SwaggerApp._create_(
    get_test_data_folder(version='1.2', which='model_subtypes'))
client = Client()

u_mission = dict(id=1, username='******', password='******')
uwi_mary = dict(id=2,
                username='******',
                password='******',
                email='*****@*****.**',
                phone='123')
uwi_kevin = dict(id=3, username='******')


@pytest.mark.skipif(sys.version_info[:2] >= (3, 3),
                    reason='httpretty corrupt in python3')
class ModelInteritanceTestCase(unittest.TestCase):
    """ test cases for model inheritance """
    @httpretty.activate
    def test_inheritantce_full(self):
        """ init a Model with every property along
        the inheritance path.
Esempio n. 52
0
from pyswagger import SwaggerApp, SwaggerSecurity
from ..utils import get_test_data_folder
import unittest


app = SwaggerApp._create_(get_test_data_folder(version='1.2', which='simple_auth')) 


class BasicAuthAndApiKeyTestCase(unittest.TestCase):
    """ test cases for authorzation related """

    def setUp(self):
        self.s = SwaggerSecurity(app)
        self.s.update_with('simple_key', '123456')
        self.s.update_with('simple_basic', ('mission', '123123'))
        self.s.update_with('simple_basic2', ('qoo', '456456'))
        self.s.update_with('simple_key2', '789789')

    def test_deleteUser(self):
        """ basic auth """
        req, _ = app.op['deleteUser'](username='******')
        self.s(req).prepare()

        self.assertTrue('Authorization' in req.header)
        self.assertEqual(req.header['Authorization'], 'Basic bWlzc2lvbjoxMjMxMjM=')

    def test_getUserByName(self):
        """ api key, passed by query """
        req, _ = app.op['getUserByName'](username='******')
        self.s(req).prepare()
Esempio n. 53
0
 def setUpClass(kls):
     kls.app = SwaggerApp._create_(
         get_test_data_folder(version='2.0', which='patch'))
Esempio n. 54
0
from pyswagger import SwaggerApp, SwaggerSecurity
from pyswagger.contrib.client.requests import Client
from pyswagger.utils import jp_compose

# load Swagger resource file into SwaggerApp object
app = SwaggerApp._create_('http://petstore.swagger.io/v2/swagger.json')

auth = SwaggerSecurity(app)
auth.update_with('api_key', '12312312312312312313q')  # api key
auth.update_with('petstore_auth', '12334546556521123fsfss')  # oauth2

# init swagger client
client = Client(auth)

# a dict is enough for representing a Model in Swagger
pet_Tom = dict(id=1, name='Tom', photoUrls=['http://test'])
# a request to create a new pet
client.request(app.op['addPet'](body=pet_Tom))

# - access an Operation object via SwaggerApp.op when operationId is defined
# - a request to get the pet back
pet = client.request(app.op['getPetById'](petId=1)).data
assert pet.id == 1
assert pet.name == 'Tom'

# new ways to get Operation object corresponding to 'getPetById'.
# 'jp_compose' stands for JSON-Pointer composition
pet = client.request(
    app.resolve(jp_compose('/pet/{petId}', base='#/paths')).get(petId=1)).data
assert pet.id == 1