Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame] | 1 | /* 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 Lin | 5158f55 | 2021-10-27 00:55:52 +0000 | [diff] [blame] | 12 | #include <stdio.h> |
| 13 | |
| 14 | #include <memory> |
Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame] | 15 | #include <string> |
| 16 | |
Zi Lin | 5158f55 | 2021-10-27 00:55:52 +0000 | [diff] [blame] | 17 | #include "config_parser.h" |
| 18 | |
| 19 | namespace mj { |
| 20 | |
| 21 | namespace internal { |
| 22 | |
| 23 | // Functor for |ScopedFILE| (below). |
| 24 | struct ScopedFILECloser { |
| 25 | inline void operator()(FILE *x) const { |
| 26 | if (x) { |
| 27 | fclose(x); |
| 28 | } |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | // Functor for |ScopedConfigEntry| (below). |
| 33 | struct 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 | |
| 45 | using ScopedFILE = std::unique_ptr<FILE, mj::internal::ScopedFILECloser>; |
| 46 | using ScopedConfigEntry = |
| 47 | std::unique_ptr<config_entry, mj::internal::ScopedConfigEntryDeleter>; |
| 48 | |
Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame] | 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 | |
Christian Blichmann | 2b9f5be | 2022-01-10 15:56:25 +0100 | [diff] [blame] | 60 | FILE *write_to_pipe(const std::string& content); |
Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame] | 61 | |
Christian Blichmann | a83c4a7 | 2022-01-10 15:56:25 +0100 | [diff] [blame] | 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 | |
Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame] | 69 | #endif /* _TEST_UTIL_H_ */ |