Skip to content

Instantly share code, notes, and snippets.

@huaxlin
Last active June 15, 2023 03:42
Show Gist options
  • Save huaxlin/cf5f9c4528d847f2ffc0900b6af03412 to your computer and use it in GitHub Desktop.
Save huaxlin/cf5f9c4528d847f2ffc0900b6af03412 to your computer and use it in GitHub Desktop.
Use `unittest.mock` to mock object when app running.

code structure:

$ tree .
.
├── mock_app_running.py
└── chatbot
   └── webhook.py

without mock:

$ python mock_app_running.py
...

####  another terminal  ####
$ curl -H 'Content-Type: application/json' -X POST localhost:7056/receive -d '{"pi":3.14,"name":"f"}'
{
  "data": "HTTPConnectionPool(host='127.0.0.1', port=4444): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7d95c9aa10>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "status": "failure"
}

mock webhook handler:

$ MOCK=1 python mock_app_running.py
***[DEBUG] mock webhook handler
...

####  another terminal  ####
$ curl -H 'Content-Type: application/json' -X POST localhost:7056/receive -d '{"pi":3.14,"name":"f"}'
{
  "data": {
    "name": "f",
    "pi": 3.14
  },
  "status": "success"
}
from flask import Flask, request, jsonify
from chatbot import webhook
app = Flask(__name__)
@app.route("/receive", methods=["POST"])
def receive():
body = request.json
try:
webhook.Handler.send(
msgtype='text',
content="Mirror, Mirror on the wall, who's the fairest of them all?"
)
except Exception as err:
return jsonify({"status": "failure", "data": str(err)})
return jsonify({"status": "success", "data": body})
if __name__ == '__main__':
import os
import unittest.mock
def main():
app.run(host="0.0.0.0", port=7056, debug=True)
if os.environ.get("MOCK", None):
print("***[DEBUG] mock webhook handler")
with unittest.mock.patch("chatbot.webhook.Handler") as mock:
main()
else:
main()
# chatbot/webhook.py
import requests
NOT_EXIST_WEBHOOK_URL = "http://127.0.0.1:4444"
class Handler:
@staticmethod
def send(msgtype, content) -> None:
print("***[DEBUG] Called Handler.send!")
resp = requests.post(NOT_EXIST_WEBHOOK_URL, timeout=1)
resp.raise_for_status()
@huaxlin
Copy link
Author

huaxlin commented Jun 15, 2023

mock send method

# mock_app_running.py
...

if __name__ == '__main__':
    import os
    import unittest.mock
    import chatbot.webhook

    def main():
        app.run(host="0.0.0.0", port=7056, debug=True)

    if os.environ.get("MOCK", None):
        print("***[DEBUG] mock webhook handler")

        def mock_send(msgtype, content) -> None:
            print(f"***[MOCK] {msgtype = }; {content = }")

        with unittest.mock.patch.object(chatbot.webhook.Handler, "send", new=mock_send):
            main()
    else:
        main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment