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