• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2022 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 #include <gtest/gtest.h>
16 #include <unistd.h>
17 
18 #include "accesstoken_kit.h"
19 #include "datashare_helper.h"
20 #include "datashare_log.h"
21 #include "hap_token_info.h"
22 #include "iservice_registry.h"
23 #include "rdb_errno.h"
24 #include "system_ability_definition.h"
25 #include "token_setproc.h"
26 
27 namespace OHOS {
28 namespace DataShare {
29 using namespace testing::ext;
30 using namespace OHOS::Security::AccessToken;
31 constexpr int STORAGE_MANAGER_MANAGER_ID = 5003;
32 std::string DATA_SHARE_URI = "datashare:///com.acts.errorcodetest";
33 std::string SLIENT_ACCESS_URI = "datashare:///com.acts.errorcodetest/entry/DB00/TBL00?Proxy=true";
34 std::string TBL_STU_NAME = "name";
35 std::string TBL_STU_AGE = "age";
36 std::shared_ptr<DataShare::DataShareHelper> g_slientAccessHelper;
37 std::shared_ptr<DataShare::DataShareHelper> dataShareHelper;
38 
39 class ErrorCodeTest : public testing::Test {
40 public:
41     static void SetUpTestCase(void);
42     static void TearDownTestCase(void);
43     void SetUp();
44     void TearDown();
45 };
46 
CreateDataShareHelper(int32_t systemAbilityId,std::string uri)47 std::shared_ptr<DataShare::DataShareHelper> CreateDataShareHelper(int32_t systemAbilityId, std::string uri)
48 {
49     LOG_INFO("CreateDataShareHelper start");
50     auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
51     if (saManager == nullptr) {
52         LOG_ERROR("GetSystemAbilityManager get samgr failed.");
53         return nullptr;
54     }
55     auto remoteObj = saManager->GetSystemAbility(systemAbilityId);
56     if (remoteObj == nullptr) {
57         LOG_ERROR("GetSystemAbility service failed.");
58         return nullptr;
59     }
60     return DataShare::DataShareHelper::Creator(remoteObj, uri);
61 }
62 
SetUpTestCase(void)63 void ErrorCodeTest::SetUpTestCase(void)
64 {
65     LOG_INFO("SetUpTestCase invoked");
66     dataShareHelper = CreateDataShareHelper(STORAGE_MANAGER_MANAGER_ID, DATA_SHARE_URI);
67     ASSERT_TRUE(dataShareHelper != nullptr);
68     int sleepTime = 3;
69     sleep(sleepTime);
70 
71     HapInfoParams info = {
72         .userID = 100,
73         .bundleName = "ohos.datashareclienttest.demo",
74         .instIndex = 0,
75         .appIDDesc = "ohos.datashareclienttest.demo"
76     };
77     HapPolicyParams policy = {
78         .apl = APL_NORMAL,
79         .domain = "test.domain",
80         .permList = {
81             {
82                 .permissionName = "ohos.permission.test",
83                 .bundleName = "ohos.datashareclienttest.demo",
84                 .grantMode = 1,
85                 .availableLevel = APL_NORMAL,
86                 .label = "label",
87                 .labelId = 1,
88                 .description = "ohos.datashareclienttest.demo",
89                 .descriptionId = 1
90             }
91         },
92         .permStateList = {
93             {
94                 .permissionName = "ohos.permission.test",
95                 .isGeneral = true,
96                 .resDeviceID = { "local" },
97                 .grantStatus = { PermissionState::PERMISSION_GRANTED },
98                 .grantFlags = { 1 }
99             }
100         }
101     };
102     AccessTokenKit::AllocHapToken(info, policy);
103     auto testTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(
104         info.userID, info.bundleName, info.instIndex);
105     SetSelfTokenID(testTokenId);
106 
107     g_slientAccessHelper = CreateDataShareHelper(STORAGE_MANAGER_MANAGER_ID, SLIENT_ACCESS_URI);
108     ASSERT_TRUE(g_slientAccessHelper != nullptr);
109     LOG_INFO("SetUpTestCase end");
110 }
111 
TearDownTestCase(void)112 void ErrorCodeTest::TearDownTestCase(void)
113 {
114     auto tokenId = AccessTokenKit::GetHapTokenID(100, "ohos.datashareclienttest.demo", 0);
115     AccessTokenKit::DeleteToken(tokenId);
116     g_slientAccessHelper = nullptr;
117     dataShareHelper = nullptr;
118 }
119 
SetUp(void)120 void ErrorCodeTest::SetUp(void) {}
TearDown(void)121 void ErrorCodeTest::TearDown(void) {}
122 
123 /**
124 * @tc.name: ErrorCodeTest_Insert_Test_001
125 * @tc.desc: Verify successful insertion operation returns positive ID
126 * @tc.type: FUNC
127 * @tc.require: None
128 * @tc.precon: None
129 * @tc.step:
130     1. Get slient access helper instance
131     2. Create test URI and DataShareValuesBucket with student data
132     3. Call Insert method with URI and values bucket
133     4. Check if returned ID is positive
134 * @tc.experct: Insert operation succeeds and returns positive ID
135 */
136 HWTEST_F(ErrorCodeTest, ErrorCodeTest_Insert_Test_001, TestSize.Level0)
137 {
138     LOG_INFO("ErrorCodeTest_Insert_Test_001::Start");
139     auto helper = g_slientAccessHelper;
140     Uri uri(SLIENT_ACCESS_URI);
141     DataShare::DataShareValuesBucket valuesBucket;
142     std::string value = "lisi";
143     valuesBucket.Put(TBL_STU_NAME, value);
144     int age = 25;
145     valuesBucket.Put(TBL_STU_AGE, age);
146 
147     int retVal = helper->Insert(uri, valuesBucket);
148     EXPECT_EQ((retVal > 0), true);
149     LOG_INFO("ErrorCodeTest_Insert_Test_001::End");
150 }
151 
152 /**
153 * @tc.name: ErrorCodeTest_QUERY_Test_001
154 * @tc.desc: Verify query operations return correct error codes for valid and invalid URIs
155 * @tc.type: FUNC
156 * @tc.require: None
157 * @tc.precon: None
158 * @tc.step:
159     1. Query existing data with valid URI and check for success
160     2. Verify row count is 1 for existing data
161     3. Query with invalid URI and check error code
162     4. Verify result set is null for invalid URI
163 * @tc.experct:
164     1. Valid query returns 0 error code and 1 row
165     2. Invalid query returns E_DB_NOT_EXIST error and null result set
166 */
167 HWTEST_F(ErrorCodeTest, ErrorCodeTest_QUERY_Test_001, TestSize.Level0)
168 {
169     LOG_INFO("ErrorCodeTest_QUERY_Test_001::Start");
170     auto helper = g_slientAccessHelper;
171     Uri uri(SLIENT_ACCESS_URI);
172     DataShare::DataSharePredicates predicates;
173     predicates.EqualTo(TBL_STU_NAME, "lisi");
174     vector<string> columns;
175     DatashareBusinessError noError;
176     auto resultSet = helper->Query(uri, predicates, columns, &noError);
177     EXPECT_EQ(noError.GetCode(), 0);
178     int result = 0;
179     if (resultSet != nullptr) {
180         resultSet->GetRowCount(result);
181     }
182     EXPECT_EQ(result, 1);
183 
184     std::string ERR_SLIENT_ACCESS_URI = "datashare:///com.acts.errorcodetest/entry/DB01/TBL01?Proxy=true";
185     Uri uriErr(ERR_SLIENT_ACCESS_URI);
186     DatashareBusinessError error;
187     resultSet = helper->Query(uriErr, predicates, columns, &error);
188     EXPECT_EQ(error.GetCode(), NativeRdb::E_DB_NOT_EXIST);
189     EXPECT_EQ(resultSet, nullptr);
190     LOG_INFO("ErrorCodeTest_QUERY_Test_001::End");
191 }
192 
193 /**
194 * @tc.name: ErrorCodeTest_QUERY_Test_002
195 * @tc.desc: Verify unauthorized query returns correct error code
196 * @tc.type: FUNC
197 * @tc.require: None
198 * @tc.precon: None
199 * @tc.step:
200     1. Insert test data using dataShareHelper
201     2. Query inserted data with predicates
202     3. Check error code and result set for unauthorized access
203     4. Clean up by deleting inserted data
204 * @tc.experct:
205     1. Insert succeeds with positive ID
206     2. Query returns 401 error code and null result set
207     3. Delete operation succeeds with positive count
208 */
209 HWTEST_F(ErrorCodeTest, ErrorCodeTest_QUERY_Test_002, TestSize.Level0)
210 {
211     LOG_INFO("ErrorCodeTest_QUERY_Test_002::Start");
212     ASSERT_TRUE(dataShareHelper != nullptr);
213     Uri uri(DATA_SHARE_URI);
214 
215     DataShare::DataShareValuesBucket valuesBucket;
216     std::string value = "wangwu";
217     valuesBucket.Put(TBL_STU_NAME, value);
218     int age = 30;
219     valuesBucket.Put(TBL_STU_AGE, age);
220     int retVal = dataShareHelper->Insert(uri, valuesBucket);
221     EXPECT_EQ((retVal > 0), true);
222 
223     DataShare::DataSharePredicates predicates;
224     predicates.EqualTo(TBL_STU_NAME, "wangwu");
225     vector<string> columns;
226     DatashareBusinessError error;
227     auto resultSet = dataShareHelper->Query(uri, predicates, columns, &error);
228     EXPECT_EQ(error.GetCode(), 401);
229     EXPECT_EQ(resultSet, nullptr);
230 
231     DataShare::DataSharePredicates deletePredicates;
232     std::string selections = TBL_STU_NAME + " = 'wangwu'";
233     deletePredicates.SetWhereClause(selections);
234     retVal = dataShareHelper->Delete(uri, deletePredicates);
235     EXPECT_EQ((retVal > 0), true);
236     LOG_INFO("ErrorCodeTest_QUERY_Test_002::End");
237 }
238 } // namespace DataShare
239 } // namespace OHOS