A `.Context` whose methods' return values can be predetermined. Primarily useful for testing Invoke-using codebases. .. note:: This class wraps its ``run``, etc methods in `unittest.mock.Mock` objects. This allows you to easily assert that the methods (still returning the values you prepare them with) were actually called. .. note:: Methods not given `Results <.Result>` to yield will raise ``NotImplementedError`` if called (since the alternative is to call the real underlying method - typically undesirable when mocking.) .. versionadded:: 1.0 .. versionchanged:: 1.5 Added ``Mock`` wrapping of ``run`` and ``sudo``.
Method | __init__ |
Create a ``Context``-like object whose methods yield `.Result` objects. |
Method | run |
Execute a local shell command, honoring config options. |
Method | set |
Modify the stored mock results for given ``attname`` (e.g. ``run``). |
Method | sudo |
Execute a shell command via ``sudo`` with password auto-response. |
Method | _normalize |
Undocumented |
Method | _yield |
Undocumented |
Inherited from Context
:
Method | cd |
Context manager that keeps directory state when executing commands. |
Method | config |
Undocumented |
Method | prefix |
Prefix all nested `run`/`sudo` commands with given command plus ``&&``. |
Property | config |
Undocumented |
Property | cwd |
Return the current working directory, accounting for uses of `cd`. |
Method | _prefix |
Prefixes ``command`` with all prefixes found in ``command_prefixes``. |
Method | _run |
Undocumented |
Method | _sudo |
Undocumented |
Inherited from DataProxy
(via Context
):
Class Method | from |
Alternate constructor for 'baby' DataProxies used as sub-dict values. |
Method | __contains__ |
Undocumented |
Method | __delattr__ |
Undocumented |
Method | __delitem__ |
Undocumented |
Method | __eq__ |
Undocumented |
Method | __getattr__ |
Undocumented |
Method | __getitem__ |
Undocumented |
Method | __iter__ |
Undocumented |
Method | __len__ |
Undocumented |
Method | __repr__ |
Undocumented |
Method | __setattr__ |
Undocumented |
Method | __setitem__ |
Undocumented |
Method | clear |
Undocumented |
Method | pop |
Undocumented |
Method | popitem |
Undocumented |
Method | setdefault |
Undocumented |
Method | update |
Undocumented |
Method | _get |
Undocumented |
Method | _set |
Convenience workaround of default 'attrs are config keys' behavior. |
Method | _track |
Undocumented |
Method | _track |
Undocumented |
Class Variable | _proxies |
Undocumented |
Property | _is |
Undocumented |
Property | _is |
Undocumented |
invoke.context.Context.__init__
Create a ``Context``-like object whose methods yield `.Result` objects. :param config: A Configuration object to use. Identical in behavior to `.Context`. :param run: A data structure indicating what `.Result` objects to return from calls to the instantiated object's `~.Context.run` method (instead of actually executing the requested shell command). Specifically, this kwarg accepts: - A single `.Result` object. - A boolean; if True, yields a `.Result` whose ``exited`` is ``0``, and if False, ``1``. - An iterable of the above values, which will be returned on each subsequent call to ``.run`` (the first item on the first call, the second on the second call, etc). - A dict mapping command strings or compiled regexen to the above values (including an iterable), allowing specific call-and-response semantics instead of assuming a call order. :param sudo: Identical to ``run``, but whose values are yielded from calls to `~.Context.sudo`. :param bool repeat: A flag determining whether results yielded by this class' methods repeat or are consumed. For example, when a single result is indicated, it will normally only be returned once, causing ``NotImplementedError`` afterwards. But when ``repeat=True`` is given, that result is returned on every call, forever. Similarly, iterable results are normally exhausted once, but when this setting is enabled, they are wrapped in `itertools.cycle`. Default: ``True``. :raises: ``TypeError``, if the values given to ``run`` or other kwargs aren't of the expected types. .. versionchanged:: 1.5 Added support for boolean and string result values. .. versionchanged:: 1.5 Added support for regex dict keys. .. versionchanged:: 1.5 Added the ``repeat`` keyword argument. .. versionchanged:: 2.0 Changed ``repeat`` default value from ``False`` to ``True``.
invoke.context.Context.run
Execute a local shell command, honoring config options. Specifically, this method instantiates a `.Runner` subclass (according to the ``runner`` config option; default is `.Local`) and calls its ``.run`` method with ``command`` and ``kwargs``. See `.Runner.run` for details on ``command`` and the available keyword arguments. .. versionadded:: 1.0
Modify the stored mock results for given ``attname`` (e.g. ``run``). This is similar to how one instantiates `MockContext` with a ``run`` or ``sudo`` dict kwarg. For example, this:: mc = MockContext(run={'mycommand': Result("mystdout")}) assert mc.run('mycommand').stdout == "mystdout" is functionally equivalent to this:: mc = MockContext() mc.set_result_for('run', 'mycommand', Result("mystdout")) assert mc.run('mycommand').stdout == "mystdout" `set_result_for` is mostly useful for modifying an already-instantiated `MockContext`, such as one created by test setup or helper methods. .. versionadded:: 1.0
invoke.context.Context.sudo
Execute a shell command via ``sudo`` with password auto-response. **Basics** This method is identical to `run` but adds a handful of convenient behaviors around invoking the ``sudo`` program. It doesn't do anything users could not do themselves by wrapping `run`, but the use case is too common to make users reinvent these wheels themselves. .. note:: If you intend to respond to sudo's password prompt by hand, just use ``run("sudo command")`` instead! The autoresponding features in this method will just get in your way. Specifically, `sudo`: * Places a `.FailingResponder` into the ``watchers`` kwarg (see :doc:`/concepts/watchers`) which: * searches for the configured ``sudo`` password prompt; * responds with the configured sudo password (``sudo.password`` from the :doc:`configuration </concepts/configuration>`); * can tell when that response causes an authentication failure (e.g. if the system requires a password and one was not configured), and raises `.AuthFailure` if so. * Builds a ``sudo`` command string using the supplied ``command`` argument, prefixed by various flags (see below); * Executes that command via a call to `run`, returning the result. **Flags used** ``sudo`` flags used under the hood include: - ``-S`` to allow auto-responding of password via stdin; - ``-p <prompt>`` to explicitly state the prompt to use, so we can be sure our auto-responder knows what to look for; - ``-u <user>`` if ``user`` is not ``None``, to execute the command as a user other than ``root``; - When ``-u`` is present, ``-H`` is also added, to ensure the subprocess has the requested user's ``$HOME`` set properly. **Configuring behavior** There are a couple of ways to change how this method behaves: - Because it wraps `run`, it honors all `run` config parameters and keyword arguments, in the same way that `run` does. - Thus, invocations such as ``c.sudo('command', echo=True)`` are possible, and if a config layer (such as a config file or env var) specifies that e.g. ``run.warn = True``, that too will take effect under `sudo`. - `sudo` has its own set of keyword arguments (see below) and they are also all controllable via the configuration system, under the ``sudo.*`` tree. - Thus you could, for example, pre-set a sudo user in a config file; such as an ``invoke.json`` containing ``{"sudo": {"user": "someuser"}}``. :param str password: Runtime override for ``sudo.password``. :param str user: Runtime override for ``sudo.user``. .. versionadded:: 1.0