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

[PR #825/4f67a3a9 backport][release_2.0] Do not rely on length of sys.argv #842

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions ansible_runner/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,15 @@
logger = logging.getLogger('ansible-runner')


class AnsibleRunnerArgumentParser(argparse.ArgumentParser):
def error(self, message):
# If no sub command was provided, print common usage then exit
if 'required: command' in message.lower():
print_common_usage()

super(AnsibleRunnerArgumentParser, self).error(message)


@contextmanager
def role_manager(vargs):
if vargs.get('role'):
Expand Down Expand Up @@ -583,7 +592,7 @@ def main(sys_args=None):
:rtype: SystemExit
"""

parser = argparse.ArgumentParser(
parser = AnsibleRunnerArgumentParser(
prog='ansible-runner',
description="Use 'ansible-runner' (with no arguments) to see basic usage"
)
Expand Down Expand Up @@ -747,11 +756,6 @@ def main(sys_args=None):
add_args_to_parser(isalive_container_group, DEFAULT_CLI_ARGS['container_group'])
add_args_to_parser(transmit_container_group, DEFAULT_CLI_ARGS['container_group'])

if len(sys.argv) == 1:
parser.print_usage()
print_common_usage()
parser.exit(status=0)

args = parser.parse_args(sys_args)

vargs = vars(args)
Expand Down
20 changes: 18 additions & 2 deletions test/integration/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,26 @@ def will_pass():
assert not os.path.exists(context['saved_temp_dir'])


def test_help():
@pytest.mark.parametrize(
('command', 'expected'),
(
(None, {'out': 'These are common Ansible Runner commands', 'err': ''}),
([], {'out': 'These are common Ansible Runner commands', 'err': ''}),
(['run'], {'out': '', 'err': 'the following arguments are required'}),
)
)
def test_help(command, expected, capsys, monkeypatch):
# Ensure that sys.argv of the test command does not affect the test environment.
monkeypatch.setattr('sys.argv', command or [])

with pytest.raises(SystemExit) as exc:
main([])
main(command)

stdout, stderr = capsys.readouterr()

assert exc.value.code == 2, 'Should raise SystemExit with return code 2'
assert expected['out'] in stdout
assert expected['err'] in stderr


def test_module_run():
Expand Down