-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathtest_e2e.py
More file actions
430 lines (338 loc) · 14.1 KB
/
test_e2e.py
File metadata and controls
430 lines (338 loc) · 14.1 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
End-to-end tests for LiveKit RTC library.
These tests verify core functionality of the LiveKit RTC library including:
- Publishing and subscribing to audio tracks
- Audio stream consumption and energy verification
- Room lifecycle events (connect, disconnect, track publish/unpublish)
- Connection state transitions
Requirements:
- LIVEKIT_URL: LiveKit server URL
- LIVEKIT_API_KEY: API key for authentication
- LIVEKIT_API_SECRET: API secret for authentication
Tests will be skipped if these environment variables are not set.
Usage:
pytest test_e2e.py -v
"""
import asyncio
import os
import uuid
from typing import Callable, TypeVar
import numpy as np
import pytest
from livekit import rtc, api
from livekit.rtc.utils import sine_wave_generator
SAMPLE_RATE = 48000
T = TypeVar("T")
async def assert_eventually(
condition: Callable[[], T],
timeout: float = 5.0,
interval: float = 0.1,
message: str = "Condition not met within timeout",
) -> T:
"""
Poll a condition until it becomes truthy or timeout is reached.
Returns immediately once condition is satisfied.
"""
deadline = asyncio.get_event_loop().time() + timeout
last_result = None
while asyncio.get_event_loop().time() < deadline:
last_result = condition()
if last_result:
return last_result
await asyncio.sleep(interval)
raise AssertionError(f"{message} (last result: {last_result})")
def skip_if_no_credentials():
required_vars = ["LIVEKIT_URL", "LIVEKIT_API_KEY", "LIVEKIT_API_SECRET"]
missing = [var for var in required_vars if not os.getenv(var)]
return pytest.mark.skipif(
bool(missing), reason=f"Missing environment variables: {', '.join(missing)}"
)
def create_token(identity: str, room_name: str) -> str:
return (
api.AccessToken()
.with_identity(identity)
.with_name(identity)
.with_grants(
api.VideoGrants(
room_join=True,
room=room_name,
)
)
.to_jwt()
)
def unique_room_name(base: str) -> str:
return f"{base}-{uuid.uuid4().hex[:8]}"
@pytest.mark.asyncio
@skip_if_no_credentials()
async def test_publish_track():
"""Test that a published track can be subscribed by another participant"""
room_name = unique_room_name("test-publish-track")
url = os.getenv("LIVEKIT_URL")
publisher_room = rtc.Room()
subscriber_room = rtc.Room()
publisher_token = create_token("publisher", room_name)
subscriber_token = create_token("subscriber", room_name)
track_published_event = asyncio.Event()
track_subscribed_event = asyncio.Event()
subscribed_track = None
@subscriber_room.on("track_published")
def on_track_published(
publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant
):
track_published_event.set()
@subscriber_room.on("track_subscribed")
def on_track_subscribed(
track: rtc.Track,
publication: rtc.RemoteTrackPublication,
participant: rtc.RemoteParticipant,
):
nonlocal subscribed_track
if track.kind == rtc.TrackKind.KIND_AUDIO:
subscribed_track = track
track_subscribed_event.set()
try:
await subscriber_room.connect(url, subscriber_token)
await publisher_room.connect(url, publisher_token)
source = rtc.AudioSource(SAMPLE_RATE, 1)
track = rtc.LocalAudioTrack.create_audio_track("test-audio", source)
options = rtc.TrackPublishOptions()
options.source = rtc.TrackSource.SOURCE_MICROPHONE
publication = await publisher_room.local_participant.publish_track(track, options)
assert publication is not None
assert publication.sid is not None
await asyncio.wait_for(track_published_event.wait(), timeout=5.0)
await asyncio.wait_for(track_subscribed_event.wait(), timeout=5.0)
assert subscribed_track is not None
assert isinstance(subscribed_track, rtc.RemoteAudioTrack)
finally:
await publisher_room.disconnect()
await subscriber_room.disconnect()
@pytest.mark.asyncio
@skip_if_no_credentials()
async def test_audio_stream_subscribe():
"""Test that published audio can be consumed and has similar energy levels"""
room_name = unique_room_name("test-audio-stream")
url = os.getenv("LIVEKIT_URL")
publisher_room = rtc.Room()
subscriber_room = rtc.Room()
publisher_token = create_token("audio-publisher", room_name)
subscriber_token = create_token("audio-subscriber", room_name)
track_subscribed_event = asyncio.Event()
subscribed_track = None
@subscriber_room.on("track_subscribed")
def on_track_subscribed(
track: rtc.Track,
publication: rtc.RemoteTrackPublication,
participant: rtc.RemoteParticipant,
):
nonlocal subscribed_track
if track.kind == rtc.TrackKind.KIND_AUDIO:
subscribed_track = track
track_subscribed_event.set()
try:
await subscriber_room.connect(url, subscriber_token)
await publisher_room.connect(url, publisher_token)
source = rtc.AudioSource(SAMPLE_RATE, 1)
track = rtc.LocalAudioTrack.create_audio_track("sine-wave", source)
options = rtc.TrackPublishOptions()
options.source = rtc.TrackSource.SOURCE_MICROPHONE
await publisher_room.local_participant.publish_track(track, options)
target_duration = 5.0
published_energy = []
async def publish_audio():
async for frame in sine_wave_generator(440, target_duration, SAMPLE_RATE):
data = np.frombuffer(frame.data.tobytes(), dtype=np.int16)
energy = np.mean(np.abs(data.astype(np.float32)))
published_energy.append(energy)
await source.capture_frame(frame)
publish_task = asyncio.create_task(publish_audio())
await asyncio.wait_for(track_subscribed_event.wait(), timeout=5.0)
assert subscribed_track is not None
audio_stream = rtc.AudioStream(
subscribed_track,
sample_rate=SAMPLE_RATE,
num_channels=1,
)
received_frames = []
target_frames = int(target_duration * SAMPLE_RATE / 480)
frame_count = 0
async for event in audio_stream:
frame = event.frame
data = np.frombuffer(frame.data, dtype=np.int16)
received_frames.append(data)
frame_count += 1
if frame_count >= target_frames:
break
await audio_stream.aclose()
await publish_task
assert len(received_frames) > 0, "No audio frames were received"
received_energy = []
for data in received_frames:
energy = np.mean(np.abs(data.astype(np.float32)))
received_energy.append(energy)
avg_received_energy = np.mean(received_energy)
avg_published_energy = np.mean(published_energy)
assert avg_received_energy > 0, "Received audio has no energy"
assert avg_published_energy > 0, "Published audio has no energy"
assert (
avg_received_energy > avg_published_energy * 0.9
and avg_received_energy < avg_published_energy * 1.1
), "Received audio energy is not within range"
finally:
await publisher_room.disconnect()
await subscriber_room.disconnect()
@pytest.mark.asyncio
@skip_if_no_credentials()
async def test_room_lifecycle_events():
"""Test that room lifecycle and track events are fired properly"""
room_name = unique_room_name("test-lifecycle-events")
url = os.getenv("LIVEKIT_URL")
room1 = rtc.Room()
room2 = rtc.Room()
token1 = create_token("participant-1", room_name)
token2 = create_token("participant-2", room_name)
events = {
"disconnected": [],
"participant_connected": [],
"participant_disconnected": [],
"local_track_published": [],
"local_track_unpublished": [],
"track_published": [],
"track_unpublished": [],
"track_subscribed": [],
"track_unsubscribed": [],
"room_updated": [],
"connection_state_changed": [],
}
@room1.on("disconnected")
def on_room1_disconnected(reason):
events["disconnected"].append("room1")
@room1.on("participant_connected")
def on_room1_participant_connected(participant: rtc.RemoteParticipant):
events["participant_connected"].append(f"room1-{participant.identity}")
@room1.on("participant_disconnected")
def on_room1_participant_disconnected(participant: rtc.RemoteParticipant):
events["participant_disconnected"].append(f"room1-{participant.identity}")
@room1.on("local_track_published")
def on_room1_local_track_published(publication: rtc.LocalTrackPublication, track):
events["local_track_published"].append(f"room1-{publication.sid}")
@room1.on("local_track_unpublished")
def on_room1_local_track_unpublished(publication: rtc.LocalTrackPublication):
events["local_track_unpublished"].append(f"room1-{publication.sid}")
@room1.on("room_updated")
def on_room1_room_updated():
events["room_updated"].append("room1")
@room1.on("connection_state_changed")
def on_room1_connection_state_changed(state: rtc.ConnectionState):
events["connection_state_changed"].append(f"room1-{state}")
@room2.on("track_published")
def on_room2_track_published(
publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant
):
events["track_published"].append(f"room2-{publication.sid}")
@room2.on("track_subscribed")
def on_room2_track_subscribed(
track: rtc.Track,
publication: rtc.RemoteTrackPublication,
participant: rtc.RemoteParticipant,
):
events["track_subscribed"].append(f"room2-{publication.sid}")
@room2.on("track_unpublished")
def on_room2_track_unpublished(
publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant
):
events["track_unpublished"].append(f"room2-{publication.sid}")
try:
await room1.connect(url, token1)
await assert_eventually(
lambda: len(events["connection_state_changed"]) > 0
and events["connection_state_changed"][-1]
== f"room1-{rtc.ConnectionState.CONN_CONNECTED}",
message="room1 connection_state_changed event not fired or did not reach CONN_CONNECTED state",
)
await room2.connect(url, token2)
await assert_eventually(
lambda: "room1-participant-2" in events["participant_connected"],
message="room1 did not receive participant_connected for participant-2",
)
await assert_eventually(
lambda: room2.remote_participants.get("participant-1") is not None,
message="room2 did not see participant-1",
)
source = rtc.AudioSource(SAMPLE_RATE, 1)
track = rtc.LocalAudioTrack.create_audio_track("test-track", source)
options = rtc.TrackPublishOptions()
options.source = rtc.TrackSource.SOURCE_MICROPHONE
publication = await room1.local_participant.publish_track(track, options)
await assert_eventually(
lambda: len(events["local_track_published"]) > 0,
message="local_track_published event not fired",
)
await assert_eventually(
lambda: any("room2" in e for e in events["track_published"]),
message="room2 did not receive track_published",
)
await assert_eventually(
lambda: len(events["track_subscribed"]) > 0, message="track_subscribed event not fired"
)
await room1.local_participant.unpublish_track(publication.sid)
await assert_eventually(
lambda: len(events["local_track_unpublished"]) > 0,
message="local_track_unpublished event not fired",
)
await assert_eventually(
lambda: len(events["track_unpublished"]) > 0,
message="track_unpublished event not fired",
)
await room2.disconnect()
await assert_eventually(
lambda: "room1-participant-2" in events["participant_disconnected"],
message="participant_disconnected not fired for participant-2",
)
await room1.disconnect()
await assert_eventually(
lambda: lambda: len(events["connection_state_changed"]) > 0
and events["connection_state_changed"][-1]
== f"room1-{rtc.ConnectionState.CONN_DISCONNECTED}",
message="room1 disconnected event not fired",
)
print("\nEvent Summary:")
for event_type, event_list in events.items():
if event_list:
print(f" {event_type}: {len(event_list)} events")
finally:
if room1.isconnected():
await room1.disconnect()
if room2.isconnected():
await room2.disconnect()
@pytest.mark.asyncio
@skip_if_no_credentials()
async def test_connection_state_transitions():
"""Test that connection state transitions work correctly"""
room_name = unique_room_name("test-connection-state")
url = os.getenv("LIVEKIT_URL")
room = rtc.Room()
token = create_token("state-test", room_name)
states = []
@room.on("connection_state_changed")
def on_state_changed(state: rtc.ConnectionState):
states.append(state)
try:
assert room.connection_state == rtc.ConnectionState.CONN_DISCONNECTED
await room.connect(url, token)
await assert_eventually(
lambda: room.connection_state == rtc.ConnectionState.CONN_CONNECTED,
message="Room did not reach CONN_CONNECTED state",
)
await assert_eventually(
lambda: rtc.ConnectionState.CONN_CONNECTED in states,
message="CONN_CONNECTED state not in state change events",
)
await room.disconnect()
await assert_eventually(
lambda: room.connection_state == rtc.ConnectionState.CONN_DISCONNECTED,
message="Room did not reach CONN_DISCONNECTED state after disconnect",
)
finally:
if room.isconnected():
await room.disconnect()