Don't mock sysv.args

Python 3.6's argparse() must do some more introspection than previous
versions because it fails with a mocked sys.argv; for reference:

  File "/usr/lib64/python3.6/argparse.py", line 1622, in __init__
    prog = _os.path.basename(_sys.argv[0])
   File ".tox/py36/lib64/python3.6/posixpath.py", line 144, in basename
    p = os.fspath(p)

Convert main() to take an args argument, which is passed in for unit
tests, but remains sys.argv for __main__ calls

Change-Id: I2e0415dab7c90825188928d60073b8135c4bde48
This commit is contained in:
Ian Wienand 2017-08-22 11:14:04 +10:00
parent 06dd472f0a
commit 83c32e66fd
2 changed files with 15 additions and 11 deletions

View File

@ -372,7 +372,10 @@ class BashateRun(object):
report.print_error(MESSAGES['E004'].msg, line)
def main():
def main(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description='A bash script style checker')
@ -385,7 +388,7 @@ def main():
help='Rules to always error (rather than warn)')
parser.add_argument('-v', '--verbose', action='store_true', default=False)
parser.add_argument('-s', '--show', action='store_true', default=False)
opts = parser.parse_args()
opts = parser.parse_args(args)
if opts.show:
messages.print_messages()

View File

@ -34,37 +34,38 @@ class TestBashate(base.TestCase):
self.run = bashate.BashateRun()
@mock.patch('bashate.bashate.BashateRun')
@mock.patch('sys.argv')
def test_main_no_files(self, m_bashaterun, m_argv):
def test_main_no_files(self, m_bashaterun):
m_run_obj = mock.MagicMock()
m_run_obj.error_count = 0
m_run_obj.warning_count = 0
m_bashaterun.return_value = m_run_obj
result = bashate.main()
result = bashate.main([])
expected_return = 1
self.assertEqual(expected_return, result)
@mock.patch('bashate.bashate.BashateRun')
@mock.patch('sys.argv')
def test_main_return_one_on_errors(self, m_bashaterun, m_argv):
def test_main_return_one_on_errors(self, m_bashaterun):
m_run_obj = mock.MagicMock()
m_run_obj.warning_count = 1
m_run_obj.error_count = 1
m_bashaterun.return_value = m_run_obj
result = bashate.main()
result = bashate.main([])
expected_return = 1
self.assertEqual(expected_return, result)
@mock.patch('bashate.bashate.BashateRun')
@mock.patch('sys.argv')
def test_main_return_one_on_ioerror(self, m_bashaterun, m_argv):
def test_main_return_one_on_ioerror(self, m_bashaterun):
m_run_obj = mock.MagicMock()
m_run_obj.error_count = 0
m_run_obj.check_files = mock.Mock(side_effect=IOError)
m_bashaterun.return_value = m_run_obj
result = bashate.main()
result = bashate.main(['--verbose',
'/path/to/fileA', '/path/to/fileB'])
m_run_obj.check_files.assert_called_with(['/path/to/fileA',
'/path/to/fileB'], True)
expected_return = 1
self.assertEqual(expected_return, result)