|
1 | 1 | from fastapi.testclient import TestClient
|
2 |
| -from labthings_fastapi import ThingServer, Thing, fastapi_endpoint |
3 | 2 | from pydantic import BaseModel
|
| 3 | +import pytest |
| 4 | +import labthings_fastapi as lt |
4 | 5 |
|
5 | 6 |
|
6 | 7 | class PostBodyModel(BaseModel):
|
7 | 8 | a: int
|
8 | 9 | b: int
|
9 | 10 |
|
10 | 11 |
|
11 |
| -class TestThing(Thing): |
12 |
| - @fastapi_endpoint("get") |
| 12 | +class MyThing(lt.Thing): |
| 13 | + @lt.fastapi_endpoint("get") |
13 | 14 | def path_from_name(self) -> str:
|
14 | 15 | return "path_from_name"
|
15 | 16 |
|
16 |
| - @fastapi_endpoint("get", path="path_from_path") |
| 17 | + @lt.fastapi_endpoint("get", path="path_from_path") |
17 | 18 | def get_method(self) -> str:
|
18 | 19 | return "get_method"
|
19 | 20 |
|
20 |
| - @fastapi_endpoint("post", path="path_from_path") |
| 21 | + @lt.fastapi_endpoint("post", path="path_from_path") |
21 | 22 | def post_method(self, body: PostBodyModel) -> str:
|
22 | 23 | return f"post_method {body.a} {body.b}"
|
23 | 24 |
|
24 | 25 |
|
25 | 26 | def test_endpoints():
|
26 |
| - server = ThingServer() |
27 |
| - server.add_thing(TestThing(), "/thing") |
| 27 | + """Check endpoints may be added to the app and work as expected.""" |
| 28 | + server = lt.ThingServer() |
| 29 | + thing = MyThing() |
| 30 | + server.add_thing(thing, "/thing") |
28 | 31 | with TestClient(server.app) as client:
|
| 32 | + # Check the function works when used directly |
| 33 | + assert thing.path_from_name() == "path_from_name" |
| 34 | + # Check it works identically over HTTP. The path is |
| 35 | + # generated from the name of the function. |
29 | 36 | r = client.get("/thing/path_from_name")
|
30 | 37 | r.raise_for_status()
|
31 | 38 | assert r.json() == "path_from_name"
|
32 | 39 |
|
| 40 | + # get_method has an explicit path - check it can be |
| 41 | + # used both directly and via that path. |
| 42 | + assert thing.get_method() == "get_method" |
33 | 43 | r = client.get("/thing/path_from_path")
|
34 | 44 | r.raise_for_status()
|
35 | 45 | assert r.json() == "get_method"
|
36 | 46 |
|
| 47 | + # post_method uses the same path, for a different |
| 48 | + # function |
| 49 | + assert thing.post_method(PostBodyModel(a=1, b=2)) == "post_method 1 2" |
37 | 50 | r = client.post("/thing/path_from_path", json={"a": 1, "b": 2})
|
38 | 51 | r.raise_for_status()
|
39 | 52 | assert r.json() == "post_method 1 2"
|
| 53 | + |
| 54 | + |
| 55 | +def test_endpoint_notconnected(mocker): |
| 56 | + """Check for the correct error if we add endpoints prematurely. |
| 57 | +
|
| 58 | + We should get this error if we call ``add_to_fastapi`` on an endpoint |
| 59 | + where the `.Thing` does not have a valid ``path`` attribute. |
| 60 | + """ |
| 61 | + thing = MyThing() |
| 62 | + |
| 63 | + with pytest.raises(lt.exceptions.NotConnectedToServerError): |
| 64 | + MyThing.get_method.add_to_fastapi(mocker.Mock(), thing) |
0 commit comments