Defining mock connections

Start with some setup.


In [ ]:
import sys
sys.path.append('/opt/rhc')

import rhc.micro as micro
import rhc.async as async

import logging
logging.basicConfig(level=logging.DEBUG)

Create a simple resource


In [ ]:
p=micro.load_connection([
    'CONNECTION placeholder http://jsonplaceholder.typicode.com',
    'RESOURCE document /posts/{id}',
])
async.wait(micro.connection.placeholder.document(1))

Define a mock for the resource

Here we define an object with a method named document and assign it to the connection's mock attribute.

Note: the method name matches the RESOURCE name.


In [ ]:
class MyMock(object):
    def document(self, method, path, headers, body):
        print('method', method)
        print('path', path)
        print('headers', headers)
        print('body', body)
        return 'foo'
micro.connection.placeholder.mock = MyMock()

Call the mocked resource

With a mock in place, we can make the same call as earlier, but instead of making a network connection, the document method on the connection's mock attribute is called.


In [ ]:
async.wait(micro.connection.placeholder.document(1))

What is going on here?

The mock is not called until the arguments provided to the partial are evaluated and prepared for the HTTP connection; this ensures that the mock data matches the actual connection data.

The mock is called with:

  1. the HTTP method
  2. the path, with any substititions
  3. headers as a dict
  4. content as a dict, or None if no content

Notes:

  • The return value from the mock will be used as the partial's response. The final line, "foo", is the return from the mock document RESOURCE as printed by the default async.wait callback handler.
  • If the mock throws an exception, the callback will be called with a non-zero result.
  • The handler, setup and wrapper functions are not called.
  • The example uses a class; it could also be a collection of functions in a module.

Here is an example of content created from unused kwargs:


In [ ]:
async.wait(micro.connection.placeholder.document(1, test='value'))

In [ ]: