xref: /aosp_15_r20/external/minijail/test_util.h (revision 4b9c6d91573e8b3a96609339b46361b5476dd0f9)
1 /* test_util.h
2  * Copyright 2021 The ChromiumOS Authors
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  *
6  * Utility functions in testing.
7  */
8 
9 #ifndef _TEST_UTIL_H_
10 #define _TEST_UTIL_H_
11 
12 #include <stdio.h>
13 
14 #include <memory>
15 #include <string>
16 
17 #include "config_parser.h"
18 
19 namespace mj {
20 
21 namespace internal {
22 
23 // Functor for |ScopedFILE| (below).
24 struct ScopedFILECloser {
operatorScopedFILECloser25   inline void operator()(FILE *x) const {
26     if (x) {
27       fclose(x);
28     }
29   }
30 };
31 
32 // Functor for |ScopedConfigEntry| (below).
33 struct ScopedConfigEntryDeleter {
operatorScopedConfigEntryDeleter34   inline void operator()(config_entry *entry) const {
35     if (entry) {
36       free(entry);
37     }
38   }
39 };
40 
41 } // namespace internal
42 
43 } // namespace mj
44 
45 using ScopedFILE = std::unique_ptr<FILE, mj::internal::ScopedFILECloser>;
46 using ScopedConfigEntry =
47     std::unique_ptr<config_entry, mj::internal::ScopedConfigEntryDeleter>;
48 
49 /*
50  * write_to_pipe: write a string as the file content into a pipe based
51  * file handle. This is particularly useful when testing with temporary data
52  * files, without dealing with complexities such as relative file path, file
53  * permission and etc. However, a pipe has limited capacity so write_to_pipe
54  * will hang when a big enough string is written. This is for use in testing
55  * only.
56  *
57  * Returns a FILE* that contains @content.
58  */
59 
60 FILE *write_to_pipe(const std::string& content);
61 
62 /*
63  * source_path: return the path to a test fixture located in the current
64  * source tree. This uses the `SRC` environment variable as the root of the
65  * tree, falling back to the current directory.
66  */
67 std::string source_path(const std::string& file);
68 
69 #endif /* _TEST_UTIL_H_ */
70