Skip to content

Commit

Permalink
Update tests and add organization_name for some of the plugins
Browse files Browse the repository at this point in the history
Signed-off-by: Alina Buzachis <[email protected]>
  • Loading branch information
alinabuzachis committed Aug 19, 2024
1 parent 7a23587 commit b6d5317
Show file tree
Hide file tree
Showing 22 changed files with 108 additions and 83 deletions.
20 changes: 0 additions & 20 deletions plugins/module_utils/common.py

This file was deleted.

62 changes: 24 additions & 38 deletions plugins/module_utils/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,28 +76,40 @@ def get_item_name(self, item):
raise EDAError(msg)

def fail_wanted_one(self, response, endpoint, query_params) -> NoReturn:
sample = response.json.copy()
if len(sample["results"]) > 1:
sample = {"results": []}
if len(response) > 1:
sample["results"] = sample["results"][:2] + ["...more results snipped..."]
url = self.client.build_url(endpoint, query_params)
host_length = len(self.client.host)
display_endpoint = url.geturl()[
host_length:
] # truncate to not include the base URL
msg = f"Request to {display_endpoint} returned {response.json['count']} items, expected 1"
msg = f"Request to {display_endpoint} returned {len(response)} items, expected 1 {sample}"
raise EDAError(msg)

def get_exactly_one(
self, endpoint, name=None, **kwargs
) -> Optional[dict[str, bool]]:
new_kwargs = kwargs.copy()
result = self.get_one_or_many(
endpoint, name=name, allow_none=False, want_one=True, **kwargs
endpoint, name=name, **kwargs
)
# typing: needed as get_one_or_many can also return lists, not expected
# to reach this ever.
if isinstance(result, list): # pragma: no cover
self.fail_wanted_one(result, endpoint, {})
return result

if len(result) == 1:
return result[0]

if len(result) > 1:
if name:
# Since we did a name or ID search and got > 1 return
# something if the id matches
for asset in result:
if str(asset["id"]) == name:
return asset
# We got > 1 and either didn't find something by ID (which means
# multiple names)
# Or we weren't running with a or search and just got back too
# many to begin with.
self.fail_wanted_one(result, endpoint, new_kwargs.get("data"))

def resolve_name_to_id(self, endpoint, name):
return self.get_exactly_one(endpoint, name)["id"]
Expand All @@ -106,13 +118,9 @@ def get_one_or_many(
self,
endpoint: str,
name: Optional[str] = None,
allow_none: bool = True,
check_exists: bool = False,
want_one: bool = True,
**kwargs: Any,
) -> Union[None, dict[str, bool], List]:
) -> List:
new_kwargs = kwargs.copy()
response = None

if name:
name_field = self.get_name_field_from_endpoint(endpoint)
Expand All @@ -133,31 +141,9 @@ def get_one_or_many(
raise EDAError("The endpoint did not provide count, results")

if response.json["count"] == 0:
if allow_none:
return None
self.fail_wanted_one(response, endpoint, new_kwargs.get("data"))
if response.json["count"] == 1:
return response.json["results"][0]
if response.json["count"] > 1:
if want_one:
if name:
# Since we did a name or ID search and got > 1 return
# something if the id matches
for asset in response.json["results"]:
if str(asset["id"]) == name:
return asset
# We got > 1 and either didn't find something by ID (which means
# multiple names)
# Or we weren't running with a or search and just got back too
# many to begin with.
self.fail_wanted_one(response, endpoint, new_kwargs.get("data"))
else:
return response.json["results"]
return []

if check_exists:
self.result["id"] = response.json["results"][0]["id"]
return self.result
return None
return response.json["results"]

def create_if_needed(
self,
Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def main() -> None:
argument_spec.update(AUTH_ARGSPEC)

required_if = [
("state", "present", ("name", "rulebook_name", "decision_environment_name"))
("state", "present", ("name", "rulebook_name", "decision_environment_name", "organization_name"))
]

module = AnsibleModule(
Expand Down
3 changes: 1 addition & 2 deletions plugins/modules/activation_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@

from ..module_utils.arguments import AUTH_ARGSPEC
from ..module_utils.client import Client
from ..module_utils.common import to_list_of_dict
from ..module_utils.controller import Controller
from ..module_utils.errors import EDAError

Expand Down Expand Up @@ -113,7 +112,7 @@ def main() -> None:
except EDAError as e:
module.fail_json(msg=f"Failed to get rulebook activations: {e}")

module.exit_json(activations=to_list_of_dict(result))
module.exit_json(activations=result)


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/controller_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def main() -> None:
ret = {}

try:
token_type = controller.get_one_or_many(token_endpoint, name=token_name)
token_type = controller.get_exactly_one(token_endpoint, name=token_name)
except EDAError as eda_err:
module.fail_json(msg=str(eda_err))

Expand Down
10 changes: 5 additions & 5 deletions plugins/modules/credential.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
organization_name:
description:
- The name of the organization.
type: int
type: str
aliases:
- org_name
description:
Expand Down Expand Up @@ -108,13 +108,13 @@ def main() -> None:
description=dict(type="str"),
inputs=dict(type="dict"),
credential_type_name=dict(type="str"),
organization_name=dict(type="int", aliases=["org_name"]),
organization_name=dict(type="str", aliases=["org_name"]),
state=dict(choices=["present", "absent"], default="present"),
)

argument_spec.update(AUTH_ARGSPEC)

required_if = [("state", "present", ("name", "credential_type_name", "inputs"))]
required_if = [("state", "present", ("name", "credential_type_name", "inputs", "organization_name"))]

module = AnsibleModule(
argument_spec=argument_spec, required_if=required_if, supports_check_mode=True
Expand Down Expand Up @@ -154,7 +154,7 @@ def main() -> None:
credential_params["credential_type_id"] = credential_type_id

organization_id = None
if module.params.get("organization_id"):
if module.params.get("organization_name"):
organization_id = lookup(
module, controller, "organizations", module.params["organization_name"]
)
Expand All @@ -164,7 +164,7 @@ def main() -> None:

# Attempt to look up credential based on the provided name
try:
credential = controller.get_one_or_many("eda-credentials", name=name)
credential = controller.get_exactly_one("eda-credentials", name=name)
except EDAError as e:
module.fail_json(msg=f"Failed to get credential: {e}")

Expand Down
3 changes: 1 addition & 2 deletions plugins/modules/credential_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@

from ..module_utils.arguments import AUTH_ARGSPEC
from ..module_utils.client import Client
from ..module_utils.common import to_list_of_dict
from ..module_utils.controller import Controller
from ..module_utils.errors import EDAError

Expand Down Expand Up @@ -111,7 +110,7 @@ def main() -> None:
except EDAError as e:
module.fail_json(msg=f"Failed to get credential: {e}")

module.exit_json(credentials=to_list_of_dict(result))
module.exit_json(credentials=result)


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/credential_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def main() -> None:

# Attempt to look up credential_type based on the provided name
try:
credential_type = controller.get_one_or_many("credential-types", name=name)
credential_type = controller.get_exactly_one("credential-types", name=name)
except EDAError as e:
module.fail_json(msg=f"Failed to get credential type: {e}")

Expand Down
3 changes: 1 addition & 2 deletions plugins/modules/credential_type_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@

from ..module_utils.arguments import AUTH_ARGSPEC
from ..module_utils.client import Client
from ..module_utils.common import to_list_of_dict
from ..module_utils.controller import Controller
from ..module_utils.errors import EDAError

Expand Down Expand Up @@ -109,7 +108,7 @@ def main() -> None:
except EDAError as e:
module.fail_json(msg=f"Failed to get credential type: {e}")

module.exit_json(credential_types=to_list_of_dict(result))
module.exit_json(credential_types=result)


if __name__ == "__main__":
Expand Down
22 changes: 20 additions & 2 deletions plugins/modules/decision_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
description:
- Name of the credential to associate with the decision environment.
type: str
organization_name:
description:
- The name of the organization.
type: str
aliases:
- organization
state:
description:
- Desired state of the resource.
Expand Down Expand Up @@ -103,12 +109,15 @@ def main() -> None:
description=dict(),
image_url=dict(),
credential=dict(),
organization_name=dict(type="str", aliases=["organization"]),
state=dict(choices=["present", "absent"], default="present"),
)

argument_spec.update(AUTH_ARGSPEC)

module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
required_if = [("state", "present", ("name", "organization_name", "image_url"))]

module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True)

client = Client(
host=module.params.get("controller_host"),
Expand All @@ -130,7 +139,7 @@ def main() -> None:
ret = {}

try:
decision_environment_type = controller.get_one_or_many(
decision_environment_type = controller.get_exactly_one(
decision_environment_endpoint, name=decision_environment_name
)
except EDAError as eda_err:
Expand Down Expand Up @@ -166,6 +175,15 @@ def main() -> None:
# in the loop above
decision_environment_type_params["credential"] = credential_type["id"]

organization_id = None
if module.params.get("organization_name"):
organization_id = controller.resolve_name_to_id(
"organizations", module.params["organization_name"]
)

if organization_id:
decision_environment_type_params["organization_id"] = organization_id

if new_name:
decision_environment_type_params["name"] = new_name
elif decision_environment_type:
Expand Down
3 changes: 1 addition & 2 deletions plugins/modules/decision_environment_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@

from ..module_utils.arguments import AUTH_ARGSPEC
from ..module_utils.client import Client
from ..module_utils.common import to_list_of_dict
from ..module_utils.controller import Controller
from ..module_utils.errors import EDAError

Expand Down Expand Up @@ -103,7 +102,7 @@ def main() -> None:
module.fail_json(msg=str(eda_err))
raise # https://github.com/ansible/ansible/pull/83814

module.exit_json(decision_environments=to_list_of_dict(ret))
module.exit_json(decision_environments=ret)


if __name__ == "__main__":
Expand Down
28 changes: 26 additions & 2 deletions plugins/modules/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
description:
- The name of the credential to associate with the project.
type: str
organization_name:
description:
- The name of the organization.
type: str
aliases:
- organization
state:
description:
- Desired state of the resource.
Expand Down Expand Up @@ -98,12 +104,17 @@ def main() -> None:
description=dict(),
url=dict(),
credential=dict(),
organization_name=dict(type="str", aliases=["organization"]),
state=dict(choices=["present", "absent"], default="present"),
)

argument_spec.update(AUTH_ARGSPEC)

module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
required_if = [
("state", "present", ("name", "url", "organization_name"))
]

module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True)

client = Client(
host=module.params.get("controller_host"),
Expand All @@ -125,7 +136,7 @@ def main() -> None:
ret = {}

try:
project_type = controller.get_one_or_many(project_endpoint, name=project_name)
project_type = controller.get_exactly_one(project_endpoint, name=project_name)
except EDAError as eda_err:
module.fail_json(msg=str(eda_err))

Expand Down Expand Up @@ -158,6 +169,19 @@ def main() -> None:
# in the loop above
project_type_params["eda_credential_id"] = credential_id["id"]

organization_id = None
if module.params.get("organization_name"):
try:
organization_id = controller.resolve_name_to_id(
"organizations", module.params["organization_name"]
)
except EDAError as eda_err:
module.fail_json(msg=str(eda_err))
raise

if organization_id:
project_type_params["organization_id"] = organization_id

if new_name:
project_type_params["name"] = new_name
elif project_type:
Expand Down
4 changes: 0 additions & 4 deletions plugins/modules/project_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,6 @@ def main() -> None:
except EDAError as eda_err:
module.fail_json(msg=str(eda_err))

if result is None:
ret = []
if not isinstance(result, list):
ret = [result]
module.exit_json(projects=ret)


Expand Down
2 changes: 1 addition & 1 deletion plugins/modules/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def main():
ret = {}

try:
user_type = controller.get_one_or_many(user_endpoint, name=username)
user_type = controller.get_exactly_one(user_endpoint, name=username)
except EDAError as eda_err:
module.fail_json(msg=str(eda_err))

Expand Down
Loading

0 comments on commit b6d5317

Please sign in to comment.