Skip to content

Commit ca739a6

Browse files
committed
raise issue on sonar.token and sonar.projectKey
1 parent 66577d7 commit ca739a6

5 files changed

Lines changed: 64 additions & 21 deletions

File tree

src/pysonar_scanner/__main__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ def scan():
4444
config = ConfigurationLoader.load()
4545
set_logging_options(config)
4646

47+
ConfigurationLoader.check_configuration(config)
48+
4749
api = build_api(config)
4850
check_version(api)
4951
update_config_with_api_urls(config, api.base_urls)

src/pysonar_scanner/api.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@
3131
SONAR_REGION,
3232
Key,
3333
)
34-
from pysonar_scanner.exceptions import MissingKeyException, SonarQubeApiException, InconsistentConfiguration
3534
from pysonar_scanner.utils import remove_trailing_slash, OsStr, ArchStr
35+
from pysonar_scanner.exceptions import SonarQubeApiException, InconsistentConfiguration
3636

3737
GLOBAL_SONARCLOUD_URL = "https://sonarcloud.io"
3838
US_SONARCLOUD_URL = "https://sonarqube.us"
@@ -98,18 +98,15 @@ class JRE:
9898

9999
@staticmethod
100100
def from_dict(dict: dict) -> "JRE":
101-
try:
102-
return JRE(
103-
id=dict["id"],
104-
filename=dict["filename"],
105-
sha256=dict["sha256"],
106-
java_path=dict["javaPath"],
107-
os=dict["os"],
108-
arch=dict["arch"],
109-
download_url=dict.get("downloadUrl", None),
110-
)
111-
except KeyError as e:
112-
raise MissingKeyException(f"Missing key in dictionary {dict}") from e
101+
return JRE(
102+
id=dict["id"],
103+
filename=dict["filename"],
104+
sha256=dict["sha256"],
105+
java_path=dict["javaPath"],
106+
os=dict["os"],
107+
arch=dict["arch"],
108+
download_url=dict.get("downloadUrl", None),
109+
)
113110

114111

115112
ApiConfiguration = TypedDict(
@@ -243,7 +240,7 @@ def get_analysis_jres(self, os: OsStr, arch: ArchStr) -> list[JRE]:
243240
res.raise_for_status()
244241
json_array = res.json()
245242
return [JRE.from_dict(jre) for jre in json_array]
246-
except (requests.RequestException, MissingKeyException) as e:
243+
except (requests.RequestException, KeyError) as e:
247244
raise SonarQubeApiException("Error while fetching the analysis version") from e
248245

249246
def download_analysis_jre(self, id: str, handle: typing.BinaryIO) -> None:

src/pysonar_scanner/configuration/configuration_loader.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@
2121

2222
from pysonar_scanner.configuration.cli import CliConfigurationLoader
2323
from pysonar_scanner.configuration.pyproject_toml import TomlConfigurationLoader
24-
from pysonar_scanner.configuration.properties import SONAR_TOKEN, SONAR_PROJECT_BASE_DIR, Key
24+
from pysonar_scanner.configuration.properties import SONAR_PROJECT_KEY, SONAR_TOKEN, SONAR_PROJECT_BASE_DIR, Key
2525
from pysonar_scanner.configuration.properties import PROPERTIES
2626
from pysonar_scanner.configuration import sonar_project_properties, environment_variables, dynamic_defaults_loader
2727

28-
from pysonar_scanner.exceptions import MissingKeyException
28+
from pysonar_scanner.exceptions import MissingProperty, MissingPropertyException
2929

3030

3131
def get_static_default_properties() -> dict[Key, any]:
@@ -56,8 +56,20 @@ def load() -> dict[Key, any]:
5656
resolved_properties.update(cli_properties)
5757
return resolved_properties
5858

59+
@staticmethod
60+
def check_configuration(config: dict[Key, any]) -> None:
61+
missing_keys = []
62+
if SONAR_TOKEN not in config:
63+
missing_keys.append(MissingProperty(SONAR_TOKEN, "--token"))
64+
65+
if SONAR_PROJECT_KEY not in config:
66+
missing_keys.append(MissingProperty(SONAR_PROJECT_KEY, "--project-key"))
67+
68+
if len(missing_keys) > 0:
69+
raise MissingPropertyException.from_missing_keys(*missing_keys)
70+
5971

6072
def get_token(config: dict[Key, any]) -> str:
6173
if SONAR_TOKEN not in config:
62-
raise MissingKeyException(f'Missing property "{SONAR_TOKEN}"')
74+
raise MissingPropertyException(f'Missing property "{SONAR_TOKEN}"')
6375
return config[SONAR_TOKEN]

src/pysonar_scanner/exceptions.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,21 @@
1919
#
2020

2121

22-
class MissingKeyException(Exception):
23-
pass
22+
from dataclasses import dataclass
23+
import logging
24+
25+
26+
@dataclass
27+
class MissingProperty:
28+
property: str
29+
cli_arg: str
30+
31+
32+
class MissingPropertyException(Exception):
33+
@staticmethod
34+
def from_missing_keys(*properties: MissingProperty) -> "MissingPropertyException":
35+
missing_properties = ", ".join([f"{prop.property} ({prop.cli_arg})" for prop in properties])
36+
return MissingPropertyException(f"Missing required properties: {missing_properties}")
2437

2538

2639
class SonarQubeApiException(Exception):

tests/unit/test_configuration_loader.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,9 @@
5151
SONAR_SCANNER_ARCH,
5252
SONAR_SCANNER_OS,
5353
)
54-
from pysonar_scanner.exceptions import MissingKeyException
5554
from pysonar_scanner.utils import Arch, Os
55+
from pysonar_scanner.configuration.configuration_loader import ConfigurationLoader, SONAR_PROJECT_BASE_DIR
56+
from pysonar_scanner.exceptions import MissingPropertyException
5657

5758

5859
# Mock utils.get_os and utils.get_arch at the module level
@@ -116,7 +117,7 @@ def test_get_token(self, mock_get_os, mock_get_arch):
116117
with self.subTest("Token is present"):
117118
self.assertEqual(configuration_loader.get_token({SONAR_TOKEN: "myToken"}), "myToken")
118119

119-
with self.subTest("Token is absent"), self.assertRaises(MissingKeyException):
120+
with self.subTest("Token is absent"), self.assertRaises(MissingPropertyException):
120121
configuration_loader.get_token({})
121122

122123
@patch("sys.argv", ["myscript.py", "--token", "myToken", "--sonar-project-key", "myProjectKey"])
@@ -428,3 +429,21 @@ def test_unknown_args_with_D_prefix(self, mock_get_os, mock_get_arch):
428429
self.assertEqual(configuration["another.unknown.property"], "anotherValue")
429430
self.assertEqual(configuration[SONAR_TOKEN], "myToken")
430431
self.assertEqual(configuration[SONAR_PROJECT_KEY], "myProjectKey")
432+
433+
def test_check_configuration(self, mock_get_os, mock_get_arch):
434+
with self.subTest("Both values present"):
435+
ConfigurationLoader.check_configuration({SONAR_TOKEN: "", SONAR_PROJECT_KEY: ""})
436+
437+
with self.subTest("missing keys"):
438+
with self.assertRaises(MissingPropertyException) as cm:
439+
ConfigurationLoader.check_configuration({SONAR_PROJECT_KEY: "myKey"})
440+
self.assertIn(SONAR_TOKEN, str(cm.exception))
441+
442+
with self.assertRaises(MissingPropertyException) as cm:
443+
ConfigurationLoader.check_configuration({SONAR_TOKEN: "myToken"})
444+
self.assertIn(SONAR_PROJECT_KEY, str(cm.exception))
445+
446+
with self.assertRaises(MissingPropertyException) as cm:
447+
ConfigurationLoader.check_configuration({})
448+
self.assertIn(SONAR_PROJECT_KEY, str(cm.exception))
449+
self.assertIn(SONAR_TOKEN, str(cm.exception))

0 commit comments

Comments
 (0)