blob: e91508670475b52bfa2cd0d356afc0b5ed146758 [file] [log] [blame]
Zi Lin171ee1e2021-10-13 03:12:18 +00001/* test_util.h
2 * Copyright 2021 The Chromium OS Authors. All rights reserved.
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
Zi Lin5158f552021-10-27 00:55:52 +000012#include <stdio.h>
13
14#include <memory>
Zi Lin171ee1e2021-10-13 03:12:18 +000015#include <string>
16
Zi Lin5158f552021-10-27 00:55:52 +000017#include "config_parser.h"
18
19namespace mj {
20
21namespace internal {
22
23// Functor for |ScopedFILE| (below).
24struct ScopedFILECloser {
25 inline void operator()(FILE *x) const {
26 if (x) {
27 fclose(x);
28 }
29 }
30};
31
32// Functor for |ScopedConfigEntry| (below).
33struct ScopedConfigEntryDeleter {
34 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
45using ScopedFILE = std::unique_ptr<FILE, mj::internal::ScopedFILECloser>;
46using ScopedConfigEntry =
47 std::unique_ptr<config_entry, mj::internal::ScopedConfigEntryDeleter>;
48
Zi Lin171ee1e2021-10-13 03:12:18 +000049/*
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
Christian Blichmann2b9f5be2022-01-10 15:56:25 +010060FILE *write_to_pipe(const std::string& content);
Zi Lin171ee1e2021-10-13 03:12:18 +000061
Christian Blichmanna83c4a72022-01-10 15:56:25 +010062/*
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 */
67std::string source_path(const std::string& file);
68
Zi Lin171ee1e2021-10-13 03:12:18 +000069#endif /* _TEST_UTIL_H_ */