charlesreid1.com blog

Creating Mock API Servers

Posted in Python

permalink

Overview

In this post we discuss a way of mocking an API server during tests. This technique will let you create a fake API server that can respond to API calls however you want.

The technique is twofold:

  • First, we create a mock API handler that extends BaseHTTPRequestHandler, which is the built-in HTTP server class in Python. We can extend the server class to control how it responds to requests - to implement a method to respond to POST requests, we implement a do_POST() method, to respond to GET requests we implement a do_GET() method, and so on. (In the example below, we restrict the types of requests to JSON content only.)

  • Second, we use the Singleton design pattern, by implementing two class methods, start_serving() and stop_serving(), that we can call before and after our tests to set up and tear down the fake API server. This method will take care of starting the HTTP server on a separate thread, so that it does not block execution.

Mock API Server Class

Let's start with the mock server class. This is going to extend the BaseHTTPRequestHandler class from the http.server module, and extend it.

We implement a stub method for the POST response behavior; this is the only type of request that our mock API server will respond to.

We also have two stub class methods to start and stop the server.

class MockAPIServer(BaseHTTPRequestHandler):
    _server = None
    _thread = None

    def do_POST(self):
        pass

    @classmethod
    def start_serving(cls):
        pass

    @classmethod
    def stop_serving(cls):
        pass

Start/Stop Serving

We start with the two class methods to start and stop the server.

Getting Bind Address/Port

Define another static method to get the address to bind to, and the port to use; in this case we'll hard code values, but this function could also find unused networking ports, etc.

    @staticmethod
    def get_addr_port():
        addr = "127.0.0.1"
        port = "9876"
        return addr, port

Start Serving

Next, the start_serving() method should start a thread (using the cls._thread attribute to store it for later) and create an underlying HTTP server (and using the self._server attribute to store it for later):

    @classmethod
    def start_serving(cls):
        # Get the bind address and port
        cls._addr, cls._port = cls.get_addr_port()

        # Create an HTTP server
        cls._server = HTTPServer((cls._addr, cls._port), cls)

        # Create a thread to run the server
        cls._thread = threading.Thread(target=cls._server.serve_forever)

        # Start the server
        cls._thread.start()

Stop Serving

The stop_serving() method stops the thread

    @classmethod
    def stop_serving(cls):
        # Shut down the server
        if cls._server is not None:
            cls._server.shutdown()

        # Let the thread rejoin the worker pool
        cls._thread.join(timeout=10)
        assert not cls._thread.is_alive()

Handling Requests

The mock API server should only process POST requests, and should only accept JSON-formatted requests. We can implement those checks and have the server return a 500 error if clients do not send a properly formatted JSON request.

Defining POST Response Method

To define a response to POST requests made to the API we are mocking, we start by validating the JSON request that is received.

Note: this utilizes several built-in methods of the HTTP server class.

    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.get("content-type"))
        # Enforce rule: JSON only
        if ctype != "application/json":
            self.send_response(400)
            self.end_headers()
            return
        # Convert received JSON to dict
        length = int(self.headers.get("content-length"))
        message = json.loads(self.rfile.read(length))

        # Process the json
        ...

Now, the JSON can be processed using a validate function, for example, or generic success/failure responses returned based on the contents of a request.

Let's do something very simple: have the API server return whatever was sent in the request.

We can turn the dictionary message (a dictionary containing the original request) back into a string, and the string into a stream of bytes. Then we can write headers and the stream of bytes into the response.

        # Send a response
        response = bytes(json.dumps(message), "utf8")
        self._set_headers()
        self.wfile.write(response)

The _set_headers() method is a short method that just sends (writes) the correct headers:

    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()

Note: the send_headers() and end_headers() methods are built-in to the HTTP server base class we are using.

Putting it all together

Putting it all together, we get one final mock API server class:

class MockAPIServer(BaseHTTPRequestHandler):
    _server = None
    _thread = None

    @staticmethod
    def get_addr_port():
        addr = "127.0.0.1"
        port = "9876"
        return addr, port

    @classmethod
    def start_serving(cls):
        # Get the bind address and port
        cls._addr, cls._port = cls.get_addr_port()

        # Create an HTTP server
        cls._server = HTTPServer((cls._addr, cls._port), cls)

        # Create a thread to run the server
        cls._thread = threading.Thread(target=cls._server.serve_forever)

        # Start the server
        cls._thread.start()

    @classmethod
    def stop_serving(cls):
        # Shut down the server
        if cls._server is not None:
            cls._server.shutdown()

        # Let the thread rejoin the worker pool
        cls._thread.join(timeout=10)
        assert not cls._thread.is_alive()

    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.get("content-type"))
        # Enforce rule: JSON only
        if ctype != "application/json":
            self.send_response(400)
            self.end_headers()
            return
        # Convert received JSON to dict
        length = int(self.headers.get("content-length"))
        message = json.loads(self.rfile.read(length))

        # Process the json

        # Send a response
        response = bytes(json.dumps(message), "utf8")
        self._set_headers()
        self.wfile.write(response)

    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()

Tags:    http    server    python    mock    mocking    api    flask    web server   

Python: From Args to Kwargs

Posted in Python

permalink

Overview

In this short blog post, we talk about how and when you can take a method signature that defines input positional arguments by name, like this:

def foo(arg1, arg2, arg3):
    pass

and write code that will return a dictionary containing a keyword arguments-like structure:

>>> foo('red', 'blue', 'green')
{
    'arg1': 'red',
    'arg2': 'blue',
    'arg3': 'green'
}

We will cover an example of writing a decorator that utilizes input arguments from both the decorator and from the function it wraps, and how to keep all of that information straight.

The Easy Way: locals()

We'll start with the easiest possible wyay to turn args into kwargs: locals(). The locals() function is one of the built-in methods provided by Python:

>>> print(help(locals))

Help on built-in function locals in module builtins:

locals()
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

This is a straightforward way to get a dictionary of input argument names mapping to the values provided by the user:

>>> def foo(arg1, arg2, arg3):
...     print(locals())
...
>>> foo('asdf', 'qwerty', 'oioioioi')
{'arg3': 'oioioioi', 'arg2': 'qwerty', 'arg1': 'asdf'}

When locals() Won't Work: Getting a Method Signature Programmatically

Sometimes, locals() won't get you what you need - like when you're decorating a function, and you don't have the original method signature.

In that case, you can still use a function handle and get the original positional argument names from the function signature.

In Python, the signature of a method can be obtained using the inspect module's signature() method, which can be passed a function:

>>> import inspect
>>> def foo(arg1, arg2, arg3):
...      pass
...
>>> print(inspect.signature(foo))
(arg1, arg2, arg3)

The _parameters attribute of the signature will yield an ordered list of parameters in the method signature, which is equivalent to the variable names that are used in the method definition (arg1, arg2, and arg3 in the example foo() function above):

>>> print(list(inspect.signature(foo)._parameters))
['arg1', 'arg2', 'arg3']

Args to Kwargs: Parameter Extraction from Decorator

We can use this to get the original variable names from a function handle, even if we don't have its original method signature (i.e., if we're a decorator and are just passed the function).

Here is an example of a decorator that extracts positional arguments from the function it decorates (and prints them out!):

import inspect

def real_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):

        # This is where the interesting stuff starts!
        # We have a handle to a function that we're
        # decorating, but we don't have its original
        # method signature.
        # No sweat. Turn positional args into augmented
        # kwargs!
        func_kwargs = {}
        sig = inspect.signature(wrapper)
        for i, p in enumerate(list(sig._parameters)):
            try:
                func_kwargs[p] = args[i]
            except IndexError:
                # Unspecified positional argument
                # (using default value)
                pass

        print(f"wrapper extracted the following params: {func_kwargs}")
        func(*args, **kwargs)

    return wrapper

# don't forget to top it off
# by decorating a simple function
# and calling it if script is run
@real_decorator
def foo(arg1, arg2, arg3):
    print("hello world!")

if  __name__=="__main__":
    foo('asdf', 'qwerty', 'wioioioio')

And when run, the result is:

$ py five.py
wrapper extracted the following params: {'arg1': 'asdf', 'arg2': 'qwerty', 'arg3': 'wioioioio'}
hello world!

Tags:    python    programming    arguments    functions    methods    parameters   

Confuse-A-Constructor: When Class A's Constructor Returns Objects of Type B

Posted in Python

permalink

Confuse-A-Constructor

Today, we are going to confuse a constructor.

What is the constructor?

One of the first concepts encountered in object-oriented programming is that of the constructor, the method that is run immediately after an object is instantiated that configures and initializes the object.

In Python, a constructor is defined by the __init__ function. The constructor is not permitted to return a value, because constructing a new instance of class A should result in an object of type A. Returning something would just be confusing things.

But does it ever make sense for a constructor of class A to return an object of type B? And if it does make sense, how do we go about doing it?

Rewiring the constructor to do... weird stuff

The answer lies in Python's __new__ method, which is a method called when a class is defined (not instantiated). The __new__ method is different from the __init__ method, and does not do the same thing.

The __new__ method for class A should only return the type of class A. If __new__ returns anything else, Python will not run the __init__ method for class A.

For example, suppose we want a wrapper class that transparently constructs different kinds of objects conditionally - based on a configuration file, or the state of a file, or some other condition. We want to construct an object of type A and get back an object of type B, C, or D. How to do that?

First, let's look at how the __new__ method works.

A simple example class

Start with a simple example class:

class A(object):

    def __init__(self, *args, **kwargs):
        print("Instance of class A created")

    def hello(self):
        print("Hello world")

Executing this gives:

In [3]: my_object = A()
Instance of class A created

In [4]: my_object.hello()
Hello world

Adding a __new__ method

Now let's look at a class A where we define the __new__ method. This method controls how the instantiation of objects of type A work, so we can do something like limiting the creation of objects of type A to when a certain condition is met:

import random

def tossCoin():
    if random.random() < 0.5:
        return True
    else:
        return False

class A5050(object):
    def __new__(cls, *args, **kwargs):
        if not tossCoin():
            raise RuntimeError("Count not create instance")
        instance = super(A5050, cls).__new__(cls, *args, **kwargs)
        return instance

    def __init__(self, *args, **kwargs):
        print("Instance of class A5050 created")

    def hello(self):
        print("Hello world")

Now we can run this block of code:

def make_a5050():
    try:
        my_object = A5050()
        my_object.hello()
    except RuntimeError:
        print("Better luck next time!")

It takes a few tries:

In [9]: make_a5050()
Better luck next time!

In [10]: make_a5050()
Instance of class A5050 created
Hello world

The __new__ method for the A5050 class raises a runtime error with a 50% probability. Otherwise, it calls the __new__ method of the parent class (object, which returns a class of type object). We pass the same arguments and keyword arguments (args/kwargs) on to the super class __new__, but we could optionally modify them here (say, add a keyword, or check the state of a file, or etc.).

This is just an example of how the instantiation behavior of a class can be modified before its constructor is even called by using the __new__ method.

When __new__ returns objects, not classes

In the above example, our __new__ method returned the result of a call to __new__ of a parent class. What happens if __new__ returns something else?

First, repeating an important point made above: if __new__ for a class returns anything other than that class type, then __init__ will not be called for that class.

That means that the __new__ method should either return a class (if returning the type of its parent class, like a normal __new__ method does), or it should return an instantiated object.

Let's imagine that we want to create different instances of different classes based on a command line flag passed to the script:

class BaseClass(object):
    def hello(self):
        print("Hello world from class %s"%(self.__class__.__name__))

class B(BaseClass):
    pass

class C(BaseClass):
    pass

class D(BaseClass):
    pass

class A(object):
    def __new__(cls, args):
        if args.B:
            return B()
        elif args.C:
            return C()
        elif args.D:
            return D()
        else:
            raise RuntimeError("Could not create instance")

if __name__=="__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-B', action='store_true',
                        help='Return object of type B')
    parser.add_argument('-C', action='store_true',
                        help='Return object of type C')
    parser.add_argument('-D', action='store_true',
                        help='Return object of type D')

    args = parser.parse_args()

    a = A(args)
    print(type(a))

Now if we run this script and pass it different flags, we get a variable a with different types:

$ py wat2.py -h
usage: wat2.py [-h] [-B] [-C] [-D]

optional arguments:
  -h, --help  show this help message and exit
  -B          Return object of type B
  -C          Return object of type C
  -D          Return object of type D

Now try the three flags:

$ py wat2.py -B
<class '__main__.B'>

$ py wat2.py -C
<class '__main__.C'>

$ py wat2.py -D
<class '__main__.D'>

Moving beyond argparse

The example above shows how the constructor can use argparse options to determine what kind of object to return with __new__, but you can use other types of conditions as well:

  • using command line options (see argparse example above)
  • using configuration file options
  • using environment variable values
  • checking status of a file or port
  • checking whether internet connection is available

Using __new__ in your patterns

We have already covered the Registry pattern in a prior blog post, but the __new__ method lends itself well to all kinds of other patterns, including the Singleton pattern and the Factory pattern.

There are some very useful patterns covered in this Github repository: https://github.com/faif/python-patterns

November 2026

Baby Mac Crypto

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

November 2017

A Hard(y) Math Problem