swadhinbiswas 🔧 fix: Use unique ports for each test file · 7/29/2026
bbe85fc
84 lines · 2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Integration tests for the HTTP QUERY method (RFC 10008)."""

import multiprocessing
import time
import socket

import pytest
import requests

from justapi import JustAPIApp

PORT = 18095


def run_server():
    app = JustAPIApp()

    @app.query("/search")
    def search(request):
        return {"query": request.get("body", b"").decode("utf-8")}

    @app.get("/hello")
    def hello(req):
        return {"message": "hello"}

    app.run(f"127.0.0.1:{PORT}")


@pytest.fixture(scope="module")
def server():
    p = multiprocessing.Process(target=run_server)
    p.start()
    # Wait for server to be ready with retry
    for _ in range(20):
        try:
            requests.get(f"http://127.0.0.1:{PORT}/hello", timeout=1)
            break
        except (requests.ConnectionError, requests.Timeout):
            time.sleep(0.5)
    try:
        yield
    finally:
        p.terminate()
        p.join(timeout=5)


def test_query_returns_body(server):
    r = requests.request(
        "QUERY",
        f"http://127.0.0.1:{PORT}/search",
        data="q=hello&limit=10",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    assert r.status_code == 200
    assert r.json() == {"query": "q=hello&limit=10"}


def test_query_requires_content_type(server):
    # Suppress the default Content-Type that `requests` would add for `data`.
    r = requests.request(
        "QUERY",
        f"http://127.0.0.1:{PORT}/search",
        data="q=hello",
        headers={"Content-Type": None},
    )
    assert r.status_code == 400
    assert "Content-Type" in r.text


def test_unknown_query_path_is_404(server):
    r = requests.request(
        "QUERY",
        f"http://127.0.0.1:{PORT}/missing",
        data="q=hello",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    assert r.status_code == 404


def test_get_still_works(server):
    r = requests.get(f"http://127.0.0.1:{PORT}/hello")
    assert r.status_code == 200
    assert r.json() == {"message": "hello"}