Uhm.Server¶
- Subclasses:
None
Methods¶
- Inherited:
- Structs:
class |
|
class |
|
class |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Virtual Methods¶
- Inherited:
|
|
|
Properties¶
Name |
Type |
Flags |
Short Description |
|---|---|---|---|
r |
Address of the local mock server if it’s running. |
||
r/w |
Whether network traffic should be logged to a trace file. |
||
r/w |
Whether network traffic should reach the Internet as normal. |
||
r |
Port of the local mock server if it’s running |
||
r |
Mock resolver used to redirect HTTP requests to the local mock server instance. |
||
r/w |
TLS certificate for the mock server to use when serving HTTPS pages. |
||
r/w |
Directory relative to which all trace files will be resolved. |
Signals¶
- Inherited:
Name |
Short Description |
|---|---|
Emitted whenever the mock server must compare two |
|
Emitted whenever the mock server is running and receives a request from a client. |
Fields¶
- Inherited:
Name |
Type |
Access |
Description |
|---|---|---|---|
parent |
r |
Class Details¶
- class Uhm.Server(**kwargs)¶
- Bases:
- Abstract:
No
- Structure:
All the fields in the
Uhm.Serverstructure are private and should never be accessed directly.New in version 0.1.0.
- classmethod new()¶
- Returns:
a new
Uhm.Server; unref withGObject.Object.unref()- Return type:
Creates a new
Uhm.Serverwith default properties.New in version 0.1.0.
- classmethod received_message_chunk_from_soup(logger, level, direction, data, user_data)¶
- Parameters:
logger (
Soup.Logger) – aSoup.Loggerlevel (
Soup.LoggerLogLevel) – the detail level of this log messagedirection (
int) – the transmission direction of the messagedata (
str) – message datauser_data (
objectorNone) – user data passed to theSoup.Logger, orNone
Convenience version of
Uhm.Server.received_message_chunk() which can be passed directly toSoup.Logger.set_printer() to forward all libsoup traffic logging to aUhm.Server. TheUhm.Servermust be passed toSoup.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-messagesfilter function installed previously by calling something likeUhm.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() orUhm.Server.start_trace_full().If
Uhm.Server:enable-onlineisFalse, this will shut down the mock server (as ifUhm.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:
Install a
Uhm.Server:compare-messagesfilter 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
Noneif the server is not running- Return type:
Gets the value of the
Uhm.Server:addressproperty.New in version 0.1.0.
- get_enable_logging()¶
- Returns:
Trueif client network traffic is being logged to a trace file;Falseotherwise- Return type:
Gets the value of the
Uhm.Server:enable-loggingproperty.New in version 0.1.0.
- get_enable_online()¶
- Returns:
Trueif the server does not intercept and handle network connections from client code;Falseotherwise- Return type:
Gets the value of the
Uhm.Server:enable-onlineproperty.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:
Gets the value of the
Uhm.Server:portproperty.New in version 0.1.0.
- get_resolver()¶
- Returns:
the mock resolver in use by the mock server, or
Noneif no resolver is active- Return type:
Uhm.ResolverorNone
Gets the value of the
Uhm.Server:resolverproperty.New in version 0.1.0.
- get_tls_certificate()¶
- Returns:
the server’s current TLS certificate; or
Noneif it’s serving HTTP only- Return type:
Gets the value of the
Uhm.Server:tls-certificateproperty.New in version 0.1.0.
- get_trace_directory()¶
-
Gets the value of the
Uhm.Server:trace-directoryproperty.New in version 0.1.0.
- load_trace(trace_file, cancellable)¶
- Parameters:
trace_file (
Gio.File) – trace file to loadcancellable (
Gio.CancellableorNone) – aGio.Cancellable, orNone
- Raises:
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.Serverwill not change. AGLib.IOErrorwill 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:
trace_file (
Gio.File) – trace file to loadcancellable (
Gio.CancellableorNone) – aGio.Cancellable, orNonecallback (
Gio.AsyncReadyCallbackorNone) – function to call once the async operation is completeuser_data (
objectorNone) – user data to pass to callback, orNone
Asynchronous version of
Uhm.Server.load_trace(). In callback, callUhm.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:
Finishes an asynchronous operation started by
Uhm.Server.load_trace_async().On error, error will be set and the state of the
Uhm.Serverwill not change. SeeUhm.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:
- Raises:
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-loggingisTrue), adding a newline character at the end. If logging is disabled but online mode is enabled (Uhm.Server:enable-onlineisTrue), 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.Serverstate 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.Serverand not (for example) logged to an application-specific file or the command line as well, it is simpler to useUhm.Server.received_message_chunk_from_soup(), passing it directly toSoup.Logger.set_printer(). See the documentation forUhm.Server.received_message_chunk_from_soup() for details.New in version 0.1.0.
- received_message_chunk_with_direction(direction, data, data_length)¶
- Parameters:
- Raises:
Convenience version of
Uhm.Server.received_message_chunk() which takes the message direction and data separately, as provided by libsoup in aSoup.LoggerPrintercallback.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:addressandUhm.Server:portonce this function has returned. AUhm.Resolver(exposed asUhm.Server:resolver) is set as the defaultGio.Resolverwhile 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:
Sets the value of the
Uhm.Server:tls-certificateproperty 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 customGio.TlsCertificateand pass it toUhm.Server.set_tls_certificate().New in version 0.1.0.
- set_enable_logging(enable_logging)¶
- Parameters:
enable_logging (
bool) –Trueto log client network traffic to a trace file;Falseotherwise
Sets the value of the
Uhm.Server:enable-loggingproperty.New in version 0.1.0.
- set_enable_online(enable_online)¶
- Parameters:
enable_online (
bool) –Trueto not intercept and handle network connections from client code;Falseotherwise
Sets the value of the
Uhm.Server:enable-onlineproperty.New in version 0.1.0.
- set_expected_domain_names(domain_names)¶
- Parameters:
domain_names ([
str] orNone) –None-terminated array of domain names to expect, orNoneto 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 callsUhm.Resolver.add_A() on the server’sUhm.Resolverfor 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.Resolverin a callback for theGObject.Object::notifysignal forUhm.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.TlsCertificateorNone) – TLS certificate for the server to use; orNoneto serve HTTP only
Sets the value of the
Uhm.Server:tls-certificateproperty.New in version 0.1.0.
- set_trace_directory(trace_directory)¶
- Parameters:
trace_directory (
Gio.FileorNone) – a directory to load/store trace files from, orNoneto unset it
Sets the value of the
Uhm.Server:trace-directoryproperty.New in version 0.1.0.
- start_trace(trace_name)¶
- Parameters:
trace_name (
str) – name of the trace- Raises:
Starts a mock server which follows the trace file of filename trace_name in the
Uhm.Server:trace-directorydirectory. SeeUhm.Server.start_trace_full() for further documentation.This function has undefined behaviour if
Uhm.Server:trace-directoryisNone.On failure, error will be set and the
Uhm.Serverstate will remain unchanged. SeeUhm.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:
Convenience function to start logging to or reading from the given trace_file, depending on the values of
Uhm.Server:enable-loggingandUhm.Server:enable-online.If
Uhm.Server:enable-loggingisTrue, 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-onlineisFalse, the given trace_file is loaded usingUhm.Server.load_trace() and then a mock server is started usingUhm.Server.run().On failure, error will be set and the
Uhm.Serverstate will remain unchanged. AGLib.IOErrorwill 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 theUhm.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() orUhm.Server.load_trace_async().New in version 0.1.0.
- do_compare_messages(expected_message, actual_message) virtual¶
- Parameters:
expected_message (
Uhm.Message) –actual_message (
Uhm.Message) –
- Return type:
Class handler for the
Uhm.Server::compare-messagessignal. Subclasses may implement this to override the default handler for the signal. The handler should returnTrueif expected_message and actual_message compare equal, andFalseotherwise.
- do_handle_message(message) virtual¶
- Parameters:
message (
Uhm.Message) –- Return type:
Class handler for the
Uhm.Server::handle-messagesignal. Subclasses may implement this to override the default handler for the signal. The default handler should always returnTrueto indicate that it has handled the message from client by setting an appropriate response on theSoup.ServerMessage.
Signal Details¶
- Uhm.Server.signals.compare_messages(server, expected_message, actual_message)¶
- Signal Name:
compare-messages- Flags:
- Parameters:
server (
Uhm.Server) – The object which received the signalexpected_message (
Uhm.Message) – a message containing the expected HTTP(S) message provided byUhm.Server::handle-messageactual_message (
Uhm.Message) – a message containing the incoming HTTP(S) request
- Return type:
Emitted whenever the mock server must compare two
Uhm.Messages 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
Trueif the messages match; andFalseotherwise. 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:
- Parameters:
server (
Uhm.Server) – The object which received the signalmessage (
Uhm.Message) – a message containing the incoming HTTP(S) request, and which the outgoing HTTP(S) response should be set on
- Return type:
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
Trueif they have handled the request and set an appropriate response; andFalseotherwise.New in version 0.1.0.
Property Details¶
- Uhm.Server.props.address¶
-
Address of the local mock server if it’s running, or
Noneotherwise. This will be non-Nonebetween calls toUhm.Server.run() andUhm.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¶
-
Trueif network traffic should be logged to a trace file (specified by callingUhm.Server.start_trace()). This operates independently of whether traffic is online or being handled locally by the mock server. Use this in conjunction withUhm.Server:enable-onlineto either log online traffic, or replay logged traffic locally.New in version 0.1.0.
- Uhm.Server.props.enable_online¶
-
Trueif network traffic should reach the Internet as normal;Falseto redirect it to the local mock server. Use this in conjunction withUhm.Server:enable-loggingto either log online traffic, or replay logged traffic locally.New in version 0.1.0.
- Uhm.Server.props.port¶
-
Port of the local mock server if it’s running, or 0 otherwise. This will be non-0 between calls to
Uhm.Server.run() andUhm.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:
- Default Value:
- Flags:
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() andUhm.Server.stop()), and isNoneotherwise.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:
- Default Value:
- Flags:
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 isNone, the server will always use HTTP. The TLS certificate may be changed after constructing theUhm.Server, but changes to the property will not take effect until the next call toUhm.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.TlsCertificateby callingGio.TlsCertificate.new_from_files().Alternatively, a default
Gio.TlsCertificatewhich wraps a dummy certificate (not signed by any certificate authority) may be set by callingUhm.Server.set_default_tls_certificate(). This may be used as theUhm.Server:tls-certificateif 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¶
-
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-NoneifUhm.Server.start_trace() is called.New in version 0.1.0.