Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support CLI arguments for cfn init #574

Merged
merged 13 commits into from
Oct 2, 2020
46 changes: 36 additions & 10 deletions src/rpdk/core/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
"""
import logging
import re
from argparse import SUPPRESS
from functools import wraps

from colorama import Fore, Style

from .exceptions import WizardAbortError, WizardValidationError
from .plugin_registry import PLUGIN_CHOICES
from .plugin_registry import get_plugin_choices
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason why we are adding this method in? seems to be the same value as PLUGIN_CHOICES

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For testing we add a dummy plugin on the fly but at that point in time PLUGIN_CHOICES is already a constant that does not includes it, making it a method allows to get the latest installed plugins.

from .project import Project

LOG = logging.getLogger(__name__)
Expand Down Expand Up @@ -42,7 +41,7 @@ def validate_type_name(value):
return value
LOG.debug("'%s' did not match '%s'", value, TYPE_NAME_REGEX)
raise WizardValidationError(
"Please enter a value matching '{}'".format(TYPE_NAME_REGEX)
"Please enter a resource type name matching '{}'".format(TYPE_NAME_REGEX)
)


Expand Down Expand Up @@ -77,7 +76,7 @@ def __call__(self, value):


validate_plugin_choice = ValidatePluginChoice( # pylint: disable=invalid-name
PLUGIN_CHOICES
get_plugin_choices()
)


Expand Down Expand Up @@ -139,10 +138,26 @@ def init(args):

check_for_existing_project(project)

type_name = input_typename()
if args.type_name:
try:
type_name = validate_type_name(args.type_name)
except WizardValidationError as error:
print(Style.BRIGHT, Fore.RED, str(error), Style.RESET_ALL, sep="")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we do it a bit more generic and reusable?

type_name = input_typename()
else:
type_name = input_typename()

if args.language:
language = args.language
LOG.warning("Language plugin '%s' selected non-interactively", language)
language = args.language.lower()
if language not in get_plugin_choices():
print(
Style.BRIGHT,
Fore.RED,
"The plugin for {} is not installed.".format(language),
Copy link
Contributor

@johnttompkins johnttompkins Sep 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"The plugin for {} is not installed.".format(language),
"The plugin for {} cannot be found.".format(language),

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably should not always print colorama otherwise it will be really hard to maintain;
maybe we can use for an abstract exception which all will change color entry

Style.RESET_ALL,
sep="",
)
language = input_language()
else:
language = input_language()

Expand Down Expand Up @@ -172,7 +187,18 @@ def setup_subparser(subparsers, parents):
parser.set_defaults(command=ignore_abort(init))

parser.add_argument(
"--force", action="store_true", help="Force files to be overwritten."
"--force",
action="store_true",
help="Force files to be overwritten.",
)

parser.add_argument(
"--language",
help="""Select a language for code generation.
The language plugin needs to be installed.""",
)

parser.add_argument(
"--type-name",
help="Selects the name of the resource type.",
)
# this is mainly for CI, so suppress it to keep it simple
parser.add_argument("--language", help=SUPPRESS)
7 changes: 7 additions & 0 deletions src/rpdk/core/plugin_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,12 @@
PLUGIN_CHOICES = sorted(PLUGIN_REGISTRY.keys())


def get_plugin_choices():
return [
entry_point.name
for entry_point in pkg_resources.iter_entry_points("rpdk.v1.languages")
]


def load_plugin(language):
return PLUGIN_REGISTRY[language]()()
81 changes: 76 additions & 5 deletions tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path
from unittest.mock import ANY, Mock, PropertyMock, patch

import pkg_resources
import pytest

from rpdk.core.exceptions import WizardAbortError, WizardValidationError
Expand All @@ -21,13 +22,25 @@
ERROR = "TUJFEL"


def test_init_method_interactive_language():
def add_dummy_language_plugin():
distribution = pkg_resources.Distribution(__file__)
entry_point = pkg_resources.EntryPoint.parse(
"dummy = rpdk.dummy:DummyLanguagePlugin", dist=distribution
)
distribution._ep_map = { # pylint: disable=protected-access
"rpdk.v1.languages": {"dummy": entry_point}
}
pkg_resources.working_set.add(distribution)


def test_init_method_interactive():
type_name = object()
language = object()

args = Mock(spec_set=["force", "language"])
args = Mock(spec_set=["force", "language", "type_name"])
args.force = False
args.language = None
args.type_name = None

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
Expand All @@ -49,12 +62,42 @@ def test_init_method_interactive_language():
mock_project.generate.assert_called_once_with()


def test_init_method_noninteractive_language():
def test_init_method_noninteractive():
add_dummy_language_plugin()

args = Mock(spec_set=["force", "language", "type_name"])
args.force = False
args.language = "dummy"
args.type_name = "Test::Test::Test"

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
mock_project.settings_path = ""
mock_project.root = Path(".")

patch_project = patch("rpdk.core.init.Project", return_value=mock_project)
patch_tn = patch("rpdk.core.init.input_typename")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do these need to be patched if we are going the non-interactive route?

patch_l = patch("rpdk.core.init.input_language")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here. no reason to patch if we are just asserting we aren't calling


with patch_project, patch_tn as mock_tn, patch_l as mock_l:
init(args)

mock_tn.assert_not_called()
mock_l.assert_not_called()

mock_project.load_settings.assert_called_once_with()
mock_project.init.assert_called_once_with(args.type_name, args.language)
mock_project.generate.assert_called_once_with()


def test_init_method_noninteractive_invalid_type_name():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

confused on this. how does init reach project init method if the typename is invalid?

add_dummy_language_plugin()
type_name = object()

args = Mock(spec_set=["force", "language"])
args = Mock(spec_set=["force", "language", "type_name"])
args.force = False
args.language = "rust1.39"
args.language = "dummy"
args.type_name = "Test"

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
Expand All @@ -76,6 +119,34 @@ def test_init_method_noninteractive_language():
mock_project.generate.assert_called_once_with()


def test_init_method_noninteractive_invalid_language():
language = object()

args = Mock(spec_set=["force", "language", "type_name"])
args.force = False
args.language = "fortran"
args.type_name = "Test::Test::Test"

mock_project = Mock(spec=Project)
mock_project.load_settings.side_effect = FileNotFoundError
mock_project.settings_path = ""
mock_project.root = Path(".")

patch_project = patch("rpdk.core.init.Project", return_value=mock_project)
patch_tn = patch("rpdk.core.init.input_typename")
patch_l = patch("rpdk.core.init.input_language", return_value=language)

with patch_project, patch_tn as mock_tn, patch_l as mock_l:
init(args)

mock_tn.assert_not_called()
mock_l.assert_called_once_with()

mock_project.load_settings.assert_called_once_with()
mock_project.init.assert_called_once_with(args.type_name, language)
mock_project.generate.assert_called_once_with()


def test_input_with_validation_valid_first_try(capsys):
sentinel1 = object()
sentinel2 = object()
Expand Down