Skip to content

Commit fc0d338

Browse files
mdellwegggainey
authored andcommitted
Use python logging facilities in openapi
1 parent e088ad2 commit fc0d338

4 files changed

Lines changed: 88 additions & 9 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replaced `debug_callback` with python logging facilities.

pulp-glue/pulp_glue/common/openapi.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
33

44
import json
5+
import logging
56
import os
67
import typing as t
78
import warnings
@@ -29,6 +30,7 @@
2930

3031
translation = get_translation(__package__)
3132
_ = translation.gettext
33+
_logger = logging.getLogger("pulp_glue.openapi")
3234

3335
UploadType = t.Union[bytes, t.IO[bytes]]
3436

@@ -176,13 +178,22 @@ def __init__(
176178
safe_calls_only: t.Optional[bool] = None,
177179
):
178180
if validate_certs is not None:
179-
warnings.warn("validate_certs is deprecated; use verify_ssl instead.")
181+
warnings.warn(
182+
"validate_certs is deprecated; use verify_ssl instead.", DeprecationWarning
183+
)
180184
verify_ssl = validate_certs
181185
if safe_calls_only is not None:
182-
warnings.warn("safe_calls_only is deprecated; use dry_run instead.")
186+
warnings.warn("safe_calls_only is deprecated; use dry_run instead.", DeprecationWarning)
183187
dry_run = safe_calls_only
188+
if debug_callback is not None:
189+
warnings.warn(
190+
"debug_callback is deprecated; use logging with level DEBUG instead.",
191+
DeprecationWarning,
192+
)
184193

185-
self._debug_callback: t.Callable[[int, str], t.Any] = debug_callback or (lambda i, x: None)
194+
self._debug_callback: t.Callable[[int, str], t.Any] = debug_callback or (
195+
lambda lvl, msg: _logger.log(logging.DEBUG + 4 - lvl, msg)
196+
)
186197
self._base_url: str = base_url
187198
self._doc_path: str = doc_path
188199
self._dry_run: bool = dry_run
@@ -635,9 +646,10 @@ def call(
635646

636647
if query_params:
637648
qs = urlencode(query_params)
638-
self._debug_callback(1, f"{operation_id} : {method} {url}?{qs}")
649+
log_msg = f"{operation_id} : {method} {url}?{qs}"
639650
else:
640-
self._debug_callback(1, f"{operation_id} : {method} {url}")
651+
log_msg = f"{operation_id} : {method} {url}"
652+
self._debug_callback(1, log_msg)
641653
self._debug_callback(
642654
2, "\n".join([f" {key}=={value}" for key, value in query_params.items()])
643655
)
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import json
2+
import logging
3+
import typing as t
4+
5+
import pytest
6+
7+
from pulp_glue.common.openapi import OpenAPI
8+
9+
TEST_SCHEMA = json.dumps(
10+
{
11+
"openapi": "3.0.3",
12+
"paths": {"test/": {"get": {"operationId": "test_id", "responses": {200: {}}}}},
13+
"components": {"schemas": {}},
14+
}
15+
).encode()
16+
17+
18+
class MockRequest:
19+
headers: t.Dict[str, str] = {}
20+
body: t.Dict[str, t.Any] = {}
21+
22+
23+
class MockResponse:
24+
status_code = 200
25+
headers: t.Dict[str, str] = {}
26+
text = "{}"
27+
content: t.Dict[str, t.Any] = {}
28+
29+
def raise_for_status(self) -> None:
30+
pass
31+
32+
33+
class MockSession:
34+
def prepare_request(self, *args: t.Any, **kwargs: t.Any) -> MockRequest:
35+
return MockRequest()
36+
37+
def send(self, request: MockRequest) -> MockResponse:
38+
return MockResponse()
39+
40+
41+
@pytest.fixture
42+
def openapi(monkeypatch: pytest.MonkeyPatch) -> OpenAPI:
43+
monkeypatch.setattr(OpenAPI, "load_api", lambda self, refresh_cache: TEST_SCHEMA)
44+
openapi = OpenAPI("base_url", "doc_path")
45+
openapi._parse_api(TEST_SCHEMA)
46+
monkeypatch.setattr(openapi, "_session", MockSession())
47+
return openapi
48+
49+
50+
def test_openapi_logs_nothing_from_info(openapi: OpenAPI, caplog: pytest.LogCaptureFixture) -> None:
51+
caplog.set_level(logging.INFO)
52+
openapi.call("test_id")
53+
assert caplog.record_tuples == []
54+
55+
56+
def test_openapi_logs_operation_info_to_debug(
57+
openapi: OpenAPI, caplog: pytest.LogCaptureFixture
58+
) -> None:
59+
caplog.set_level(logging.DEBUG)
60+
openapi.call("test_id")
61+
assert caplog.record_tuples == [
62+
("pulp_glue.openapi", logging.DEBUG + 3, "test_id : get test/"),
63+
("pulp_glue.openapi", logging.DEBUG + 2, ""),
64+
("pulp_glue.openapi", logging.DEBUG + 1, "{}"),
65+
("pulp_glue.openapi", logging.DEBUG + 3, "Response: 200"),
66+
("pulp_glue.openapi", logging.DEBUG + 1, "{}"),
67+
]

pulp_cli/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import sys
34
import typing as t
@@ -208,9 +209,8 @@ def main(
208209
timeout: int,
209210
cid: str,
210211
) -> None:
211-
def _debug_callback(level: int, x: str) -> None:
212-
if verbose >= level:
213-
click.secho(x, err=True, bold=True)
212+
if verbose:
213+
logging.basicConfig(level=logging.DEBUG + 4 - verbose, format="%(message)s")
214214

215215
api_kwargs = dict(
216216
base_url=base_url,
@@ -220,7 +220,6 @@ def _debug_callback(level: int, x: str) -> None:
220220
verify_ssl=verify_ssl,
221221
refresh_cache=refresh_api,
222222
dry_run=dry_run,
223-
debug_callback=_debug_callback,
224223
user_agent=f"Pulp-CLI/{__version__}",
225224
cid=cid,
226225
)

0 commit comments

Comments
 (0)