Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[bin] Added --arg option to pass arguments to methods
  • Loading branch information
nemesisdesign committed Dec 11, 2015
1 parent d191c14 commit f55cc4a
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 15 deletions.
68 changes: 53 additions & 15 deletions bin/netjsonconfig
Expand Up @@ -48,20 +48,27 @@ config.add_argument('--templates', '-t',
output = parser.add_argument_group('output')

output.add_argument('--backend', '-b',
required=True,
choices=['openwrt', 'openwisp'],
action='store',
type=str,
help='Configuration backend: openwrt or openwisp')
required=True,
choices=['openwrt', 'openwisp'],
action='store',
type=str,
help='Configuration backend: openwrt or openwisp')

output.add_argument('--method', '-m',
required=True,
choices=['render', 'generate', 'write'],
action='store',
help='Backend method to use. '\
'"render" returns the configuration in text format'\
'"generate" returns a tar.gz archive as output; '\
'"write" is like generate but writes to disk; ')
required=True,
choices=['render', 'generate', 'write'],
action='store',
help='Backend method to use. '\
'"render" returns the configuration in text format'\
'"generate" returns a tar.gz archive as output; '\
'"write" is like generate but writes to disk; ')

output.add_argument('--args', '-a',
nargs='*', # zero or more
action='store',
type=str,
default=[],
help='Optional arguments that can be passed to methods')

debug = parser.add_argument_group('debug')

Expand All @@ -83,14 +90,42 @@ def _load(config):
try:
return open(config, 'r').read()
except IOError:
print('netjsonconfig: cannot open "{0}": file not found'.format(config))
print('netjsonconfig: cannot open "{0}": '\
'file not found'.format(config))
sys.exit(1)
else:
return config.strip()

def parse_method_arguments(arguments):
"""
ensures arguments format is correct
"""
kwargs = {}
for method_arg in arguments:
if method_arg.count('=') != 1:
message = '--arg option expects arguments in the following format: '\
'arg1=val1 arg2=val2'
print('netjsonconfig: {0}'.format(message))
sys.exit(3)
key, val = method_arg.split('=')
kwargs[key] = recognize_method_argument(val)
return kwargs

def recognize_method_argument(arg_string):
"""
allows to recognize booleans
"""
if arg_string in ['True', '1']:
return True
elif arg_string in ['False', '0']:
return False
return arg_string

args = parser.parse_args()
config = _load(args.config)
templates = [_load(template) for template in args.templates]
method = args.method
method_arguments = parse_method_arguments(args.args)

backends = {
'openwrt': netjsonconfig.OpenWrt,
Expand All @@ -105,7 +140,7 @@ except TypeError as e:
sys.exit(2)

try:
output = getattr(instance, args.method)()
output = getattr(instance, method)(**method_arguments)
if output:
print(output)
except netjsonconfig.exceptions.ValidationError as e:
Expand All @@ -115,4 +150,7 @@ except netjsonconfig.exceptions.ValidationError as e:
else:
info = str(e)
print(message + info)
sys.exit(3)
sys.exit(4)
except TypeError as e:
print('netjsonconfig: {0}'.format(e))
sys.exit(5)
34 changes: 34 additions & 0 deletions tests/test_bin.py
Expand Up @@ -74,3 +74,37 @@ def test_invalid_template(self):
self.assertIn('"WRONG": file not found', e.output.decode())
else:
self.fail('subprocess.CalledProcessError not raised')

def test_invalid_arguments(self):
command = "netjsonconfig -c '{}' -b openwrt -m render -a WRONG"
try:
output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as e:
self.assertIn('--arg option expects', e.output.decode())
else:
self.fail('subprocess.CalledProcessError not raised')

def test_arg_exception(self):
command = "netjsonconfig -c '{}' -b openwrt -m write"
try:
output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as e:
self.assertIn('write() missing 1 required', e.output.decode())
self.assertIn('name', e.output.decode())
else:
self.fail('subprocess.CalledProcessError not raised')

def test_valid_arg(self):
config = json.dumps({
'general': {'hostname': 'template_test'},
'files': [
{
'path': '/etc/test.txt',
'contents': 'test_valid_arg'
}
]
})
command = "netjsonconfig --config '{0}' -b openwrt -m render -a files=False".format(config)
output = subprocess.check_output(command, shell=True).decode()
self.assertNotIn('test.txt', output)
self.assertNotIn('test_valid_arg', output)

0 comments on commit f55cc4a

Please sign in to comment.