Skip to content

Commit

Permalink
Allow mocking of galaxy roles (#1320)
Browse files Browse the repository at this point in the history
Allows us to mock old standlone galaxy roles with names like foo.bar.
  • Loading branch information
ssbarnea committed Feb 8, 2021
1 parent 2e9ee83 commit c546e9a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
4 changes: 3 additions & 1 deletion .ansible-lint
Expand Up @@ -9,9 +9,11 @@ exclude_paths:
mock_modules:
- zuul_return
- fake_namespace.fake_collection.fake_module
# note the foo.bar is invalid as being neither a module or a collection
mock_roles:
- mocked_role
- fake_namespace.fake_collection.fake_role
- author.role_name # old standalone galaxy role
- fake_namespace.fake_collection.fake_role # role within a collection

# Enable checking of loop variable prefixes in roles
loop_var_prefix: "{role}_"
Expand Down
23 changes: 16 additions & 7 deletions src/ansiblelint/_prerun.py
@@ -1,4 +1,5 @@
import os
import re
import subprocess
import sys
from typing import List, Optional
Expand All @@ -10,6 +11,7 @@
ANSIBLE_MIN_VERSION,
ANSIBLE_MISSING_RC,
ANSIBLE_MOCKED_MODULE,
INVALID_CONFIG_RC,
)


Expand Down Expand Up @@ -116,12 +118,8 @@ def _prepare_ansible_paths() -> None:


def _make_module_stub(module_name: str) -> None:
if "." not in module_name:
os.makedirs(".cache/modules", exist_ok=True)
_write_module_stub(
filename=f".cache/modules/{module_name}.py", name=module_name
)
else:
# a.b.c is treated a collection
if re.match(r"\w+\.\w+\.\w+", module_name):
namespace, collection, module_file = module_name.split(".")
path = f".cache/collections/ansible_collections/{ namespace }/{ collection }/plugins/modules"
os.makedirs(path, exist_ok=True)
Expand All @@ -131,6 +129,17 @@ def _make_module_stub(module_name: str) -> None:
namespace=namespace,
collection=collection,
)
elif "." in module_name:
print(
"Config error: %s is not a valid module name." % module_name,
file=sys.stderr,
)
sys.exit(INVALID_CONFIG_RC)
else:
os.makedirs(".cache/modules", exist_ok=True)
_write_module_stub(
filename=f".cache/modules/{module_name}.py", name=module_name
)


def _write_module_stub(
Expand Down Expand Up @@ -159,7 +168,7 @@ def _update_env(varname: str, value: List[str]) -> None:
def _perform_mockings() -> None:
"""Mock modules and roles."""
for role_name in options.mock_roles:
if "." in role_name:
if re.match(r"\w+\.\w+\.\w+", role_name):
namespace, collection, role_dir = role_name.split(".")
path = f".cache/collections/ansible_collections/{ namespace }/{ collection }/roles/{ role_dir }/"
else:
Expand Down

0 comments on commit c546e9a

Please sign in to comment.