1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include <atomic> 17 #include <chrono> 18 #include <hwext/gtest-ext.h> 19 #include <hwext/gtest-tag.h> 20 #include <thread> 21 22 #include "i_semaphore.h" 23 24 namespace { 25 using namespace testing::ext; 26 27 class SemaphoreTest : public testing::Test { 28 protected: SetUpTestCase()29 static void SetUpTestCase() {} TearDownTestCase()30 static void TearDownTestCase() {} 31 }; 32 33 /** 34 * @tc.name: SemaphoreTest 35 * @tc.desc: CtorDtor. 36 * @tc.type: FUNC 37 */ 38 HWTEST_F(SemaphoreTest, CtorDtor, TestSize.Level1) 39 { 40 auto semaphore = GetSemaphoreFactory().Create(1); 41 EXPECT_NE(semaphore, nullptr); 42 EXPECT_TRUE(semaphore->TryWait()); 43 EXPECT_FALSE(semaphore->TimedWait(1, 0)); 44 } 45 46 /** 47 * @tc.name: SemaphoreTest 48 * @tc.desc: Wait. 49 * @tc.type: FUNC 50 */ 51 HWTEST_F(SemaphoreTest, Wait, TestSize.Level1) 52 { 53 auto semaphore = GetSemaphoreFactory().Create(1); 54 ASSERT_NE(semaphore, nullptr); 55 EXPECT_TRUE(semaphore->Wait()); 56 EXPECT_FALSE(semaphore->TryWait()); 57 } 58 59 /** 60 * @tc.name: SemaphoreTest 61 * @tc.desc: Post. 62 * @tc.type: FUNC 63 */ 64 HWTEST_F(SemaphoreTest, Post, TestSize.Level1) 65 { 66 auto semaphore = GetSemaphoreFactory().Create(0); 67 ASSERT_NE(semaphore, nullptr); 68 EXPECT_TRUE(semaphore->Post()); 69 } 70 71 /** 72 * @tc.name: SemaphoreTest 73 * @tc.desc: Post. 74 * @tc.type: FUNC 75 */ 76 HWTEST_F(SemaphoreTest, WaitPost, TestSize.Level1) 77 { 78 auto readySem = GetSemaphoreFactory().Create(0); 79 auto finishSem = GetSemaphoreFactory().Create(0); 80 ASSERT_NE(readySem, nullptr); 81 ASSERT_NE(finishSem, nullptr); 82 83 auto done = std::make_shared<bool>(false); 84 ASSERT_NE(done, nullptr); 85 __anon79e07c660202() 86 std::thread bgThread([=]() { 87 readySem->Wait(); 88 *done = true; 89 finishSem->Post(); 90 }); 91 92 EXPECT_TRUE(readySem->Post()); 93 EXPECT_TRUE(finishSem->Wait()); 94 EXPECT_TRUE(*done); 95 96 bgThread.join(); 97 } 98 } // namespace