folly: replace old-style header guards with "pragma once"
[folly.git] / folly / experimental / TestUtil.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <map>
20 #include <string>
21 #include <folly/Range.h>
22 #include <folly/experimental/io/FsUtil.h>
23
24 namespace folly {
25 namespace test {
26
27 /**
28  * Temporary file.
29  *
30  * By default, the file is created in a system-specific location (the value
31  * of the TMPDIR environment variable, or /tmp), but you can override that
32  * with a different (non-empty) directory passed to the constructor.
33  *
34  * By default, the file is closed and deleted when the TemporaryFile object
35  * is destroyed, but both these behaviors can be overridden with arguments
36  * to the constructor.
37  */
38 class TemporaryFile {
39  public:
40   enum class Scope {
41     PERMANENT,
42     UNLINK_IMMEDIATELY,
43     UNLINK_ON_DESTRUCTION
44   };
45   explicit TemporaryFile(StringPiece namePrefix = StringPiece(),
46                          fs::path dir = fs::path(),
47                          Scope scope = Scope::UNLINK_ON_DESTRUCTION,
48                          bool closeOnDestruction = true);
49   ~TemporaryFile();
50
51   // Movable, but not copiable
52   TemporaryFile(TemporaryFile&&) = default;
53   TemporaryFile& operator=(TemporaryFile&&) = default;
54
55   int fd() const { return fd_; }
56   const fs::path& path() const;
57
58  private:
59   Scope scope_;
60   bool closeOnDestruction_;
61   int fd_;
62   fs::path path_;
63 };
64
65 /**
66  * Temporary directory.
67  *
68  * By default, the temporary directory is created in a system-specific
69  * location (the value of the TMPDIR environment variable, or /tmp), but you
70  * can override that with a non-empty directory passed to the constructor.
71  *
72  * By default, the directory is recursively deleted when the TemporaryDirectory
73  * object is destroyed, but that can be overridden with an argument
74  * to the constructor.
75  */
76
77 class TemporaryDirectory {
78  public:
79   enum class Scope {
80     PERMANENT,
81     DELETE_ON_DESTRUCTION
82   };
83   explicit TemporaryDirectory(StringPiece namePrefix = StringPiece(),
84                               fs::path dir = fs::path(),
85                               Scope scope = Scope::DELETE_ON_DESTRUCTION);
86   ~TemporaryDirectory();
87
88   // Movable, but not copiable
89   TemporaryDirectory(TemporaryDirectory&&) = default;
90   TemporaryDirectory& operator=(TemporaryDirectory&&) = default;
91
92   const fs::path& path() const { return path_; }
93
94  private:
95   Scope scope_;
96   fs::path path_;
97 };
98
99 /**
100  * Changes into a temporary directory, and deletes it with all its contents
101  * upon destruction, also changing back to the original working directory.
102  */
103 class ChangeToTempDir {
104 public:
105   ChangeToTempDir();
106   ~ChangeToTempDir();
107
108   // Movable, but not copiable
109   ChangeToTempDir(ChangeToTempDir&&) = default;
110   ChangeToTempDir& operator=(ChangeToTempDir&&) = default;
111
112   const fs::path& path() const { return dir_.path(); }
113
114 private:
115   fs::path initialPath_;
116   TemporaryDirectory dir_;
117 };
118
119 /**
120  * Easy PCRE regex matching. Note that pattern must match the ENTIRE target,
121  * so use .* at the start and end of the pattern, as appropriate.  See
122  * http://regex101.com/ for a PCRE simulator.
123  */
124 #define EXPECT_PCRE_MATCH(pattern_stringpiece, target_stringpiece) \
125   EXPECT_PRED2( \
126     ::folly::test::detail::hasPCREPatternMatch, \
127     pattern_stringpiece, \
128     target_stringpiece \
129   )
130 #define EXPECT_NO_PCRE_MATCH(pattern_stringpiece, target_stringpiece) \
131   EXPECT_PRED2( \
132     ::folly::test::detail::hasNoPCREPatternMatch, \
133     pattern_stringpiece, \
134     target_stringpiece \
135   )
136
137 namespace detail {
138   bool hasPCREPatternMatch(StringPiece pattern, StringPiece target);
139   bool hasNoPCREPatternMatch(StringPiece pattern, StringPiece target);
140 }  // namespace detail
141
142 /**
143  * Use these patterns together with CaptureFD and EXPECT_PCRE_MATCH() to
144  * test for the presence (or absence) of log lines at a particular level:
145  *
146  *   CaptureFD stderr(2);
147  *   LOG(INFO) << "All is well";
148  *   EXPECT_NO_PCRE_MATCH(glogErrOrWarnPattern(), stderr.readIncremental());
149  *   LOG(ERROR) << "Uh-oh";
150  *   EXPECT_PCRE_MATCH(glogErrorPattern(), stderr.readIncremental());
151  */
152 inline std::string glogErrorPattern() { return ".*(^|\n)E[0-9].*"; }
153 inline std::string glogWarningPattern() { return ".*(^|\n)W[0-9].*"; }
154 // Error OR warning
155 inline std::string glogErrOrWarnPattern() { return ".*(^|\n)[EW][0-9].*"; }
156
157 /**
158  * Temporarily capture a file descriptor by redirecting it into a file.
159  * You can consume its entire output thus far via read(), incrementally
160  * via readIncremental(), or via callback using chunk_cob.
161  * Great for testing logging (see also glog*Pattern()).
162  */
163 class CaptureFD {
164 private:
165   struct NoOpChunkCob { void operator()(StringPiece) {} };
166 public:
167   using ChunkCob = std::function<void(folly::StringPiece)>;
168
169   /**
170    * chunk_cob is is guaranteed to consume all the captured output. It is
171    * invoked on each readIncremental(), and also on FD release to capture
172    * as-yet unread lines.  Chunks can be empty.
173    */
174   explicit CaptureFD(int fd, ChunkCob chunk_cob = NoOpChunkCob());
175   ~CaptureFD();
176
177   /**
178    * Restore the captured FD to its original state. It can be useful to do
179    * this before the destructor so that you can read() the captured data and
180    * log about it to the formerly captured stderr or stdout.
181    */
182   void release();
183
184   /**
185    * Reads the whole file into a string, but does not remove the redirect.
186    */
187   std::string read() const;
188
189   /**
190    * Read any bytes that were appended to the file since the last
191    * readIncremental.  Great for testing line-by-line output.
192    */
193   std::string readIncremental();
194
195 private:
196   ChunkCob chunkCob_;
197   TemporaryFile file_;
198
199   int fd_;
200   int oldFDCopy_;  // equal to fd_ after restore()
201
202   off_t readOffset_;  // for incremental reading
203 };
204
205 class EnvVarSaver {
206 public:
207   EnvVarSaver();
208   ~EnvVarSaver();
209 private:
210   std::map<std::string, std::string> saved_;
211 };
212
213 }  // namespace test
214 }  // namespace folly