testing¶
The fabric.testing subpackage contains a handful of test helper modules:
fabric.testing.basewhich only depends on things likemockand is appropriate in just about any test paradigm;fabric.testing.fixtures, containingpytestfixtures and thus only of interest for users ofpytest.
All are documented below. Please note the module-level documentation which contains install instructions!
testing.base¶
This module contains helpers/fixtures to assist in testing Fabric-driven code.
It is not intended for production use, and pulls in some test-oriented
dependencies such as mock. You can install
an ‘extra’ variant of Fabric to get these dependencies if you aren’t already
using them for your own testing purposes: pip install fabric[testing].
Note
If you’re using pytest for your test suite, you may be interested in
grabbing fabric[pytest] instead, which encompasses the dependencies of
both this module and the fabric.testing.fixtures module, which contains
pytest fixtures.
New in version 2.1.
-
class
fabric.testing.base.Command(cmd=None, out=b'', err=b'', in_=None, exit=0, waits=0)¶ Data record specifying params of a command execution to mock/expect.
Parameters: - cmd (str) – Command string to expect. If not given, no expectations about the
command executed will be set up. Default:
None. - out (bytes) – Data yielded as remote stdout. Default:
b"". - err (bytes) – Data yielded as remote stderr. Default:
b"". - exit (int) – Remote exit code. Default:
0. - waits (int) – Number of calls to the channel’s
exit_status_readythat should returnFalsebefore it then returnsTrue. Default:0(exit_status_readywill returnTrueimmediately).
New in version 2.1.
-
__weakref__¶ list of weak references to the object (if defined)
- cmd (str) – Command string to expect. If not given, no expectations about the
command executed will be set up. Default:
-
class
fabric.testing.base.MockChannel(*args, **kwargs)¶ Mock subclass that tracks state for its
recv(_stderr)?methods.Turns out abusing function closures inside MockRemote to track this state only worked for 1 command per session!
New in version 2.1.
-
class
fabric.testing.base.MockRemote¶ Class representing mocked remote state.
By default this class is set up for start/stop style patching as opposed to the more common context-manager or decorator approach; this is so it can be used in situations requiring setup/teardown semantics.
Defaults to setting up a single anonymous
Session, so it can be used as a “request & forget” pytest fixture. Users requiring detailed remote session expectations can call methods likeexpect, which wipe that anonymous Session & set up a new one instead.New in version 2.1.
-
__weakref__¶ list of weak references to the object (if defined)
-
expect(*args, **kwargs)¶ Convenience method for creating & ‘expect’ing a single
Session.Returns the single
MockChannelyielded by that Session.New in version 2.1.
-
expect_sessions(*sessions)¶ Sets the mocked remote environment to expect the given
sessions.Returns a list of
MockChannelobjects, one per inputSession.New in version 2.1.
-
sanity()¶ Run post-execution sanity checks (usually ‘was X called’ tests.)
New in version 2.1.
-
start()¶ Start patching SSHClient with the stored sessions, returning channels.
New in version 2.1.
-
stop()¶ Stop patching SSHClient.
New in version 2.1.
-
-
class
fabric.testing.base.MockSFTP(autostart=True)¶ Class managing mocked SFTP remote state.
Used in start/stop fashion in eg doctests; wrapped in the SFTP fixtures in conftest.py for main use.
New in version 2.1.
-
__weakref__¶ list of weak references to the object (if defined)
-
-
class
fabric.testing.base.Session(host=None, user=None, port=None, commands=None, cmd=None, out=None, in_=None, err=None, exit=None, waits=None)¶ A mock remote session of a single connection and 1 or more command execs.
Allows quick configuration of expected remote state, and also helps generate the necessary test mocks used by
MockRemoteitself. Only useful when handed intoMockRemote.The parameters
cmd,out,err,exitandwaitsare all shorthand for the same constructor arguments for a single anonymousCommand; seeCommandfor details.To give fully explicit
Commandobjects, use thecommandsparameter.Parameters: - user (str) –
- host (str) –
- port (int) – Sets up expectations that a connection will be generated to the given
user, host and/or port. If
None(default), no expectations are generated / any value is accepted. - commands –
Iterable of
Commandobjects, used when mocking nontrivial sessions involving >1 command execution per host. Default:None.Note
Giving
cmd,outetc alongside explicitcommandsis not allowed and will result in an error.
New in version 2.1.
-
__weakref__¶ list of weak references to the object (if defined)
-
generate_mocks()¶ -
Specifically, the client will expect itself to be connected to
self.host(if given), the channels will be associated with the client’sTransport, and the channels will expect/provide command-execution behavior as specified on theCommandobjects supplied to thisSession.The client is then attached as
self.clientand the channels asself.channels.Returns: None- this is mostly a “deferred setup” method and callers will just reference the above attributes (and call more methods) as needed.New in version 2.1.
testing.fixtures¶
pytest fixtures for easy use of Fabric test helpers.
To get Fabric plus this module’s dependencies (as well as those of the main
fabric.testing.base module which these fixtures wrap), pip install
fabric[pytest].
The simplest way to get these fixtures loaded into your test suite so Pytest
notices them is to import them into a conftest.py (docs).
For example, if you intend to use the remote and client fixtures:
from fabric.testing.fixtures import client, remote
New in version 2.1.
-
fabric.testing.fixtures.client()¶ Mocks
SSHClientfor testing calls toconnect().Yields a mocked
SSHClientinstance.This fixture updates
get_transportto return a mock that appears active on first check, then inactive after, matching most tests’ needs by default:Connectioninstantiates, with a None.transport.- Calls to
.open()test.is_connected, which returnsFalsewhen.transportis falsey, and so the first open will callSSHClient.connectregardless. .open()then sets.transporttoSSHClient.get_transport(), soConnection.transportis effectivelyclient.get_transport.return_value.- Subsequent activity will want to think the mocked SSHClient is
“connected”, meaning we want the mocked transport’s
.activeto beTrue. - This includes
Connection.close, which short-circuits if.is_connected; having a staticallyTrueactive flag means a full open -> close cycle will run without error. (Only tests that double-close or double-open should have issues here.)
End result is that:
.is_connectedbehaves False after instantiation and before.open, then True after.open.closewill work normally on 1st call.closewill behave “incorrectly” on subsequent calls (since it’ll think connection is still live.) Tests that check the idempotency of.closewill need to tweak their mock mid-test.
For ‘full’ fake remote session interaction (i.e. stdout/err reading/writing, channel opens, etc) see
remote.New in version 2.1.
-
fabric.testing.fixtures.connection()¶ Yields a
Connectionobject with mocked methods.Specifically:
- the hostname is set to
"host"and the username to"user"; - the primary API members (
Connection.run,Connection.local, etc) are replaced withmock.Mockinstances; - the
run.in_streamconfig option is set toFalseto avoid attempts to read from stdin (which typically plays poorly with pytest and other capturing test runners);
New in version 2.1.
- the hostname is set to
-
fabric.testing.fixtures.cxn()¶ Yields a
Connectionobject with mocked methods.Specifically:
- the hostname is set to
"host"and the username to"user"; - the primary API members (
Connection.run,Connection.local, etc) are replaced withmock.Mockinstances; - the
run.in_streamconfig option is set toFalseto avoid attempts to read from stdin (which typically plays poorly with pytest and other capturing test runners);
New in version 2.1.
- the hostname is set to
-
fabric.testing.fixtures.remote()¶ Fixture allowing setup of a mocked remote session & access to sub-mocks.
Yields a
MockRemoteobject (which may need to be updated viaMockRemote.expect,MockRemote.expect_sessions, etc; otherwise a default session will be used) & callsMockRemote.sanityandMockRemote.stopon teardown.New in version 2.1.
-
fabric.testing.fixtures.sftp()¶ Fixture allowing setup of a mocked remote SFTP session.
Yields a 3-tuple of: Transfer() object, SFTPClient object, and mocked OS module.
For many/most tests which only want the Transfer and/or SFTPClient objects, see
sftp_objsandtransferwhich wrap this fixture.New in version 2.1.