def test_schema_construction(self):
        """Construction of the top level dictionary."""
        patterns = [
            url(r'^example/?$', views.ExampleListView.as_view()),
        ]
        generator = SchemaGenerator(patterns=patterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)

        assert 'openapi' in schema
        assert 'paths' in schema
Example #2
0
    def test_repeat_operation_ids(self):
        router = routers.SimpleRouter()
        router.register('account', views.ExampleGenericViewSet, basename="account")
        urlpatterns = router.urls

        generator = SchemaGenerator(patterns=urlpatterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)
        schema_str = str(schema)
        print(schema_str)
        assert schema_str.count("operationId") == 2
        assert schema_str.count("newExample") == 1
        assert schema_str.count("oldExample") == 1
    def test_component_name(self):
        patterns = [
            path('example/', views.ExampleAutoSchemaComponentName.as_view()),
        ]

        generator = SchemaGenerator(patterns=patterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)

        print(schema)
        assert 'components' in schema
        assert 'schemas' in schema['components']
        assert 'Ulysses' in schema['components']['schemas']
    def test_repeat_operation_ids(self):
        router = routers.SimpleRouter()
        router.register('account', views.ExampleGenericViewSet, basename="account")
        urlpatterns = router.urls

        generator = SchemaGenerator(patterns=urlpatterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)
        schema_str = str(schema)
        print(schema_str)
        assert schema_str.count("operationId") == 2
        assert schema_str.count("newExample") == 1
        assert schema_str.count("oldExample") == 1
Example #5
0
def WebSchemaAPIView(request):
    """
    Use SchemaGenerator to generate Zubhub Web API Schema instead of get_schema_view.

    this is neccessary because `get_schema_view` somehow ignores 
    some api endpoints even when told to generate schema for those.
    Returns Web API schema.
    """

    from rest_framework.schemas.openapi import SchemaGenerator
    from .urls import schema_url_patterns

    generator = SchemaGenerator(title='Zubhub Web Server API', patterns=schema_url_patterns)

    return Response(generator.get_schema())
Example #6
0
 def generateSchema():
     generator = SchemaGenerator(title="Experimenter API")
     schema = generator.get_schema()
     paths = schema["paths"]
     for path in paths:
         if "/api/v1/" in path:
             for method in paths[path]:
                 paths[path][method]["tags"] = ["Core: Public"]
         elif "/api/v2/" in path:
             for method in paths[path]:
                 paths[path][method]["tags"] = ["Core: Private"]
         elif "/api/v3/" in path:
             for method in paths[path]:
                 paths[path][method]["tags"] = ["Rapid: Private"]
     return json.dumps(schema, indent=2)
    def test_paths_construction(self):
        """Construction of the `paths` key."""
        patterns = [
            url(r'^example/?$', views.ExampleListView.as_view()),
        ]
        generator = SchemaGenerator(patterns=patterns)
        generator._initialise_endpoints()

        paths = generator.get_paths()

        assert '/example/' in paths
        example_operations = paths['/example/']
        assert len(example_operations) == 2
        assert 'get' in example_operations
        assert 'post' in example_operations
Example #8
0
    def test_paths_construction(self):
        """Construction of the `paths` key."""
        patterns = [
            url(r'^example/?$', views.ExampleListView.as_view()),
        ]
        generator = SchemaGenerator(patterns=patterns)
        generator._initialise_endpoints()

        paths = generator.get_paths()

        assert '/example/' in paths
        example_operations = paths['/example/']
        assert len(example_operations) == 2
        assert 'get' in example_operations
        assert 'post' in example_operations
Example #9
0
    def test_auto_generated_apiview_tags(self):
        class RestaurantAPIView(views.ExampleGenericAPIView):
            pass

        class BranchAPIView(views.ExampleGenericAPIView):
            pass

        url_patterns = [
            url(r'^any-dash_underscore/?$', RestaurantAPIView.as_view()),
            url(r'^restaurants/branches/?$', BranchAPIView.as_view())
        ]
        generator = SchemaGenerator(patterns=url_patterns)
        schema = generator.get_schema(request=create_request('/'))
        assert schema['paths']['/any-dash_underscore/']['get']['tags'] == ['any-dash-underscore']
        assert schema['paths']['/restaurants/branches/']['get']['tags'] == ['restaurants']
    def test_schema_information(self):
        """Construction of the top level dictionary."""
        patterns = [
            url(r'^example/?$', views.ExampleListView.as_view()),
        ]
        generator = SchemaGenerator(patterns=patterns,
                                    title='My title',
                                    version='1.2.3',
                                    description='My description')

        request = create_request('/')
        schema = generator.get_schema(request=request)

        assert schema['info']['title'] == 'My title'
        assert schema['info']['version'] == '1.2.3'
        assert schema['info']['description'] == 'My description'
    def test_operation_id_viewset(self):
        router = routers.SimpleRouter()
        router.register('account', views.ExampleViewSet, basename="account")
        urlpatterns = router.urls

        generator = SchemaGenerator(patterns=urlpatterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)
        print(schema)
        assert schema['paths']['/account/']['get']['operationId'] == 'listExampleViewSets'
        assert schema['paths']['/account/']['post']['operationId'] == 'createExampleViewSet'
        assert schema['paths']['/account/{id}/']['get']['operationId'] == 'retrieveExampleViewSet'
        assert schema['paths']['/account/{id}/']['put']['operationId'] == 'updateExampleViewSet'
        assert schema['paths']['/account/{id}/']['patch']['operationId'] == 'partialUpdateExampleViewSet'
        assert schema['paths']['/account/{id}/']['delete']['operationId'] == 'destroyExampleViewSet'
    def test_serializer_model(self):
        """Construction of the top level dictionary."""
        patterns = [
            url(r'^example/?$', views.ExampleGenericAPIViewModel.as_view()),
        ]

        generator = SchemaGenerator(patterns=patterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)

        print(schema)

        assert 'components' in schema
        assert 'schemas' in schema['components']
        assert 'ExampleModel' in schema['components']['schemas']
Example #13
0
def test_api_auto_genereation():
    openapi_schema = SchemaGenerator().get_schema()

    assert '/books/' in openapi_schema['paths']
    parameters = openapi_schema['paths']['/books/']['get']['parameters']
    assert len(parameters) > 10
    assert parameters[0]['name'] == 'limit'
    assert parameters[0]['schema'] == {'type': 'integer'}
    assert parameters[1]['name'] == 'offset'
    assert parameters[1]['schema'] == {'type': 'integer'}
    assert parameters[2]['name'] == 'amazon_rating'

    assert '/nofiltercls/' in openapi_schema['paths']

    assert '/books/{id}/' not in openapi_schema['paths']

    assert '/books/{id}/act/' in openapi_schema['paths']
    parameters = openapi_schema['paths']['/books/{id}/act/']['get'][
        'parameters']
    assert len(parameters) == 1
    assert parameters[0]['name'] == 'id'

    assert '/select/{id}/' in openapi_schema['paths']
    parameters = openapi_schema['paths']['/select/{id}/']['get']['parameters']
    assert len(parameters) == 1
    assert parameters[0]['name'] == 'id'

    assert '/old_books/{id}/' in openapi_schema['paths']
    get_parameters = openapi_schema['paths']['/old_books/{id}/']['get'][
        'parameters']
    assert len(get_parameters) > 10
    put_parameters = openapi_schema['paths']['/old_books/{id}/']['put'][
        'parameters']
    assert len(put_parameters) == 1
    assert put_parameters[0]['name'] == 'id'
    def test_serializer_datefield(self):
        patterns = [
            url(r'^example/?$', views.ExampleGenericViewSet.as_view({"get": "get"})),
        ]
        generator = SchemaGenerator(patterns=patterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)

        response = schema['paths']['/example/']['get']['responses']
        response_schema = response['200']['content']['application/json']['schema']['properties']

        assert response_schema['date']['type'] == response_schema['datetime']['type'] == 'string'

        assert response_schema['date']['format'] == 'date'
        assert response_schema['datetime']['format'] == 'date-time'
    def test_duplicate_operation_id(self):
        patterns = [
            path('duplicate1/', views.ExampleOperationIdDuplicate1.as_view()),
            path('duplicate2/', views.ExampleOperationIdDuplicate2.as_view()),
        ]

        generator = SchemaGenerator(patterns=patterns)
        request = create_request('/')

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            generator.get_schema(request=request)

            assert len(w) == 1
            assert issubclass(w[-1].category, UserWarning)
            print(str(w[-1].message))
            assert 'You have a duplicated operationId' in str(w[-1].message)
Example #16
0
    def test_serializer_datefield(self):
        patterns = [
            url(r'^example/?$',
                views.ExampleGenericViewSet.as_view({"get": "get"})),
        ]
        generator = SchemaGenerator(patterns=patterns)

        request = create_request('/')
        schema = generator.get_schema(request=request)

        response = schema['paths']['/example/']['get']['responses']
        response_schema = response['200']['content']['application/json'][
            'schema']['properties']

        assert response_schema['date']['type'] == response_schema['datetime'][
            'type'] == 'string'

        assert response_schema['date']['format'] == 'date'
        assert response_schema['datetime']['format'] == 'date-time'
    def test_duplicate_component_name(self):
        patterns = [
            path('duplicate1/', views.ExampleAutoSchemaDuplicate1.as_view()),
            path('duplicate2/', views.ExampleAutoSchemaDuplicate2.as_view()),
        ]

        generator = SchemaGenerator(patterns=patterns)
        request = create_request('/')

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            schema = generator.get_schema(request=request)

            assert len(w) == 1
            assert issubclass(w[-1].category, UserWarning)
            assert 'has been overriden with a different value.' in str(w[-1].message)

        assert 'components' in schema
        assert 'schemas' in schema['components']
        assert 'Duplicate' in schema['components']['schemas']
Example #18
0
    def test_overridden_get_tags_method(self):
        class MySchema(AutoSchema):
            def get_tags(self, path, method):
                if path.endswith('/new/'):
                    tags = ['tag1', 'tag2']
                elif path.endswith('/old/'):
                    tags = ['tag2', 'tag3']
                else:
                    tags = ['tag4', 'tag5']

                return tags

        class ExampleStringTagsViewSet(views.ExampleGenericViewSet):
            schema = MySchema()

        router = routers.SimpleRouter()
        router.register('example', ExampleStringTagsViewSet, basename="example")
        generator = SchemaGenerator(patterns=router.urls)
        schema = generator.get_schema(request=create_request('/'))
        assert schema['paths']['/example/new/']['get']['tags'] == ['tag1', 'tag2']
        assert schema['paths']['/example/old/']['get']['tags'] == ['tag2', 'tag3']
Example #19
0
    def handle(self, *args, **options):

        # the location where the markdown and other files live
        docs_dir = os.path.join(os.path.dirname(settings.MAIN_DOC_YAML),
                                'docs')

        if options['site_dir']:
            site_dir = options['site_dir']
        else:
            site_dir = os.path.join(os.path.dirname(settings.MAIN_DOC_YAML),
                                    'site')

        kwargs = {'config_file': settings.MAIN_DOC_YAML, 'site_dir': site_dir}

        # build docs
        build.build(mkdocs_config.load_config(**kwargs), dirty=False)

        # generate the openAPI spec:
        generator = SchemaGenerator(title='WebMEV REST API Specification')
        schema = generator.get_schema(request=None, public=True)
        renderer = JSONOpenAPIRenderer()
        output = renderer.render(schema, renderer_context={})
        with open(os.path.join(site_dir, 'openapi_spec.json'), 'w') as fout:
            fout.write(output.decode())

        # add the information relevant for the commit/push
        kwargs['remote_name'] = options['remote_name']
        kwargs['remote_branch'] = options['remote_branch']

        # due to the way config info is accessed from within the mkdocs gh_deploy
        # function below, it needs both dict-like access and attribute-like access
        # UserDict fits that bill
        config = UserDict(kwargs)
        config.config_file_path = settings.MAIN_DOC_YAML

        if options['push']:
            gh_deploy.gh_deploy(config, message=options['message'])
Example #20
0
 def introspect(self, request):
     """
     description = ActionProviderDescription(
     globus_auth_scope=config.our_scope,
     title="What Time Is It Right Now?",
     admin_contact="*****@*****.**",
     synchronous=False,
     input_schema=schema,
     api_version="1.0",
     subtitle=(
         "From the makers of Philbert: "
         "Another exciting promotional tie-in for whattimeisitrightnow.com"
     ),
     description="",
     keywords=["time", "whattimeisitnow", "productivity"],
     visible_to=["all_authenticated_users"],
     runnable_by=["all_authenticated_users"],
     administered_by=["*****@*****.**"],
     )
     """
     # Generate a path based on the standard automate URLs above
     patterns = [path(request.path, include(self.urls()))]
     generator = SchemaGenerator(patterns=patterns)
     return Response(generator.get_schema())
Example #21
0
class PersonViewSet(GenericViewSet):
    """사람 ViewSet."""

    http_method_names = ["get", "post"]
    generator = SchemaGenerator(title="Person API")
    schema = CustomSchema

    queryset = Person.objects.all()
    serializer_class = PersonSerializer
    swagger_schema = MyAutoSchema

    def list(self, request, *args, **kwargs):
        """Get Request 에 대응."""
        return Response("Hello")

    @swagger_auto_schema(responses={404: "slug not found"})
    def create(self, request, *args, **kwargs):
        """Post Request 에 대응."""
        return Response("hi")

    @action(detail=False, methods=["post"], schema=None)
    def hi_there(self):
        """커스텀 연산."""
        pass
def create_view(view_cls, method, request):
    generator = SchemaGenerator()
    view = generator.create_view(view_cls.as_view(), method, request)
    return view
Example #23
0
def create_view(view_cls, method, request):
    generator = SchemaGenerator()
    view = generator.create_view(view_cls.as_view(), method, request)
    return view