Example #1
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()
        ), [])
Example #2
0
 def test_random_name_v2_0(self):
     """
     """
     path = get_test_data_folder(version='2.0', which='random_file_name')
     path = os.path.join(path, 'test_random.json')
     # should not raise ValueError
     app = SwaggerApp.create(path)
Example #3
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)
Example #4
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, {})
Example #5
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)
Example #6
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)),
            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)
Example #7
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)
Example #8
0
 def test_empty_operation_id(self):
     """ when operationId is empty, should not raise SchemaError """
     try:
         app = SwaggerApp.create(
             get_test_data_folder(version="2.0",
                                  which=os.path.join("schema", "emptyOp")))
     except errs.SchemaError:
         self.fail(
             "SchemaError is raised when 'operationId' is empty and 'tags' is not"
         )
Example #9
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)
Example #10
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)
Example #11
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, {})
Example #12
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')
Example #13
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')
Example #14
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()), [])
Example #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)
Example #16
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()), [])
Example #17
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")]]
            ),
        )
Example #18
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))
Example #19
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))
Example #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()), [])
Example #21
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()
        ), [])
Example #22
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')
            ]]))
Example #23
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()),
            [])
Example #24
0
 def setUpClass(kls):
     kls.app = SwaggerApp.create(get_test_data_folder(
         version='2.0',
         which=os.path.join('io', 'response')
     ))
Example #25
0
 def setUpClass(kls):
     kls.app = SwaggerApp.create(get_test_data_folder(
         version='2.0',
         which=os.path.join('io', 'response')
     ))
Example #26
0
 def setUpClass(kls):
     kls.app = SwaggerApp.create(get_test_data_folder(
         version='2.0',
         which=path.join('render', 'operation')
     ))
     kls.rnd = Renderer()
Example #27
0
 def test_empty_operation_id(self):
     """ when operationId is empty, should not raise SchemaError """
     try:
         app = SwaggerApp.create(get_test_data_folder(version="2.0", which=os.path.join("schema", "emptyOp")))
     except errs.SchemaError:
         self.fail("SchemaError is raised when 'operationId' is empty and 'tags' is not")