Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / mojo / public / utility / tests / thread_unittest.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "mojo/public/utility/thread.h"
6
7 #include "mojo/public/system/macros.h"
8 #include "testing/gtest/include/gtest/gtest.h"
9
10 namespace mojo {
11 namespace {
12
13 class SetIntThread : public Thread {
14  public:
15   SetIntThread(int* int_to_set, int value)
16       : int_to_set_(int_to_set),
17         value_(value) {
18   }
19   SetIntThread(const Options& options, int* int_to_set, int value)
20       : Thread(options),
21         int_to_set_(int_to_set),
22         value_(value) {
23   }
24
25   virtual ~SetIntThread() {
26   }
27
28   virtual void Run() MOJO_OVERRIDE {
29     *int_to_set_ = value_;
30   }
31
32  private:
33   int* const int_to_set_;
34   const int value_;
35
36   MOJO_DISALLOW_COPY_AND_ASSIGN(SetIntThread);
37 };
38
39 TEST(ThreadTest, CreateAndJoin) {
40   int value = 0;
41
42   // Not starting the thread should result in a no-op.
43   {
44     SetIntThread thread(&value, 1234567);
45   }
46   EXPECT_EQ(0, value);
47
48   // Start and join.
49   {
50     SetIntThread thread(&value, 12345678);
51     thread.Start();
52     thread.Join();
53     EXPECT_EQ(12345678, value);
54   }
55
56   // Ditto, with non-default (but reasonable) stack size.
57   {
58     Thread::Options options;
59     options.set_stack_size(1024 * 1024);  // 1 MB.
60     SetIntThread thread(options, &value, 12345678);
61     thread.Start();
62     thread.Join();
63     EXPECT_EQ(12345678, value);
64   }
65 }
66
67 // Tests of assertions for Debug builds.
68 // Note: It's okay to create threads, despite gtest having to fork. (The threads
69 // are in the child process.)
70 #if !defined(NDEBUG)
71 TEST(ThreadTest, DebugAssertionFailures) {
72   // Can only start once.
73   EXPECT_DEATH({
74     int value = 0;
75     SetIntThread thread(&value, 1);
76     thread.Start();
77     thread.Start();
78   }, "");
79
80   // Must join (if you start).
81   EXPECT_DEATH({
82     int value = 0;
83     SetIntThread thread(&value, 2);
84     thread.Start();
85   }, "");
86
87   // Can only join once.
88   EXPECT_DEATH({
89     int value = 0;
90     SetIntThread thread(&value, 3);
91     thread.Start();
92     thread.Join();
93     thread.Join();
94   }, "");
95
96   // Stack too big (we're making certain assumptions here).
97   EXPECT_DEATH({
98     int value = 0;
99     Thread::Options options;
100     options.set_stack_size(static_cast<size_t>(-1));
101     SetIntThread thread(options, &value, 4);
102     thread.Start();
103     thread.Join();
104   }, "");
105 }
106 #endif  // !defined(NDEBUG)
107
108 }  // namespace
109 }  // namespace mojo
110