From 1fd2f5838de8f5c41532dff34fcb0732d89d6093 Mon Sep 17 00:00:00 2001 From: Brian Rutledge Date: Thu, 9 Jul 2020 05:49:35 -0400 Subject: [PATCH] Use verbose property for logging setup --- tests/test_upload.py | 48 ++++++++++++++++++-------------------------- tests/test_utils.py | 28 +++++++++++++------------- twine/settings.py | 20 ++++++++++-------- 3 files changed, 45 insertions(+), 51 deletions(-) diff --git a/tests/test_upload.py b/tests/test_upload.py index bd70fd22..6ef7c19b 100644 --- a/tests/test_upload.py +++ b/tests/test_upload.py @@ -11,7 +11,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import logging import os import pretend @@ -55,13 +54,7 @@ def upload_settings(make_settings, stub_repository): return upload_settings -@pytest.fixture -def caplog(caplog): - caplog.set_level(logging.INFO, logger="twine") - return caplog - - -def test_make_package_pre_signed_dist(upload_settings, caplog): +def test_make_package_pre_signed_dist(upload_settings, capsys): """Create a PackageFile and print path, size, and user-provided signature.""" filename = helpers.WHEEL_FIXTURE expected_size = "15.4 KB" @@ -76,12 +69,12 @@ def test_make_package_pre_signed_dist(upload_settings, caplog): assert package.filename == filename assert package.gpg_signature is not None - captured = caplog.text - assert captured.count(f"{filename} ({expected_size})") == 1 - assert captured.count(f"Signed with {signed_filename}") == 1 + captured = capsys.readouterr() + assert captured.out.count(f"{filename} ({expected_size})") == 1 + assert captured.out.count(f"Signed with {signed_filename}") == 1 -def test_make_package_unsigned_dist(upload_settings, monkeypatch, caplog): +def test_make_package_unsigned_dist(upload_settings, monkeypatch, capsys): """Create a PackageFile and print path, size, and Twine-generated signature.""" filename = helpers.NEW_WHEEL_FIXTURE expected_size = "21.9 KB" @@ -100,9 +93,9 @@ def stub_sign(package, *_): assert package.filename == filename assert package.gpg_signature is not None - captured = caplog.text - assert captured.count(f"{filename} ({expected_size})") == 1 - assert captured.count(f"Signed with {package.signed_filename}") == 1 + captured = capsys.readouterr() + assert captured.out.count(f"{filename} ({expected_size})") == 1 + assert captured.out.count(f"Signed with {package.signed_filename}") == 1 def test_successs_prints_release_urls(upload_settings, stub_repository, capsys): @@ -125,7 +118,7 @@ def test_successs_prints_release_urls(upload_settings, stub_repository, capsys): assert captured.out.count(NEW_RELEASE_URL) == 1 -def test_print_packages_if_verbose(upload_settings, caplog): +def test_print_packages_if_verbose(upload_settings, capsys): """Print the path and file size of each distribution attempting to be uploaded.""" dists_to_upload = { helpers.WHEEL_FIXTURE: "15.4 KB", @@ -136,14 +129,13 @@ def test_print_packages_if_verbose(upload_settings, caplog): upload_settings.verbose = True - result = upload.upload(upload_settings, dists_to_upload) - + result = upload.upload(upload_settings, dists_to_upload.keys()) assert result is None - captured = caplog.text + captured = capsys.readouterr() for filename, size in dists_to_upload.items(): - assert captured.count(f"{filename} ({size})") == 1 + assert captured.out.count(f"{filename} ({size})") == 1 def test_success_with_pre_signed_distribution(upload_settings, stub_repository): @@ -189,10 +181,8 @@ def test_success_when_gpg_is_run(upload_settings, stub_repository, monkeypatch): @pytest.mark.parametrize("verbose", [False, True]) -def test_exception_for_http_status(verbose, upload_settings, stub_response, caplog): +def test_exception_for_http_status(verbose, upload_settings, stub_response, capsys): upload_settings.verbose = verbose - log_level = logging.INFO if verbose else logging.WARNING - caplog.set_level(log_level, logger="twine") stub_response.is_redirect = False stub_response.status_code = 403 @@ -202,15 +192,15 @@ def test_exception_for_http_status(verbose, upload_settings, stub_response, capl with pytest.raises(requests.HTTPError): upload.upload(upload_settings, [helpers.WHEEL_FIXTURE]) - captured = caplog.text - assert RELEASE_URL not in captured + captured = capsys.readouterr() + assert RELEASE_URL not in captured.out if verbose: - assert stub_response.text in captured - assert "--verbose" not in captured + assert stub_response.text in captured.out + assert "--verbose" not in captured.out else: - assert stub_response.text not in captured - assert "--verbose" in captured + assert stub_response.text not in captured.out + assert "--verbose" in captured.out def test_get_config_old_format(make_settings, pypirc): diff --git a/tests/test_utils.py b/tests/test_utils.py index 75960cb8..e6d890eb 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -import logging + import os.path import textwrap @@ -273,7 +273,12 @@ def test_check_status_code_for_deprecated_pypi_url(repo_url): @pytest.mark.parametrize( "repo_url", ["https://pypi.python.org", "https://testpypi.python.org"], ) -def test_check_status_code_for_missing_status_code(caplog, repo_url): +@pytest.mark.parametrize( + "verbose", [True, False], +) +def test_check_status_code_for_missing_status_code( + capsys, repo_url, verbose, make_settings +): """Print HTTP errors based on verbosity level.""" response = pretend.stub( status_code=403, @@ -282,22 +287,17 @@ def test_check_status_code_for_missing_status_code(caplog, repo_url): text="Forbidden", ) - caplog.set_level(logging.INFO, logger="twine") + make_settings(verbose=verbose) with pytest.raises(requests.HTTPError): - utils.check_status_code(response, True) - - # Different messages are printed based on the verbose level - captured = caplog.text - assert "Content received from server:\nForbidden\n" in captured + utils.check_status_code(response, verbose) - caplog.set_level(logging.WARNING, logger="twine") - - with pytest.raises(requests.HTTPError): - utils.check_status_code(response, False) + captured = capsys.readouterr() - captured = caplog.text - assert "NOTE: Try --verbose to see response content.\n" in captured + if verbose: + assert captured.out == "Content received from server:\nForbidden\n" + else: + assert captured.out == "NOTE: Try --verbose to see response content.\n" @pytest.mark.parametrize( diff --git a/twine/settings.py b/twine/settings.py index 45d258ac..73d4608c 100644 --- a/twine/settings.py +++ b/twine/settings.py @@ -25,13 +25,6 @@ from twine import utils -def _setup_logging(verbose: bool) -> None: - """Initialize a logger based on the --verbose option.""" - root_logger = logging.getLogger("twine") - root_logger.addHandler(logging.StreamHandler(sys.stdout)) - root_logger.setLevel(logging.INFO if verbose else logging.WARNING) - - class Settings: """Object that manages the configuration for Twine. @@ -130,7 +123,6 @@ def __init__( self.config_file = config_file self.comment = comment self.verbose = verbose - _setup_logging(verbose) self.disable_progress_bar = disable_progress_bar self.skip_existing = skip_existing self._handle_repository_options( @@ -158,6 +150,18 @@ def password(self) -> Optional[str]: # Workaround for https://github.com/python/mypy/issues/5858 return cast(Optional[str], self.auth.password) + @property + def verbose(self) -> bool: + return self._verbose + + @verbose.setter + def verbose(self, verbose: bool) -> None: + """Initialize a logger based on the --verbose option.""" + self._verbose = verbose + root_logger = logging.getLogger("twine") + root_logger.addHandler(logging.StreamHandler(sys.stdout)) + root_logger.setLevel(logging.INFO if verbose else logging.WARNING) + @staticmethod def register_argparse_arguments(parser: argparse.ArgumentParser) -> None: """Register the arguments for argparse."""