Virtualising nameko services

I’ve recently been playing around a lot with microservices frameworks, including Nameko. I also got to meet its author who’s a really nice guy! When discussing Nameko, and Service Virtualisation, he expressed his curiosity regarding the ability to virtualise Nameko services.

Let’s take a look at using the HoverPy python library to capture and simulate interactions with an HTTP nameko service. You’ll need to install Nameko and install HoverPy respectively.

Creating a Nameko service

This example was pulled from the http section of the Nameko documentation.

import json
from nameko.web.handlers import http

class HttpService:
    name = "http_service"

    @http('GET', '/get/<int:value>')
    def get_method(self, request, value):
        return json.dumps({'value': value})

    @http('POST', '/post')
    def do_post(self, request):
        return u"received: {}".format(request.get_data(as_text=True))

Spin up your service:

$ nameko run hello

Building our client

Now let’s build a client we can conveniently switch between capture and simulate mode.

# helloClient.py

import requests
import argparse
from hoverpy import HoverPy

def callNamekoHTTPService():
  for i in range(5):
    print(requests.get("http://127.0.0.1:8000/get/%i"%i).text)
    print(requests.post("http://127.0.0.1:8000/post", data="post body %i" % i).text)

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description='Nameko client, with virtualisation support')
  parser.add_argument('-s','--simulate', help='Description for bar argument', default=False)
  args = vars(parser.parse_args())

  with HoverPy(capture=not args["simulate"]):
    callNamekoHTTPService()

Let’s invoke our client:

python helloClient.py

Output:

{"value": 0}
received: post body 0
{"value": 1}
received: post body 1
{"value": 2}
received: post body 2
{"value": 3}
received: post body 3
{"value": 4}
received: post body 4

We can now invoke our client again, in simualte mode:

python helloClient.py --simulate=True
{"value": 0}
received: post body 0
{"value": 1}
received: post body 1
{"value": 2}
received: post body 2
{"value": 3}
received: post body 3
{"value": 4}
received: post body 4

This time, we are pulling the data from our stored database, and no longer getting it from the live Nameko server. Well that’s fine and dandy, however Nameko is really about RPCs over AMQP, and currently AMQP is not supported in HoverPy, in a future update I’ll look at recording our interactions over AMQP.