This repository has been archived by the owner on Sep 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ws_response.py
93 lines (71 loc) · 2.59 KB
/
ws_response.py
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
85
86
87
88
89
90
91
92
93
import json
from .utils import get_resolved_values
from .ws_message import WSMessage
class WSResponse:
"""
A class representing an expected message to be received through the websocket
Attributes:
attributes (dict)
triggers (list)
Methods:
with_attribute(key, value=None):
Adds an attribute and returns the WSResponse
with_trigger(message: WSResponse):
Adds a trigger and returns the WSResponse
is_match(response: dict):
Checks if this WSResponse instance matches an input response and returns the result as a bool
Usage:
response = (
WSResponse()
.with_attribute("type", "example")
.with_attribute("body")
.with_trigger(
WSMessage()
)
)
"""
def __init__(self):
self.attributes = {}
self.triggers = []
def __str__(self) -> str:
return json.dumps(self.attributes)
def with_attribute(self, attribute: str, value: object = None) -> "WSResponse":
"""
Adds a key/value pair to the attributes dictionary
Parameters:
attribute (str): The key of the attribute
value (obj, optional): The value of the attribute
Returns:
(WSResponse): The WSResponse instance with_attribute was called on
"""
self.attributes[attribute] = value
return self
def with_trigger(self, message: WSMessage) -> "WSResponse":
"""
Adds a trigger to the triggers list
Parameters:
message (WSMessage): The message object to send to the websocket
Returns:
(WSResponse): The WSResponse instance with_trigger was called on
"""
self.triggers.append(message)
return self
def is_match(self, response: dict) -> bool:
"""
Checks if this WSResponse instance matches an input response by checking all attributes are present
Parameters:
response (dict): The response to check against for a match
Returns:
(bool): True if the response matches based on the attributes
"""
# pylint:disable=consider-using-dict-items
for key in self.attributes:
resolved_values = get_resolved_values(response, key)
if not resolved_values:
return False
if self.attributes[key] is None:
continue
if any(self.attributes[key] == value for value in resolved_values):
continue
return False
return True