xref: /freebsd/contrib/kyua/engine/googletest.cpp (revision 8a7df6c58d549bd2eaa5cad30b2ef93c3eca3c18)
1 // Copyright 2024 The Kyua Authors.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 //   notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 //   notice, this list of conditions and the following disclaimer in the
12 //   documentation and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors
14 //   may be used to endorse or promote products derived from this software
15 //   without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 #include "engine/googletest.hpp"
30 
31 extern "C" {
32 #include <unistd.h>
33 }
34 
35 #include <cerrno>
36 #include <cstdlib>
37 #include <fstream>
38 
39 #include "engine/googletest_list.hpp"
40 #include "engine/googletest_result.hpp"
41 #include "engine/exceptions.hpp"
42 #include "model/test_case.hpp"
43 #include "model/test_program.hpp"
44 #include "model/test_result.hpp"
45 #include "utils/defs.hpp"
46 #include "utils/env.hpp"
47 #include "utils/format/macros.hpp"
48 #include "utils/fs/path.hpp"
49 #include "utils/logging/macros.hpp"
50 #include "utils/optional.ipp"
51 #include "utils/process/exceptions.hpp"
52 #include "utils/process/operations.hpp"
53 #include "utils/process/status.hpp"
54 #include "utils/stream.hpp"
55 
56 namespace config = utils::config;
57 namespace fs = utils::fs;
58 namespace process = utils::process;
59 
60 using utils::optional;
61 
62 
63 namespace {
64 
65 
66 /// Basename of the file containing the result written by the googletest
67 /// testcase.
68 ///
69 /// TODO: Use more structured output format someday, like the googletest's JSON
70 /// or XML format to avoid dealing with upstream formatting changes, as there's
71 /// no guarantee that the output format (which is more or less custom/freeform)
72 /// won't change in the future, making compatibility with all versions
73 /// potentially difficult to scrape for.
74 ///
75 /// Using either format will require pulling in a third party library and
76 /// understanding the schema of the format. As it stands in 1.9.0,
77 /// googletest doesn't document this expectation very well and instead seems
78 /// to rely on third-party solutions for doing structured output via the
79 /// listener interfaces.
80 
81 
82 /// Magic numbers returned by exec_list when exec(2) fails.
83 enum list_exit_code {
84     exit_eacces = 90,
85     exit_enoent,
86     exit_enoexec,
87 };
88 
89 
90 }  // anonymous namespace
91 
92 
93 /// Executes a test program's list operation.
94 ///
95 /// This method is intended to be called within a subprocess and is expected
96 /// to terminate execution either by exec(2)ing the test program or by
97 /// exiting with a failure.
98 ///
99 /// \param test_program The test program to execute.
100 void
101 engine::googletest_interface::exec_list(
102     const model::test_program& test_program,
103     const config::properties_map& /*vars*/) const
104 {
105     const process::args_vector args{
106         "--gtest_color=no",
107         "--gtest_list_tests",
108     };
109 
110     try {
111         process::exec_unsafe(test_program.absolute_path(), args);
112     } catch (const process::system_error& e) {
113         if (e.original_errno() == EACCES)
114             ::_exit(exit_eacces);
115         else if (e.original_errno() == ENOENT)
116             ::_exit(exit_enoent);
117         else if (e.original_errno() == ENOEXEC)
118             ::_exit(exit_enoexec);
119         throw;
120     }
121 }
122 
123 
124 /// Computes the test cases list of a test program.
125 ///
126 /// \param status The termination status of the subprocess used to execute
127 ///     the exec_test() method or none if the test timed out.
128 /// \param stdout_path Path to the file containing the stdout of the test.
129 ///
130 /// \return A list of test cases.
131 ///
132 /// \throw error If there is a problem parsing the test case list.
133 model::test_cases_map
134 engine::googletest_interface::parse_list(
135     const optional< process::status >& status,
136     const fs::path& stdout_path,
137     const fs::path& /* stderr_path */) const
138 {
139     if (!status)
140         throw engine::error("Test case list timed out");
141     if (status.get().exited()) {
142         const int exitstatus = status.get().exitstatus();
143         if (exitstatus == EXIT_SUCCESS) {
144             // Nothing to do; fall through.
145         } else if (exitstatus == exit_eacces) {
146             throw engine::error("Permission denied to run test program");
147         } else if (exitstatus == exit_enoent) {
148             throw engine::error("Cannot find test program");
149         } else if (exitstatus == exit_enoexec) {
150             throw engine::error("Invalid test program format");
151         } else {
152             throw engine::error("Test program did not exit cleanly; exited "
153                                 "with status: " + std::to_string(exitstatus));
154         }
155     } else {
156         throw engine::error("Test program received signal");
157     }
158 
159     std::ifstream input(stdout_path.c_str());
160     if (!input)
161         throw engine::load_error(stdout_path, "Cannot open file for read");
162     const model::test_cases_map test_cases = parse_googletest_list(input);
163 
164     return test_cases;
165 }
166 
167 
168 /// Executes a test case of the test program.
169 ///
170 /// This method is intended to be called within a subprocess and is expected
171 /// to terminate execution either by exec(2)ing the test program or by
172 /// exiting with a failure.
173 ///
174 /// \param test_program The test program to execute.
175 /// \param test_case_name Name of the test case to invoke.
176 /// \param vars User-provided variables to pass to the test program.
177 void
178 engine::googletest_interface::exec_test(
179     const model::test_program& test_program,
180     const std::string& test_case_name,
181     const config::properties_map& vars,
182     const fs::path& /* control_directory */) const
183 {
184     for (config::properties_map::const_iterator iter = vars.begin();
185          iter != vars.end(); ++iter) {
186         utils::setenv(F("TEST_ENV_%s") % (*iter).first, (*iter).second);
187     }
188 
189     process::args_vector args{
190         "--gtest_color=no",
191         F("--gtest_filter=%s") % (test_case_name)
192     };
193     process::exec(test_program.absolute_path(), args);
194     __builtin_unreachable();
195 }
196 
197 
198 /// Computes the result of a test case based on its termination status.
199 ///
200 /// \param status The termination status of the subprocess used to execute
201 ///     the exec_test() method or none if the test timed out.
202 /// \param stdout_path Path to the file containing the stdout of the
203 ///     test.
204 ///
205 /// \return A test result.
206 model::test_result
207 engine::googletest_interface::compute_result(
208     const optional< process::status >& status,
209     const fs::path& /* control_directory */,
210     const fs::path& stdout_path,
211     const fs::path& /* stderr_path */) const
212 {
213     if (!status) {
214         return model::test_result(model::test_result_broken,
215                                   "Test case body timed out");
216     }
217 
218     return calculate_googletest_result(status, stdout_path);
219 }
220