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 
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.
58 using google::protobuf::io::win32::close;
59 using google::protobuf::io::win32::dup2;
60 using google::protobuf::io::win32::dup;
61 using google::protobuf::io::win32::mkdir;
62 using google::protobuf::io::win32::open;
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 
73 string TestSourceDir() {
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  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 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 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  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()) {
166  }
167  }
168 
169  string GetTempDir() {
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:
182  string name_;
183 };
184 
185 TempDirDeleter temp_dir_deleter_;
186 
187 } // namespace
188 
189 string TestTempDir() {
190  return temp_dir_deleter_.GetTempDir();
191 }
192 
193 // TODO(kenton): Share duplicated code below. Too busy/lazy for now.
194 
197 static int original_stdout_ = -1;
198 static int original_stderr_ = -1;
199 
201  GOOGLE_CHECK_EQ(original_stdout_, -1) << "Already capturing.";
202 
203  stdout_capture_filename_ = TestTempDir() + "/captured_stdout";
204 
205  int fd = open(stdout_capture_filename_.c_str(),
206  O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777);
207  GOOGLE_CHECK(fd >= 0) << "open: " << strerror(errno);
208 
209  original_stdout_ = dup(1);
210  close(1);
211  dup2(fd, 1);
212  close(fd);
213 }
214 
216  GOOGLE_CHECK_EQ(original_stderr_, -1) << "Already capturing.";
217 
218  stderr_capture_filename_ = TestTempDir() + "/captured_stderr";
219 
220  int fd = open(stderr_capture_filename_.c_str(),
221  O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777);
222  GOOGLE_CHECK(fd >= 0) << "open: " << strerror(errno);
223 
224  original_stderr_ = dup(2);
225  close(2);
226  dup2(fd, 2);
227  close(fd);
228 }
229 
231  GOOGLE_CHECK_NE(original_stdout_, -1) << "Not capturing.";
232 
233  close(1);
234  dup2(original_stdout_, 1);
235  original_stdout_ = -1;
236 
237  string result;
239 
240  remove(stdout_capture_filename_.c_str());
241 
242  return result;
243 }
244 
246  GOOGLE_CHECK_NE(original_stderr_, -1) << "Not capturing.";
247 
248  close(2);
249  dup2(original_stderr_, 2);
250  original_stderr_ = -1;
251 
252  string result;
254 
255  remove(stderr_capture_filename_.c_str());
256 
257  return result;
258 }
259 
260 ScopedMemoryLog* ScopedMemoryLog::active_log_ = NULL;
261 
264  active_log_ = this;
266 }
267 
270  active_log_ = NULL;
271 }
272 
273 const std::vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) {
274  GOOGLE_CHECK(level == ERROR ||
275  level == WARNING);
276  return messages_[level];
277 }
278 
279 void ScopedMemoryLog::HandleLog(LogLevel level, const char* filename,
280  int line, const string& message) {
282  if (level == ERROR || level == WARNING) {
283  active_log_->messages_[level].push_back(message);
284  }
285 }
286 
287 namespace {
288 
289 // Force shutdown at process exit so that we can test for memory leaks. To
290 // actually check for leaks, I suggest using the heap checker included with
291 // google-perftools. Set it to "draconian" mode to ensure that every last
292 // call to malloc() has a corresponding free().
293 struct ForceShutdown {
294  ~ForceShutdown() {
296  // Test to shutdown the library twice, which should succeed.
298  }
299 } force_shutdown;
300 
301 } // namespace
302 
303 } // namespace protobuf
304 } // namespace google
google::protobuf::GetCapturedTestStderr
string GetCapturedTestStderr()
Definition: googletest.cc:245
GOOGLE_CHECK_EQ
#define GOOGLE_CHECK_EQ(A, B)
Definition: logging.h:156
google::protobuf::ScopedMemoryLog::~ScopedMemoryLog
virtual ~ScopedMemoryLog()
Definition: googletest.cc:268
google::protobuf::GetCapturedTestStdout
string GetCapturedTestStdout()
Definition: googletest.cc:230
NULL
NULL
Definition: test_security_zap.cpp:405
google::protobuf::ScopedMemoryLog::GetMessages
const std::vector< string > & GetMessages(LogLevel error)
Definition: googletest.cc:273
FATAL
const int FATAL
Definition: log_severity.h:60
google::protobuf::TestSourceDir
string TestSourceDir()
Definition: googletest.cc:73
google::protobuf::original_stdout_
static int original_stdout_
Definition: googletest.cc:197
google::protobuf::ScopedMemoryLog::ScopedMemoryLog
ScopedMemoryLog()
Definition: googletest.cc:262
google::protobuf::LogLevel
LogLevel
Definition: logging.h:45
string
GLsizei const GLchar *const * string
Definition: glcorearb.h:3083
errno
int errno
google::protobuf::File::WriteStringToFileOrDie
static void WriteStringToFileOrDie(const string &contents, const string &name)
Definition: file.cc:112
google::protobuf::CaptureTestStdout
void CaptureTestStdout()
Definition: googletest.cc:200
b
GLboolean GLboolean GLboolean b
Definition: glcorearb.h:3228
google::protobuf::ScopedMemoryLog::old_handler_
LogHandler * old_handler_
Definition: protobuf/src/google/protobuf/testing/googletest.h:91
google::protobuf::CaptureTestStderr
void CaptureTestStderr()
Definition: googletest.cc:215
strutil.h
O_BINARY
#define O_BINARY
Definition: googletest.cc:69
google::protobuf::ScopedMemoryLog::HandleLog
static void HandleLog(LogLevel level, const char *filename, int line, const string &message)
Definition: googletest.cc:279
prefix
static const char prefix[]
Definition: test_pair_ipc.cpp:26
google::protobuf::File::ReadFileToStringOrDie
static void ReadFileToStringOrDie(const string &name, string *output)
Definition: file.cc:89
GOOGLE_LOG
#define GOOGLE_LOG(LEVEL)
Definition: logging.h:146
google::protobuf::WARNING
static const LogLevel WARNING
Definition: protobuf/src/google/protobuf/testing/googletest.h:71
name_
string name_
Definition: googletest.cc:182
google::protobuf::HasPrefixString
bool HasPrefixString(const string &str, const string &prefix)
Definition: strutil.h:115
google::protobuf::ERROR
static const LogLevel ERROR
Definition: protobuf/src/google/protobuf/testing/googletest.h:70
GOOGLE_CHECK_NE
#define GOOGLE_CHECK_NE(A, B)
Definition: logging.h:157
GOOGLE_CHECK
#define GOOGLE_CHECK(EXPRESSION)
Definition: logging.h:153
google::protobuf::StringReplace
void StringReplace(const string &s, const string &oldsub, const string &newsub, bool replace_all, string *res)
Definition: strutil.cc:148
google::protobuf::stderr_capture_filename_
static string stderr_capture_filename_
Definition: googletest.cc:196
google::protobuf::ScopedMemoryLog::messages_
std::map< LogLevel, std::vector< string > > messages_
Definition: protobuf/src/google/protobuf/testing/googletest.h:90
google::protobuf::stdout_capture_filename_
static string stdout_capture_filename_
Definition: googletest.cc:195
google::protobuf::SetLogHandler
LogHandler * SetLogHandler(LogHandler *new_func)
Definition: common.cc:271
googletest.h
GetTempDir
static string GetTempDir()
Definition: glog/src/googletest.h:78
strerror
char * strerror(int errno)
io_win32.h
file.h
google::protobuf::ScopedMemoryLog::active_log_
static ScopedMemoryLog * active_log_
Definition: protobuf/src/google/protobuf/testing/googletest.h:96
google::protobuf::original_stderr_
static int original_stderr_
Definition: googletest.cc:198
google::protobuf::TestTempDir
string TestTempDir()
Definition: googletest.cc:189
google::protobuf::ShutdownProtobufLibrary
void ShutdownProtobufLibrary()
Definition: common.cc:356
level
GLint level
Definition: glcorearb.h:2773
google
Definition: data_proto2_to_proto3_util.h:11
message
GLenum GLuint GLenum GLsizei const GLchar * message
Definition: glcorearb.h:2695
google::protobuf::File::DeleteRecursively
static void DeleteRecursively(const string &name, void *dummy1, void *dummy2)
Definition: file.cc:146
google::protobuf::File::Exists
static bool Exists(const string &name)
Definition: file.cc:69


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:52