Skip to content

Commit 589081e

Browse files
committed
raise issue on sonar.token and sonar.projectKey
1 parent 7dadf89 commit 589081e

5 files changed

Lines changed: 63 additions & 21 deletions

File tree

src/pysonar_scanner/__main__.py

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

45+
ConfigurationLoader.check_configuration(config)
46+
4547
api = build_api(config)
4648
check_version(api)
4749
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,7 +31,7 @@
3131
SONAR_REGION,
3232
Key,
3333
)
34-
from pysonar_scanner.exceptions import MissingKeyException, SonarQubeApiException, InconsistentConfiguration
34+
from pysonar_scanner.exceptions import SonarQubeApiException, InconsistentConfiguration
3535
from pysonar_scanner.utils import Arch, Os, remove_trailing_slash
3636

3737
GLOBAL_SONARCLOUD_URL = "https://sonarcloud.io"
@@ -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(
@@ -246,7 +243,7 @@ def get_analysis_jres(self, os: Optional[Os] = None, arch: Optional[Arch] = None
246243
res.raise_for_status()
247244
json_array = res.json()
248245
return [JRE.from_dict(jre) for jre in json_array]
249-
except (requests.RequestException, MissingKeyException) as e:
246+
except (requests.RequestException, KeyError) as e:
250247
raise SonarQubeApiException("Error while fetching the analysis version") from e
251248

252249
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
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]:
@@ -55,8 +55,20 @@ def load() -> dict[Key, any]:
5555
resolved_properties.update(cli_properties)
5656
return resolved_properties
5757

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

5971
def get_token(config: dict[Key, any]) -> str:
6072
if SONAR_TOKEN not in config:
61-
raise MissingKeyException(f'Missing property "{SONAR_TOKEN}"')
73+
raise MissingPropertyException(f'Missing property "{SONAR_TOKEN}"')
6274
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: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
SONAR_SCANNER_JAVA_OPTS,
4949
)
5050
from pysonar_scanner.configuration.configuration_loader import ConfigurationLoader, SONAR_PROJECT_BASE_DIR
51-
from pysonar_scanner.exceptions import MissingKeyException
51+
from pysonar_scanner.exceptions import MissingPropertyException
5252

5353

5454
class TestConfigurationLoader(pyfakefs.TestCase):
@@ -88,7 +88,7 @@ def test_get_token(self):
8888
with self.subTest("Token is present"):
8989
self.assertEqual(configuration_loader.get_token({SONAR_TOKEN: "myToken"}), "myToken")
9090

91-
with self.subTest("Token is absent"), self.assertRaises(MissingKeyException):
91+
with self.subTest("Token is absent"), self.assertRaises(MissingPropertyException):
9292
configuration_loader.get_token({})
9393

9494
@patch("sys.argv", ["myscript.py", "--token", "myToken", "--sonar-project-key", "myProjectKey"])
@@ -394,3 +394,21 @@ def test_unknown_args_with_D_prefix(self):
394394
self.assertEqual(configuration["another.unknown.property"], "anotherValue")
395395
self.assertEqual(configuration[SONAR_TOKEN], "myToken")
396396
self.assertEqual(configuration[SONAR_PROJECT_KEY], "myProjectKey")
397+
398+
def test_check_configuration(self):
399+
with self.subTest("Both values present"):
400+
ConfigurationLoader.check_configuration({SONAR_TOKEN: "", SONAR_PROJECT_KEY: ""})
401+
402+
with self.subTest("missing keys"):
403+
with self.assertRaises(MissingPropertyException) as cm:
404+
ConfigurationLoader.check_configuration({SONAR_PROJECT_KEY: "myKey"})
405+
self.assertIn(SONAR_TOKEN, str(cm.exception))
406+
407+
with self.assertRaises(MissingPropertyException) as cm:
408+
ConfigurationLoader.check_configuration({SONAR_TOKEN: "myToken"})
409+
self.assertIn(SONAR_PROJECT_KEY, str(cm.exception))
410+
411+
with self.assertRaises(MissingPropertyException) as cm:
412+
ConfigurationLoader.check_configuration({})
413+
self.assertIn(SONAR_PROJECT_KEY, str(cm.exception))
414+
self.assertIn(SONAR_TOKEN, str(cm.exception))

0 commit comments

Comments
 (0)