-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_integration.py
More file actions
264 lines (222 loc) · 7.88 KB
/
test_integration.py
File metadata and controls
264 lines (222 loc) · 7.88 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""Integration tests for the PubSub system."""
import json
import sqlite3
import sys
import threading
import time
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
class TestIntegration:
"""Integration tests for the complete PubSub system."""
def test_json_message_structure(self):
"""Test JSON message structure for pub/sub."""
message = {
"topic": "test",
"message_id": "123",
"message": "Hello World",
"producer": "test_producer",
}
# Test serialization
json_str = json.dumps(message)
parsed = json.loads(json_str)
assert parsed["topic"] == "test"
assert parsed["message"] == "Hello World"
assert parsed["producer"] == "test_producer"
def test_database_integration(self):
"""Test database operations integration."""
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
# Create tables
cursor.execute(
"""
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
topic TEXT,
message TEXT,
producer TEXT
)
"""
)
cursor.execute(
"""
CREATE TABLE subscriptions (
id INTEGER PRIMARY KEY,
consumer TEXT,
topic TEXT
)
"""
)
# Test message flow
cursor.execute(
"INSERT INTO messages (topic, message, producer) VALUES (?, ?, ?)",
("sports", "Game started", "sports_bot"),
)
cursor.execute(
"INSERT INTO subscriptions (consumer, topic) VALUES (?, ?)", ("alice", "sports")
)
# Verify integration
cursor.execute(
"""
SELECT m.topic, m.message, s.consumer
FROM messages m
JOIN subscriptions s ON m.topic = s.topic
WHERE s.consumer = ?
""",
("alice",),
)
result = cursor.fetchone()
assert result is not None
assert result[0] == "sports"
assert result[1] == "Game started"
assert result[2] == "alice"
conn.close()
def test_concurrent_operations(self):
"""Test concurrent database operations."""
import os
import tempfile
# Use a temporary file instead of in-memory database for thread safety
temp_db = tempfile.NamedTemporaryFile(delete=False, suffix=".db")
temp_db.close()
db_path = temp_db.name
try:
# Create the database schema
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE test_messages (
id INTEGER PRIMARY KEY,
content TEXT,
thread_id INTEGER
)
"""
)
conn.commit()
conn.close()
# Thread-safe lock for database operations
db_lock = threading.Lock()
def insert_messages(thread_id):
"""Insert messages from a thread."""
with db_lock:
thread_conn = sqlite3.connect(db_path)
thread_cursor = thread_conn.cursor()
# noinspection PyShadowingNames
for i in range(3):
thread_cursor.execute(
"INSERT INTO test_messages (content, thread_id) VALUES (?, ?)",
(f"Message {i}", thread_id),
)
thread_conn.commit()
thread_conn.close()
# Create threads
threads = []
for i in range(3):
t = threading.Thread(target=insert_messages, args=(i,))
threads.append(t)
t.start()
# Wait for all threads
for t in threads:
t.join()
# Verify all messages were inserted
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM test_messages")
count = cursor.fetchone()[0]
assert count == 9 # 3 threads × 3 messages each
conn.close()
finally:
# Clean up temporary database file
if os.path.exists(db_path):
os.unlink(db_path)
def test_message_queue_simulation(self):
"""Test message queue behavior simulation."""
from collections import deque
# Simulate a message queue
message_queue = deque()
processed_messages = []
# Producer adds messages
messages = [
{"topic": "news", "content": "Breaking news"},
{"topic": "sports", "content": "Game update"},
{"topic": "weather", "content": "Storm warning"},
]
for msg in messages:
message_queue.append(msg)
# Consumer processes messages
while message_queue:
msg = message_queue.popleft()
processed_messages.append(msg)
time.sleep(0.001) # Simulate processing time
assert len(processed_messages) == 3
assert processed_messages[0]["topic"] == "news"
assert processed_messages[1]["topic"] == "sports"
assert processed_messages[2]["topic"] == "weather"
@pytest.mark.parametrize(
"topic,message_count",
[
("tech", 5),
("finance", 3),
("health", 7),
],
)
def test_topic_message_distribution(self, topic, message_count):
"""Test message distribution across different topics."""
messages = []
# Generate messages for the topic
for i in range(message_count):
message = {
"topic": topic,
"message_id": f"{topic}_{i}",
"content": f"Message {i} for {topic}",
"timestamp": time.time(),
}
messages.append(message)
# Verify message structure
assert len(messages) == message_count
for msg in messages:
assert msg["topic"] == topic
assert "message_id" in msg
assert "content" in msg
assert "timestamp" in msg
def test_websocket_message_format(self):
"""Test WebSocket message format compliance."""
# Mock WebSocket message format
websocket_message = {
"event": "message",
"data": {
"topic": "updates",
"message_id": "ws_001",
"message": "WebSocket test message",
"producer": "websocket_client",
"timestamp": time.time(),
},
}
# Validate structure
assert "event" in websocket_message
assert "data" in websocket_message
assert websocket_message["event"] == "message"
data = websocket_message["data"]
assert "topic" in data
assert "message_id" in data
assert "message" in data
assert "producer" in data
assert "timestamp" in data
def test_subscription_matching(self):
"""Test subscription topic matching logic."""
# Simulate subscription patterns
subscriptions = {
"alice": ["sports", "news"],
"bob": ["tech", "finance"],
"charlie": ["sports", "tech", "news"],
}
# Test message routing
message_topic = "sports"
eligible_consumers = []
for consumer, topics in subscriptions.items():
if message_topic in topics:
eligible_consumers.append(consumer)
assert "alice" in eligible_consumers
assert "charlie" in eligible_consumers
assert "bob" not in eligible_consumers
assert len(eligible_consumers) == 2