|
16 | 16 | from pyramid.testing import testConfig |
17 | 17 | from pyramid_openapi3.exceptions import RequestValidationError |
18 | 18 |
|
| 19 | +import json |
19 | 20 | import os |
20 | 21 | import pytest |
21 | 22 | import tempfile |
@@ -126,6 +127,61 @@ def test_add_spec_view() -> None: |
126 | 127 | assert view(request=None, context=None).body == MINIMAL_DOCUMENT |
127 | 128 |
|
128 | 129 |
|
| 130 | +def test_add_spec_view_json_not_served_by_default() -> None: |
| 131 | + """Test that the JSON spec route is not registered unless opted in.""" |
| 132 | + with testConfig() as config: |
| 133 | + config.include("pyramid_openapi3") |
| 134 | + |
| 135 | + with tempfile.NamedTemporaryFile() as document: |
| 136 | + document.write(MINIMAL_DOCUMENT) |
| 137 | + document.seek(0) |
| 138 | + |
| 139 | + config.pyramid_openapi3_spec( |
| 140 | + document.name, route="/foo.yaml", route_name="foo_api_spec" |
| 141 | + ) |
| 142 | + |
| 143 | + # no route registered for the (guessed) json variant |
| 144 | + route_request = config.registry.queryUtility( |
| 145 | + IRouteRequest, name="foo_api_spec_json" |
| 146 | + ) |
| 147 | + assert route_request is None |
| 148 | + |
| 149 | + |
| 150 | +def test_add_spec_view_json() -> None: |
| 151 | + """Test registration of a view that serves the openapi document as JSON.""" |
| 152 | + with testConfig() as config: |
| 153 | + config.include("pyramid_openapi3") |
| 154 | + |
| 155 | + with tempfile.NamedTemporaryFile() as document: |
| 156 | + document.write(MINIMAL_DOCUMENT) |
| 157 | + document.seek(0) |
| 158 | + |
| 159 | + config.pyramid_openapi3_spec( |
| 160 | + document.name, |
| 161 | + route="/foo.yaml", |
| 162 | + route_name="foo_api_spec", |
| 163 | + route_json="/foo.json", |
| 164 | + ) |
| 165 | + |
| 166 | + # assert route |
| 167 | + mapper = config.registry.getUtility(IRoutesMapper) |
| 168 | + routes = mapper.get_routes() |
| 169 | + assert routes[1].name == "foo_api_spec_json" |
| 170 | + assert routes[1].path == "/foo.json" |
| 171 | + |
| 172 | + # assert view |
| 173 | + request = config.registry.queryUtility( |
| 174 | + IRouteRequest, name="foo_api_spec_json" |
| 175 | + ) |
| 176 | + view = config.registry.adapters.registered( |
| 177 | + (IViewClassifier, request, Interface), IView, name="" |
| 178 | + ) |
| 179 | + response = view(request=None, context=None) |
| 180 | + assert response.content_type == "application/json" |
| 181 | + spec = config.registry.settings["pyramid_openapi3"]["spec"] |
| 182 | + assert json.loads(response.body) == spec.read_value() |
| 183 | + |
| 184 | + |
129 | 185 | def test_add_spec_view_already_defined() -> None: |
130 | 186 | """Test that creating a spec more than once raises an Exception.""" |
131 | 187 | with testConfig() as config: |
|
0 commit comments