Skip to content

Commit

Permalink
Updated spec_url to allow for file in root, without a path prefix, wh…
Browse files Browse the repository at this point in the history
…en Configuration path set to None.

Also made spec_url more resilient to path and filename values with leading/trailing slashes.
  • Loading branch information
gdub committed Apr 19, 2023
1 parent 78edc00 commit 21de0a4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
7 changes: 5 additions & 2 deletions spectree/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import posixpath
import warnings
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union
Expand Down Expand Up @@ -65,7 +66,7 @@ class Configuration(BaseSettings):
license: Optional[License] = None

# SpecTree configurations
#: OpenAPI doc route path prefix (i.e. /apidoc/)
#: OpenAPI doc route path prefix (i.e. /apidoc/) or empty string for no path prefix.
path: str = "apidoc"
#: OpenAPI file route path suffix (i.e. /apidoc/openapi.json)
filename: str = "openapi.json"
Expand Down Expand Up @@ -117,7 +118,9 @@ def convert_to_lower_case(cls, values: Mapping[str, Any]) -> Dict[str, Any]:

@property
def spec_url(self) -> str:
return f"/{self.path}/{self.filename}"
sep = posixpath.sep
parts = (sep, self.path.lstrip(sep), self.filename.lstrip(sep))
return posixpath.join(*parts)

def swagger_oauth2_config(self) -> Dict[str, str]:
"""
Expand Down
22 changes: 22 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ def test_config_case():
assert config.title == "Demo"


@pytest.mark.parametrize("filename", ["openapi.json", "/openapi.json"])
@pytest.mark.parametrize("path", ["", "/"])
def test_config_spec_url_when_given_empty_path(path, filename):
"""
Test spec_url given empty path values and filename values with and
without leading slash.
"""
config = Configuration(path=path, filename=filename)
assert config.spec_url == "/openapi.json"


@pytest.mark.parametrize("filename", ["openapi.json", "/openapi.json"])
@pytest.mark.parametrize("path", ["prefix", "/prefix", "prefix/", "/prefix/"])
def test_config_spec_url_when_given_path_and_filename(path, filename):
"""
Test spec_url given path and filename values with and without
leading/trailing slashes.
"""
config = Configuration(path=path, filename=filename)
assert config.spec_url == "/prefix/openapi.json"


@pytest.mark.parametrize(("secure_item"), SECURITY_SCHEMAS)
def test_update_security_scheme(secure_item: Type[SecurityScheme]):
# update and validate each schema type
Expand Down

0 comments on commit 21de0a4

Please sign in to comment.