API Reference

The mbtest.server module

mbtest.server.mock_server(request, executable=PosixPath('node_modules/.bin/mb'), port=2525, *, timeout=5, debug=True, allow_injection=True, local_only=True, data_dir='.mbdb')[source]

Pytest fixture, making available a mock server, running one or more imposters, one for each domain being mocked.

Use in a pytest conftest.py fixture as follows:

@pytest.fixture(scope="session")
def mock_server(request):
    return server.mock_server(request)

Test will look like:

def test_an_imposter(mock_server):
    imposter = Imposter(Stub(Predicate(path='/test'),
                             Response(body='sausages')),
                        record_requests=True)

    with mock_server(imposter) as s:
        r = requests.get(f"{imposter.url}/test")

        assert_that(r, is_response().with_status_code(200).and_body("sausages"))
        assert_that(s, had_request(path='/test', method="GET"))
Parameters:
  • request (FixtureRequest) – Request for a fixture from a test or fixture function.

  • executable (str | Path) – Alternate location for the Mountebank executable.

  • port (int) – Server port.

  • timeout (int) – specifies how long to wait for the Mountebank server to start.

  • debug (bool) – Start the server in debug mode, which records all requests. This needs to be True for the mbtest.matchers.had_request() matcher to work.

  • allow_injection (bool) – Allow JavaScript injection. If True, local_only should also be True,as per Mountebank security.

  • local_only (bool) – Accept request only from localhost.

  • data_dir (str | None) – Persist all operations to disk, in this directory.

Return type:

MountebankServer

Returns:

Mock server.

class mbtest.server.MountebankServer(port, scheme='http', host='localhost', imposters_path='imposters')[source]

Allow addition of imposters to an already running Mountebank mock server.

Test will look like:

def test_an_imposter(mock_server):
    mb = MountebankServer(1234)
    imposter = Imposter(Stub(Predicate(path='/test'),
                             Response(body='sausages')),
                        record_requests=True)

    with mb(imposter):
        r = requests.get(f"{imposter.url}/test")

        assert_that(r, is_response().with_status_code(200).and_body("sausages"))
        assert_that(imposter, had_request(path='/test', method="GET"))

Imposters will be torn down when the with block is exited.

Parameters:
  • port (int) – Server port.

  • scheme (str) – Server scheme, if not http.

  • host (str) – Server host, if not localhost.

  • imposters_path (str) – Imposters path, if not imposters.

add_imposters(definition)[source]

Add imposters to Mountebank server.

Parameters:

definition (Imposter | Iterable[Imposter]) – One or more Imposters.

Return type:

None

add_impostor(definition)[source]

Add single imposter to Mountebank server.

Parameters:

definition (Imposter) – One or more Imposters.

Return type:

None

delete_imposters()[source]

Delete all impostors from server.

Return type:

None

delete_impostor(imposter)[source]

Delete impostor from server.

Return type:

None

get_actual_requests()[source]
Return type:

Sequence[Request]

property server_url: URL
query_all_imposters()[source]

Yield all imposters running on the server, including those defined elsewhere.

Return type:

Sequence[Imposter]

get_replayable_imposter(imposter)[source]

Retrieve a replayable version of an imposter.

Calls GET /imposters/{port}?replayable=true&removeProxies=true, which returns the imposter with all proxy responses captured as concrete stubs, ready to replay without an upstream service.

Parameters:

imposter (Imposter) – The running imposter to retrieve.

Return type:

Imposter

Returns:

A new Imposter object populated with the recorded stubs.

import_running_imposters()[source]

Replaces all running imposters with those defined on the server

Return type:

None

get_running_imposters()[source]

Returns all imposters that the instance is aware of

Return type:

Sequence[Imposter]

class mbtest.server.ExecutingMountebankServer(executable=PosixPath('node_modules/.bin/mb'), port=2525, *, timeout=5, debug=True, allow_injection=True, local_only=True, data_dir='.mbdb')[source]

A Mountebank mock server, running one or more imposters, one for each domain being mocked.

Test will look like:

def test_an_imposter(mock_server):
    mb = ExecutingMountebankServer()
    imposter = Imposter(Stub(Predicate(path='/test'),
                             Response(body='sausages')),
                        record_requests=True)

    with mb(imposter) as s:
        r = requests.get(f"{imposter.url}/test")

        assert_that(r, is_response().with_status_code(200).and_body("sausages"))
        assert_that(s, had_request(path='/test', method="GET"))

    mb.close()

The mountebank server will be started when this class is instantiated, and needs to be closed if it’s not to be left running. Consider using the mock_server() pytest fixture, which will take care of this for you.

Parameters:
  • executable (str | Path) – Optional, alternate location for the Mountebank executable.

  • port (int) – Server port.

  • timeout (float) – How long to wait for the Mountebank server to start.

  • debug (bool) – Start the server in debug mode, which records all requests. This needs to be True for the mbtest.matchers.had_request() matcher to work.

  • allow_injection (bool) –

    Allow JavaScript injection. If True, local_only should also be True,as per Mountebank security.

  • local_only (bool) – Accept request only from localhost.

  • data_dir (str | None) – Persist all operations to disk, in this directory.

running: ClassVar[set[int]] = {}
start_lock = <unlocked _thread.lock object>
close()[source]
Return type:

None

exception mbtest.server.MountebankException[source]

Exception using Mountebank server.

exception mbtest.server.MountebankPortInUseException[source]

Mountebank server failed to start - port already in use.

exception mbtest.server.MountebankTimeoutError[source]

Mountebank server failed to start in time.

The mbtest.imposters.imposters module

class mbtest.imposters.imposters.Imposter(stubs, port=None, *, protocol=Protocol.HTTP, name=None, default_response=None, key=None, cert=None, record_requests=True, mutual_auth=False, host=None, server_url=None)[source]

Represents a Mountebank imposter. Think of an imposter as a mock website, running a protocol, on a specific port. Required behaviors are specified using stubs.

Parameters:
  • stubs (Stub | Iterable[Stub]) – One or more Stubs.

  • port (int | None) – Port.

  • protocol (Protocol | str) – Protocol to run on.

  • name (str | None) – Imposter name - useful for interactive exploration of imposters on http://localhost:2525/imposters

  • default_response (HttpResponse | None) – The default response to send if no predicate matches.

  • record_requests (bool) – Record requests made against this imposter, so they can be asserted against later.

  • mutual_auth (bool) – Server will request a client certificate.

  • key (str | None) – SSL server certificate.

  • cert (str | None) – SSL server certificate.

class Protocol(*values)[source]

Imposter Protocol.

HTTP = 'http'
HTTPS = 'https'
SMTP = 'smtp'
TCP = 'tcp'
stubs: list[Stub]
port: int | None = None
protocol: Protocol = 'http'
name: str | None = None
default_response: HttpResponse | None = None
record_requests: bool = True
mutual_auth: bool = False
key: str | None = None
cert: str | None = None
host: str | None = None
server_url: URL | None = None
property url: URL | None
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Imposter

Returns:

Converted object.

save(path)[source]

Save this imposter to a JSON file for later replay.

The saved file can be loaded with from_file() and posted to a Mountebank server, or used directly with Mountebank’s --configfile option.

Parameters:

path (Path | str) – Destination file path.

Return type:

None

classmethod from_file(path)[source]

Load an imposter from a JSON file previously saved with save().

Parameters:

path (Path | str) – Source file path.

Return type:

Imposter

Returns:

An Imposter object.

get_actual_requests()[source]
Return type:

Sequence[Request]

attach(host, port, server_url)[source]

Attach imposter to a running MB server.

Return type:

None

property attached: bool

Imposter is attached to a running MB server.

property configuration_url: URL
query_all_stubs()[source]

Return all stubs running on the impostor, including those defined elsewhere.

Return type:

list[Stub]

playback()[source]
Return type:

list[Stub]

add_stubs(definition, index=None)[source]

Add one or more stubs to a running impostor.

Return type:

None

add_stub(definition, index=None)[source]

Add a stub to a running impostor. Returns index of new stub.

Return type:

int

delete_stub(index)[source]

Remove a stub from a running impostor.

Return type:

Stub

update_stub(index, definition)[source]

Change a stub in an existing imposter. Returns index of changed stub.

Return type:

int

class mbtest.imposters.imposters.Request[source]
static from_json(json)[source]
Return type:

Request

class mbtest.imposters.imposters.HttpRequest(method, path, query, headers, body=None)[source]
method: str
path: str
query: Mapping[str, str]
headers: Mapping[str, str]
body: str | None = None
static from_json(json)[source]
Return type:

HttpRequest

property json: MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | None
class mbtest.imposters.imposters.Address(address, name)[source]
address: str
name: str
class mbtest.imposters.imposters.SentEmail(from_, to, cc, bcc, subject, text)[source]
from_: Address
to: list[Address]
cc: list[Address]
bcc: list[Address]
subject: str
text: str
static from_json(json)[source]
Return type:

SentEmail

mbtest.imposters.imposters.smtp_imposter(name='smtp', *, record_requests=True)[source]

Canned SMTP server imposter.

Return type:

Imposter

The mbtest.imposters.stubs module

class mbtest.imposters.stubs.Stub(predicates=None, responses=None)[source]

Represents a Mountebank stub. Think of a stub as a behavior, triggered by a matching predicate.

Parameters:
predicates: list[BasePredicate]
responses: list[BaseResponse]
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Stub

Returns:

Converted object.

class mbtest.imposters.stubs.AddStub(stub=<factory>, index=None)[source]

Represents a Mountebank add stub request <http://localhost:2525/docs/api/overview#add-stub>. To add new stab to an existing imposter.

Parameters:
  • index (int | None) – The index in imposter stubs array. If you leave off the index field, the stub will be added to the end of the existing stubs array.

  • stub (Stub) – The stub that will be added to the existing stubs array

stub: Stub
index: int | None = None
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

AddStub

Returns:

Converted object.

The mbtest.imposters.predicates module

class mbtest.imposters.predicates.BasePredicate[source]
classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

BasePredicate

Returns:

Converted object.

class mbtest.imposters.predicates.LogicallyCombinablePredicate[source]
class mbtest.imposters.predicates.Predicate(*, path=None, method=None, query=None, body=None, headers=None, xpath=None, jsonpath=None, form=None, operator=Operator.EQUALS, case_sensitive=True)[source]

Represents a Mountebank predicate. A predicate can be thought of as a trigger, which may or may not match a request.

Parameters:
exception InvalidPredicateOperator[source]
class Method(*values)[source]

Predicate HTTP method.

DELETE = 'DELETE'
GET = 'GET'
HEAD = 'HEAD'
POST = 'POST'
PUT = 'PUT'
PATCH = 'PATCH'
OPTIONS = 'OPTIONS'
class Operator(*values)[source]

Predicate operator.

EQUALS = 'equals'
DEEP_EQUALS = 'deepEquals'
CONTAINS = 'contains'
STARTS_WITH = 'startsWith'
ENDS_WITH = 'endsWith'
MATCHES = 'matches'
EXISTS = 'exists'
classmethod has_value(name)[source]
Return type:

bool

path: str | None = None
method: Method | None = None
query: Mapping[str, str | int | bool] | None = None
body: str | MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | None = None
headers: Mapping[str, str] | None = None
xpath: str | None = None
jsonpath: str | None = None
form: Mapping[str, str] | None = None
operator: Operator = 'equals'
case_sensitive: bool = True
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Predicate

Returns:

Converted object.

fields_as_structure()[source]
Return type:

dict[str, Any]

class mbtest.imposters.predicates.AndPredicate(left, right)[source]
left: BasePredicate
right: BasePredicate
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

AndPredicate

Returns:

Converted object.

class mbtest.imposters.predicates.OrPredicate(left, right)[source]
left: BasePredicate
right: BasePredicate
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

OrPredicate

Returns:

Converted object.

class mbtest.imposters.predicates.NotPredicate(inverted)[source]
inverted: BasePredicate
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

NotPredicate

Returns:

Converted object.

class mbtest.imposters.predicates.TcpPredicate(data)[source]

Represents a Mountebank TCP predicate. A predicate can be thought of as a trigger, which may or may not match a request.

Parameters:

data (str) – Data to match the request.

data: str
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

TcpPredicate

Returns:

Converted object.

class mbtest.imposters.predicates.InjectionPredicate(inject)[source]

Represents a Mountebank injection predicate. A predicate can be thought of as a trigger, which may or may not match a request.

Injection requires Mountebank version 2.0 or higher.

Parameters:

inject (str) – JavaScript function to inject.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

InjectionPredicate

Returns:

Converted object.

The mbtest.imposters.responses module

class mbtest.imposters.responses.BaseResponse[source]
classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

BaseResponse

Returns:

Converted object.

class mbtest.imposters.responses.HttpResponse(body='', status_code=HTTPStatus.OK, headers=None, mode=None)[source]

Represents a Mountebank HTTP response.

Parameters:
body: str | MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | Element | bytes = ''
status_code: HTTPStatus | int | str = 200
headers: Mapping[str, str] | None = None
mode: Mode
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

HttpResponse

Returns:

Converted object.

class mbtest.imposters.responses.Response(*, body='', status_code=HTTPStatus.OK, wait=None, repeat=None, headers=None, mode=None, copy=None, decorate=None, lookup=None, shell_transform=None, http_response=None)[source]

Represents a Mountebank ‘is’ response behavior.

Parameters:
class Mode(*values)[source]
TEXT = 'text'
BINARY = 'binary'
http_response: HttpResponse
wait: int | str | None = None
repeat: int | None = None
copy: list[Copy] | None = None
decorate: str | None = None
lookup: list[Lookup] | None = None
shell_transform: str | Iterable[str] | None = None
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Response

Returns:

Converted object.

property body: str | MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | Element | bytes
property status_code: HTTPStatus | int | str
property headers: Mapping[str, str] | None
property mode: Mode
class mbtest.imposters.responses.TcpResponse(data)[source]
data: str
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

TcpResponse

Returns:

Converted object.

class mbtest.imposters.responses.FaultResponse(fault)[source]

Represents a Mountebank fault response.

Parameters:

fault (Fault) – The fault to simulate.

class Fault(*values)[source]
CONNECTION_RESET_BY_PEER = 'CONNECTION_RESET_BY_PEER'
RANDOM_DATA_THEN_CLOSE = 'RANDOM_DATA_THEN_CLOSE'
fault: Fault
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

FaultResponse

Returns:

Converted object.

class mbtest.imposters.responses.Proxy(to, wait=None, inject_headers=None, mode=Mode.ONCE, predicate_generators=<factory>, decorate=None)[source]

Represents a Mountebank proxy.

Parameters:

to (URL | str) – The origin server, to which the request should proxy.

class Mode(*values)[source]

Defines the replay behavior of the proxy.

ONCE = 'proxyOnce'
ALWAYS = 'proxyAlways'
TRANSPARENT = 'proxyTransparent'
to: URL | str
wait: int | None = None
inject_headers: Mapping[str, str] | None = None
mode: Mode = 'proxyOnce'
predicate_generators: list[PredicateGenerator]
decorate: str | None = None
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Proxy

Returns:

Converted object.

class mbtest.imposters.responses.PredicateGenerator(path=False, query=False, operator=Operator.EQUALS, case_sensitive=True)[source]

Represents a Mountebank predicate generator.

Parameters:

path (bool) – Include the path in the generated predicate.

path: bool = False
query: bool | MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] = False
operator: Operator = 'equals'
case_sensitive: bool = True
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

PredicateGenerator

Returns:

Converted object.

class mbtest.imposters.responses.InjectionResponse(inject)[source]

Represents a Mountebank injection response.

Injection requires Mountebank version 2.0 or higher.

Parameters:

inject (str) – JavaScript function to inject .

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

InjectionResponse

Returns:

Converted object.

The mbtest.imposters.behaviors.copy module

class mbtest.imposters.behaviors.copy.Copy(from_, into, using)[source]

Represents a copy behavior.

Parameters:
  • from – The name of the request field to copy from, or, if the request field is an object, then an object specifying the path to the request field.

  • into (str) – The token to replace in the response with the selected request value.

  • using (Using) – The configuration needed to select values from the response.

from_: str | MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]
into: str
using: Using
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Copy

Returns:

Converted object.

The mbtest.imposters.behaviors.lookup module

class mbtest.imposters.behaviors.lookup.Lookup(key, datasource_path, datasource_key_column, into)[source]

Represents a lookup behavior.

Parameters:
  • key (Key) – How to select the key from the request.

  • datasource_path (str | Path) – The path to the data source.

  • datasource_key_column (str) – The header of the column to match against the key.

  • into (str) – The token to replace in the response with the selected request value.

key: Key
datasource_path: str | Path
datasource_key_column: str
into: str
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Lookup

Returns:

Converted object.

class mbtest.imposters.behaviors.lookup.Key(from_, using, index=0)[source]

The information on how to select the key from the request.

Parameters:
  • from – The name of the request field to copy from, or, if the request field is an object, then an object specifying the path to the request field.

  • using (Using) – The configuration needed to select values from the response

  • index (int) – Index of the iten from the result array to be selected.

from_: str
using: Using
index: int = 0
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Key

Returns:

Converted object.

The mbtest.imposters.behaviors.using module

class mbtest.imposters.behaviors.using.Using(selector)[source]

How to select values from the response.

Parameters:

selector (str) – The selector used to select the value(s) from the request.

class Method(*values)[source]
REGEX = 'regex'
XPATH = 'xpath'
JSONPATH = 'jsonpath'
selector: str
abstract property method: Method
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

Using

Returns:

Converted object.

class mbtest.imposters.behaviors.using.UsingRegex(selector, ignore_case=False, multiline=False)[source]

Select values from the response using a regular expression.

Parameters:
  • selector (str) – The selector used to select the value(s) from the request.

  • ignore_case (bool) – Uses a case-insensitive regular expression

  • multiline (bool) – Uses a multiline regular expression

ignore_case: bool = False
multiline: bool = False
property method: Method
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

UsingRegex

Returns:

Converted object.

class mbtest.imposters.behaviors.using.UsingXpath(selector, ns=None)[source]

Select values from the response using an xpath expression.

Parameters:
ns: MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | None = None
property method: Method
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

UsingXpath

Returns:

Converted object.

class mbtest.imposters.behaviors.using.UsingJsonpath(selector)[source]

Select values from the response using a jsonpath expression.

Parameters:

selector (str) – The selector used to select the value(s) from the request.

property method: Method
classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

UsingJsonpath

Returns:

Converted object.

The mbtest.matchers module

mbtest.matchers.had_request(*, method=<IsAnything(ANYTHING)>, path=<IsAnything(ANYTHING)>, query=<IsAnything(ANYTHING)>, headers=<IsAnything(ANYTHING)>, body=<IsAnything(ANYTHING)>, times=<IsAnything(ANYTHING)>)[source]

Mountebank server has recorded call matching.

Build criteria with with_ and and_ methods:

assert_that(server, had_request().with_path(“/test”).and_method(“GET”))

Available attributes as per parameters.

Parameters:
Return type:

Matcher[Imposter | MountebankServer]

class mbtest.matchers.HadRequest(*, method=<IsAnything(ANYTHING)>, path=<IsAnything(ANYTHING)>, query=<IsAnything(ANYTHING)>, headers=<IsAnything(ANYTHING)>, body=<IsAnything(ANYTHING)>, times=<IsAnything(ANYTHING)>)[source]

Mountebank server has recorded call matching

Parameters:
describe_to(description)[source]

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters:

description (Description) – The description to be built or appended to.

Return type:

None

static append_matcher_description(field_matcher, field_name, description)[source]
Return type:

None

describe_mismatch(item, mismatch_description)[source]

Generates a description of why the matcher has not accepted the item.

The description will be part of a larger description of why a matching failed, so it should be concise.

This method assumes that matches(item) is False, but will not check this.

Parameters:
Return type:

None

with_method(method)[source]

Matches the HTTP method of recorded requests.

Parameters:

method (str | Matcher[str]) – Expected HTTP method string or a matcher for the method.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_method(method)

Matches the HTTP method of recorded requests.

Parameters:

method (str | Matcher[str]) – Expected HTTP method string or a matcher for the method.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_path(path)[source]

Matches the path of recorded requests.

Parameters:

path (furl | URL | str | Matcher[furl | URL | str]) – Expected path string/object or a matcher for the path.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_path(path)

Matches the path of recorded requests.

Parameters:

path (furl | URL | str | Matcher[furl | URL | str]) – Expected path string/object or a matcher for the path.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_query(query)[source]

Matches the query parameters of recorded requests.

Parameters:

query (Mapping[str, str] | Matcher[Mapping[str, str]]) – Expected query mapping or a matcher for query parameters.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_query(query)

Matches the query parameters of recorded requests.

Parameters:

query (Mapping[str, str] | Matcher[Mapping[str, str]]) – Expected query mapping or a matcher for query parameters.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_headers(headers)[source]

Matches the headers of recorded requests.

Parameters:

headers (Mapping[str, str] | Matcher[Mapping[str, str]]) – Expected headers mapping or a matcher for headers.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_headers(headers)

Matches the headers of recorded requests.

Parameters:

headers (Mapping[str, str] | Matcher[Mapping[str, str]]) – Expected headers mapping or a matcher for headers.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_body(body)[source]

Matches the raw body text of recorded requests.

Parameters:

body (str | Matcher[str]) – Expected body string or a matcher for the body.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_body(body)

Matches the raw body text of recorded requests.

Parameters:

body (str | Matcher[str]) – Expected body string or a matcher for the body.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_json(json)[source]

Matches the JSON payload of recorded requests.

Parameters:

json (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | Matcher[MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]]) – Expected JSON object or a matcher for the JSON payload.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_json(json)

Matches the JSON payload of recorded requests.

Parameters:

json (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None] | Matcher[MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]]) – Expected JSON object or a matcher for the JSON payload.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

with_times(times)[source]

Matches the count of recorded requests matching the criteria.

Parameters:

times (int | Matcher[int]) – Expected count integer or a matcher for the count.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

and_times(times)

Matches the count of recorded requests matching the criteria.

Parameters:

times (int | Matcher[int]) – Expected count integer or a matcher for the count.

Return type:

HadRequest

Returns:

This matcher instance for chaining.

mbtest.matchers.email_sent(from_=<IsAnything(ANYTHING)>, to=<IsAnything(ANYTHING)>, subject=<IsAnything(ANYTHING)>, body_text=<IsAnything(ANYTHING)>)[source]

Mountebank SMTP server was asked to sent email matching.

Build criteria with with_ and and_ methods:

assert_that(server, email_sent().with_body_text(“hello”).and_subject(“hi”))

Available attributes as per parameters.

Parameters:
Return type:

Matcher[Imposter | MountebankServer]

class mbtest.matchers.EmailSent(from_=<IsAnything(ANYTHING)>, to=<IsAnything(ANYTHING)>, subject=<IsAnything(ANYTHING)>, body_text=<IsAnything(ANYTHING)>)[source]

Mountebank SMTP server was asked to sent email matching.

Parameters:
describe_to(description)[source]

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters:

description (Description) – The description to be built or appended to.

Return type:

None

describe_mismatch(item, mismatch_description)[source]

Generates a description of why the matcher has not accepted the item.

The description will be part of a larger description of why a matching failed, so it should be concise.

This method assumes that matches(item) is False, but will not check this.

Parameters:
Return type:

None

static get_sent_email(actual)[source]
Return type:

Sequence[SentEmail]

get_matching_emails(sent_email)[source]
Return type:

Sequence[SentEmail]

with_from_(from_)[source]

Matches the sender address of sent emails.

Parameters:

from – Expected sender address or a matcher for the sender.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

and_from_(from_)

Matches the sender address of sent emails.

Parameters:

from – Expected sender address or a matcher for the sender.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

with_to(to)[source]

Matches the recipient addresses of sent emails.

Parameters:

to (Sequence[Address] | Matcher[Sequence[Address]]) – Expected sequence of recipient addresses or a matcher for them.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

and_to(to)

Matches the recipient addresses of sent emails.

Parameters:

to (Sequence[Address] | Matcher[Sequence[Address]]) – Expected sequence of recipient addresses or a matcher for them.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

with_subject(subject)[source]

Matches the subject line of sent emails.

Parameters:

subject (str | Matcher[str]) – Expected subject string or a matcher for the subject.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

and_subject(subject)

Matches the subject line of sent emails.

Parameters:

subject (str | Matcher[str]) – Expected subject string or a matcher for the subject.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

with_body_text(body_text)[source]

Matches the plain text body of sent emails.

Parameters:

body_text (str | Matcher[str]) – Expected body text string or a matcher for the body text.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

and_body_text(body_text)

Matches the plain text body of sent emails.

Parameters:

body_text (str | Matcher[str]) – Expected body text string or a matcher for the body text.

Return type:

EmailSent

Returns:

This matcher instance for chaining.

The mbtest.imposters.base module

class mbtest.imposters.base.JsonSerializable[source]

Object capable of being converted to a JSON serializable structure (using as_structure()) or from such a structure ((using from_structure()).

abstractmethod as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

abstractmethod classmethod from_structure(structure)[source]

Convert from a JSON serializable structure.

Parameters:

structure (MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]) – JSON structure to be converted.

Return type:

JsonSerializable

Returns:

Converted object.

static add_if_true(dictionary, key, value)[source]

Add key/value to dictionary only if value is truthy.

Return type:

None

static one_or_many(value)[source]

Normalise None / a single item / an iterable to a list, or None.

Return type:

list[TypeVar(_T)] | None

static as_json_object(value)[source]

Narrow a JsonValue value to a JsonObject (dict[str, JsonValue]).

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

class mbtest.imposters.base.Injecting(inject)[source]
inject: str
as_structure()[source]

Convert to a JSON serializable structure.

Return type:

MutableMapping[str, str | int | float | bool | MutableSequence[JsonValue] | MutableMapping[str, JsonValue] | None]

Returns:

Structure suitable for JSON serialisation.

Indices and tables