Ejemplo n.º 1
0
def test_base_cmdloop_without_queue():
    # Create a cmd2.Cmd() instance and make sure basic settings are like we want for test
    app = cmd2.Cmd()
    app.use_rawinput = True
    app.intro = 'Hello World, this is an intro ...'
    app.stdout = StdOut()

    # Mock out the input call so we don't actually wait for a user's response on stdin
    m = mock.MagicMock(name='input', return_value='quit')
    sm.input = m

    # Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
    testargs = ["prog"]
    expected = app.intro + '\n'
    with mock.patch.object(sys, 'argv', testargs):
        # Run the command loop
        app.cmdloop()
    out = app.stdout.buffer
    assert out == expected
Ejemplo n.º 2
0
def test_existing_history_file(hist_file, capsys):
    import atexit
    import readline

    # Create the history file before making cmd2 app
    with open(hist_file, 'w'):
        pass

    # Create a new cmd2 app
    cmd2.Cmd(persistent_history_file=hist_file)
    _, err = capsys.readouterr()

    # Make sure there were no errors
    assert err == ''

    # Unregister the call to write_history_file that cmd2 did
    atexit.unregister(readline.write_history_file)

    # Remove created history file
    os.remove(hist_file)
Ejemplo n.º 3
0
def test_history_can_create_directory(mocker):
    # Mock out atexit.register so the persistent file doesn't written when this function
    # exists because we will be deleting the directory it needs to go to.
    mock_register = mocker.patch('atexit.register')

    # Create a temp path for us to use and let it get deleted
    with tempfile.TemporaryDirectory() as test_dir:
        pass
    assert not os.path.isdir(test_dir)

    # Add some subdirectories for the complete history file directory
    hist_file_dir = os.path.join(test_dir, 'subdir1', 'subdir2')
    hist_file = os.path.join(hist_file_dir, 'hist_file')

    # Make sure cmd2 creates the history file directory
    cmd2.Cmd(persistent_history_file=hist_file)
    assert os.path.isdir(hist_file_dir)

    # Cleanup
    os.rmdir(hist_file_dir)
Ejemplo n.º 4
0
def test_new_history_file(hist_file, capsys):
    import atexit
    import readline

    # Remove any existing history file
    try:
        os.remove(hist_file)
    except OSError:
        pass

    # Create a new cmd2 app
    cmd2.Cmd(persistent_history_file=hist_file)
    _, err = capsys.readouterr()

    # Make sure there were no errors
    assert err == ''

    # Unregister the call to write_history_file that cmd2 did
    atexit.unregister(readline.write_history_file)

    # Remove created history file
    os.remove(hist_file)
Ejemplo n.º 5
0
def test_history_file_conversion_no_truncate_on_init(hist_file, capsys):
    # make sure we don't truncate the plain text history file on init
    # it shouldn't get converted to pickle format until we save history

    # first we need some plain text commands in the history file
    with open(hist_file, 'w') as hfobj:
        hfobj.write('help\n')
        hfobj.write('alias\n')
        hfobj.write('alias create s shortcuts\n')

    # Create a new cmd2 app
    cmd2.Cmd(persistent_history_file=hist_file)

    # history should be initialized, but the file on disk should
    # still be plain text
    with open(hist_file, 'r') as hfobj:
        histlist = hfobj.readlines()

    assert len(histlist) == 3
    # history.get() is overridden to be one based, not zero based
    assert histlist[0] == 'help\n'
    assert histlist[1] == 'alias\n'
    assert histlist[2] == 'alias create s shortcuts\n'
Ejemplo n.º 6
0
def test_history_edit(monkeypatch):
    app = cmd2.Cmd(multiline_commands=['alias'])

    # Set a fake editor just to make sure we have one.  We aren't really
    # going to call it due to the mock
    app.editor = 'fooedit'

    # Mock out the _run_editor call so we don't actually open an editor
    edit_mock = mock.MagicMock(name='_run_editor')
    monkeypatch.setattr("cmd2.Cmd._run_editor", edit_mock)

    # Mock out the run_script call since the mocked edit won't produce a file
    run_script_mock = mock.MagicMock(name='do_run_script')
    monkeypatch.setattr("cmd2.Cmd.do_run_script", run_script_mock)

    # Put commands in history
    run_cmd(app, 'help')
    run_cmd(app, 'alias create my_alias history;')

    run_cmd(app, 'history -e 1:2')

    # Make sure both functions were called
    edit_mock.assert_called_once()
    run_script_mock.assert_called_once()
Ejemplo n.º 7
0
def base_app():
    return cmd2.Cmd()
Ejemplo n.º 8
0
Archivo: conftest.py Proyecto: zde/cmd2
def base_app():
    c = cmd2.Cmd()
    c.stdout = StdOut()
    return c
Ejemplo n.º 9
0
def base_app():
    return cmd2.Cmd(include_py=True, include_ipy=True)
Ejemplo n.º 10
0
def abbrev_app():
    app = cmd2.Cmd()
    app.abbrev = True
    app.stdout = StdOut()
    return app
Ejemplo n.º 11
0
def noarglist_app():
    cmd2.set_use_arg_list(False)
    app = cmd2.Cmd()
    app.stdout = StdOut()
    return app
Ejemplo n.º 12
0
def input_parser():
    c = cmd2.Cmd()
    return c.inputParser
Ejemplo n.º 13
0
def parser():
    c = cmd2.Cmd()
    c.multilineCommands = ['multiline']
    c.case_insensitive = True
    c._init_parser()
    return c.parser
Ejemplo n.º 14
0
def base_app():
    c = cmd2.Cmd()
    c.stdout = StdSim(c.stdout)
    return c
Ejemplo n.º 15
0
def cs_app():
    cmd2.Cmd.case_insensitive = False
    c = cmd2.Cmd()
    return c
Ejemplo n.º 16
0
def test_history_file_is_directory(capsys):
    with tempfile.TemporaryDirectory() as test_dir:
        # Create a new cmd2 app
        cmd2.Cmd(persistent_history_file=test_dir)
        _, err = capsys.readouterr()
        assert 'is a directory' in err
Ejemplo n.º 17
0
def test_commandset_settables():
    # Define an arbitrary class with some attribute
    class Arbitrary:
        def __init__(self):
            self.some_value = 5

    # Declare a CommandSet with a settable of some arbitrary property
    class WithSettablesA(CommandSetBase):
        def __init__(self):
            super(WithSettablesA, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = 'addon'
            self.my_int = 11

            self.add_settable(
                Settable(
                    'arbitrary_value',
                    int,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # Declare a CommandSet with an empty settable prefix
    class WithSettablesNoPrefix(CommandSetBase):
        def __init__(self):
            super(WithSettablesNoPrefix, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = ''
            self.my_int = 11

            self.add_settable(
                Settable(
                    'another_value',
                    float,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # Declare a commandset with duplicate settable name
    class WithSettablesB(CommandSetBase):
        def __init__(self):
            super(WithSettablesB, self).__init__()

            self._arbitrary = Arbitrary()
            self._settable_prefix = 'some'
            self.my_int = 11

            self.add_settable(
                Settable(
                    'arbitrary_value',
                    int,
                    'Some settable value',
                    settable_object=self._arbitrary,
                    settable_attrib_name='some_value',
                ))

    # create the command set and cmd2
    cmdset = WithSettablesA()
    arbitrary2 = Arbitrary()
    app = cmd2.Cmd(command_sets=[cmdset], auto_load_commands=False)
    setattr(app, 'str_value', '')
    app.add_settable(
        Settable('always_prefix_settables', bool, 'Prefix settables', app))
    app._settables['str_value'] = Settable('str_value', str, 'String value',
                                           app)

    assert 'arbitrary_value' in app.settables.keys()
    assert 'always_prefix_settables' in app.settables.keys()
    assert 'str_value' in app.settables.keys()

    # verify the settable shows up
    out, err = run_cmd(app, 'set')
    assert 'arbitrary_value: 5' in out
    out, err = run_cmd(app, 'set arbitrary_value')
    assert out == ['arbitrary_value: 5']

    # change the value and verify the value changed
    out, err = run_cmd(app, 'set arbitrary_value 10')
    expected = """
arbitrary_value - was: 5
now: 10
"""
    assert out == normalize(expected)
    out, err = run_cmd(app, 'set arbitrary_value')
    assert out == ['arbitrary_value: 10']

    # can't add to cmd2 now because commandset already has this settable
    with pytest.raises(KeyError):
        app.add_settable(
            Settable('arbitrary_value', int, 'This should fail', app))

    cmdset.add_settable(
        Settable('arbitrary_value',
                 int,
                 'Replaced settable',
                 settable_object=arbitrary2,
                 settable_attrib_name='some_value'))

    # Can't add a settable to the commandset that already exists in cmd2
    with pytest.raises(KeyError):
        cmdset.add_settable(
            Settable('always_prefix_settables', int, 'This should also fail',
                     cmdset))

    # Can't remove a settable from the CommandSet if it is elsewhere and not in the CommandSet
    with pytest.raises(KeyError):
        cmdset.remove_settable('always_prefix_settables')

    # verify registering a commandset with duplicate settable names fails
    cmdset_dupname = WithSettablesB()
    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_dupname)

    # unregister the CommandSet and verify the settable is now gone
    app.unregister_command_set(cmdset)
    out, err = run_cmd(app, 'set')
    assert 'arbitrary_value' not in out
    out, err = run_cmd(app, 'set arbitrary_value')
    expected = """
Parameter 'arbitrary_value' not supported (type 'set' for list of parameters).
"""
    assert err == normalize(expected)

    # Add a commandset with no prefix
    cmdset_nopfx = WithSettablesNoPrefix()
    app.register_command_set(cmdset_nopfx)

    with pytest.raises(ValueError):
        app.always_prefix_settables = True

    app.unregister_command_set(cmdset_nopfx)

    # turn on prefixes and add the commandset back
    app.always_prefix_settables = True

    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_nopfx)

    app.register_command_set(cmdset)

    # Verify the settable is back with the defined prefix.
    assert 'addon.arbitrary_value' in app.settables.keys()

    # rename the prefix and verify that the prefix changes everywhere
    cmdset._settable_prefix = 'some'
    assert 'addon.arbitrary_value' not in app.settables.keys()
    assert 'some.arbitrary_value' in app.settables.keys()

    out, err = run_cmd(app, 'set')
    assert 'some.arbitrary_value: 5' in out
    out, err = run_cmd(app, 'set some.arbitrary_value')
    assert out == ['some.arbitrary_value: 5']

    # verify registering a commandset with duplicate prefix and settable names fails
    with pytest.raises(CommandSetRegistrationError):
        app.register_command_set(cmdset_dupname)

    cmdset_dupname.remove_settable('arbitrary_value')

    app.register_command_set(cmdset_dupname)

    with pytest.raises(KeyError):
        cmdset_dupname.add_settable(
            Settable(
                'arbitrary_value',
                int,
                'Some settable value',
                settable_object=cmdset_dupname._arbitrary,
                settable_attrib_name='some_value',
            ))
Ejemplo n.º 18
0
def input_parser():
    c = cmd2.Cmd()
    return c.parser_manager.input_source_parser
Ejemplo n.º 19
0
def cs_app():
    c = cmd2.Cmd()
    return c
Ejemplo n.º 20
0
#p=cmd2.Cmd(work())
#p.cmdloop()

class Job(object):
    def __init__(self, name=''):
        self.name = name
        self.state = 'not started'
    def do_run(self, *args):
        'Start the job'
        self.state = 'started'
        print(self)
    def do_stop(self, *args):
        'End the job'
        self.state = 'ended'
        print(self)
    def do_pause(self, *args):
        'Pause the job'
        self.state = 'paused'
        print(self)
    def do_resume(self, *args):
        'Resume the job'
        self.state = 'resumed'
        print(self)
    def do_raise_exc(self, *args):
        'Simulate a method raising an exception'
        raise RuntimeError('some error')
    def __str__(self):
        return 'job %(name)s %(state)s' % vars(self)
		
jobCLI = cmd2.Cmd(Job())
jobCLI.cmdloop()