From 21de0a42e74914d8b7fb39f9afc0fd21b66d52c1 Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Tue, 18 Apr 2023 21:17:11 -0500 Subject: [PATCH] Updated spec_url to allow for file in root, without a path prefix, when Configuration path set to None. Also made spec_url more resilient to path and filename values with leading/trailing slashes. --- spectree/config.py | 7 +++++-- tests/test_config.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/spectree/config.py b/spectree/config.py index 0e0bfd06..bc981d70 100644 --- a/spectree/config.py +++ b/spectree/config.py @@ -1,3 +1,4 @@ +import posixpath import warnings from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union @@ -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" @@ -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]: """ diff --git a/tests/test_config.py b/tests/test_config.py index 17cfb4f8..208222cb 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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