Home > Software design >  How to check app response from localhost with only 1 terminal
How to check app response from localhost with only 1 terminal

Time:06-29

  • I normally test my app by opening another terminal (client), and send post requests from there.
  • In that window, I compare the results I received to the results I had expected.
  • How can I automate this process? (for example as a Makefile target check_app).

Here is a minimal example (server):

from flask import Flask, request, jsonify
from typing import Any, Dict, List, Final

RAISE: Final[int] = 33

app = Flask(__name__)

@app.route("/analyze", methods=["POST"])
def update_salary() -> List[Dict[str, Any]]:
    return jsonify([
        {
            "name": entry["name"],
            "salary": entry["salary"] RAISE
        }
        for entry in request.get_json()
        if request.is_json
    ])

and here is the client

import json
import requests
from typing import Final

URL: Final[str] = "http://127.0.0.1:5000/analyze"

with open("input.json") as fl:
    data = json.load(fl)

response = requests.post(URL, json=data)

for entry in response.json():
    name = entry["name"]
    new_salary = entry["salary"]
    print(f"Hey {name} your new salary is {new_salary}")

The steps I do are:

$ flask run # automagically runs wsgi.py in terminal 1
$ python main.py    # sends post request in terminal 2

EDIT Here is my unsuccessful attempt based on the comments:

.ONESHELL:
test:
    @kill -9 $$(lsof -t -i tcp:5000)
    @flask run &
    @cd ../sender
    @python main.py > received.txt
    @diff received.txt expected.txt
    @cd -

I get the error:

Traceback (most recent call last):
  File "/home/oren/.local/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/home/oren/.local/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/home/oren/.local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

CodePudding user response:

Here is the complete makefile based on the comments from @Mark Setchell:

.ONESHELL:
test:
    @echo "[ - ] testing app"
    @kill -9 $$(lsof -t -i tcp:5000)
    @flask run 1>/dev/null 2>/dev/null &
    @sleep 2
    @cd ../sender
    @python main.py > received.txt
    @if cmp -s -- received.txt expected.txt; \
    then echo "[ > ] PASS            
  • Related