1 | /** |
2 | * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | * |
16 | * \author guonix |
17 | * \date Nov 2020 |
18 | * \brief |
19 | */ |
20 | |
21 | #include <chrono> |
22 | #include <gtest/gtest.h> |
23 | #include "task-inl.h" |
24 | |
25 | using namespace proxima::be::query; |
26 | using namespace proxima::be::query::test; |
27 | |
28 | const std::string kName("task name" ); |
29 | const int kCode = 0; |
30 | const int kMillSeconds = 100; |
31 | |
32 | TEST(TaskTest, TestDefaultContructor) { |
33 | TaskImpl task(kName, kCode); |
34 | ASSERT_EQ(task.name(), kName); |
35 | ASSERT_EQ(task.status(), Task::Status::INITIALIZED); |
36 | ASSERT_FALSE(task.running()); |
37 | ASSERT_FALSE(task.finished()); |
38 | } |
39 | |
40 | TEST(TaskTest, TestExitCode) { |
41 | TaskImpl task(kName, kCode); |
42 | task.status(Task::Status::SCHEDULED); |
43 | ASSERT_EQ(task.run(), kCode); |
44 | ASSERT_EQ(task.exit_code(), kCode); |
45 | ASSERT_TRUE(task.finished()); |
46 | ASSERT_TRUE(task.wait_finish()); |
47 | } |
48 | |
49 | TEST(TaskTest, TestAsyncRun) { |
50 | TaskPtr task = CreateTask(kName, kCode, kMillSeconds); |
51 | |
52 | ASSERT_EQ(task->status(), Task::Status::INITIALIZED); |
53 | |
54 | { |
55 | auto begin = std::chrono::steady_clock::now(); |
56 | // Async run task |
57 | std::thread runner( |
58 | [](TaskPtr task) { |
59 | task->status(Task::Status::SCHEDULED); |
60 | task->run(); |
61 | }, |
62 | task); |
63 | |
64 | // Wait finish |
65 | ASSERT_TRUE(task->wait_finish()); |
66 | auto end = std::chrono::steady_clock::now(); |
67 | auto comsuption = |
68 | std::chrono::duration_cast<std::chrono::milliseconds>(end - begin); |
69 | |
70 | ASSERT_TRUE(comsuption.count() >= kMillSeconds); |
71 | ASSERT_TRUE(task->finished()); |
72 | runner.join(); |
73 | } |
74 | } |
75 | |