Skip to content

Commit

Permalink
[bin] Fixed binary standard output + added test
Browse files Browse the repository at this point in the history
  • Loading branch information
nemesifier committed Dec 16, 2015
1 parent b7259b4 commit 219f638
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
21 changes: 20 additions & 1 deletion bin/netjsonconfig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python

import sys
import six
import argparse

import netjsonconfig
Expand Down Expand Up @@ -121,6 +122,24 @@ def recognize_method_argument(arg_string):
return False
return arg_string


def print_output(output):
"""
prints result to standard output
"""
# if file object, get bytes
if hasattr(output, 'getvalue'):
output = output.getvalue()
# python2: always print
# python3: if string, just print
if isinstance(output, six.string_types):
print(output)
# python2: never enters this block
# python3: writes binary data to standard output
else:
sys.stdout.buffer.write(output)


args = parser.parse_args()
config = _load(args.config)
templates = [_load(template) for template in args.templates]
Expand All @@ -142,7 +161,7 @@ except TypeError as e:
try:
output = getattr(instance, method)(**method_arguments)
if output:
print(output)
print_output(output)
except netjsonconfig.exceptions.ValidationError as e:
message = 'netjsonconfig: JSON Schema violation\n'
if not args.verbose:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_bin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import json
import unittest
import subprocess
import tarfile

from netjsonconfig.utils import _TabsMixin

Expand All @@ -9,6 +11,10 @@ class TestBin(unittest.TestCase, _TabsMixin):
"""
tests for netjsonconfig command line tool
"""
@classmethod
def tearDownClass(self):
os.remove('test.tar.gz')

def test_file_not_found(self):
with self.assertRaises(subprocess.CalledProcessError):
output = subprocess.check_output("netjsonconfig -c WRONG -b openwrt -m generate", shell=True)
Expand Down Expand Up @@ -107,3 +113,10 @@ def test_valid_arg(self):
output = subprocess.check_output(command, shell=True).decode()
self.assertNotIn('test.txt', output)
self.assertNotIn('test_valid_arg', output)

def test_generate_redirection(self):
command = """netjsonconfig -c '{"general": { "hostname": "example" }}' -b openwrt -m generate > test.tar.gz"""
subprocess.check_output(command, shell=True)
tar = tarfile.open('test.tar.gz', 'r')
self.assertEqual(len(tar.getmembers()), 1)
tar.close()

0 comments on commit 219f638

Please sign in to comment.