Skip to content

Commit 5852e43

Browse files
authored
Merge pull request #599 from NHSDigital/APM-7323-Sonarqube-fix
Refactor YAML parameters and improve variable handling
2 parents f1d754a + e25ceaa commit 5852e43

37 files changed

Lines changed: 941 additions & 855 deletions

ansible/collections/ansible_collections/nhsd/apigee/plugins/action/add_policy_to_pre_flow.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def run(self, tmp=None, task_vars=None):
3232
proxies_dir = args.dist_dir.joinpath(
3333
"proxies", args.proxy_dir, "apiproxy/proxies"
3434
)
35-
proxies_files = [f for f in proxies_dir.glob("*.xml")]
35+
proxies_files = list(proxies_dir.glob("*.xml"))
3636

3737
if len(proxies_files) != 1:
3838
return {
@@ -57,13 +57,12 @@ def run(self, tmp=None, task_vars=None):
5757
name = step.find("Name")
5858
if name.text == args.policy_name:
5959
return {"changed": False}
60-
break
6160

6261
result = {"changed": True}
6362
if diff_mode:
6463
result["diff"] = {
6564
"before": etree.tostring(tree, pretty_print=True).decode(),
66-
"before_header": str(proxies_file)
65+
"before_header": str(proxies_file),
6766
}
6867

6968
step = etree.Element("Step")
@@ -76,8 +75,8 @@ def run(self, tmp=None, task_vars=None):
7675
result["diff"].update(
7776
{
7877
"after": etree.tostring(tree, pretty_print=True).decode(),
79-
"after_header": str(proxies_file)
80-
}
78+
"after_header": str(proxies_file),
79+
}
8180
)
8281

8382
if check_mode or result["changed"] is False:

ansible/collections/ansible_collections/nhsd/apigee/plugins/module_utils/apigee_action.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55

66
class ApigeeAction(ansible.plugins.action.ActionBase):
7-
def validate_args(self, Validator: pydantic.BaseModel):
7+
def validate_args(self, validator: type[pydantic.BaseModel]):
88
"""Returns two-length tuple of validated_args and errors dicts."""
99
try:
10-
args = Validator(**self._task.args)
10+
args = validator(**self._task.args)
1111
return args, {}
1212
except pydantic.ValidationError as e:
1313
return (

ansible/collections/ansible_collections/nhsd/apigee/plugins/module_utils/models/ansible/validate_manifest.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,14 @@ def check_service_name(cls, service_name, values):
5353
def prepend_dist_dir_to_spec_paths(cls, manifest, values):
5454
dist_dir = values.get("dist_dir")
5555
print(dist_dir)
56-
if not dist_dir:
57-
return manifest
58-
apigee = manifest["apigee"]
59-
for env_dict in apigee["environments"]:
60-
for spec_dict in env_dict["specs"]:
61-
path = spec_dict.get("path")
62-
if path is not None:
63-
spec_dict["path"] = os.path.join(dist_dir, path)
56+
if dist_dir:
57+
apigee = manifest["apigee"]
58+
for env_dict in apigee["environments"]:
59+
for spec_dict in env_dict["specs"]:
60+
path = spec_dict.get("path")
61+
if path is not None:
62+
spec_dict["path"] = os.path.join(dist_dir, path)
63+
6464
return manifest
6565

6666
@pydantic.validator("manifest")

ansible/collections/ansible_collections/nhsd/apigee/plugins/module_utils/models/apigee/product.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import json
2-
from typing import Union, Literal, List, Dict, Any, Type
2+
from typing import Optional, Union, Literal, List, Dict, Any, Type
33
from typing_extensions import Annotated
44
from pydantic import (
55
Field,
@@ -110,29 +110,34 @@ def _literal_name(class_):
110110
+ ")$)"
111111
)
112112

113+
113114
class ApigeeProductAttributeOther(BaseModel):
114115
name: constr(regex=PRODUCT_ATTRIBUTE_REGEX)
115116
value: str
116117

118+
117119
ApigeeProductAttributeSpecial = Annotated[
118-
Union [
120+
Union[
119121
ApigeeProductAttributeAccess,
120122
ApigeeProductAttributeRateLimit,
121123
ApigeeProductAttributeRateLimiting,
122124
],
123-
Field(discriminator="name")
125+
Field(discriminator="name"),
124126
]
125127

128+
126129
def _count_cls(items: List[Any], cls: Type):
127130
return sum(isinstance(item, cls) for item in items)
128131

129132

130133
class ApigeeProduct(BaseModel):
131134
name: str
132135
approvalType: Literal["auto", "manual"] = "manual"
133-
attributes: List[Union[ApigeeProductAttributeSpecial, ApigeeProductAttributeOther]] = [{"name": "access", "value": "private"}]
134-
description: str = None
135-
displayName: str = None
136+
attributes: List[
137+
Union[ApigeeProductAttributeSpecial, ApigeeProductAttributeOther]
138+
] = [{"name": "access", "value": "private"}]
139+
description: Optional[str] = None
140+
displayName: Optional[str] = None
136141

137142
# Note: This value is manually inserted by apigee_environment
138143
# object that contains this product. So if you do not provide a

ansible/collections/ansible_collections/nhsd/apigee/plugins/module_utils/models/apigee/rate_limiting_config.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
Pydantic class for the rateliming config JSON, attached to products
33
and apps to control the ApplyRateLimiting shared flow.
44
"""
5-
from typing import Literal
5+
6+
from typing import Literal, Optional
67

78
from pydantic import BaseModel, conint, constr, Extra
89

910

1011
class ExcludeNoneModel(BaseModel):
11-
1212
"""
1313
Providing default values for ratelimiting here would mean that
1414
changing defaults required a redeploy for all proxies.
@@ -21,26 +21,27 @@ class ExcludeNoneModel(BaseModel):
2121
update the defaults for everyone by just by updating the shared
2222
flow.
2323
"""
24+
2425
def dict(self, **kwargs):
2526
kwargs["exclude_none"] = True
2627
return super().dict(**kwargs)
2728

2829
class Config:
29-
extra=Extra.forbid
30+
extra = Extra.forbid
3031

3132

3233
class QuotaConfig(ExcludeNoneModel):
33-
enabled: bool = None
34+
enabled: Optional[bool] = None
3435
interval: conint(gt=0) = None
3536
limit: conint(gt=0) = None
3637
timeunit: Literal["minute", "hour", "day", "week", "month"] = None
3738

3839

3940
class SpikeArrestConfig(ExcludeNoneModel):
40-
enabled: bool = None
41-
ratelimit: constr(regex=r"^[1-9][0-9]*(ps|pm)$") = None
41+
enabled: Optional[bool] = None
42+
ratelimit: Optional[constr(regex=r"^[1-9][0-9]*(ps|pm)$")] = None
4243

4344

4445
class RateLimitingConfig(ExcludeNoneModel):
45-
quota: QuotaConfig = None
46-
spikeArrest: SpikeArrestConfig = None
46+
quota: Optional[QuotaConfig] = None
47+
spikeArrest: Optional[SpikeArrestConfig] = None

ansible/collections/ansible_collections/nhsd/apigee/plugins/module_utils/models/manifest/meta.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
_REGISTRY_DATA = {}
1010

1111

12-
1312
class ManifestMetaApi(pydantic.BaseModel):
1413
name: pydantic.constr(regex=r"^[a-z][a-z0-9]*(-[a-z0-9]+)*$")
1514
id: typing.Optional[pydantic.UUID4] = pydantic.Field(
@@ -29,7 +28,7 @@ def dict(self, **kwargs):
2928
{
3029
"guid": str(native["guid"]),
3130
"spec_guids": [str(guid) for guid in spec_guids],
32-
}
31+
}
3332
)
3433
return native
3534

@@ -58,7 +57,9 @@ def validate_guid(cls, guid, values):
5857
guid = _REGISTRY_DATA[name]["guid"]
5958
registered_guid = _REGISTRY_DATA[name]["guid"]
6059
if str(guid) != registered_guid:
61-
raise ValueError(f"Supplied guid {guid} does not match registered guid {registered_guid}")
60+
raise ValueError(
61+
f"Supplied guid {guid} does not match registered guid {registered_guid}"
62+
)
6263
return guid
6364

6465
@pydantic.validator("spec_guids")
@@ -78,11 +79,12 @@ def validate_spec_guids(cls, spec_guids, values):
7879
if str(spec_guid) not in registered_spec_guids:
7980
invalid.append(str(spec_guid))
8081
if len(invalid) > 0:
81-
raise ValueError(f"Supplied spec_guids {invalid} do not match registered spec_guids {registered_spec_guids}")
82+
raise ValueError(
83+
f"Supplied spec_guids {invalid} do not match registered spec_guids {registered_spec_guids}"
84+
)
8285
return spec_guids
8386

8487

85-
8688
class ManifestMeta(pydantic.BaseModel):
8789
schema_version: pydantic.constr(regex=r"[1-9][0-9]*(\.[0-9]+){0,2}")
8890
api: ManifestMetaApi
@@ -91,7 +93,7 @@ class ManifestMeta(pydantic.BaseModel):
9193
def validate_schema_version(cls, schema_version):
9294
semantic_parts = schema_version.split(".")
9395

94-
MAJOR, MINOR, PATCH = [int(x) for x in SCHEMA_VERSION.split(".")]
96+
MAJOR, _, _ = [int(x) for x in SCHEMA_VERSION.split(".")]
9597
major = int(semantic_parts[0])
9698

9799
# Checking against minor/patch would not allow to us deploy

ansible/collections/ansible_collections/nhsd/apigee/scripts/update_schema.py

Lines changed: 40 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88
import typing
99

1010
from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest import meta
11-
from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest.manifest import Manifest
11+
from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest.manifest import (
12+
Manifest,
13+
)
1214

13-
14-
SCHEMA_VERSION_REGEX = re.compile(r"^([1-9][0-9]*)\.([0-9]+)\.([0-9]+)$")
15+
SCHEMA_VERSION_REGEX = re.compile(r"^([1-9]\d*)\.(\d+)\.(\d+)$")
1516

1617

1718
class SchemaString:
@@ -23,7 +24,9 @@ def __init__(self, schema_or_major: typing.Union[str, int], minor=None, patch=No
2324
match = re.match(SCHEMA_VERSION_REGEX, schema_version)
2425
if not match:
2526
raise ValueError(f"Invalid SchemaString {schema_version}")
26-
self.major, self.minor, self.patch = [int(match.group(x)) for x in range(1, 4)]
27+
self.major, self.minor, self.patch = [
28+
int(match.group(x)) for x in range(1, 4)
29+
]
2730
elif isinstance(schema_or_major, int):
2831
if not isinstance(minor, int) and isinstance(patch, int):
2932
raise ValueError("SchemaString.__init__ requires major, minor, patch")
@@ -47,41 +50,51 @@ def __lt__(self, other):
4750
return (
4851
self.major < other.major
4952
or (self.major == other.major and self.minor < other.minor)
50-
or (self.major == other.major and self.minor == other.minor and self.patch < other.patch)
53+
or (
54+
self.major == other.major
55+
and self.minor == other.minor
56+
and self.patch < other.patch
57+
)
5158
)
5259

5360
def __le__(self, other):
5461
return self < other or self == other
5562

5663
def __gt__(self, other):
57-
return not self <= other
64+
return (self.major, self.minor, self.patch) > (
65+
other.major,
66+
other.minor,
67+
other.patch,
68+
)
5869

5970
def __ge__(self, other):
60-
return not self < other
71+
return (self.major, self.minor, self.patch) >= (
72+
other.major,
73+
other.minor,
74+
other.patch,
75+
)
6176

6277
def valid_increments(self):
6378
return [
6479
SchemaString(self.major + 1, 0, 0),
6580
SchemaString(self.major, self.minor + 1, 0),
66-
SchemaString(self.major, self.minor, self.patch + 1)
81+
SchemaString(self.major, self.minor, self.patch + 1),
6782
]
6883

6984

7085
def main():
71-
"""
72-
73-
"""
86+
""" """
7487
UPDATED_SCHEMA_VERSION = SchemaString(meta.SCHEMA_VERSION)
7588

7689
script_dir = pathlib.Path(__file__).parent
77-
relative_schema_dir = script_dir.joinpath(f"../tests/unit/plugins/module_utils/models/manifest/schema_versions/")
78-
79-
# last_schema_file_name = pathlib.Path(f"v{}.json")
90+
relative_schema_dir = script_dir.joinpath(
91+
"../tests/unit/plugins/module_utils/models/manifest/schema_versions/"
92+
)
8093

8194
schema_dir_glob = relative_schema_dir.glob("v*.json")
8295

8396
SCHEMA_VERSION = SchemaString("1.0.0")
84-
SCHEMA_FILE_NAME_PATTERN = re.compile(r"v([1-9][0-9]*\.[0-9]+\.[0-9]+)\.json$")
97+
SCHEMA_FILE_NAME_PATTERN = re.compile(r"v([1-9]\d*\.\d+\.\d+)\.json$")
8598
for schema_file in schema_dir_glob:
8699
match = re.match(SCHEMA_FILE_NAME_PATTERN, schema_file.name)
87100
schema_version = SchemaString(match.group(1))
@@ -100,17 +113,22 @@ def main():
100113
fromfile=str(SCHEMA_VERSION),
101114
tofile=str(UPDATED_SCHEMA_VERSION),
102115
)
103-
deltas = [delta for delta in deltas]
116+
deltas = list(deltas)
104117

105118
if not deltas:
106-
raise ValueError(f"No difference between proposed {UPDATED_SCHEMA_VERSION} schema and current {meta.SCHEMA_VERSION}")
119+
raise ValueError(
120+
f"No difference between proposed {UPDATED_SCHEMA_VERSION} schema and current {meta.SCHEMA_VERSION}"
121+
)
107122

108123
if UPDATED_SCHEMA_VERSION not in SCHEMA_VERSION.valid_increments():
109-
raise ValueError(f"""{UPDATED_SCHEMA_VERSION} is invalid increment after current {SCHEMA_VERSION}.
124+
raise ValueError(
125+
f"""{UPDATED_SCHEMA_VERSION} is invalid increment after current {SCHEMA_VERSION}.
110126
Please increment major, minor or patch integer, e.g:
111-
""" + f"\n".join(str(x) for x in SCHEMA_VERSION.valid_increments()))
127+
"""
128+
+ "\n".join(str(x) for x in SCHEMA_VERSION.valid_increments())
129+
)
112130

113-
print("-"*50)
131+
print("-" * 50)
114132
for delta in deltas:
115133
if delta.startswith("+"):
116134
col = colorama.Fore.GREEN
@@ -122,7 +140,7 @@ def main():
122140
print(colorama.Fore.RESET)
123141

124142
_input = None
125-
print("-"*50)
143+
print("-" * 50)
126144
print("Confirm spec changes? ", end="")
127145
while _input not in ["y", "n"]:
128146
if _input is not None:
@@ -139,8 +157,7 @@ def main():
139157

140158
with open(new_schema_file, "w") as f:
141159
f.write(new_schema)
142-
print(
143-
f"""Wrote {new_schema_file}"
160+
print(f"""Wrote {new_schema_file}"
144161
Validate this file by executing
145162
$ make test
146163
in {script_dir.parent}""")

0 commit comments

Comments
 (0)