Debian Codegraph @

tests/systestdriver.cpp

raw symbols SCIP
1 /* Copyright (C) 2019 by Jeremy Tan */
2 /* Copyright (C) 2025 FontForge Contributors - C++ port */
3 /*
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6
7 * Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
9
10 * Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
15 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
20 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
21 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
22 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 /**
27 * A test driver for the system tests that FontForge has.
28 * Runs each test in its own directory, clearing it out first if it exists.
29 * Tests will be skipped (return code 77) if required inputs are missing.
30 *
31 * This is a standalone tool with no FontForge library dependencies.
32 */
33
34 #include <cxxopts.hpp>
35
36 #include <cctype>
37 #include <cstdio>
38 #include <cstdlib>
39 #include <filesystem>
40 #include <string>
41 #include <vector>
42
43 #ifdef _WIN32
44 #include <windows.h>
45 #else
46 #include <unistd.h>
47 #include <sys/types.h>
48 #include <sys/wait.h>
49 #endif
50
51 namespace fs = std::filesystem;
52
53 struct ArgData {
54 std::string mode;
55 std::string binary;
56 fs::path script;
57 std::string desc;
58 fs::path exedir;
59 fs::path libdir;
60 std::vector<fs::path> argdirs;
61 fs::path workdir;
62 bool skip_as_pass = false;
63 };
64
65 /* ==================== Environment Utilities ==================== */
66
67 static bool set_env(const char* name, const char* value) {
68 #ifdef _WIN32
69 return _putenv_s(name, value) == 0;
70 #else
71 return setenv(name, value, 1) == 0;
72 #endif
73 }
74
75 #ifdef _WIN32
76 static std::string get_env(const char* name) {
77 const char* val = getenv(name);
78 return val ? val : "";
79 }
80 #endif
81
82 /* ==================== Argument Resolution ==================== */
83
84 static bool resolve_args(const ArgData& args, std::vector<std::string>& argv) {
85 for (auto& arg : argv) {
86 bool found = false;
87 for (const auto& dir : args.argdirs) {
88 fs::path path = dir / arg;
89 if (fs::exists(path)) {
90 arg = path.string();
91 found = true;
92 break;
93 }
94 }
95 if (!found) {
96 fprintf(stderr, "could not resolve the location to %s\n",
97 arg.c_str());
98 return false;
99 }
100 }
101 return true;
102 }
103
104 static bool setup_test_dir(ArgData& args) {
105 std::string basename = args.script.filename().string();
106
107 // Replace non-alphanumeric with underscore
108 for (char& c : basename) {
109 if (!isalnum(static_cast<unsigned char>(c))) {
110 c = '_';
111 }
112 }
113
114 std::string dir_name = basename + "_" + args.mode;
115 fs::path name = fs::path("systests") / dir_name;
116
117 std::error_code ec;
118 fs::remove_all(name, ec);
119 if (ec) {
120 fprintf(stderr, "failed to remove existing directory: %s (%s)\n",
121 name.string().c_str(), ec.message().c_str());
122 return false;
123 }
124
125 if (!fs::create_directories(name, ec) && ec) {
126 fprintf(stderr, "failed to create working directory: %s (%s)\n",
127 name.string().c_str(), ec.message().c_str());
128 return false;
129 }
130
131 args.workdir = fs::absolute(name);
132 return true;
133 }
134
135 /* ==================== Process Execution ==================== */
136
137 #ifdef _WIN32
138
139 static int run_process(const std::string& workdir,
140 const std::vector<std::string>& argv_vec) {
141 // Build command line
142 std::string cmdline;
143 for (size_t i = 0; i < argv_vec.size(); i++) {
144 if (i > 0) cmdline += ' ';
145 // Quote arguments containing spaces
146 if (argv_vec[i].find(' ') != std::string::npos) {
147 cmdline += '"';
148 cmdline += argv_vec[i];
149 cmdline += '"';
150 } else {
151 cmdline += argv_vec[i];
152 }
153 }
154
155 STARTUPINFOA si = {0};
156 PROCESS_INFORMATION pi = {0};
157 si.cb = sizeof(si);
158
159 // CreateProcessA modifies the command line, so we need a mutable copy
160 std::vector<char> cmdline_buf(cmdline.begin(), cmdline.end());
161 cmdline_buf.push_back('\0');
162
163 if (!CreateProcessA(nullptr, cmdline_buf.data(), nullptr, nullptr, FALSE, 0,
164 nullptr, workdir.c_str(), &si, &pi)) {
165 fprintf(stderr, "CreateProcess failed: %lu\n", GetLastError());
166 return 1;
167 }
168
169 WaitForSingleObject(pi.hProcess, INFINITE);
170
171 DWORD exit_code = 1;
172 GetExitCodeProcess(pi.hProcess, &exit_code);
173
174 CloseHandle(pi.hProcess);
175 CloseHandle(pi.hThread);
176
177 return static_cast<int>(exit_code);
178 }
179
180 #else // POSIX
181
182 static int run_process(const std::string& workdir,
183 const std::vector<std::string>& argv_vec) {
184 pid_t pid = fork();
185
186 if (pid < 0) {
187 fprintf(stderr, "fork failed\n");
188 return 1;
189 }
190
191 if (pid == 0) {
192 // Child process
193 if (chdir(workdir.c_str()) != 0) {
194 _exit(127);
195 }
196
197 // Build argv for execvp
198 std::vector<char*> argv;
199 for (const auto& s : argv_vec) {
200 argv.push_back(const_cast<char*>(s.c_str()));
201 }
202 argv.push_back(nullptr);
203
204 execvp(argv[0], argv.data());
205
206 // If we get here, exec failed
207 _exit(127);
208 }
209
210 // Parent process
211 int status;
212 waitpid(pid, &status, 0);
213
214 if (WIFEXITED(status)) {
215 return WEXITSTATUS(status);
216 }
217
218 return 1;
219 }
220
221 #endif
222
223 static int run_executable(const ArgData& args,
224 const std::vector<std::string>& argv_vec) {
225 // Print command
226 fprintf(stderr, "Running:");
227 for (const auto& s : argv_vec) {
228 fprintf(stderr, " %s", s.c_str());
229 }
230 fprintf(stderr, "\n");
231 fflush(stderr);
232
233 return run_process(args.workdir.string(), argv_vec);
234 }
235
236 static int run_ff_systest(const ArgData& args,
237 const std::vector<std::string>& extra_args) {
238 std::vector<std::string> test_args;
239 test_args.push_back(args.binary);
240 test_args.push_back("-lang");
241 test_args.push_back(args.mode);
242 test_args.push_back("-script");
243 test_args.push_back(args.script.string());
244 for (const auto& arg : extra_args) {
245 test_args.push_back(arg);
246 }
247
248 return run_executable(args, test_args);
249 }
250
251 static int run_pyhook_systest(const ArgData& args,
252 const std::vector<std::string>& extra_args) {
253 #ifdef _WIN32
254 // Add exedir to PATH
255 std::string path = args.exedir.string() + ";" + get_env("PATH");
256 set_env("PATH", path.c_str());
257 #endif
258
259 set_env("PYTHONPATH", args.libdir.string().c_str());
260
261 std::vector<std::string> test_args;
262 test_args.push_back(args.binary);
263 test_args.push_back("-Ss");
264 test_args.push_back(args.script.string());
265 for (const auto& arg : extra_args) {
266 test_args.push_back(arg);
267 }
268
269 return run_executable(args, test_args);
270 }
271
272 /* ==================== Main ==================== */
273
274 int main(int argc, char* argv[]) {
275 ArgData args;
276 std::vector<std::string> extra_args;
277
278 try {
279 cxxopts::Options options("systestdriver",
280 "System test driver for FontForge");
281
282 options.add_options()("m,mode", "The mode to run in (ff|py|pyhook)",
283 cxxopts::value<std::string>())(
284 "b,binary", "The path to the executable",
285 cxxopts::value<std::string>())("c,script",
286 "The path to the test script",
287 cxxopts::value<std::string>())(
288 "d,desc", "The test description", cxxopts::value<std::string>())(
289 "e,exedir", "Directory containing built executables",
290 cxxopts::value<std::string>())(
291 "l,libdir", "Directory containing built libraries",
292 cxxopts::value<std::string>())(
293 "a,argdir", "Directories to resolve test arguments",
294 cxxopts::value<std::vector<std::string>>())(
295 "s,skip-as-pass", "Exit 0 instead of 77 for skipped tests")(
296 "h,help", "Print usage");
297
298 options.allow_unrecognised_options();
299
300 auto result = options.parse(argc, argv);
301
302 if (result.count("help")) {
303 printf("%s\n", options.help().c_str());
304 return 0;
305 }
306
307 if (result.count("mode")) args.mode = result["mode"].as<std::string>();
308 if (result.count("binary"))
309 args.binary = result["binary"].as<std::string>();
310 if (result.count("script"))
311 args.script = result["script"].as<std::string>();
312 if (result.count("desc")) args.desc = result["desc"].as<std::string>();
313 if (result.count("exedir"))
314 args.exedir = result["exedir"].as<std::string>();
315 if (result.count("libdir"))
316 args.libdir = result["libdir"].as<std::string>();
317 if (result.count("argdir")) {
318 for (const auto& dir :
319 result["argdir"].as<std::vector<std::string>>()) {
320 args.argdirs.push_back(fs::path(dir));
321 }
322 }
323 args.skip_as_pass = result.count("skip-as-pass") > 0;
324
325 // Collect unrecognized options as extra arguments
326 extra_args = result.unmatched();
327
328 } catch (const cxxopts::exceptions::exception& e) {
329 fprintf(stderr, "Error parsing options: %s\n", e.what());
330 return 1;
331 }
332
333 // Make paths absolute
334 if (!args.script.empty()) args.script = fs::absolute(args.script);
335 if (!args.exedir.empty()) args.exedir = fs::absolute(args.exedir);
336 if (!args.libdir.empty()) args.libdir = fs::absolute(args.libdir);
337 for (auto& dir : args.argdirs) {
338 dir = fs::absolute(dir);
339 }
340
341 // Validate required arguments
342 if (args.mode.empty() || args.binary.empty() || args.script.empty() ||
343 args.exedir.empty() || args.libdir.empty() || args.argdirs.empty()) {
344 fprintf(stderr, "missing one or more required arguments\n");
345 return 1;
346 }
347
348 if (args.mode != "ff" && args.mode != "py" && args.mode != "pyhook") {
349 fprintf(stderr, "unknown mode '%s'\n", args.mode.c_str());
350 return 1;
351 }
352
353 fprintf(stderr, "Test %s(mode=%s): %s\n", args.script.string().c_str(),
354 args.mode.c_str(), args.desc.c_str());
355
356 int retcode = 0;
357
358 if (!resolve_args(args, extra_args)) {
359 fprintf(stderr, "Test %s skipped as a required file is missing!\n",
360 args.script.string().c_str());
361 retcode = args.skip_as_pass ? 0 : 77;
362 } else if (!setup_test_dir(args)) {
363 fprintf(stderr,
364 "Test %s errored as test directory could not be set up\n",
365 args.script.string().c_str());
366 retcode = 1;
367 } else {
368 if (args.mode == "pyhook") {
369 retcode = run_pyhook_systest(args, extra_args);
370 } else {
371 retcode = run_ff_systest(args, extra_args);
372 }
373
374 fprintf(stderr, "Test %s %s with exit code %d\n",
375 args.script.string().c_str(),
376 retcode == 0 ? "passed"
377 : retcode == 77 ? "skipped"
378 : "failed",
379 retcode);
380 }
381
382 return retcode;
383 }