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 #include <unistd.h> 14 15 #include <memory> 16 #include <string> 17 18 #include "config_parser.h" 19 20 namespace mj { 21 22 namespace internal { 23 24 // Functor for |ScopedFILE| (below). 25 struct ScopedFILECloser { operatorScopedFILECloser26 inline void operator()(FILE *x) const { 27 if (x) { 28 fclose(x); 29 } 30 } 31 }; 32 33 // Functor for |ScopedConfigEntry| (below). 34 struct ScopedConfigEntryDeleter { operatorScopedConfigEntryDeleter35 inline void operator()(config_entry *entry) const { 36 if (entry) { 37 free(entry); 38 } 39 } 40 }; 41 42 // Functor for |ScopedStr| (below). 43 struct ScopedStrDeleter { operatorScopedStrDeleter44 inline void operator()(char *str) const { 45 if (str) { 46 free(str); 47 } 48 } 49 }; 50 51 } // namespace internal 52 53 } // namespace mj 54 55 using ScopedFILE = std::unique_ptr<FILE, mj::internal::ScopedFILECloser>; 56 using ScopedConfigEntry = 57 std::unique_ptr<config_entry, mj::internal::ScopedConfigEntryDeleter>; 58 using ScopedStr = std::unique_ptr<char, mj::internal::ScopedStrDeleter>; 59 60 class ScopedFD { 61 public: ScopedFD(int fd)62 explicit ScopedFD(int fd) : fd_(fd) {} ~ScopedFD()63 ~ScopedFD() { 64 if (fd_ != -1) 65 close(fd_); 66 } 67 68 ScopedFD(const ScopedFD&) = delete; 69 ScopedFD& operator=(const ScopedFD&) = delete; 70 get()71 int get() const { return fd_; } 72 73 private: 74 int fd_ = -1; 75 }; 76 77 /* 78 * write_to_pipe: write a string as the file content into a pipe based 79 * file handle. This is particularly useful when testing with temporary data 80 * files, without dealing with complexities such as relative file path, file 81 * permission and etc. However, a pipe has limited capacity so write_to_pipe 82 * will hang when a big enough string is written. This is for use in testing 83 * only. 84 * 85 * Returns a FILE* that contains @content. 86 */ 87 88 FILE *write_to_pipe(const std::string& content); 89 90 /* 91 * source_path: return the path to a test fixture located in the current 92 * source tree. This uses the `SRC` environment variable as the root of the 93 * tree, falling back to the current directory. 94 */ 95 std::string source_path(const std::string& file); 96 97 #endif /* _TEST_UTIL_H_ */ 98