blob: 6a6875745839f499758bc811199a303e05e931ab [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/asyncinvoker.h"
12#include "webrtc/base/asyncudpsocket.h"
13#include "webrtc/base/event.h"
14#include "webrtc/base/gunit.h"
15#include "webrtc/base/physicalsocketserver.h"
16#include "webrtc/base/socketaddress.h"
17#include "webrtc/base/thread.h"
18
19#if defined(WEBRTC_WIN)
20#include <comdef.h> // NOLINT
21#endif
22
23using namespace rtc;
24
25// Generates a sequence of numbers (collaboratively).
26class TestGenerator {
27 public:
28 TestGenerator() : last(0), count(0) {}
29
30 int Next(int prev) {
31 int result = prev + last;
32 last = result;
33 count += 1;
34 return result;
35 }
36
37 int last;
38 int count;
39};
40
41struct TestMessage : public MessageData {
42 explicit TestMessage(int v) : value(v) {}
43 virtual ~TestMessage() {}
44
45 int value;
46};
47
48// Receives on a socket and sends by posting messages.
49class SocketClient : public TestGenerator, public sigslot::has_slots<> {
50 public:
51 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
52 Thread* post_thread, MessageHandler* phandler)
53 : socket_(AsyncUDPSocket::Create(socket, addr)),
54 post_thread_(post_thread),
55 post_handler_(phandler) {
56 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
57 }
58
59 ~SocketClient() {
60 delete socket_;
61 }
62
63 SocketAddress address() const { return socket_->GetLocalAddress(); }
64
65 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
66 const SocketAddress& remote_addr,
67 const PacketTime& packet_time) {
68 EXPECT_EQ(size, sizeof(uint32));
69 uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
70 uint32 result = Next(prev);
71
72 post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
73 }
74
75 private:
76 AsyncUDPSocket* socket_;
77 Thread* post_thread_;
78 MessageHandler* post_handler_;
79};
80
81// Receives messages and sends on a socket.
82class MessageClient : public MessageHandler, public TestGenerator {
83 public:
84 MessageClient(Thread* pth, Socket* socket)
85 : socket_(socket) {
86 }
87
88 virtual ~MessageClient() {
89 delete socket_;
90 }
91
92 virtual void OnMessage(Message *pmsg) {
93 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
94 int result = Next(msg->value);
95 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
96 delete msg;
97 }
98
99 private:
100 Socket* socket_;
101};
102
103class CustomThread : public rtc::Thread {
104 public:
105 CustomThread() {}
106 virtual ~CustomThread() { Stop(); }
107 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000108
109 bool WrapCurrent() {
110 return Thread::WrapCurrent();
111 }
112 void UnwrapCurrent() {
113 Thread::UnwrapCurrent();
114 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115};
116
117
118// A thread that does nothing when it runs and signals an event
119// when it is destroyed.
120class SignalWhenDestroyedThread : public Thread {
121 public:
122 SignalWhenDestroyedThread(Event* event)
123 : event_(event) {
124 }
125
126 virtual ~SignalWhenDestroyedThread() {
127 Stop();
128 event_->Set();
129 }
130
131 virtual void Run() {
132 // Do nothing.
133 }
134
135 private:
136 Event* event_;
137};
138
139// Function objects to test Thread::Invoke.
140struct FunctorA {
141 int operator()() { return 42; }
142};
143class FunctorB {
144 public:
145 explicit FunctorB(bool* flag) : flag_(flag) {}
146 void operator()() { if (flag_) *flag_ = true; }
147 private:
148 bool* flag_;
149};
150struct FunctorC {
151 int operator()() {
152 Thread::Current()->ProcessMessages(50);
153 return 24;
154 }
155};
156
157// See: https://code.google.com/p/webrtc/issues/detail?id=2409
158TEST(ThreadTest, DISABLED_Main) {
159 const SocketAddress addr("127.0.0.1", 0);
160
161 // Create the messaging client on its own thread.
162 Thread th1;
163 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
164 SOCK_DGRAM);
165 MessageClient msg_client(&th1, socket);
166
167 // Create the socket client on its own thread.
168 Thread th2;
169 AsyncSocket* asocket =
170 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
171 SocketClient sock_client(asocket, addr, &th1, &msg_client);
172
173 socket->Connect(sock_client.address());
174
175 th1.Start();
176 th2.Start();
177
178 // Get the messages started.
179 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
180
181 // Give the clients a little while to run.
182 // Messages will be processed at 100, 300, 500, 700, 900.
183 Thread* th_main = Thread::Current();
184 th_main->ProcessMessages(1000);
185
186 // Stop the sending client. Give the receiver a bit longer to run, in case
187 // it is running on a machine that is under load (e.g. the build machine).
188 th1.Stop();
189 th_main->ProcessMessages(200);
190 th2.Stop();
191
192 // Make sure the results were correct
193 EXPECT_EQ(5, msg_client.count);
194 EXPECT_EQ(34, msg_client.last);
195 EXPECT_EQ(5, sock_client.count);
196 EXPECT_EQ(55, sock_client.last);
197}
198
199// Test that setting thread names doesn't cause a malfunction.
200// There's no easy way to verify the name was set properly at this time.
201TEST(ThreadTest, Names) {
202 // Default name
203 Thread *thread;
204 thread = new Thread();
205 EXPECT_TRUE(thread->Start());
206 thread->Stop();
207 delete thread;
208 thread = new Thread();
209 // Name with no object parameter
210 EXPECT_TRUE(thread->SetName("No object", NULL));
211 EXPECT_TRUE(thread->Start());
212 thread->Stop();
213 delete thread;
214 // Really long name
215 thread = new Thread();
216 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
217 EXPECT_TRUE(thread->Start());
218 thread->Stop();
219 delete thread;
220}
221
222// Test that setting thread priorities doesn't cause a malfunction.
223// There's no easy way to verify the priority was set properly at this time.
224TEST(ThreadTest, Priorities) {
225 Thread *thread;
226 thread = new Thread();
227 EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
228 EXPECT_TRUE(thread->Start());
229 thread->Stop();
230 delete thread;
231 thread = new Thread();
232 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
233 EXPECT_TRUE(thread->Start());
234 thread->Stop();
235 delete thread;
236
237 thread = new Thread();
238 EXPECT_TRUE(thread->Start());
239#if defined(WEBRTC_WIN)
240 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
241#else
242 EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
243#endif
244 thread->Stop();
245 delete thread;
246
247}
248
249TEST(ThreadTest, Wrap) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 CustomThread* cthread = new CustomThread();
251 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000252 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 EXPECT_FALSE(cthread->IsOwned());
254 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000255 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 delete cthread;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257}
258
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259TEST(ThreadTest, Invoke) {
260 // Create and start the thread.
261 Thread thread;
262 thread.Start();
263 // Try calling functors.
264 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
265 bool called = false;
266 FunctorB f2(&called);
267 thread.Invoke<void>(f2);
268 EXPECT_TRUE(called);
269 // Try calling bare functions.
270 struct LocalFuncs {
271 static int Func1() { return 999; }
272 static void Func2() {}
273 };
274 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
275 thread.Invoke<void>(&LocalFuncs::Func2);
276}
277
278class AsyncInvokeTest : public testing::Test {
279 public:
280 void IntCallback(int value) {
281 EXPECT_EQ(expected_thread_, Thread::Current());
282 int_value_ = value;
283 }
284 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
285 expected_thread_ = thread;
286 invoker->AsyncInvoke(thread, FunctorC(),
287 &AsyncInvokeTest::IntCallback,
288 static_cast<AsyncInvokeTest*>(this));
289 invoke_started_.Set();
290 }
291 void SetExpectedThreadForIntCallback(Thread* thread) {
292 expected_thread_ = thread;
293 }
294
295 protected:
296 enum { kWaitTimeout = 1000 };
297 AsyncInvokeTest()
298 : int_value_(0),
299 invoke_started_(true, false),
300 expected_thread_(NULL) {}
301
302 int int_value_;
303 Event invoke_started_;
304 Thread* expected_thread_;
305};
306
307TEST_F(AsyncInvokeTest, FireAndForget) {
308 AsyncInvoker invoker;
309 // Create and start the thread.
310 Thread thread;
311 thread.Start();
312 // Try calling functor.
313 bool called = false;
314 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
315 EXPECT_TRUE_WAIT(called, kWaitTimeout);
316}
317
318TEST_F(AsyncInvokeTest, WithCallback) {
319 AsyncInvoker invoker;
320 // Create and start the thread.
321 Thread thread;
322 thread.Start();
323 // Try calling functor.
324 SetExpectedThreadForIntCallback(Thread::Current());
325 invoker.AsyncInvoke(&thread, FunctorA(),
326 &AsyncInvokeTest::IntCallback,
327 static_cast<AsyncInvokeTest*>(this));
328 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
329}
330
331TEST_F(AsyncInvokeTest, CancelInvoker) {
332 // Create and start the thread.
333 Thread thread;
334 thread.Start();
335 // Try destroying invoker during call.
336 {
337 AsyncInvoker invoker;
338 invoker.AsyncInvoke(&thread, FunctorC(),
339 &AsyncInvokeTest::IntCallback,
340 static_cast<AsyncInvokeTest*>(this));
341 }
342 // With invoker gone, callback should be cancelled.
343 Thread::Current()->ProcessMessages(kWaitTimeout);
344 EXPECT_EQ(0, int_value_);
345}
346
347TEST_F(AsyncInvokeTest, CancelCallingThread) {
348 AsyncInvoker invoker;
349 { // Create and start the thread.
350 Thread thread;
351 thread.Start();
352 // Try calling functor.
353 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
354 static_cast<AsyncInvokeTest*>(this),
355 &invoker, Thread::Current()));
356 // Wait for the call to begin.
357 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
358 }
359 // Calling thread is gone. Return message shouldn't happen.
360 Thread::Current()->ProcessMessages(kWaitTimeout);
361 EXPECT_EQ(0, int_value_);
362}
363
364TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
365 Thread thread;
366 thread.Start();
367 {
368 AsyncInvoker invoker;
369 // Try calling functor.
370 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
371 static_cast<AsyncInvokeTest*>(this),
372 &invoker, Thread::Current()));
373 // Wait for the call to begin.
374 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
375 }
376 // Invoker is destroyed. Function should not execute.
377 Thread::Current()->ProcessMessages(kWaitTimeout);
378 EXPECT_EQ(0, int_value_);
379}
380
381TEST_F(AsyncInvokeTest, Flush) {
382 AsyncInvoker invoker;
383 bool flag1 = false;
384 bool flag2 = false;
385 // Queue two async calls to the current thread.
386 invoker.AsyncInvoke<void>(Thread::Current(),
387 FunctorB(&flag1));
388 invoker.AsyncInvoke<void>(Thread::Current(),
389 FunctorB(&flag2));
390 // Because we haven't pumped messages, these should not have run yet.
391 EXPECT_FALSE(flag1);
392 EXPECT_FALSE(flag2);
393 // Force them to run now.
394 invoker.Flush(Thread::Current());
395 EXPECT_TRUE(flag1);
396 EXPECT_TRUE(flag2);
397}
398
399TEST_F(AsyncInvokeTest, FlushWithIds) {
400 AsyncInvoker invoker;
401 bool flag1 = false;
402 bool flag2 = false;
403 // Queue two async calls to the current thread, one with a message id.
404 invoker.AsyncInvoke<void>(Thread::Current(),
405 FunctorB(&flag1),
406 5);
407 invoker.AsyncInvoke<void>(Thread::Current(),
408 FunctorB(&flag2));
409 // Because we haven't pumped messages, these should not have run yet.
410 EXPECT_FALSE(flag1);
411 EXPECT_FALSE(flag2);
412 // Execute pending calls with id == 5.
413 invoker.Flush(Thread::Current(), 5);
414 EXPECT_TRUE(flag1);
415 EXPECT_FALSE(flag2);
416 flag1 = false;
417 // Execute all pending calls. The id == 5 call should not execute again.
418 invoker.Flush(Thread::Current());
419 EXPECT_FALSE(flag1);
420 EXPECT_TRUE(flag2);
421}
422
423
424#if defined(WEBRTC_WIN)
425class ComThreadTest : public testing::Test, public MessageHandler {
426 public:
427 ComThreadTest() : done_(false) {}
428 protected:
429 virtual void OnMessage(Message* message) {
430 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
431 // S_FALSE means the thread was already inited for a multithread apartment.
432 EXPECT_EQ(S_FALSE, hr);
433 if (SUCCEEDED(hr)) {
434 CoUninitialize();
435 }
436 done_ = true;
437 }
438 bool done_;
439};
440
441TEST_F(ComThreadTest, ComInited) {
442 Thread* thread = new ComThread();
443 EXPECT_TRUE(thread->Start());
444 thread->Post(this, 0);
445 EXPECT_TRUE_WAIT(done_, 1000);
446 delete thread;
447}
448#endif