def test_pyscript_with_exception(base_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) python_script = os.path.join(test_dir, 'scripts', 'raises_exception.py') run_cmd(base_app, "pyscript {}".format(python_script)) out, err = capsys.readouterr() assert err.startswith('Traceback') assert err.endswith("TypeError: unsupported operand type(s) for +: 'int' and 'str'\n")
def test_base_py(base_app, capsys): run_cmd(base_app, 'py qqq=3') out, err = capsys.readouterr() assert out == '' run_cmd(base_app, 'py print(qqq)') out, err = capsys.readouterr() assert out.rstrip() == '3'
def test_base_invalid_option(base_app, capsys): run_cmd(base_app, 'show -z') out, err = capsys.readouterr() show_help = run_cmd(base_app, 'help show') expected = ['no such option: -z'] expected.extend(show_help) # 'show -h' is the same as 'help show', other than whitespace differences of an extra newline present in 'help show' assert normalize(str(out)) == expected
def test_set_not_supported(base_app, capsys): run_cmd(base_app, 'set qqq True') out, err = capsys.readouterr() expected = normalize(""" EXCEPTION of type 'LookupError' occurred with message: 'Parameter 'qqq' not supported (type 'show' for list of parameters).' To enable full traceback, run the following command: 'set debug true' """) assert normalize(str(err)) == expected
def test_base_run_pyscript(base_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) python_script = os.path.join(test_dir, 'script.py') expected = 'This is a python script running ...\n' run_cmd(base_app, "pyscript {}".format(python_script)) out, err = capsys.readouterr() assert out == expected
def test_recursive_pyscript_not_allowed(base_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) python_script = os.path.join(test_dir, 'scripts', 'recursive.py') expected = 'ERROR: Recursively entering interactive Python consoles is not allowed.\n' run_cmd(base_app, "pyscript {}".format(python_script)) out, err = capsys.readouterr() assert err == expected
def test_base_list(base_app): run_cmd(base_app, 'help') run_cmd(base_app, 'shortcuts') out = run_cmd(base_app, 'list') expected = _normalize(""" -------------------------[2] shortcuts """) assert out == expected
def test_save_invalid_path(base_app, capsys): # Just run help to make sure there is something in the history run_cmd(base_app, 'help') invalid_path = '/no_such_path/foobar.txt' run_cmd(base_app, 'save {}'.format(invalid_path)) out, err = capsys.readouterr() assert out == '' assert err.startswith("ERROR: Saving '{}' - ".format(invalid_path))
def test_load_with_nonexistent_file(base_app, capsys): # The way the load command works, we can't directly capture its stdout or stderr run_cmd(base_app, 'load does_not_exist.txt') out, err = capsys.readouterr() # The load command requires a path to an existing file assert str(err).startswith("ERROR") assert "does not exist or is not a file" in str(err) assert base_app.cmdqueue == []
def test_base_py_interactive(base_app): # Mock out the InteractiveConsole.interact() call so we don't actually wait for a user's response on stdin m = mock.MagicMock(name='interact') InteractiveConsole.interact = m run_cmd(base_app, "py") # Make sure our mock was called once and only once m.assert_called_once()
def test_load_with_empty_args(base_app, capsys): # The way the load command works, we can't directly capture its stdout or stderr run_cmd(base_app, 'load') out, err = capsys.readouterr() # The load command requires a file path argument, so we should get an error message expected = normalize("""ERROR: load command requires a file path:\n""") assert normalize(str(err)) == expected assert base_app.cmdqueue == []
def test_history_with_integer_argument(base_app): run_cmd(base_app, 'help') run_cmd(base_app, 'shortcuts') out = run_cmd(base_app, 'history 1') expected = normalize(""" -------------------------[1] help """) assert out == expected
def test_history_script_format(base_app): run_cmd(base_app, 'help') run_cmd(base_app, 'shortcuts') out = run_cmd(base_app, 'history -s') expected = normalize(""" help shortcuts """) assert out == expected
def test_edit_no_editor(base_app, capsys): # Purposely set the editor to None base_app.editor = None # Make sure we get an exception, but cmd2 handles it run_cmd(base_app, 'edit') out, err = capsys.readouterr() expected = _expected_no_editor_error() assert normalize(str(err)) == expected
def test_pyscript_with_noarglist(noarglist_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) python_script = os.path.join(test_dir, '..', 'examples', 'scripts', 'arg_printer.py') expected = """Running Python script 'arg_printer.py' which was called with 2 arguments arg 1: 'foo' arg 2: 'bar' """ run_cmd(noarglist_app, 'pyscript {} foo bar'.format(python_script)) out, err = capsys.readouterr() assert out == expected
def test_cmdresult(cmdresult_app): arg = 'foo' run_cmd(cmdresult_app, 'affirmative {}'.format(arg)) assert cmdresult_app._last_result assert cmdresult_app._last_result == cmd2.CmdResult(arg) arg = 'bar' run_cmd(cmdresult_app, 'negative {}'.format(arg)) assert not cmdresult_app._last_result assert cmdresult_app._last_result == cmd2.CmdResult('', arg)
def test_save_tempfile(base_app): # Just run help to make sure there is something in the history run_cmd(base_app, 'help') out = run_cmd(base_app, 'save *') output = out[0] assert output.startswith('Saved to ') # Delete the tempfile which was created temp_file = output.split('Saved to ')[1].strip() os.remove(temp_file)
def test_base_set(base_app): out = run_cmd(base_app, 'set quiet True') expected = _normalize(""" quiet - was: False now: True """) assert out == expected out = run_cmd(base_app, 'show quiet') assert out == ['quiet: True']
def test_base_set(base_app): out = run_cmd(base_app, 'set quiet True') expected = normalize(""" quiet - was: False now: True """) assert out == expected out = run_cmd(base_app, 'show quiet') assert out == ['quiet: True']
def test_send_to_paste_buffer(base_app): # Test writing to the PasteBuffer/Clipboard run_cmd(base_app, 'help >') expected = normalize(BASE_HELP) assert normalize(cmd2.get_paste_buffer()) == expected # Test appending to the PasteBuffer/Clipboard run_cmd(base_app, 'help history >>') expected = normalize(BASE_HELP + '\n' + HELP_HISTORY) assert normalize(cmd2.get_paste_buffer()) == expected
def test_load_with_binary_file(base_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'scripts', 'binary.bin') # The way the load command works, we can't directly capture its stdout or stderr run_cmd(base_app, 'load {}'.format(filename)) out, err = capsys.readouterr() # The load command requires non-empty scripts files assert str(err).startswith("ERROR") assert "is not an ASCII or UTF-8 encoded text file" in str(err) assert base_app.cmdqueue == []
def test_base_load_default_file(base_app, capsys): # TODO: Make sure to remove the 'command.txt' file in case it exists # The way the load command works, we can't directly capture its stdout or stderr run_cmd(base_app, 'load') out, err = capsys.readouterr() # The default file 'command.txt' doesn't exist, so we should get an error message expected = normalize("""ERROR: Problem accessing script from command.txt: [Errno 2] No such file or directory: 'command.txt.txt' To enable full traceback, run the following command: 'set debug true' """) assert normalize(str(err)) == expected
def test_edit_blank(base_app, monkeypatch): # Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock base_app.editor = 'fooedit' # Mock out the os.system call so we don't actually open an editor m = mock.MagicMock(name='system') monkeypatch.setattr("os.system", m) # Run help command just so we have a command in history run_cmd(base_app, 'help') run_cmd(base_app, 'edit') # We have an editor, so should expect a system call m.assert_called_once()
def test_edit_file(base_app, request, monkeypatch): # Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock base_app.editor = 'fooedit' # Mock out the os.system call so we don't actually open an editor m = mock.MagicMock(name='system') monkeypatch.setattr("os.system", m) test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'script.txt') run_cmd(base_app, 'edit {}'.format(filename)) # We think we have an editor, so should expect a system call m.assert_called_once_with('{} {}'.format(base_app.editor, filename))
def test_base_relative_load(base_app, request): test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'script.txt') assert base_app.cmdqueue == [] assert base_app._script_dir == [] assert base_app._current_script_dir is None # Run the load command, which populates the command queue and sets the script directory run_cmd(base_app, '_relative_load {}'.format(filename)) assert base_app.cmdqueue == ['help history', 'eos'] sdir = os.path.dirname(filename) assert base_app._script_dir == [sdir] assert base_app._current_script_dir == sdir
def test_load_with_utf8_file(base_app, capsys, request): test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'scripts', 'utf8.txt') assert base_app.cmdqueue == [] assert base_app._script_dir == [] assert base_app._current_script_dir is None # Run the load command, which populates the command queue and sets the script directory run_cmd(base_app, 'load {}'.format(filename)) assert base_app.cmdqueue == ['!echo γνωρίζω', 'eos'] sdir = os.path.dirname(filename) assert base_app._script_dir == [sdir] assert base_app._current_script_dir == sdir
def test_optparser_nosuchoption(_cmdline_app, capsys): run_cmd(_cmdline_app, 'say -a') out, err = capsys.readouterr() expected = normalize(""" no such option: -a Repeats what you tell me to. Usage: speak [options] (text to say) Options: -h, --help show this help message and exit -p, --piglatin atinLay -s, --shout N00B EMULATION MODE -r REPEAT, --repeat=REPEAT output [n] times""") assert normalize(str(out)) == expected
def test_optparser(_cmdline_app, capsys): run_cmd(_cmdline_app, 'say -h') out, err = capsys.readouterr() expected = normalize(""" Repeats what you tell me to. Usage: speak [options] (text to say) Options: -h, --help show this help message and exit -p, --piglatin atinLay -s, --shout N00B EMULATION MODE -r REPEAT, --repeat=REPEAT output [n] times""") # NOTE: For some reason this extra cast to str is required for Python 2.7 but not 3.x assert normalize(str(out)) == expected
def test_base_shell(base_app, monkeypatch): m = mock.Mock() monkeypatch.setattr("os.system", m) out = run_cmd(base_app, 'shell echo a') assert out == [] assert m.called m.assert_called_with('echo a')
def test_optarser_correct_args_with_quotes_and_midline_options(_cmdline_app): out = run_cmd( _cmdline_app, "speak 'This is a' -s test of the emergency broadcast system!") expected = normalize( """THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM!""") assert out == expected
def test_base_relative_load(base_app, request): test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'script.txt') # The way the load command works, we can't directly capture its stdout or stderr run_cmd(base_app, '_relative_load {}'.format(filename)) # But what we can do is check the history to see what commands have been run ... out = run_cmd(base_app, 'history') # TODO: Figure out why when we unit test the command this way the commands from the script aren't shown in history # NOTE: It works correctly when we run it at the command line expected = normalize(""" -------------------------[1] _relative_load {} """.format(filename)) assert out == expected
def test_base_history(base_app): run_cmd(base_app, 'help') run_cmd(base_app, 'shortcuts') out = run_cmd(base_app, 'history') expected = _normalize(""" -------------------------[1] help -------------------------[2] shortcuts """) assert out == expected out = run_cmd(base_app, 'history he') expected = _normalize(""" -------------------------[1] help """) assert out == expected out = run_cmd(base_app, 'history sh') expected = _normalize(""" -------------------------[2] shortcuts """) assert out == expected
def test_base_load(base_app): base_app.read_file_or_url = mock.Mock( return_value=StringIO('set quiet True\n') ) out = run_cmd(base_app, 'load myfname') expected = _normalize(""" quiet - was: False now: True """) assert out == expected
def test_base_shortcuts(base_app): out = run_cmd(base_app, 'shortcuts') expected = _normalize(""" Single-key shortcuts for other commands: !: shell ?: help @: load @@: _relative_load """) assert out == expected
def test_base_help(base_app): out = run_cmd(base_app, 'help') expected = _normalize(""" Documented commands (type help <topic>): ======================================== _load ed history list py save shortcuts _relative_load edit l load r set show cmdenvironment hi li pause run shell Undocumented commands: ====================== EOF eof exit help q quit """) assert out == expected
def test_base_help_history(base_app): out = run_cmd(base_app, 'help history') expected = _normalize(""" history [arg]: lists past commands issued | no arg: list all | arg is integer: list one history item, by index | arg is string: string search | arg is /enclosed in forward-slashes/: regular expression search Usage: history [options] (limit on which commands to include) Options: -h, --help show this help message and exit -s, --script Script format; no separation lines """) assert out == expected
def test_base_show(base_app): out = run_cmd(base_app, 'show') expected = _normalize(""" abbrev: True case_insensitive: True colors: True continuation_prompt: > debug: False default_file_name: command.txt echo: False feedback_to_output: False prompt: (Cmd) quiet: False timing: False """) # ignore "editor: vi" (could be others) out = [l for l in out if not l.startswith('editor: ')] assert out == expected
def test_base_set_not_supported(base_app): out = run_cmd(base_app, 'set qqq True') assert out == []
def notest_base_(base_app): out = run_cmd(base_app, 'shortcuts') expected = _normalize(""" """) assert out == expected
def test_base_with_transcript(_cmdline_app): app = _cmdline_app transcript = """ (Cmd) help Documented commands (type help <topic>): ======================================== _load ed history list pause run set show _relative_load edit l load py save shell speak cmdenvironment hi li orate r say shortcuts Undocumented commands: ====================== EOF eof exit help q quit (Cmd) help say Repeats what you tell me to. Usage: speak [options] (text to say) Options: -h, --help show this help message and exit -p, --piglatin atinLay -s, --shout N00B EMULATION MODE -r REPEAT, --repeat=REPEAT output [n] times (Cmd) say goodnight, Gracie goodnight, Gracie (Cmd) say -ps --repeat=5 goodnight, Gracie OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY (Cmd) set abbrev: True case_insensitive: True colors: True continuation_prompt: > debug: False default_file_name: command.txt echo: False editor: /\w*/ feedback_to_output: False maxrepeats: 3 prompt: (Cmd) quiet: False timing: False (Cmd) set maxrepeats 5 maxrepeats - was: 3 now: 5 (Cmd) say -ps --repeat=5 goodnight, Gracie OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY (Cmd) hi -------------------------[1] help -------------------------[2] help say -------------------------[3] say goodnight, Gracie -------------------------[4] say -ps --repeat=5 goodnight, Gracie -------------------------[5] set -------------------------[6] set maxrepeats 5 -------------------------[7] say -ps --repeat=5 goodnight, Gracie (Cmd) run 4 say -ps --repeat=5 goodnight, Gracie OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY OODNIGHT, GRACIEGAY (Cmd) orate Four score and > seven releases ago > our BDFL > Four score and seven releases ago our BDFL (Cmd) & look, a shortcut! look, a shortcut! (Cmd) say put this in a file > myfile.txt (Cmd) say < myfile.txt put this in a file (Cmd) set prompt "---> " prompt - was: (Cmd) now: ---> ---> say goodbye goodbye """ for cmd, expected in _get_transcript_blocks(transcript): out = run_cmd(app, "help") assert out == expected
def test_base_py(base_app): out = run_cmd(base_app, 'py qqq=3') assert out == [] out = run_cmd(base_app, 'py print qqq') assert out == []
def test_base_error(base_app): out = run_cmd(base_app, 'meow') assert out == ["*** Unknown syntax: meow"]