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 std::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   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)) {
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 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:
TempDirDeleter()162   TempDirDeleter() {}
~TempDirDeleter()163   ~TempDirDeleter() {
164     if (!name_.empty()) {
165       File::DeleteRecursively(name_, NULL, NULL);
166     }
167   }
168 
GetTempDir()169   std::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   std::string name_;
183 };
184 
185 TempDirDeleter temp_dir_deleter_;
186 
187 }  // namespace
188 
TestTempDir()189 std::string TestTempDir() { return temp_dir_deleter_.GetTempDir(); }
190 
191 // TODO(kenton):  Share duplicated code below.  Too busy/lazy for now.
192 
193 static std::string stdout_capture_filename_;
194 static std::string stderr_capture_filename_;
195 static int original_stdout_ = -1;
196 static int original_stderr_ = -1;
197 
CaptureTestStdout()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 
CaptureTestStderr()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 
GetCapturedTestStdout()228 std::string GetCapturedTestStdout() {
229   GOOGLE_CHECK_NE(original_stdout_, -1) << "Not capturing.";
230 
231   close(1);
232   dup2(original_stdout_, 1);
233   original_stdout_ = -1;
234 
235   std::string result;
236   File::ReadFileToStringOrDie(stdout_capture_filename_, &result);
237 
238   remove(stdout_capture_filename_.c_str());
239 
240   return result;
241 }
242 
GetCapturedTestStderr()243 std::string GetCapturedTestStderr() {
244   GOOGLE_CHECK_NE(original_stderr_, -1) << "Not capturing.";
245 
246   close(2);
247   dup2(original_stderr_, 2);
248   original_stderr_ = -1;
249 
250   std::string result;
251   File::ReadFileToStringOrDie(stderr_capture_filename_, &result);
252 
253   remove(stderr_capture_filename_.c_str());
254 
255   return result;
256 }
257 
258 ScopedMemoryLog* ScopedMemoryLog::active_log_ = NULL;
259 
ScopedMemoryLog()260 ScopedMemoryLog::ScopedMemoryLog() {
261   GOOGLE_CHECK(active_log_ == NULL);
262   active_log_ = this;
263   old_handler_ = SetLogHandler(&HandleLog);
264 }
265 
~ScopedMemoryLog()266 ScopedMemoryLog::~ScopedMemoryLog() {
267   SetLogHandler(old_handler_);
268   active_log_ = NULL;
269 }
270 
GetMessages(LogLevel level)271 const std::vector<std::string>& ScopedMemoryLog::GetMessages(LogLevel level) {
272   GOOGLE_CHECK(level == ERROR ||
273                level == WARNING);
274   return messages_[level];
275 }
276 
HandleLog(LogLevel level,const char * filename,int line,const std::string & message)277 void ScopedMemoryLog::HandleLog(LogLevel level, const char* filename, int line,
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 {
~ForceShutdowngoogle::protobuf::__anona42a84ac0211::ForceShutdown292   ~ForceShutdown() {
293     ShutdownProtobufLibrary();
294     // Test to shutdown the library twice, which should succeed.
295     ShutdownProtobufLibrary();
296   }
297 } force_shutdown;
298 
299 }  // namespace
300 
301 }  // namespace protobuf
302 }  // namespace google
303