swadhinbiswas test(py): add comprehensive test suite for Python bindings · 7/8/2026
f693697
67 lines · 1.8 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
import json
import asyncio
import threading
from justapi import JustAPIApp

class MyPlugin:
    def __init__(self):
        self.built = False
        self.started = False
        self.shutdown = False

    def build(self, app: JustAPIApp):
        self.built = True
        app.get("/from-plugin", self.handler)

    def on_startup(self):
        self.started = True

    async def on_shutdown(self):
        self.shutdown = True

    def handler(self, request):
        return {"message": "hello from plugin"}

def test_plugin_registration():
    app = JustAPIApp()
    plugin = MyPlugin()
    app.use(plugin)

    assert plugin.built is True
    # The plugin was appended to app's plugins list.
    
    # We can't easily test on_startup/on_shutdown without running the server, 
    # but we can test if the route was registered correctly using the TestClient.
    from justapi import JustAPITestClient
    client = JustAPITestClient(app)
    
    resp = client.get("/from-plugin")
    assert resp["status"] == 200
    assert json.loads(bytes(resp["body"])) == {"message": "hello from plugin"}

def test_plugin_hooks_in_real_server():
    app = JustAPIApp()
    plugin = MyPlugin()
    app.use(plugin)

    # Run the server in a thread
    def run_server():
        try:
            app.run("127.0.0.1:0")
        except Exception:
            pass

    server_thread = threading.Thread(target=run_server, daemon=True)
    server_thread.start()

    # Give it a tiny bit of time to start
    import time
    time.sleep(0.5)

    assert plugin.started is True
    assert plugin.shutdown is False
    
    # We can't cleanly test shutdown hook here because shutting down
    # requires a ctrl-c signal or something that our test runner might not
    # want to handle gracefully for a daemon thread, but we tested startup!