1 // 2 // Copyright (C) 2014 The Android Open Source Project 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 17 #include "trunks/scoped_key_handle.h" 18 19 #include <gmock/gmock.h> 20 #include <gtest/gtest.h> 21 22 #include "trunks/mock_tpm.h" 23 #include "trunks/tpm_generated.h" 24 #include "trunks/trunks_factory_for_test.h" 25 26 using testing::_; 27 using testing::DoAll; 28 using testing::Invoke; 29 using testing::NiceMock; 30 using testing::Return; 31 using testing::SetArgPointee; 32 using testing::WithArgs; 33 34 namespace trunks { 35 36 // A test fixture for TpmState tests. 37 class ScopedKeyHandleTest : public testing::Test { 38 public: 39 ScopedKeyHandleTest() {} 40 ~ScopedKeyHandleTest() override {} 41 42 void SetUp() override { 43 factory_.set_tpm(&mock_tpm_); 44 } 45 46 protected: 47 TrunksFactoryForTest factory_; 48 NiceMock<MockTpm> mock_tpm_; 49 }; 50 51 TEST_F(ScopedKeyHandleTest, FlushHandle) { 52 TPM_HANDLE handle = TPM_RH_FIRST; 53 ScopedKeyHandle scoped_handle(factory_, handle); 54 EXPECT_CALL(mock_tpm_, FlushContextSync(handle, _)) 55 .WillOnce(Return(TPM_RC_SUCCESS)); 56 } 57 58 TEST_F(ScopedKeyHandleTest, GetTest) { 59 TPM_HANDLE handle = TPM_RH_FIRST; 60 ScopedKeyHandle scoped_handle(factory_, handle); 61 EXPECT_EQ(handle, scoped_handle.get()); 62 } 63 64 TEST_F(ScopedKeyHandleTest, ReleaseTest) { 65 TPM_HANDLE handle = TPM_RH_FIRST; 66 ScopedKeyHandle scoped_handle(factory_, handle); 67 EXPECT_EQ(handle, scoped_handle.release()); 68 EXPECT_EQ(0u, scoped_handle.get()); 69 } 70 71 TEST_F(ScopedKeyHandleTest, ResetAndFlush) { 72 TPM_HANDLE old_handle = TPM_RH_FIRST; 73 TPM_HANDLE new_handle = TPM_RH_NULL; 74 ScopedKeyHandle scoped_handle(factory_, old_handle); 75 EXPECT_EQ(old_handle, scoped_handle.get()); 76 EXPECT_CALL(mock_tpm_, FlushContextSync(old_handle, _)) 77 .WillOnce(Return(TPM_RC_SUCCESS)); 78 scoped_handle.reset(new_handle); 79 EXPECT_EQ(new_handle, scoped_handle.get()); 80 EXPECT_CALL(mock_tpm_, FlushContextSync(new_handle, _)) 81 .WillOnce(Return(TPM_RC_SUCCESS)); 82 } 83 84 TEST_F(ScopedKeyHandleTest, NullReset) { 85 TPM_HANDLE handle = TPM_RH_FIRST; 86 ScopedKeyHandle scoped_handle(factory_, handle); 87 EXPECT_EQ(handle, scoped_handle.get()); 88 EXPECT_CALL(mock_tpm_, FlushContextSync(handle, _)) 89 .WillOnce(Return(TPM_RC_SUCCESS)); 90 scoped_handle.reset(); 91 EXPECT_EQ(0u, scoped_handle.get()); 92 } 93 94 } // namespace trunks 95