1
1
from fastapi .testclient import TestClient
2
2
import pytest
3
3
import labthings_fastapi as lt
4
- from labthings_fastapi .exceptions import PropertyNotObservableError
4
+ from labthings_fastapi .exceptions import (
5
+ PropertyNotObservableError ,
6
+ InvocationCancelledError ,
7
+ )
5
8
6
9
7
10
class ThingWithProperties (lt .Thing ):
@@ -27,6 +30,18 @@ def increment_dataprop(self):
27
30
"""Increment the data property."""
28
31
self .dataprop += 1
29
32
33
+ @lt .thing_action
34
+ def raise_error (self ):
35
+ r"""Raise an exception to test for error status."""
36
+ self .dataprop += 1
37
+ raise Exception ("A deliberate failure." )
38
+
39
+ @lt .thing_action
40
+ def cancel_myself (self ):
41
+ """Increment the data property, then pretend to be cancelled."""
42
+ self .dataprop += 1
43
+ raise InvocationCancelledError ()
44
+
30
45
31
46
@pytest .fixture
32
47
def thing ():
@@ -154,19 +169,27 @@ def test_observing_action_error(thing, mocker):
154
169
thing .observe_action ("non_property" , mocker .Mock ())
155
170
156
171
157
- def test_observing_action_with_ws (client , ws ):
172
+ @pytest .mark .parametrize (
173
+ argnames = ["name" , "final_status" ],
174
+ argvalues = [
175
+ ("increment_dataprop" , "completed" ),
176
+ ("raise_error" , "error" ),
177
+ ("cancel_myself" , "cancelled" ),
178
+ ],
179
+ )
180
+ def test_observing_action_with_ws (client , ws , name , final_status ):
158
181
"""Observe an action with a websocket, checking the status changes correctly."""
159
182
# Observe the property.
160
183
ws .send_json (
161
184
{
162
185
"messageType" : "addActionObservation" ,
163
- "data" : {"increment_dataprop" : True },
186
+ "data" : {name : True },
164
187
}
165
188
)
166
189
# Invoke the action (via HTTP)
167
- client .post ("/thing/increment_dataprop " )
190
+ client .post (f "/thing/{ name } " )
168
191
# We should see the status go through the expected sequence
169
- for expected_status in ["pending" , "running" , "completed" ]:
192
+ for expected_status in ["pending" , "running" , final_status ]:
170
193
message = ws .receive_json (mode = "text" )
171
194
assert message ["messageType" ] == "actionStatus"
172
195
assert message ["data" ]["status" ] == expected_status
0 commit comments