Skip to content

Instantly share code, notes, and snippets.

@ambertests
Last active January 10, 2019 15:56
Show Gist options
  • Save ambertests/09d62d1cdf45f67b998ccc37ea42cdca to your computer and use it in GitHub Desktop.
Save ambertests/09d62d1cdf45f67b998ccc37ea42cdca to your computer and use it in GitHub Desktop.
Example of a Hoverfly middleware script which creates a response based on csv lookup
#!/usr/local/bin/python3
import sys, csv
import json
import logging
logging.basicConfig(filename='middleware.log', level=logging.DEBUG)
logging.debug('middleware called')
tokens = {}
# CSV file containing our user ids and tokens
with open('auth_test.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader: tokens[row['token']] = row['uid']
def main():
data = sys.stdin.readlines()
# this is a json string in one line so we are interested in that one line
payload = data[0]
payload_dict = json.loads(payload)
uid = None
if "request" in payload_dict and "body" in payload_dict["request"]:
request_body = payload_dict["request"]["body"]
if request_body and request_body[0] in ["[", "{"]:
json_body = json.loads(request_body)
token = json_body['token']
uid = tokens.get(token)
if "response" in payload_dict and "body" in payload_dict["response"]:
if uid:
payload_dict["response"] = {
"status": 200,
"body": "{\"valid\":true, \"userId\":\"%s\"}" % uid,
"encodedBody": False,
"headers": {
"Content-Type": [
"application/json"
],
"Transfer-Encoding": [
"chunked"
]
},
"templated": False
}
logging.debug("New Response Body: " + payload_dict['response']['body'])
print(json.dumps(payload_dict))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment