Imported Upstream version 1.12.0
[platform/core/ml/nnfw.git] / tests / nnfw_api / src / NNPackages.cc
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. 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
17 #include "NNPackages.h"
18
19 #include <unistd.h>
20 #include <libgen.h>
21 #include <string.h>
22 #include <dirent.h>
23 #include <assert.h>
24 #include <stdexcept>
25
26 // NOTE Must match `enum TestPackages`
27 const char *TEST_PACKAGE_NAMES[] = {
28   // for validation test
29   "add",
30   "add_no_manifest",
31   "add_invalid_manifest",
32
33   // for dynamic tensor test
34   "while_dynamic",
35   "if_dynamic",
36 };
37
38 NNPackages &NNPackages::get()
39 {
40   static NNPackages instance;
41   return instance;
42 }
43
44 void NNPackages::init(const char *argv0)
45 {
46   char raw_dir[1024];
47   char cwd[1024];
48   strncpy(raw_dir, argv0, sizeof(raw_dir) - 1);
49   char *dir_path = dirname(raw_dir);
50   if (dir_path[0] == '/')
51   {
52     // If it is an absolute path, just use it
53     _base_path = dir_path;
54   }
55   else
56   {
57     // If it is a relative path, prepend CWD
58     getcwd(cwd, sizeof(cwd));
59     _base_path = cwd;
60     _base_path += "/";
61     _base_path += dir_path;
62   }
63 }
64
65 void NNPackages::checkAll()
66 {
67   assert(!_base_path.empty());
68
69   for (int i = 0; i < NNPackages::COUNT; i++)
70   {
71     std::string package_name = TEST_PACKAGE_NAMES[i];
72     std::string path = getModelAbsolutePath(i);
73
74     DIR *dir = opendir(path.c_str());
75     if (!dir)
76     {
77       std::string msg = "missing nnpackage: " + package_name + ", path: " + path +
78                         "\nPlease run \'[install_dir]/test/onert-test prepare-model\' to "
79                         "download nnpackage";
80       throw std::runtime_error{msg};
81     }
82     closedir(dir);
83   }
84 }
85
86 std::string NNPackages::getModelAbsolutePath(int package_no)
87 {
88   if (package_no < 0 || package_no >= NNPackages::COUNT)
89   {
90     throw std::runtime_error{"Invalid package_no: " + std::to_string(package_no)};
91   }
92
93   const char *package_dir = TEST_PACKAGE_NAMES[package_no];
94   return getModelAbsolutePath(package_dir);
95 }
96
97 std::string NNPackages::getModelAbsolutePath(const char *package_name)
98 {
99   return _base_path + "/nnfw_api_gtest_models/" + package_name + "/" + package_name;
100 }