• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
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 
TestSourceDir()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)) {
95       GOOGLE_LOG(FATAL)
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 
GetTemporaryDirectoryName()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:
TempDirDeleter()162   TempDirDeleter() {}
~TempDirDeleter()163   ~TempDirDeleter() {
164     if (!name_.empty()) {
165       File::DeleteRecursively(name_, NULL, NULL);
166     }
167   }
168 
GetTempDir()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 
TestTempDir()189 string TestTempDir() {
190   return temp_dir_deleter_.GetTempDir();
191 }
192 
193 // TODO(kenton):  Share duplicated code below.  Too busy/lazy for now.
194 
195 static string stdout_capture_filename_;
196 static string stderr_capture_filename_;
197 static int original_stdout_ = -1;
198 static int original_stderr_ = -1;
199 
CaptureTestStdout()200 void CaptureTestStdout() {
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 
CaptureTestStderr()215 void CaptureTestStderr() {
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 
GetCapturedTestStdout()230 string GetCapturedTestStdout() {
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;
238   File::ReadFileToStringOrDie(stdout_capture_filename_, &result);
239 
240   remove(stdout_capture_filename_.c_str());
241 
242   return result;
243 }
244 
GetCapturedTestStderr()245 string GetCapturedTestStderr() {
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;
253   File::ReadFileToStringOrDie(stderr_capture_filename_, &result);
254 
255   remove(stderr_capture_filename_.c_str());
256 
257   return result;
258 }
259 
260 ScopedMemoryLog* ScopedMemoryLog::active_log_ = NULL;
261 
ScopedMemoryLog()262 ScopedMemoryLog::ScopedMemoryLog() {
263   GOOGLE_CHECK(active_log_ == NULL);
264   active_log_ = this;
265   old_handler_ = SetLogHandler(&HandleLog);
266 }
267 
~ScopedMemoryLog()268 ScopedMemoryLog::~ScopedMemoryLog() {
269   SetLogHandler(old_handler_);
270   active_log_ = NULL;
271 }
272 
GetMessages(LogLevel level)273 const std::vector<string>& ScopedMemoryLog::GetMessages(LogLevel level) {
274   GOOGLE_CHECK(level == ERROR ||
275                level == WARNING);
276   return messages_[level];
277 }
278 
HandleLog(LogLevel level,const char * filename,int line,const string & message)279 void ScopedMemoryLog::HandleLog(LogLevel level, const char* filename,
280                                 int line, const string& message) {
281   GOOGLE_CHECK(active_log_ != NULL);
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 {
~ForceShutdowngoogle::protobuf::__anon653e70240211::ForceShutdown294   ~ForceShutdown() {
295     ShutdownProtobufLibrary();
296     // Test to shutdown the library twice, which should succeed.
297     ShutdownProtobufLibrary();
298   }
299 } force_shutdown;
300 
301 }  // namespace
302 
303 }  // namespace protobuf
304 }  // namespace google
305