protobuf/src/google/protobuf/testing/googletest.cc
Go to the documentation of this file.
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: kenton@google.com (Kenton Varda)
32 // emulates google3/testing/base/public/googletest.cc
33 
34 #include <google/protobuf/testing/googletest.h>
35 #include <google/protobuf/testing/file.h>
36 #include <google/protobuf/io/io_win32.h>
37 #include <google/protobuf/stubs/strutil.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <errno.h>
41 #include <stdlib.h>
42 #ifdef _MSC_VER
43 // #include <direct.h>
44 #else
45 #include <unistd.h>
46 #endif
47 #include <stdio.h>
48 #include <fcntl.h>
49 #include <iostream>
50 #include <fstream>
51 
52 namespace google {
53 namespace protobuf {
54 
55 #ifdef _WIN32
56 // DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
57 // them like we do below.
59 using google::protobuf::io::win32::dup2;
60 using google::protobuf::io::win32::dup;
61 using google::protobuf::io::win32::mkdir;
63 #endif
64 
65 #ifndef O_BINARY
66 #ifdef _O_BINARY
67 #define O_BINARY _O_BINARY
68 #else
69 #define O_BINARY 0 // If this isn't defined, the platform doesn't need it.
70 #endif
71 #endif
72 
74 #ifndef GOOGLE_THIRD_PARTY_PROTOBUF
75 #ifdef GOOGLE_PROTOBUF_TEST_SOURCE_PATH
76  return GOOGLE_PROTOBUF_TEST_SOURCE_PATH;
77 #else
78 #ifndef _MSC_VER
79  // automake sets the "srcdir" environment variable.
80  char* result = getenv("srcdir");
81  if (result != NULL) {
82  return result;
83  }
84 #endif // _MSC_VER
85 
86  // Look for the "src" directory.
87  std::string prefix = ".";
88 
89  // Keep looking further up the directory tree until we find
90  // src/.../descriptor.cc. It is important to look for a particular file,
91  // keeping in mind that with Bazel builds the directory structure under
92  // bazel-bin/ looks similar to the main directory tree in the Git repo.
93  while (!File::Exists(prefix + "/src/google/protobuf/descriptor.cc")) {
94  if (!File::Exists(prefix)) {
96  << "Could not find protobuf source code. Please run tests from "
97  "somewhere within the protobuf source package.";
98  }
99  prefix += "/..";
100  }
101  return prefix + "/src";
102 #endif // GOOGLE_PROTOBUF_TEST_SOURCE_PATH
103 #else
104  return "third_party/protobuf/src";
105 #endif // GOOGLE_THIRD_PARTY_PROTOBUF
106 }
107 
108 namespace {
109 
110 std::string GetTemporaryDirectoryName() {
111  // Tests run under Bazel "should not" use /tmp. Bazel sets this environment
112  // variable for tests to use instead.
113  char *from_environment = getenv("TEST_TMPDIR");
114  if (from_environment != NULL && from_environment[0] != '\0') {
115  return std::string(from_environment) + "/protobuf_tmpdir";
116  }
117 
118  // tmpnam() is generally not considered safe but we're only using it for
119  // testing. We cannot use tmpfile() or mkstemp() since we're creating a
120  // directory.
121  char b[L_tmpnam + 1]; // HPUX multithread return 0 if s is 0
122 #pragma GCC diagnostic push
123 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
124  std::string result = tmpnam(b);
125 #pragma GCC diagnostic pop
126 #ifdef _WIN32
127  // Avoid a trailing dot by changing it to an underscore. On Win32 the names of
128  // files and directories can, but should not, end with dot.
129  //
130  // In MS-DOS and FAT16 filesystem the filenames were 8dot3 style so it didn't
131  // make sense to have a name ending in dot without an extension, so the shell
132  // silently ignored trailing dots. To this day the Win32 API still maintains
133  // this behavior and silently ignores trailing dots in path arguments of
134  // functions such as CreateFile{A,W}. Even POSIX API function implementations
135  // seem to wrap the Win32 API functions (e.g. CreateDirectoryA) and behave
136  // this way.
137  // It's possible to avoid this behavior and create files / directories with
138  // trailing dots (using CreateFileW / CreateDirectoryW and prefixing the path
139  // with "\\?\") but these will be degenerate in the sense that you cannot
140  // chdir into such directories (or navigate into them with Windows Explorer)
141  // nor can you open such files with some programs (e.g. Notepad).
142  if (result[result.size() - 1] == '.') {
143  result[result.size() - 1] = '_';
144  }
145  // On Win32, tmpnam() returns a file prefixed with '\', but which is supposed
146  // to be used in the current working directory. WTF?
147  if (HasPrefixString(result, "\\")) {
148  result.erase(0, 1);
149  }
150  // The Win32 API accepts forward slashes as a path delimiter as long as the
151  // path doesn't use the "\\?\" prefix.
152  // Let's avoid confusion and use only forward slashes.
153  result = StringReplace(result, "\\", "/", true);
154 #endif // _WIN32
155  return result;
156 }
157 
158 // Creates a temporary directory on demand and deletes it when the process
159 // quits.
160 class TempDirDeleter {
161  public:
162  TempDirDeleter() {}
163  ~TempDirDeleter() {
164  if (!name_.empty()) {
165  File::DeleteRecursively(name_, NULL, NULL);
166  }
167  }
168 
170  if (name_.empty()) {
171  name_ = GetTemporaryDirectoryName();
172  GOOGLE_CHECK(mkdir(name_.c_str(), 0777) == 0) << strerror(errno);
173 
174  // Stick a file in the directory that tells people what this is, in case
175  // we abort and don't get a chance to delete it.
176  File::WriteStringToFileOrDie("", name_ + "/TEMP_DIR_FOR_PROTOBUF_TESTS");
177  }
178  return name_;
179  }
180 
181  private:
183 };
184 
185 TempDirDeleter temp_dir_deleter_;
186 
187 } // namespace
188 
189 std::string TestTempDir() { return temp_dir_deleter_.GetTempDir(); }
190 
191 // TODO(kenton): Share duplicated code below. Too busy/lazy for now.
192 
195 static int original_stdout_ = -1;
196 static int original_stderr_ = -1;
197 
198 void CaptureTestStdout() {
199  GOOGLE_CHECK_EQ(original_stdout_, -1) << "Already capturing.";
200 
201  stdout_capture_filename_ = TestTempDir() + "/captured_stdout";
202 
203  int fd = open(stdout_capture_filename_.c_str(),
204  O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777);
205  GOOGLE_CHECK(fd >= 0) << "open: " << strerror(errno);
206 
207  original_stdout_ = dup(1);
208  close(1);
209  dup2(fd, 1);
210  close(fd);
211 }
212 
213 void CaptureTestStderr() {
214  GOOGLE_CHECK_EQ(original_stderr_, -1) << "Already capturing.";
215 
216  stderr_capture_filename_ = TestTempDir() + "/captured_stderr";
217 
218  int fd = open(stderr_capture_filename_.c_str(),
219  O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777);
220  GOOGLE_CHECK(fd >= 0) << "open: " << strerror(errno);
221 
222  original_stderr_ = dup(2);
223  close(2);
224  dup2(fd, 2);
225  close(fd);
226 }
227 
229  GOOGLE_CHECK_NE(original_stdout_, -1) << "Not capturing.";
230 
231  close(1);
232  dup2(original_stdout_, 1);
233  original_stdout_ = -1;
234 
237 
238  remove(stdout_capture_filename_.c_str());
239 
240  return result;
241 }
242 
244  GOOGLE_CHECK_NE(original_stderr_, -1) << "Not capturing.";
245 
246  close(2);
247  dup2(original_stderr_, 2);
248  original_stderr_ = -1;
249 
252 
253  remove(stderr_capture_filename_.c_str());
254 
255  return result;
256 }
257 
258 ScopedMemoryLog* ScopedMemoryLog::active_log_ = NULL;
259 
261  GOOGLE_CHECK(active_log_ == NULL);
262  active_log_ = this;
264 }
265 
268  active_log_ = NULL;
269 }
270 
271 const std::vector<std::string>& ScopedMemoryLog::GetMessages(LogLevel level) {
272  GOOGLE_CHECK(level == ERROR ||
273  level == WARNING);
274  return messages_[level];
275 }
276 
278  const std::string& message) {
279  GOOGLE_CHECK(active_log_ != NULL);
280  if (level == ERROR || level == WARNING) {
281  active_log_->messages_[level].push_back(message);
282  }
283 }
284 
285 namespace {
286 
287 // Force shutdown at process exit so that we can test for memory leaks. To
288 // actually check for leaks, I suggest using the heap checker included with
289 // google-perftools. Set it to "draconian" mode to ensure that every last
290 // call to malloc() has a corresponding free().
291 struct ForceShutdown {
292  ~ForceShutdown() {
294  // Test to shutdown the library twice, which should succeed.
296  }
297 } force_shutdown;
298 
299 } // namespace
300 
301 } // namespace protobuf
302 } // namespace google
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
filename
const char * filename
Definition: bloaty/third_party/zlib/contrib/minizip/ioapi.h:135
google::protobuf::GetCapturedTestStdout
string GetCapturedTestStdout()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:230
google::protobuf::ScopedMemoryLog::~ScopedMemoryLog
virtual ~ScopedMemoryLog()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:268
google::protobuf::ScopedMemoryLog::active_log_
static ScopedMemoryLog * active_log_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.h:96
google::protobuf::ScopedMemoryLog::old_handler_
LogHandler * old_handler_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.h:91
google::protobuf::original_stdout_
static int original_stdout_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:197
google::protobuf::ScopedMemoryLog::ScopedMemoryLog
ScopedMemoryLog()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:262
google::protobuf::TestSourceDir
string TestSourceDir()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:73
GOOGLE_CHECK_EQ
#define GOOGLE_CHECK_EQ(A, B)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:156
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
google::protobuf::LogLevel
LogLevel
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:45
google::protobuf
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:12
google::protobuf::File::WriteStringToFileOrDie
static void WriteStringToFileOrDie(const string &contents, const string &name)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/file.cc:112
message
char * message
Definition: libuv/docs/code/tty-gravity/main.c:12
google::protobuf::CaptureTestStdout
void CaptureTestStdout()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:200
O_BINARY
#define O_BINARY
Definition: protobuf/src/google/protobuf/testing/googletest.cc:69
google::protobuf::CaptureTestStderr
void CaptureTestStderr()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:215
google::protobuf::GetCapturedTestStderr
string GetCapturedTestStderr()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:245
google::protobuf::ScopedMemoryLog::HandleLog
static void HandleLog(LogLevel level, const char *filename, int line, const string &message)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:279
google::protobuf::ScopedMemoryLog::GetMessages
const std::vector< string > & GetMessages(LogLevel error)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:273
gtest_test_utils.GetTempDir
def GetTempDir()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:144
name_
std::string name_
Definition: protobuf/src/google/protobuf/testing/googletest.cc:182
google::protobuf::File::ReadFileToStringOrDie
static void ReadFileToStringOrDie(const string &name, string *output)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/file.cc:89
close
#define close
Definition: test-fs.c:48
google::protobuf::WARNING
static const LogLevel WARNING
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.h:71
b
uint64_t b
Definition: abseil-cpp/absl/container/internal/layout_test.cc:53
google::protobuf::HasPrefixString
bool HasPrefixString(const string &str, const string &prefix)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/strutil.h:115
google::protobuf::ERROR
static const LogLevel ERROR
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.h:70
FATAL
#define FATAL(msg)
Definition: task.h:88
google::protobuf::StringReplace
void StringReplace(const string &s, const string &oldsub, const string &newsub, bool replace_all, string *res)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/strutil.cc:148
google::protobuf::stderr_capture_filename_
static string stderr_capture_filename_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:196
google::protobuf::ScopedMemoryLog::messages_
std::map< LogLevel, std::vector< string > > messages_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.h:90
google::protobuf::stdout_capture_filename_
static string stdout_capture_filename_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:195
google::protobuf::SetLogHandler
LogHandler * SetLogHandler(LogHandler *new_func)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/common.cc:271
prefix
static const char prefix[]
Definition: head_of_line_blocking.cc:28
regen-readme.line
line
Definition: regen-readme.py:30
GOOGLE_CHECK
#define GOOGLE_CHECK(EXPRESSION)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:153
open
#define open
Definition: test-fs.c:46
GOOGLE_CHECK_NE
#define GOOGLE_CHECK_NE(A, B)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:157
google::protobuf::TestTempDir
string TestTempDir()
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:189
client.level
level
Definition: examples/python/async_streaming/client.py:118
google::protobuf::original_stderr_
static int original_stderr_
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/googletest.cc:198
google::protobuf::ShutdownProtobufLibrary
void ShutdownProtobufLibrary()
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/common.cc:356
GOOGLE_LOG
#define GOOGLE_LOG(LEVEL)
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/logging.h:146
getenv
#define getenv(ptr)
Definition: ares_private.h:106
google
Definition: bloaty/third_party/protobuf/benchmarks/util/data_proto2_to_proto3_util.h:11
google::protobuf::File::DeleteRecursively
static void DeleteRecursively(const string &name, void *dummy1, void *dummy2)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/file.cc:146
errno.h
google::protobuf::File::Exists
static bool Exists(const string &name)
Definition: bloaty/third_party/protobuf/src/google/protobuf/testing/file.cc:69


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:43