-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtest_room.cpp
More file actions
357 lines (281 loc) · 12.9 KB
/
Copy pathtest_room.cpp
File metadata and controls
357 lines (281 loc) · 12.9 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
/*
* Copyright 2025 LiveKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <livekit/livekit.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <future>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "../common/test_common.h"
using namespace std::chrono_literals;
namespace livekit::test {
// Server-dependent tests - require LIVEKIT_URL and LIVEKIT_TOKEN_A env vars
class RoomTest : public ::testing::Test {
protected:
void SetUp() override {
livekit::initialize(livekit::LogLevel::Info);
const char* url_env = std::getenv("LIVEKIT_URL");
const char* token_env = std::getenv("LIVEKIT_TOKEN_A");
if (url_env && token_env) {
server_url_ = url_env;
token_ = token_env;
server_available_ = true;
}
}
void TearDown() override { livekit::shutdown(); }
bool server_available_ = false;
std::string server_url_;
std::string token_;
};
TEST_F(RoomTest, ConnectToServer) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
RoomOptions options;
bool connected = room.connect(server_url_, token_, options);
EXPECT_TRUE(connected) << "Should connect to server successfully";
if (connected) {
EXPECT_FALSE(room.localParticipant().expired()) << "Local participant should exist after connect";
}
}
TEST_F(RoomTest, ConnectWithInvalidToken) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
RoomOptions options;
bool connected = room.connect(server_url_, "invalid_token", options);
EXPECT_FALSE(connected) << "Should fail to connect with invalid token";
}
TEST_F(RoomTest, ConnectWithInvalidUrl) {
Room room;
RoomOptions options;
bool connected = room.connect("wss://invalid.example.com", "token", options);
EXPECT_FALSE(connected) << "Should fail to connect to invalid URL";
}
TEST_F(RoomTest, ConnectWithLiteralTokenSource) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
RoomOptions options;
auto token_source = LiteralTokenSource::create(server_url_, token_);
const auto details = token_source->fetch().get();
ASSERT_TRUE(details);
const bool connected = room.connect(details.value().server_url, details.value().participant_token, options);
EXPECT_TRUE(connected) << "Should connect to server via fetched literal token source credentials";
if (connected) {
EXPECT_FALSE(room.localParticipant().expired()) << "Local participant should exist after connect";
EXPECT_EQ(room.connectionState(), ConnectionState::Connected);
}
}
TEST_F(RoomTest, ConnectWithCustomTokenSource) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
RoomOptions options;
auto token_source = CustomTokenSource::create(
[this](const TokenRequestOptions& options) -> std::future<Result<TokenSourceResponse, TokenSourceError>> {
std::promise<Result<TokenSourceResponse, TokenSourceError>> promise;
TokenSourceResponse details;
details.server_url = server_url_;
// Note: token_ is generated by livekit-cli prior to this test run and passed in via environment variables
details.participant_token = token_;
promise.set_value(Result<TokenSourceResponse, TokenSourceError>::success(details));
return promise.get_future();
});
TokenRequestOptions request;
request.room_name = "integration-room";
const auto details = token_source->fetch(request).get();
ASSERT_TRUE(details);
const bool connected = room.connect(details.value().server_url, details.value().participant_token, options);
EXPECT_TRUE(connected) << "Should connect to server via fetched custom token source credentials";
}
namespace {
class DisconnectTrackingDelegate : public RoomDelegate {
public:
void onDisconnected(Room&, const DisconnectedEvent& ev) override {
{
const std::scoped_lock<std::mutex> lock(mutex_);
last_reason_ = ev.reason;
}
count.fetch_add(1);
cv_.notify_all();
}
bool waitForDisconnect(std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mutex_);
return cv_.wait_for(lock, timeout, [this]() { return count.load() > 0; });
}
DisconnectReason lastReason() const {
const std::scoped_lock<std::mutex> lock(mutex_);
return last_reason_;
}
std::atomic<int> count{0};
private:
mutable std::mutex mutex_;
std::condition_variable cv_;
DisconnectReason last_reason_ = DisconnectReason::Unknown;
};
class TokenRefreshTrackingDelegate : public RoomDelegate {
public:
void onTokenRefreshed(Room&, const TokenRefreshedEvent& ev) override {
{
const std::scoped_lock<std::mutex> lock(mutex_);
refreshed_token_ = ev.token;
}
refresh_count_.fetch_add(1, std::memory_order_relaxed);
cv_.notify_all();
}
bool waitForRefresh(std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mutex_);
return cv_.wait_for(lock, timeout, [this]() { return refresh_count_.load(std::memory_order_relaxed) > 0; });
}
std::string refreshedToken() const {
const std::scoped_lock<std::mutex> lock(mutex_);
return refreshed_token_;
}
int refreshCount() const { return refresh_count_.load(std::memory_order_relaxed); }
private:
mutable std::mutex mutex_;
std::condition_variable cv_;
std::atomic<int> refresh_count_{0};
std::string refreshed_token_;
};
} // namespace
// livekit-server sends RefreshToken immediately after join, then every ~5 minutes.
// See pkg/service/roommanager.go (refreshToken on session start + tokenRefreshInterval).
TEST_F(RoomTest, ServerRefreshTokenFiresDelegate) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
TokenRefreshTrackingDelegate delegate;
room.setDelegate(&delegate);
RoomOptions options;
ASSERT_TRUE(room.connect(server_url_, token_, options)) << "connect failed";
ASSERT_EQ(room.connectionState(), ConnectionState::Connected);
ASSERT_TRUE(delegate.waitForRefresh(30s))
<< "onTokenRefreshed should fire after join (livekit-server pushes RefreshToken on connect)";
const std::string refreshed = delegate.refreshedToken();
EXPECT_FALSE(refreshed.empty());
EXPECT_EQ(std::count(refreshed.begin(), refreshed.end(), '.'), 2)
<< "refreshed token should be a well-formed JWT (header.payload.signature)";
EXPECT_NE(refreshed, token_) << "server-issued refresh JWT should differ from the join token";
room.disconnect();
}
// Case: User calls disconnect()
TEST_F(RoomTest, UserDisconnect) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
Room room;
DisconnectTrackingDelegate delegate;
room.setDelegate(&delegate);
RoomOptions options;
ASSERT_TRUE(room.connect(server_url_, token_, options)) << "connect failed";
ASSERT_EQ(room.connectionState(), ConnectionState::Connected);
ASSERT_NE(room.localParticipant().lock(), nullptr);
EXPECT_NO_THROW(room.disconnect()) << "disconnect should not throw on a connected room";
EXPECT_EQ(room.connectionState(), ConnectionState::Disconnected);
EXPECT_EQ(room.localParticipant().lock(), nullptr) << "local participant should be cleared after disconnect";
EXPECT_EQ(delegate.count.load(), 1) << "onDisconnected should fire exactly once";
EXPECT_EQ(delegate.lastReason(), DisconnectReason::ClientInitiated);
// Calling again on an already-disconnected room is a no-op
EXPECT_NO_THROW(room.disconnect()) << "second disconnect should not throw on an already-disconnected room";
EXPECT_EQ(delegate.count.load(), 1) << "delegate must not double-fire";
}
// Case: Room goes out of scope while still connected
TEST_F(RoomTest, DestructorDisconnect) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
std::unique_ptr<Room> room = std::make_unique<Room>();
DisconnectTrackingDelegate delegate;
room->setDelegate(&delegate);
RoomOptions options;
ASSERT_TRUE(room->connect(server_url_, token_, options));
ASSERT_EQ(room->connectionState(), ConnectionState::Connected);
room.reset(); // invokes destructor which calls disconnect()
EXPECT_EQ(delegate.count.load(), 1) << "destructor should fire onDisconnected exactly once";
EXPECT_EQ(delegate.lastReason(), DisconnectReason::ClientInitiated);
}
// Case: server deletes the room while the client is connected.
TEST_F(RoomTest, ServerDeletedRoomDisconnectsAndTearsDownLocally) {
ASSERT_TRUE(server_available_) << "LIVEKIT_URL and LIVEKIT_TOKEN_A not set";
if (server_url_ != kLocalTestLiveKitUrl) {
GTEST_SKIP() << "server-delete integration test requires local livekit-server";
}
const char* room_name = std::getenv("LIVEKIT_ROOM");
ASSERT_NE(room_name, nullptr) << "LIVEKIT_ROOM not set";
ASSERT_NE(std::string(room_name), "") << "LIVEKIT_ROOM must be non-empty";
Room room;
DisconnectTrackingDelegate delegate;
room.setDelegate(&delegate);
RoomOptions options;
ASSERT_TRUE(room.connect(server_url_, token_, options)) << "connect failed";
ASSERT_EQ(room.connectionState(), ConnectionState::Connected);
ASSERT_NE(room.localParticipant().lock(), nullptr);
const std::string delete_command = std::string("lk --dev room delete --yes ") + room_name;
ASSERT_EQ(std::system(delete_command.c_str()), 0) << "failed to delete local test room";
ASSERT_TRUE(delegate.waitForDisconnect(10s)) << "server room deletion should disconnect the client";
EXPECT_EQ(room.connectionState(), ConnectionState::Disconnected);
EXPECT_EQ(room.localParticipant().lock(), nullptr) << "local participant should be cleared after server disconnect";
EXPECT_EQ(delegate.count.load(), 1) << "onDisconnected should fire exactly once";
EXPECT_EQ(delegate.lastReason(), DisconnectReason::RoomDeleted);
EXPECT_FALSE(room.disconnect()) << "disconnect after server teardown should be a no-op";
EXPECT_EQ(delegate.count.load(), 1) << "delegate must not double-fire";
}
// Verifies that participant handles handed out by Room expire once the Room is
// destroyed. Because the accessors return std::weak_ptr and the Room is the
// sole owner of the participant shared_ptrs, a consumer that caches the handles
// can detect teardown via expired()/lock() == nullptr. Requires a second peer
// (TOKEN_B) so the room under test has a remote participant to observe.
class RoomLifecycleTest : public LiveKitTestBase {};
TEST_F(RoomLifecycleTest, ParticipantHandlesExpireOnRoomDestruction) {
if (!config_.available) {
throw std::runtime_error("RoomLifecycleTest: test configuration not set up");
}
RoomOptions options;
options.auto_subscribe = true;
// 1. Connect the room under test plus a peer so a remote participant exists.
auto room = std::make_unique<Room>();
ASSERT_TRUE(room->connect(config_.url, config_.token_a, options)) << "Room failed to connect";
auto peer = std::make_unique<Room>();
ASSERT_TRUE(peer->connect(config_.url, config_.token_b, options)) << "Peer failed to connect";
ASSERT_FALSE(peer->localParticipant().expired());
const std::string peer_identity = lockLocalParticipant(*peer)->identity();
ASSERT_TRUE(waitForParticipant(room.get(), peer_identity, 10s)) << "Peer not visible to room";
// 2. Store the local participant handle. Keep the weak_ptr itself - locking
// it here would co-own the participant and keep it alive past teardown,
// defeating the check.
std::weak_ptr<LocalParticipant> local_handle = room->localParticipant();
ASSERT_FALSE(local_handle.expired()) << "Local participant should be live while connected";
// 3. Store the remote participant handles (again, as weak_ptr).
std::vector<std::weak_ptr<RemoteParticipant>> remote_handles = room->remoteParticipants();
ASSERT_FALSE(remote_handles.empty()) << "Expected at least one remote participant";
for (const auto& handle : remote_handles) {
EXPECT_FALSE(handle.expired()) << "Remote participant should be live while connected";
}
std::weak_ptr<RemoteParticipant> remote_by_identity = room->remoteParticipant(peer_identity);
ASSERT_FALSE(remote_by_identity.expired());
// 4. Destroy the room.
room.reset();
// 5. Validate every cached handle now reports as expired / null.
EXPECT_TRUE(local_handle.expired());
EXPECT_EQ(local_handle.lock(), nullptr);
EXPECT_TRUE(remote_by_identity.expired());
EXPECT_EQ(remote_by_identity.lock(), nullptr);
for (const auto& handle : remote_handles) {
EXPECT_TRUE(handle.expired());
EXPECT_EQ(handle.lock(), nullptr);
}
peer.reset();
}
} // namespace livekit::test