• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 
16 #include "medialibrary_unittest_utils.h"
17 
18 #include <cerrno>
19 #include <fstream>
20 #include <sys/stat.h>
21 
22 #include "ability_context_impl.h"
23 #include "fetch_result.h"
24 #include "media_log.h"
25 #include "media_file_utils.h"
26 #include "media_smart_map_column.h"
27 #include "medialibrary_data_manager.h"
28 #include "medialibrary_unistore_manager.h"
29 #include "mimetype_utils.h"
30 #include "result_set_utils.h"
31 #include "scanner_utils.h"
32 #include "userfilemgr_uri.h"
33 
34 using namespace std;
35 using namespace OHOS::DataShare;
36 using namespace OHOS::AppExecFwk;
37 namespace OHOS {
38 namespace Media {
IsValid()39 bool MediaLibraryUnitTestUtils::IsValid()
40 {
41     return isValid_;
42 }
43 
Init()44 void MediaLibraryUnitTestUtils::Init()
45 {
46     auto stageContext = std::make_shared<AbilityRuntime::ContextImpl>();
47     auto abilityContextImpl = std::make_shared<OHOS::AbilityRuntime::AbilityContextImpl>();
48     abilityContextImpl->SetStageContext(stageContext);
49     int32_t sceneCode = 0;
50     MediaLibraryDataManager::GetInstance()->InitMediaLibraryMgr(abilityContextImpl, abilityContextImpl, sceneCode);
51     auto ret = MediaLibraryDataManager::GetInstance()->InitMediaLibraryMgr(abilityContextImpl, abilityContextImpl,
52         sceneCode);
53     CHECK_AND_RETURN_LOG(ret == E_OK, "InitMediaLibraryMgr failed, ret: %{public}d", ret);
54     isValid_ = true;
55 }
56 
InitUnistore()57 int32_t MediaLibraryUnitTestUtils::InitUnistore()
58 {
59     auto stageContext = std::make_shared<AbilityRuntime::ContextImpl>();
60     auto abilityContextImpl = std::make_shared<OHOS::AbilityRuntime::AbilityContextImpl>();
61     abilityContextImpl -> SetStageContext(stageContext);
62     int32_t ret = MediaLibraryUnistoreManager::GetInstance().Init(abilityContextImpl);
63     if (ret != E_OK) {
64         MEDIA_ERR_LOG("init MediaLibraryUnistoreManager failed");
65     }
66     return ret;
67 }
68 
InitUnistore(const NativeRdb::RdbStoreConfig & config,int version,NativeRdb::RdbOpenCallback & openCallback)69 int32_t MediaLibraryUnitTestUtils::InitUnistore(const NativeRdb::RdbStoreConfig &config, int version,
70     NativeRdb::RdbOpenCallback &openCallback)
71 {
72     auto stageContext = std::make_shared<AbilityRuntime::ContextImpl>();
73     auto abilityContextImpl = std::make_shared<OHOS::AbilityRuntime::AbilityContextImpl>();
74     abilityContextImpl->SetStageContext(stageContext);
75     int32_t ret = MediaLibraryUnistoreManager::GetInstance().Init(abilityContextImpl, config, version, openCallback);
76     MediaLibraryDataManager::GetInstance()->rdbStore_ = MediaLibraryUnistoreManager::GetInstance().GetRdbStore();
77     if (ret != E_OK) {
78         MEDIA_ERR_LOG("init MediaLibraryUnistoreManager with config failed");
79     }
80     return ret;
81 }
82 
StopUnistore()83 void MediaLibraryUnitTestUtils::StopUnistore()
84 {
85     MediaLibraryDataManager::GetInstance()->rdbStore_ = nullptr;
86     MediaLibraryUnistoreManager::GetInstance().Stop();
87 }
88 
InitRootDirs()89 void MediaLibraryUnitTestUtils::InitRootDirs()
90 {
91     for (const auto &dir : TEST_ROOT_DIRS) {
92         shared_ptr<FileAsset> dirAsset = nullptr;
93         if (!CreateAlbum(dir, nullptr, dirAsset)) {
94             isValid_ = false;
95             return;
96         }
97         rootDirAssetMap_[dir] = dirAsset;
98     }
99 }
100 
CleanTestFiles()101 void MediaLibraryUnitTestUtils::CleanTestFiles()
102 {
103     system("rm -rf /storage/cloud/files/Audio/*");
104     system("rm -rf /storage/cloud/files/Audios/*");
105     system("rm -rf /storage/cloud/files/Camera/*");
106     system("rm -rf /storage/cloud/files/Docs/Documents/*");
107     system("rm -rf /storage/cloud/files/Docs/Download/*");
108     system("rm -rf /storage/cloud/files/Photo/*");
109     system("rm -rf /storage/cloud/files/Pictures/*");
110     system("rm -rf /storage/cloud/files/Pictures/*");
111     system("rm -rf /storage/cloud/files/Videos/*");
112     system("rm -rf /storage/cloud/files/.*");
113     auto rdbStore = MediaLibraryDataManager::GetInstance()->rdbStore_;
114     NativeRdb::AbsRdbPredicates predicates(MEDIALIBRARY_TABLE);
115     predicates.GreaterThan(MEDIA_DATA_DB_ID, to_string(0));
116     int32_t deletedRows = -1;
117     auto ret = rdbStore->Delete(deletedRows, predicates);
118     MEDIA_INFO_LOG("CleanTestFiles Delete retVal: %{public}d, deletedRows: %{public}d", ret, deletedRows);
119 }
120 
CleanBundlePermission()121 void MediaLibraryUnitTestUtils::CleanBundlePermission()
122 {
123     auto rdbStore = MediaLibraryDataManager::GetInstance()->rdbStore_;
124     NativeRdb::AbsRdbPredicates predicates(BUNDLE_PERMISSION_TABLE);
125     predicates.GreaterThan(MEDIA_DATA_DB_ID, to_string(0));
126     int32_t deletedRows = -1;
127     auto ret = rdbStore->Delete(deletedRows, predicates);
128     MEDIA_INFO_LOG("CleanBundlePermission Delete retVal: %{public}d, deletedRows: %{public}d", ret, deletedRows);
129 }
130 
GetRootAsset(const string & dir)131 shared_ptr<FileAsset> MediaLibraryUnitTestUtils::GetRootAsset(const string &dir)
132 {
133     if (rootDirAssetMap_.find(dir) != rootDirAssetMap_.end()) {
134         return rootDirAssetMap_[dir];
135     }
136     return nullptr;
137 }
138 
IsFileExists(const string filePath)139 bool MediaLibraryUnitTestUtils::IsFileExists(const string filePath)
140 {
141     struct stat statInfo {};
142     int errCode = stat(filePath.c_str(), &statInfo);
143     return (errCode == 0);
144 }
145 
GetFileAsset(const int fileId,shared_ptr<FileAsset> & fileAsset)146 bool MediaLibraryUnitTestUtils::GetFileAsset(const int fileId, shared_ptr<FileAsset> &fileAsset)
147 {
148     if (!MediaLibraryUnitTestUtils::IsValid()) {
149         MEDIA_ERR_LOG("MediaLibraryDataManager invalid");
150         exit(1);
151     }
152     vector<string> columns;
153     DataSharePredicates predicates;
154     string selections = MEDIA_DATA_DB_ID + " = " + to_string(fileId);
155     predicates.SetWhereClause(selections);
156     Uri queryFileUri(MEDIALIBRARY_DATA_URI);
157     int errCode = 0;
158     MediaLibraryCommand cmd(queryFileUri, Media::OperationType::QUERY);
159     auto resultSet = MediaLibraryDataManager::GetInstance()->Query(cmd, columns, predicates, errCode);
160     if (resultSet == nullptr) {
161         MEDIA_ERR_LOG("GetFileAsset::resultSet == nullptr");
162         return false;
163     }
164     auto result = make_shared<DataShareResultSet>(resultSet);
165     shared_ptr<FetchResult<FileAsset>> fetchFileResult = make_unique<FetchResult<FileAsset>>(move(result));
166     if (fetchFileResult->GetCount() <= 0) {
167         MEDIA_ERR_LOG("GetFileAsset::GetCount <= 0");
168         return false;
169     }
170     auto firstAsset = fetchFileResult->GetFirstObject();
171     fileAsset = move(firstAsset);
172     if (fileAsset == nullptr) {
173         MEDIA_ERR_LOG("GetFileAsset::fileAsset = nullptr.");
174         return false;
175     }
176     return true;
177 }
178 
CreateAlbum(string displayName,shared_ptr<FileAsset> parentAlbumAsset,shared_ptr<FileAsset> & albumAsset)179 bool MediaLibraryUnitTestUtils::CreateAlbum(string displayName, shared_ptr<FileAsset> parentAlbumAsset,
180     shared_ptr<FileAsset> &albumAsset)
181 {
182     if (!MediaLibraryUnitTestUtils::IsValid()) {
183         MEDIA_ERR_LOG("MediaLibraryDataManager invalid");
184         exit(1);
185     }
186     Uri createAlbumUri(MEDIALIBRARY_DATA_URI + "/" + MEDIA_ALBUMOPRN + "/" + MEDIA_ALBUMOPRN_CREATEALBUM);
187     string dirPath;
188     if (parentAlbumAsset == nullptr) {
189         dirPath = ROOT_MEDIA_DIR + displayName;
190     } else {
191         dirPath = parentAlbumAsset->GetPath() + "/" + displayName;
192     }
193     DataShareValuesBucket valuesBucket;
194     valuesBucket.Put(MEDIA_DATA_DB_FILE_PATH, dirPath);
195     valuesBucket.Put(MEDIA_DATA_DB_NAME, displayName);
196     MediaLibraryCommand cmd(createAlbumUri);
197     auto retVal = MediaLibraryDataManager::GetInstance()->Insert(cmd, valuesBucket);
198     MEDIA_INFO_LOG("CreateAlbum:: %{private}s, retVal: %{public}d", dirPath.c_str(), retVal);
199     if (retVal <= 0) {
200         MEDIA_ERR_LOG("CreateAlbum::create failed, %{private}s", dirPath.c_str());
201         return false;
202     }
203     if (!GetFileAsset(retVal, albumAsset)) {
204         MEDIA_ERR_LOG("CreateAlbum::GetFileAsset failed, %{private}s", dirPath.c_str());
205         return false;
206     }
207     return true;
208 }
209 
CreateFile(string displayName,shared_ptr<FileAsset> parentAlbumAsset,shared_ptr<FileAsset> & fileAsset)210 bool MediaLibraryUnitTestUtils::CreateFile(string displayName, shared_ptr<FileAsset> parentAlbumAsset,
211     shared_ptr<FileAsset> &fileAsset)
212 {
213     if (!MediaLibraryUnitTestUtils::IsValid()) {
214         MEDIA_ERR_LOG("MediaLibraryDataManager invalid");
215         exit(1);
216     }
217     Uri createAssetUri(MEDIALIBRARY_DATA_URI + "/" + Media::MEDIA_FILEOPRN + "/" + Media::MEDIA_FILEOPRN_CREATEASSET);
218     DataShareValuesBucket valuesBucket;
219     string relativePath = MediaFileUtils::AddDocsToRelativePath(parentAlbumAsset->GetRelativePath() +
220         parentAlbumAsset->GetDisplayName() + "/");
221     string mimeType = MimeTypeUtils::GetMimeTypeFromExtension(ScannerUtils::GetFileExtension(displayName));
222     MediaType mediaType = MimeTypeUtils::GetMediaTypeFromMimeType(mimeType);
223     valuesBucket.Put(MEDIA_DATA_DB_MEDIA_TYPE, mediaType);
224     valuesBucket.Put(MEDIA_DATA_DB_NAME, displayName);
225     valuesBucket.Put(MEDIA_DATA_DB_RELATIVE_PATH, relativePath);
226     MediaLibraryCommand cmd(createAssetUri);
227     int32_t retVal = MediaLibraryDataManager::GetInstance()->Insert(cmd, valuesBucket);
228     MEDIA_INFO_LOG("CreateFile:: %{private}s, retVal: %{public}d", (relativePath + displayName).c_str(), retVal);
229     if (retVal <= 0) {
230         MEDIA_ERR_LOG("CreateFile::create failed, %{private}s", (relativePath + displayName).c_str());
231         return false;
232     }
233     if (!GetFileAsset(retVal, fileAsset)) {
234         MEDIA_ERR_LOG("CreateFile::GetFileAsset failed, %{private}s", (relativePath + displayName).c_str());
235         return false;
236     }
237     return true;
238 }
239 
CreateFileFS(const string & filePath)240 bool MediaLibraryUnitTestUtils::CreateFileFS(const string &filePath)
241 {
242     bool errCode = false;
243 
244     if (filePath.empty()) {
245         return errCode;
246     }
247 
248     ofstream file(filePath);
249     if (!file) {
250         MEDIA_ERR_LOG("Output file path could not be created");
251         return errCode;
252     }
253 
254     const mode_t CHOWN_RW_UG = 0660;
255     if (chmod(filePath.c_str(), CHOWN_RW_UG) == 0) {
256         errCode = true;
257     }
258 
259     file.close();
260 
261     return errCode;
262 }
263 
DeleteDir(const string & path,const string & dirId)264 bool MediaLibraryUnitTestUtils::DeleteDir(const string &path, const string &dirId)
265 {
266     string cmd = "rm -rf " + path;
267     system(cmd.c_str());
268 
269     auto rdbStore = MediaLibraryDataManager::GetInstance()->rdbStore_;
270     NativeRdb::AbsRdbPredicates predicates(MEDIALIBRARY_TABLE);
271     predicates.EqualTo(MEDIA_DATA_DB_ID, dirId)->Or()->EqualTo(MEDIA_DATA_DB_PARENT_ID, dirId);
272     int32_t deletedRows = -1;
273     auto ret = rdbStore->Delete(deletedRows, predicates);
274     return ret == 0;
275 }
276 
TrashFile(shared_ptr<FileAsset> & fileAsset)277 void MediaLibraryUnitTestUtils::TrashFile(shared_ptr<FileAsset> &fileAsset)
278 {
279     DataShareValuesBucket valuesBucket;
280     valuesBucket.Put(SMARTALBUMMAP_DB_ALBUM_ID, TRASH_ALBUM_ID_VALUES);
281     valuesBucket.Put(SMARTALBUMMAP_DB_CHILD_ASSET_ID, fileAsset->GetId());
282     string uriString = MEDIALIBRARY_DATA_URI + "/" + MEDIA_SMARTALBUMMAPOPRN + "/" +
283         MEDIA_SMARTALBUMMAPOPRN_ADDSMARTALBUM;
284     Uri uri(uriString);
285     MediaLibraryCommand cmd(uri);
286     MediaLibraryDataManager::GetInstance()->Insert(cmd, valuesBucket);
287 }
288 
RecoveryFile(shared_ptr<FileAsset> & fileAsset)289 void MediaLibraryUnitTestUtils::RecoveryFile(shared_ptr<FileAsset> &fileAsset)
290 {
291     DataShareValuesBucket valuesBucket;
292     valuesBucket.Put(SMARTALBUMMAP_DB_ALBUM_ID, TRASH_ALBUM_ID_VALUES);
293     valuesBucket.Put(SMARTALBUMMAP_DB_CHILD_ASSET_ID, fileAsset->GetId());
294     string uriString = MEDIALIBRARY_DATA_URI + "/" + MEDIA_SMARTALBUMMAPOPRN + "/" +
295         MEDIA_SMARTALBUMMAPOPRN_REMOVESMARTALBUM;
296     Uri uri(uriString);
297     MediaLibraryCommand cmd(uri);
298     MediaLibraryDataManager::GetInstance()->Insert(cmd, valuesBucket);
299 }
300 
WaitForCallback(shared_ptr<TestScannerCallback> callback)301 void MediaLibraryUnitTestUtils::WaitForCallback(shared_ptr<TestScannerCallback> callback)
302 {
303     std::mutex mutex;
304     std::unique_lock<std::mutex> lock(mutex);
305     const int waitSeconds = 10;
306     callback->condVar_.wait_until(lock, std::chrono::system_clock::now() + std::chrono::seconds(waitSeconds));
307 }
308 
GrantUriPermission(const int32_t fileId,const string & bundleName,const string & mode,const int32_t tableType)309 int32_t MediaLibraryUnitTestUtils::GrantUriPermission(const int32_t fileId, const string &bundleName,
310     const string &mode, const int32_t tableType)
311 {
312     Uri addPermission(MEDIALIBRARY_BUNDLEPERM_URI + "/" + BUNDLE_PERMISSION_INSERT);
313     DataShareValuesBucket values;
314     values.Put(PERMISSION_FILE_ID, fileId);
315     values.Put(PERMISSION_BUNDLE_NAME, bundleName);
316     values.Put(PERMISSION_MODE, mode);
317     values.Put(PERMISSION_TABLE_TYPE, tableType);
318     MediaLibraryCommand cmd(addPermission);
319     return MediaLibraryDataManager::GetInstance()->Insert(cmd, values);
320 }
321 
TestScannerCallback()322 TestScannerCallback::TestScannerCallback() : status_(-1) {}
323 
OnScanFinished(const int32_t status,const std::string & uri,const std::string & path)324 int32_t TestScannerCallback::OnScanFinished(const int32_t status, const std::string &uri, const std::string &path)
325 {
326     status_ = status;
327     condVar_.notify_all();
328     return E_OK;
329 }
330 
writeBytesToFile(size_t numBytes,const char * path,size_t & resultFileSize)331 bool MediaLibraryUnitTestUtils::writeBytesToFile(size_t numBytes, const char* path, size_t& resultFileSize)
332 {
333     int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
334     if (fd == -1) {
335         MEDIA_ERR_LOG("Error: Unable to open file %{public}s for writing, errno: %{public}d", path, errno);
336         return false;
337     }
338 
339     char dummyByte = '\0'; // A dummy byte to be written
340 
341     for (size_t i = 0; i < numBytes; ++i) {
342         if (write(fd, &dummyByte, sizeof(char)) == -1) {
343             MEDIA_ERR_LOG("Error while writing to file %{public}s, errno: %{public}d", path, errno);
344             close(fd);
345             return false;
346         }
347     }
348 
349     close(fd);
350 
351     struct stat statbuf;
352     if (lstat(path, &statbuf) == -1) {
353         MEDIA_ERR_LOG("Failed to get file size of %{public}s, errno is %{public}d", path, errno);
354         return false;
355     }
356 
357     resultFileSize = statbuf.st_size;
358     MEDIA_INFO_LOG("File %{public}s successfully written, File size after writing: %{public}zu", path, resultFileSize);
359 
360     return true;
361 }
362 }
363 }
364