farm-ng-core
test_common.h
Go to the documentation of this file.
1 // Copyright 2022, farm-ng inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <gtest/gtest.h>
18 
19 #include <regex>
20 
21 namespace farm_ng::testing {
22 
24  public:
26  orig_std_err_buffer_ = std::cerr.rdbuf();
27  std::cerr.rdbuf(buffer_.rdbuf());
28  }
29  ~CaptureStdErr() { std::cerr.rdbuf(orig_std_err_buffer_); }
30 
31  std::string buffer() const { return buffer_.str(); }
32 
33  private:
34  std::stringstream buffer_;
35  std::streambuf* orig_std_err_buffer_;
36 };
37 
38 // These are macros so we see the line number in the test where the error
39 // occurs.
40 #define EXPECT_CONTAINS(str, regex) \
41  EXPECT_TRUE(std::regex_search((str), (regex))) \
42  << FARM_FORMAT("str = `{}`", str)
43 
44 #define EXPECT_NOT_CONTAINS(str, regex) \
45  EXPECT_FALSE(std::regex_search((str), (regex))) \
46  << FARM_FORMAT("str = `{}`", str)
47 } // namespace farm_ng::testing
farm_ng::testing::CaptureStdErr
Definition: test_common.h:23
farm_ng::testing::CaptureStdErr::buffer
std::string buffer() const
Definition: test_common.h:31
farm_ng::testing
Definition: test_common.h:21
farm_ng::testing::CaptureStdErr::CaptureStdErr
CaptureStdErr()
Definition: test_common.h:25
farm_ng::testing::CaptureStdErr::~CaptureStdErr
~CaptureStdErr()
Definition: test_common.h:29