Skip to content

Commit

Permalink
Use verbose property for logging setup
Browse files Browse the repository at this point in the history
  • Loading branch information
bhrutledge committed Jul 9, 2020
1 parent 8eabc53 commit 1fd2f58
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 51 deletions.
48 changes: 19 additions & 29 deletions tests/test_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -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"
Expand All @@ -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):
Expand All @@ -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",
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down
28 changes: 14 additions & 14 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand All @@ -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(
Expand Down
20 changes: 12 additions & 8 deletions twine/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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."""
Expand Down

0 comments on commit 1fd2f58

Please sign in to comment.