Skip to content

Commit abb4c3c

Browse files
committed
cleanup, no warn on tests
1 parent e38a5bd commit abb4c3c

File tree

10 files changed

+83
-51
lines changed

10 files changed

+83
-51
lines changed

cloudsmith_cli/cli/commands/main.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
"""Main command/entrypoint."""
22

3+
from functools import partial
4+
35
import click
46

7+
from cloudsmith_cli.cli import config
58
from cloudsmith_cli.cli.warnings import get_or_create_warnings
69

710
from ...core.api.version import get_version as get_api_version
@@ -53,12 +56,22 @@ def print_version():
5356
is_flag=True,
5457
is_eager=True,
5558
)
59+
@click.option(
60+
"--no-warn",
61+
help="Don't display auth or config warnings",
62+
envvar="CLOUDSMITH_CLI_NO_WARN",
63+
is_flag=True,
64+
default=None,
65+
)
5666
@decorators.common_cli_config_options
5767
@click.pass_context
58-
def main(ctx, opts, version):
68+
def main(ctx, opts, version, no_warn):
5969
"""Handle entrypoint to CLI."""
6070
# pylint: disable=unused-argument
6171

72+
if no_warn:
73+
opts.no_warn = True
74+
6275
if version:
6376
print_version()
6477
elif ctx.invoked_subcommand is None:
@@ -67,9 +80,12 @@ def main(ctx, opts, version):
6780

6881
@main.result_callback()
6982
@click.pass_context
70-
def result_callback(ctx, opts, **kwargs):
83+
def result_callback(ctx, _, **kwargs):
7184
"""Callback for main function. Required for saving warnings til the end."""
7285

7386
warnings = get_or_create_warnings(ctx)
74-
if warnings:
75-
click.echo(warnings.report())
87+
opts = config.get_or_create_options(ctx)
88+
89+
if warnings and not opts.no_warn:
90+
click_warn_partial = partial(click.secho, fg="yellow")
91+
warnings.display(click_warn_partial)

cloudsmith_cli/cli/config.py

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ class ConfigReader(ConfigFileReader):
7979
config_name = "standard"
8080
config_searchpath = list(_CFG_SEARCH_PATHS)
8181
config_section_schemas = [ConfigSchema.Default, ConfigSchema.Profile]
82-
config_warning_issued = False
8382

8483
@classmethod
8584
def select_config_schema_for(cls, section_name):
@@ -150,19 +149,6 @@ def has_default_file(cls):
150149

151150
return False
152151

153-
@classmethod
154-
def config_already_warned(cls):
155-
"""
156-
Check if a configuration file warning has been issued.
157-
This is required as configs are gathered at the root of the
158-
command chain as well as for command verbs
159-
"""
160-
if cls.config_warning_issued:
161-
return True
162-
163-
cls.config_warning_issued = True
164-
return False
165-
166152
@classmethod
167153
def load_config(cls, opts, path=None, warnings=None, profile=None):
168154
"""Load a configuration file into an options object."""
@@ -176,18 +162,20 @@ def load_config(cls, opts, path=None, warnings=None, profile=None):
176162
config = cls.read_config()
177163
values = config.get("default", {})
178164
cls._load_values_into_opts(opts, values)
165+
existing_config_paths = {
166+
path: os.path.exists(path) for path in cls.config_files
167+
}
179168

180169
if profile and profile != "default":
181170
try:
182171
values = config["profile:%s" % profile]
183172
cls._load_values_into_opts(opts, values)
184173
except KeyError:
185-
warning = ProfileNotFoundWarning(path=path, profile=profile)
174+
warning = ProfileNotFoundWarning(
175+
paths=existing_config_paths, profile=profile
176+
)
186177
warnings.append(warning)
187178

188-
existing_config_paths = {
189-
path: os.path.exists(path) for path in cls.config_files
190-
}
191179
if not any(list(existing_config_paths.values())):
192180
config_load_warning = ConfigLoadWarning(
193181
paths=existing_config_paths,
@@ -283,13 +271,11 @@ def get_creds_reader():
283271

284272
def load_config_file(self, path, warnings=None, profile=None):
285273
"""Load the standard config file."""
286-
print("load_config_file")
287274
config_cls = self.get_config_reader()
288275
return config_cls.load_config(self, path, warnings=warnings, profile=profile)
289276

290277
def load_creds_file(self, path, warnings=None, profile=None):
291278
"""Load the credentials config file."""
292-
print("load_creds_file")
293279
config_cls = self.get_creds_reader()
294280
return config_cls.load_config(self, path, warnings=warnings, profile=profile)
295281

cloudsmith_cli/cli/tests/commands/policy/test_licence.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,9 @@ def assert_output_matches_policy_config(output, config_file_path):
8585
return output_table["Identifier"]
8686

8787

88-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
88+
@pytest.mark.usefixtures(
89+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
90+
)
8991
def test_license_policy_commands(runner, organization, tmp_path):
9092
"""Test CRUD operations for license policies."""
9193

cloudsmith_cli/cli/tests/commands/policy/test_vulnerability.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ def assert_output_matches_policy_config(output, config_file_path):
8787
return output_table["Identifier"]
8888

8989

90-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
90+
@pytest.mark.usefixtures(
91+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
92+
)
9193
def test_vulnerability_policy_commands(runner, organization, tmp_path):
9294
"""Test CRUD operations for vulnerability policies."""
9395

cloudsmith_cli/cli/tests/commands/test_main.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@
66

77

88
class TestMainCommand:
9+
@pytest.mark.usefixtures("set_no_warn_env_var")
910
@pytest.mark.parametrize("option", ["-V", "--version"])
1011
def test_main_version(self, runner, option):
1112
"""Test the output of `cloudsmith --version`."""
1213
result = runner.invoke(main, [option])
1314
assert result.exit_code == 0
14-
15-
assert "CLI Package Version: " + get_version() in result.output
16-
assert "API Package Version: " + get_api_version() in result.output
15+
assert (
16+
result.output == "Versions:\n"
17+
"CLI Package Version: " + get_version() + "\n"
18+
"API Package Version: " + get_api_version() + "\n"
19+
)
1720

1821
@pytest.mark.parametrize("option", ["-h", "--help"])
1922
def test_main_help(self, runner, option):

cloudsmith_cli/cli/tests/commands/test_package_commands.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
from ..utils import random_str
1212

1313

14-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
14+
@pytest.mark.usefixtures(
15+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
16+
)
1517
@pytest.mark.parametrize(
1618
"filesize",
1719
[
@@ -80,7 +82,9 @@ def test_push_and_delete_raw_package(
8082
assert len(data) == 0
8183

8284

83-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
85+
@pytest.mark.usefixtures(
86+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
87+
)
8488
def test_list_packages_with_sort(runner, organization, tmp_repository, tmp_path):
8589
"""Test listing packages with different sort options."""
8690
org_repo = f'{organization}/{tmp_repository["slug"]}'

cloudsmith_cli/cli/tests/commands/test_repos.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ def assert_output_is_equal_to_repo_config(output, organisation, repo_config_file
7272
)
7373

7474

75-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
75+
@pytest.mark.usefixtures(
76+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
77+
)
7678
def test_repos_commands(runner, organization, tmp_path):
7779
"""Test CRUD operations for repositories."""
7880

cloudsmith_cli/cli/tests/commands/test_upstream.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
from ..utils import random_str
77

88

9-
@pytest.mark.usefixtures("set_api_key_env_var", "set_api_host_env_var")
9+
@pytest.mark.usefixtures(
10+
"set_api_key_env_var", "set_api_host_env_var", "set_no_warn_env_var"
11+
)
1012
@pytest.mark.parametrize("upstream_format", UPSTREAM_FORMATS)
1113
def test_upstream_commands(
1214
runner, organization, upstream_format, tmp_repository, tmp_path

cloudsmith_cli/cli/tests/conftest.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,9 @@ def set_api_host_env_var(api_host):
7373
def set_api_key_env_var(api_key):
7474
"""Set the CLOUDSMITH_API_KEY environment variable."""
7575
os.environ["CLOUDSMITH_API_KEY"] = api_key
76+
77+
78+
@pytest.fixture()
79+
def set_no_warn_env_var():
80+
"""Set the CLOUDSMITH_API_KEY environment variable."""
81+
os.environ["CLOUDSMITH_CLI_NO_WARN"] = "True"

cloudsmith_cli/cli/warnings.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,14 @@ class CliWarning(ABC):
1010
def __repr__(self):
1111
return self.__str__()
1212

13-
def __str__(self):
14-
return f"{self.__class__.__name__}"
13+
def __hash__(self):
14+
return hash(self.__str__())
15+
16+
def __eq__(self, other):
17+
if not isinstance(other, self.__class__):
18+
return False
19+
20+
return self.__dict__ == other.__dict__
1521

1622

1723
class ConfigLoadWarning(CliWarning):
@@ -23,22 +29,24 @@ def __init__(self, paths: Dict[str, bool]):
2329
self.paths = paths
2430
self.message = "Failed to load config files. Tried the following paths: \n"
2531
for path, exists in paths.items():
26-
self.message += f" - {path} - exists: {exists})\n"
27-
self.message += "You may need to run `cloudsmith login` to authenticate and create a config file."
32+
self.message += f" - {path} - exists: {exists}\n"
33+
self.message += "You may need to run `cloudsmith login` to authenticate and create a config file. \n"
2834

2935
def __str__(self):
3036
return f"{self.__class__.__name__} - {self.paths}"
3137

3238

3339
class ProfileNotFoundWarning(CliWarning):
3440
"""
35-
Warning for issues loading the configuration file.
41+
Warning for issues finding the requested profile.
3642
"""
3743

38-
def __init__(self, path, profile):
39-
self.path = path
44+
def __init__(self, paths, profile):
45+
self.path = paths
4046
self.profile = profile
41-
self.message = f"Failed to load config file: {path} for profile: {profile}"
47+
self.message = f"Failed to load profile {profile} from config. Tried the following paths: \n"
48+
for path, exists in paths.items():
49+
self.message += f" - {path} - exists: {exists}\n"
4250

4351
def __str__(self):
4452
return f"{self.__class__.__name__} - {self.path} - {self.profile}"
@@ -51,11 +59,11 @@ class ApiAuthenticationWarning(CliWarning):
5159

5260
def __init__(self, cloudsmith_host):
5361
self.cloudsmith_host = cloudsmith_host
54-
self.message = "\n".join(
62+
self.message = "".join(
5563
[
56-
"Failed to authenticate with Cloudsmith API",
57-
"Please check your credentials and try again",
58-
f"Host: {cloudsmith_host}",
64+
"Failed to authenticate with Cloudsmith API ",
65+
"Please check your credentials and try again.\n",
66+
f"Host: {cloudsmith_host}\n",
5967
]
6068
)
6169

@@ -78,20 +86,21 @@ def append(self, warning: CliWarning):
7886
def __dedupe__(self) -> List[CliWarning]:
7987
return list(set(self.warnings))
8088

81-
def report(self) -> List[CliWarning]:
82-
return self.__dedupe__()
83-
84-
def __str__(self) -> str:
85-
return ",".join([str(x) for x in self.warnings])
89+
def display(self, display_fn):
90+
for warning in self.__dedupe__():
91+
display_fn(warning.message)
8692

8793
def __repr__(self) -> str:
94+
return self.__str__()
95+
96+
def __str__(self) -> str:
8897
return ",".join([str(x) for x in self.warnings])
8998

9099
def __len__(self) -> int:
91100
return len(self.warnings)
92101

93102

94103
def get_or_create_warnings(ctx):
95-
"""Get or create the options object."""
104+
"""Get or create the warnings object."""
96105

97106
return ctx.ensure_object(CliWarnings)

0 commit comments

Comments
 (0)