Uhm.Server

g GObject.Object GObject.Object Uhm.Server Uhm.Server GObject.Object->Uhm.Server

Subclasses:

None

Methods

Inherited:

GObject.Object (37)

Structs:

GObject.ObjectClass (5)

class

error_quark ()

class

new ()

class

received_message_chunk_from_soup (logger, level, direction, data, user_data)

compare_messages_remove_filter (filter_id)

end_trace ()

filter_ignore_parameter_values (parameter_names)

get_address ()

get_enable_logging ()

get_enable_online ()

get_port ()

get_resolver ()

get_tls_certificate ()

get_trace_directory ()

load_trace (trace_file, cancellable)

load_trace_async (trace_file, cancellable, callback, *user_data)

load_trace_finish (result)

received_message_chunk (message_chunk, message_chunk_length)

received_message_chunk_with_direction (direction, data, data_length)

run ()

set_default_tls_certificate ()

set_enable_logging (enable_logging)

set_enable_online (enable_online)

set_expected_domain_names (domain_names)

set_tls_certificate (tls_certificate)

set_trace_directory (trace_directory)

start_trace (trace_name)

start_trace_full (trace_file)

stop ()

unload_trace ()

Virtual Methods

Inherited:

GObject.Object (7)

do_compare_messages (expected_message, actual_message)

do_handle_message (message)

Properties

Name

Type

Flags

Short Description

address

str

r

Address of the local mock server if it’s running.

enable-logging

bool

r/w

Whether network traffic should be logged to a trace file.

enable-online

bool

r/w

Whether network traffic should reach the Internet as normal.

port

int

r

Port of the local mock server if it’s running

resolver

Uhm.Resolver

r

Mock resolver used to redirect HTTP requests to the local mock server instance.

tls-certificate

Gio.TlsCertificate

r/w

TLS certificate for the mock server to use when serving HTTPS pages.

trace-directory

Gio.File

r/w

Directory relative to which all trace files will be resolved.

Signals

Inherited:

GObject.Object (1)

Name

Short Description

compare-messages

Emitted whenever the mock server must compare two Uhm.Message s for equality; e.g.

handle-message

Emitted whenever the mock server is running and receives a request from a client.

Fields

Inherited:

GObject.Object (1)

Name

Type

Access

Description

parent

GObject.Object

r

Class Details

class Uhm.Server(**kwargs)
Bases:

GObject.Object

Abstract:

No

Structure:

Uhm.ServerClass

All the fields in the Uhm.Server structure are private and should never be accessed directly.

New in version 0.1.0.

classmethod error_quark()
Return type:

int

classmethod new()
Returns:

a new Uhm.Server; unref with GObject.Object.unref()

Return type:

Uhm.Server

Creates a new Uhm.Server with default properties.

New in version 0.1.0.

classmethod received_message_chunk_from_soup(logger, level, direction, data, user_data)
Parameters:

Convenience version of Uhm.Server.received_message_chunk() which can be passed directly to Soup.Logger.set_printer() to forward all libsoup traffic logging to a Uhm.Server. The Uhm.Server must be passed to Soup.Logger.set_printer() as its user data.

UhmServer *mock_server;
SoupSession *session;
SoupLogger *logger;

mock_server = uhm_server_new ();
session = soup_session_new ();

logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
soup_logger_set_printer (logger, uhm_server_received_message_chunk_from_soup, g_object_ref (mock_server), g_object_unref);
soup_session_add_feature (session, SOUP_SESSION_FEATURE (logger));
g_object_unref (logger);

/* Do something with mock_server here. */

New in version 0.3.0.

compare_messages_remove_filter(filter_id)
Parameters:

filter_id (int) – filter ID returned by the filter addition function

Remove a Uhm.Server :compare-messages filter function installed previously by calling something like Uhm.Server.filter_ignore_parameter_values().

It is an error to call this function with an invalid filter_id.

New in version 0.5.0.

end_trace()

Convenience function to finish logging to or reading from a trace file previously passed to Uhm.Server.start_trace() or Uhm.Server.start_trace_full().

If Uhm.Server :enable-online is False, this will shut down the mock server (as if Uhm.Server.stop() had been called).

New in version 0.1.0.

filter_ignore_parameter_values(parameter_names)
Parameters:

parameter_names ([str]) – None-terminated array of parameter names to ignore

Returns:

opaque filter ID used with Uhm.Server.compare_messages_remove_filter() to remove the filter later

Return type:

int

Install a Uhm.Server :compare-messages filter function which will override the default comparison function to one which ignores differences in the values of the given query parameter_names. The named parameters must still be present in the query, however.

The filter will remain in place for the lifetime of the Uhm.Server, until uhm_server_compare_messages_remove_filter() is called with the returned filter ID.

Note that currently only one of the installed comparison functions will be used. This may change in future.

New in version 0.5.0.

get_address()
Returns:

the physical address of the listening socket the server is currently bound to; or None if the server is not running

Return type:

str or None

Gets the value of the Uhm.Server :address property.

New in version 0.1.0.

get_enable_logging()
Returns:

True if client network traffic is being logged to a trace file; False otherwise

Return type:

bool

Gets the value of the Uhm.Server :enable-logging property.

New in version 0.1.0.

get_enable_online()
Returns:

True if the server does not intercept and handle network connections from client code; False otherwise

Return type:

bool

Gets the value of the Uhm.Server :enable-online property.

New in version 0.1.0.

get_port()
Returns:

the port of the listening socket the server is currently bound to; or 0 if the server is not running

Return type:

int

Gets the value of the Uhm.Server :port property.

New in version 0.1.0.

get_resolver()
Returns:

the mock resolver in use by the mock server, or None if no resolver is active

Return type:

Uhm.Resolver or None

Gets the value of the Uhm.Server :resolver property.

New in version 0.1.0.

get_tls_certificate()
Returns:

the server’s current TLS certificate; or None if it’s serving HTTP only

Return type:

Gio.TlsCertificate or None

Gets the value of the Uhm.Server :tls-certificate property.

New in version 0.1.0.

get_trace_directory()
Returns:

the directory to load/store trace files from, or None

Return type:

Gio.File or None

Gets the value of the Uhm.Server :trace-directory property.

New in version 0.1.0.

load_trace(trace_file, cancellable)
Parameters:
Raises:

GLib.Error

Synchronously loads the given trace_file of network messages, ready to simulate a network conversation by matching requests against the file and returning the associated responses. Call Uhm.Server.run() to start the mock server afterwards.

Loading the trace file may be cancelled from another thread using cancellable.

On error, error will be set and the state of the Uhm.Server will not change. A GLib.IOError will be set if there is a problem reading the trace file.

New in version 0.1.0.

load_trace_async(trace_file, cancellable, callback, *user_data)
Parameters:

Asynchronous version of Uhm.Server.load_trace(). In callback, call Uhm.Server.load_trace_finish() to complete the operation.

New in version 0.1.0.

load_trace_finish(result)
Parameters:

result (Gio.AsyncResult) – asynchronous operation result passed to the callback

Raises:

GLib.Error

Finishes an asynchronous operation started by Uhm.Server.load_trace_async().

On error, error will be set and the state of the Uhm.Server will not change. See Uhm.Server.load_trace() for details on the error domains used.

New in version 0.1.0.

received_message_chunk(message_chunk, message_chunk_length)
Parameters:
  • message_chunk (str) – single line of a message which was received

  • message_chunk_length (int) – length of message_chunk in bytes

Raises:

GLib.Error

Indicates to the mock server that a single new line of a message was received from the real server. The message line may be appended to the current trace file if logging is enabled (Uhm.Server :enable-logging is True), adding a newline character at the end. If logging is disabled but online mode is enabled (Uhm.Server :enable-online is True), the message line will be compared to the next expected line in the existing trace file. Otherwise, this function is a no-op.

On failure, error will be set and the Uhm.Server state will remain unchanged apart from the parse state machine, which will remain in the state reached after parsing message_chunk. A %G_IO_ERROR will be returned if writing to the trace file failed. If in comparison mode and the received message chunk corresponds to an unexpected message in the trace file, a %UHM_SERVER_ERROR will be returned.

In common cases where message log data only needs to be passed to a Uhm.Server and not (for example) logged to an application-specific file or the command line as well, it is simpler to use Uhm.Server.received_message_chunk_from_soup(), passing it directly to Soup.Logger.set_printer(). See the documentation for Uhm.Server.received_message_chunk_from_soup() for details.

New in version 0.1.0.

received_message_chunk_with_direction(direction, data, data_length)
Parameters:
  • direction (int) – single character indicating the direction of message transmission

  • data (str) – single line of a message which was received

  • data_length (int) – length of data in bytes

Raises:

GLib.Error

Convenience version of Uhm.Server.received_message_chunk() which takes the message direction and data separately, as provided by libsoup in a Soup.LoggerPrinter callback.

UhmServer *mock_server;
SoupSession *session;
SoupLogger *logger;

static void
soup_log_printer (SoupLogger *logger, SoupLoggerLogLevel level, char direction, const char *data, gpointer user_data)
{
    /* Pass the data to libuhttpmock. */
UhmServer *mock_server = UHM_SERVER (user_data);
    uhm_server_received_message_chunk_with_direction (mock_server, direction, data, strlen (data), NULL);
}

mock_server = uhm_server_new ();
session = soup_session_new ();

logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
soup_logger_set_printer (logger, (SoupLoggerPrinter) soup_log_printer, g_object_ref (mock_server), g_object_unref);
soup_session_add_feature (session, SOUP_SESSION_FEATURE (logger));
g_object_unref (logger);

/* Do something with mock_server here. */

New in version 0.3.0.

run()

Runs the mock server, binding to a loopback TCP/IP interface and preparing a HTTPS server which is ready to accept requests. The TCP/IP address and port number are chosen randomly out of the loopback addresses, and are exposed as Uhm.Server :address and Uhm.Server :port once this function has returned. A Uhm.Resolver (exposed as Uhm.Server :resolver) is set as the default Gio.Resolver while the server is running.

The server is started in a worker thread, so this function returns immediately and the server continues to run in the background. Use Uhm.Server.stop() to shut it down.

This function always succeeds.

New in version 0.1.0.

set_default_tls_certificate()
Returns:

the default certificate set as Uhm.Server :tls-certificate

Return type:

Gio.TlsCertificate

Sets the value of the Uhm.Server :tls-certificate property to the default TLS certificate built in to libuhttpmock. This default certificate is not signed by any certificate authority, and contains minimal metadata details. It may be used by clients which have no special certificate requirements; clients which have special requirements should construct a custom Gio.TlsCertificate and pass it to Uhm.Server.set_tls_certificate().

New in version 0.1.0.

set_enable_logging(enable_logging)
Parameters:

enable_logging (bool) – True to log client network traffic to a trace file; False otherwise

Sets the value of the Uhm.Server :enable-logging property.

New in version 0.1.0.

set_enable_online(enable_online)
Parameters:

enable_online (bool) – True to not intercept and handle network connections from client code; False otherwise

Sets the value of the Uhm.Server :enable-online property.

New in version 0.1.0.

set_expected_domain_names(domain_names)
Parameters:

domain_names ([str] or None) – None-terminated array of domain names to expect, or None to not expect any

Set the domain names which are expected to have requests made of them by the client code interacting with this Uhm.Server. This is a convenience method which calls Uhm.Resolver.add_A() on the server’s Uhm.Resolver for each of the domain names listed in domain_names. It associates them with the server’s current IP address, and automatically updates the mappings if the IP address or resolver change.

Note that this will reset all records on the server’s Uhm.Resolver, replacing all of them with the provided domain_names.

It is safe to add further domain names to the Uhm.Resolver in a callback for the GObject.Object ::notify signal for Uhm.Server :resolver; that signal is emitted after the resolver is cleared and these domain_names are added.

New in version 0.3.0.

set_tls_certificate(tls_certificate)
Parameters:

tls_certificate (Gio.TlsCertificate or None) – TLS certificate for the server to use; or None to serve HTTP only

Sets the value of the Uhm.Server :tls-certificate property.

New in version 0.1.0.

set_trace_directory(trace_directory)
Parameters:

trace_directory (Gio.File or None) – a directory to load/store trace files from, or None to unset it

Sets the value of the Uhm.Server :trace-directory property.

New in version 0.1.0.

start_trace(trace_name)
Parameters:

trace_name (str) – name of the trace

Raises:

GLib.Error

Starts a mock server which follows the trace file of filename trace_name in the Uhm.Server :trace-directory directory. See Uhm.Server.start_trace_full() for further documentation.

This function has undefined behaviour if Uhm.Server :trace-directory is None.

On failure, error will be set and the Uhm.Server state will remain unchanged. See Uhm.Server.start_trace_full() for details of the error domains used.

New in version 0.1.0.

start_trace_full(trace_file)
Parameters:

trace_file (Gio.File) – a trace file to load

Raises:

GLib.Error

Convenience function to start logging to or reading from the given trace_file, depending on the values of Uhm.Server :enable-logging and Uhm.Server :enable-online.

If Uhm.Server :enable-logging is True, a log handler will be set up to redirect all client network activity into the given trace_file. If trace_file already exists, it will be overwritten.

If Uhm.Server :enable-online is False, the given trace_file is loaded using Uhm.Server.load_trace() and then a mock server is started using Uhm.Server.run().

On failure, error will be set and the Uhm.Server state will remain unchanged. A GLib.IOError will be set if logging is enabled (Uhm.Server :enable-logging) and there is a problem writing to the trace file; or if a trace needs to be loaded and there is a problem reading from the trace file.

New in version 0.1.0.

stop()

Stops a mock server started by calling Uhm.Server.run(). This shuts down the server’s worker thread and unbinds it from its TCP/IP socket.

This unloads any trace file loaded by calling Uhm.Server.load_trace() (or its asynchronous counterpart). It also resets the set of domain names loaded into the Uhm.Server :resolver.

This function always succeeds.

New in version 0.1.0.

unload_trace()

Unloads the current trace file of network messages, as loaded by Uhm.Server.load_trace() or Uhm.Server.load_trace_async().

New in version 0.1.0.

do_compare_messages(expected_message, actual_message) virtual
Parameters:
Return type:

bool

Class handler for the Uhm.Server ::compare-messages signal. Subclasses may implement this to override the default handler for the signal. The handler should return True if expected_message and actual_message compare equal, and False otherwise.

do_handle_message(message) virtual
Parameters:

message (Uhm.Message) –

Return type:

bool

Class handler for the Uhm.Server ::handle-message signal. Subclasses may implement this to override the default handler for the signal. The default handler should always return True to indicate that it has handled the message from client by setting an appropriate response on the Soup.ServerMessage.

Signal Details

Uhm.Server.signals.compare_messages(server, expected_message, actual_message)
Signal Name:

compare-messages

Flags:

RUN_LAST

Parameters:
Return type:

bool

Emitted whenever the mock server must compare two Uhm.Message s for equality; e.g. when in the testing or comparison modes. Test code may connect to this signal and implement a handler which checks custom properties of the messages. The default handler compares the URI and method of the messages, but no headers and not the message bodies.

Signal handlers should return True if the messages match; and False otherwise. The first signal handler executed when this signal is emitted wins.

New in version 1.0.0.

Uhm.Server.signals.handle_message(server, message)
Signal Name:

handle-message

Flags:

RUN_LAST

Parameters:
  • server (Uhm.Server) – The object which received the signal

  • message (Uhm.Message) – a message containing the incoming HTTP(S) request, and which the outgoing HTTP(S) response should be set on

Return type:

bool

Emitted whenever the mock server is running and receives a request from a client. Test code may connect to this signal and implement a handler which builds and returns a suitable response for a given message. The default handler reads a request–response pair from the current trace file, matches the requests and then returns the given response. If the requests don’t match, an error is raised.

Signal handlers should return True if they have handled the request and set an appropriate response; and False otherwise.

New in version 0.1.0.

Property Details

Uhm.Server.props.address
Name:

address

Type:

str

Default Value:

None

Flags:

READABLE

Address of the local mock server if it’s running, or None otherwise. This will be non-None between calls to Uhm.Server.run() and Uhm.Server.stop(). The address is a physical IP address, e.g. 127.0.0.1.

This should not normally need to be passed into client code under test, unless the code references IP addresses specifically. The mock server runs a DNS resolver which automatically redirects client requests for known domain names to this address (Uhm.Server :resolver).

New in version 0.1.0.

Uhm.Server.props.enable_logging
Name:

enable-logging

Type:

bool

Default Value:

False

Flags:

READABLE, WRITABLE

True if network traffic should be logged to a trace file (specified by calling Uhm.Server.start_trace()). This operates independently of whether traffic is online or being handled locally by the mock server. Use this in conjunction with Uhm.Server :enable-online to either log online traffic, or replay logged traffic locally.

New in version 0.1.0.

Uhm.Server.props.enable_online
Name:

enable-online

Type:

bool

Default Value:

False

Flags:

READABLE, WRITABLE

True if network traffic should reach the Internet as normal; False to redirect it to the local mock server. Use this in conjunction with Uhm.Server :enable-logging to either log online traffic, or replay logged traffic locally.

New in version 0.1.0.

Uhm.Server.props.port
Name:

port

Type:

int

Default Value:

0

Flags:

READABLE

Port of the local mock server if it’s running, or 0 otherwise. This will be non-0 between calls to Uhm.Server.run() and Uhm.Server.stop().

It is intended that this port be passed into the client code under test, to substitute for the default HTTPS port (443) which it would otherwise use.

New in version 0.1.0.

Uhm.Server.props.resolver
Name:

resolver

Type:

Uhm.Resolver

Default Value:

None

Flags:

READABLE

Mock resolver used to redirect HTTP requests from specified domain names to the local mock server instance. This will always be set while the server is running (between calls to Uhm.Server.run() and Uhm.Server.stop()), and is None otherwise.

Use the resolver specified in this property to add domain names which are expected to be requested by the current trace. Domain names not added to the resolver will be rejected by the mock server. The set of domain names in the resolver will be reset when Uhm.Server.stop() is called.

New in version 0.1.0.

Uhm.Server.props.tls_certificate
Name:

tls-certificate

Type:

Gio.TlsCertificate

Default Value:

None

Flags:

READABLE, WRITABLE

TLS certificate for the mock server to use when serving HTTPS pages. If this is non-None, the server will always use HTTPS. If it is None, the server will always use HTTP. The TLS certificate may be changed after constructing the Uhm.Server, but changes to the property will not take effect until the next call to Uhm.Server.run().

A certificate and private key may be generated by executing:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -nodes. These files may then be used to construct a Gio.TlsCertificate by calling Gio.TlsCertificate.new_from_files().

Alternatively, a default Gio.TlsCertificate which wraps a dummy certificate (not signed by any certificate authority) may be set by calling Uhm.Server.set_default_tls_certificate(). This may be used as the Uhm.Server :tls-certificate if the code under test has no specific requirements of the certificate used by the mock server it’s tested against.

New in version 0.1.0.

Uhm.Server.props.trace_directory
Name:

trace-directory

Type:

Gio.File

Default Value:

None

Flags:

READABLE, WRITABLE

Directory relative to which all trace files specified in calls to Uhm.Server.start_trace() will be resolved. This is not used for any other methods, but must be non-None if Uhm.Server.start_trace() is called.

New in version 0.1.0.