1 // Copyright (c) 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // ---
31 //
32 // For now, this unit test does not cover all features of
33 // gflags.cc
34 
35 #include "config_for_unittests.h"
36 #include <gflags/gflags.h>
37 
38 #include <math.h>       // for isinf() and isnan()
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif     // for unlink()
45 #include <vector>
46 #include <string>
47 #include "util.h"
48 TEST_INIT
49 EXPECT_DEATH_INIT
50 
51 // I don't actually use this header file, but #include it under the
52 // old location to make sure that the include-header-forwarding
53 // works.  But don't bother on windows; the windows port is so new
54 // it never had the old location-names.
55 #ifndef _MSC_VER
56 #include <google/gflags_completions.h>
57 void (*unused_fn)() = &GOOGLE_NAMESPACE::HandleCommandLineCompletions;
58 #endif
59 
60 using std::string;
61 using std::vector;
62 using GOOGLE_NAMESPACE::int32;
63 using GOOGLE_NAMESPACE::FlagRegisterer;
64 using GOOGLE_NAMESPACE::StringFromEnv;
65 using GOOGLE_NAMESPACE::RegisterFlagValidator;
66 using GOOGLE_NAMESPACE::CommandLineFlagInfo;
67 using GOOGLE_NAMESPACE::GetAllFlags;
68 
69 DEFINE_string(test_tmpdir, "/tmp/gflags_unittest", "Dir we use for temp files");
70 #ifdef _MSC_VER  // in MSVC, we run from the vsprojects directory
71 DEFINE_string(srcdir, "..\\..",
72               "Source-dir root, needed to find gflags_unittest_flagfile");
73 #else
74 DEFINE_string(srcdir, StringFromEnv("SRCDIR", "."),
75               "Source-dir root, needed to find gflags_unittest_flagfile");
76 #endif
77 
78 DECLARE_string(tryfromenv);   // in gflags.cc
79 
80 DEFINE_bool(test_bool, false, "tests bool-ness");
81 DEFINE_int32(test_int32, -1, "");
82 DEFINE_int64(test_int64, -2, "");
83 DEFINE_uint64(test_uint64, 2, "");
84 DEFINE_double(test_double, -1.0, "");
85 DEFINE_string(test_string, "initial", "");
86 
87 //
88 // The below ugliness gets some additional code coverage in the -helpxml
89 // and -helpmatch test cases having to do with string lengths and formatting
90 //
91 DEFINE_bool(test_bool_with_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_long_name,
92             false,
93             "extremely_extremely_extremely_extremely_extremely_extremely_extremely_extremely_long_meaning");
94 
95 DEFINE_string(test_str1, "initial", "");
96 DEFINE_string(test_str2, "initial", "");
97 DEFINE_string(test_str3, "initial", "");
98 
99 // This is used to test setting tryfromenv manually
100 DEFINE_string(test_tryfromenv, "initial", "");
101 
102 // Don't try this at home!
103 static int changeable_var = 12;
104 DEFINE_int32(changeable_var, ++changeable_var, "");
105 
106 static int changeable_bool_var = 8008;
107 DEFINE_bool(changeable_bool_var, ++changeable_bool_var == 8009, "");
108 
109 static int changeable_string_var = 0;
ChangeableString()110 static string ChangeableString() {
111   char r[] = {static_cast<char>('0' + ++changeable_string_var), '\0'};
112   return r;
113 }
114 DEFINE_string(changeable_string_var, ChangeableString(), "");
115 
116 // These are never used in this unittest, but can be used by
117 // gflags_unittest.sh when it needs to specify flags
118 // that are legal for gflags_unittest but don't need to
119 // be a particular value.
120 DEFINE_bool(unused_bool, true, "unused bool-ness");
121 DEFINE_int32(unused_int32, -1001, "");
122 DEFINE_int64(unused_int64, -2001, "");
123 DEFINE_uint64(unused_uint64, 2000, "");
124 DEFINE_double(unused_double, -1000.0, "");
125 DEFINE_string(unused_string, "unused", "");
126 
127 // These flags are used by gflags_unittest.sh
128 DEFINE_bool(changed_bool1, false, "changed");
129 DEFINE_bool(changed_bool2, false, "changed");
130 DEFINE_bool(long_helpstring, false,
131             "This helpstring goes on forever and ever and ever and ever and "
132             "ever and ever and ever and ever and ever and ever and ever and "
133             "ever and ever and ever and ever and ever and ever and ever and "
134             "ever and ever and ever and ever and ever and ever and ever and "
135             "ever and ever and ever and ever and ever and ever and ever and "
136             "ever and ever and ever and ever and ever and ever and ever and "
137             "ever and ever and ever and ever and ever and ever and ever and "
138             "ever and ever and ever and ever and ever and ever and ever and "
139             "ever and ever and ever and ever and ever and ever and ever and "
140             "ever and ever and ever and ever and ever and ever and ever and "
141             "ever.  This is the end of a long helpstring");
142 
143 
AlwaysFail(const char * flag,bool value)144 static bool AlwaysFail(const char* flag, bool value) { return value == false; }
145 DEFINE_bool(always_fail, false, "will fail to validate when you set it");
146 DEFINE_validator(always_fail, AlwaysFail);
147 
148 // See the comment by GetAllFlags in gflags.h
DeadlockIfCantLockInValidators(const char * flag,bool value)149 static bool DeadlockIfCantLockInValidators(const char* flag, bool value) {
150   if (!value) {
151     return true;
152   }
153   vector<CommandLineFlagInfo> dummy;
154   GetAllFlags(&dummy);
155   return true;
156 }
157 DEFINE_bool(deadlock_if_cant_lock,
158             false,
159             "will deadlock if set to true and "
160             "if locking of registry in validators fails.");
161 DEFINE_validator(deadlock_if_cant_lock, DeadlockIfCantLockInValidators);
162 
163 #define MAKEFLAG(x) DEFINE_int32(test_flag_num##x, x, "Test flag")
164 
165 // Define 10 flags
166 #define MAKEFLAG10(x)                           \
167   MAKEFLAG(x##0);                               \
168   MAKEFLAG(x##1);                               \
169   MAKEFLAG(x##2);                               \
170   MAKEFLAG(x##3);                               \
171   MAKEFLAG(x##4);                               \
172   MAKEFLAG(x##5);                               \
173   MAKEFLAG(x##6);                               \
174   MAKEFLAG(x##7);                               \
175   MAKEFLAG(x##8);                               \
176   MAKEFLAG(x##9)
177 
178 // Define 100 flags
179 #define MAKEFLAG100(x)                          \
180   MAKEFLAG10(x##0);                             \
181   MAKEFLAG10(x##1);                             \
182   MAKEFLAG10(x##2);                             \
183   MAKEFLAG10(x##3);                             \
184   MAKEFLAG10(x##4);                             \
185   MAKEFLAG10(x##5);                             \
186   MAKEFLAG10(x##6);                             \
187   MAKEFLAG10(x##7);                             \
188   MAKEFLAG10(x##8);                             \
189   MAKEFLAG10(x##9)
190 
191 // Define a bunch of command-line flags.  Each occurrence of the MAKEFLAG100
192 // macro defines 100 integer flags.  This lets us test the effect of having
193 // many flags on startup time.
194 MAKEFLAG100(1);
195 MAKEFLAG100(2);
196 MAKEFLAG100(3);
197 MAKEFLAG100(4);
198 MAKEFLAG100(5);
199 MAKEFLAG100(6);
200 MAKEFLAG100(7);
201 MAKEFLAG100(8);
202 MAKEFLAG100(9);
203 MAKEFLAG100(10);
204 MAKEFLAG100(11);
205 MAKEFLAG100(12);
206 MAKEFLAG100(13);
207 MAKEFLAG100(14);
208 MAKEFLAG100(15);
209 
210 #undef MAKEFLAG100
211 #undef MAKEFLAG10
212 #undef MAKEFLAG
213 
214 // This is a pseudo-flag -- we want to register a flag with a filename
215 // at the top level, but there is no way to do this except by faking
216 // the filename.
217 namespace fLI {
218   static const int32 FLAGS_nonotldflag1 = 12;
219   int32 FLAGS_tldflag1 = FLAGS_nonotldflag1;
220   int32 FLAGS_notldflag1 = FLAGS_nonotldflag1;
221   static FlagRegisterer o_tldflag1(
222     "tldflag1", "int32",
223     "should show up in --helpshort", "gflags_unittest.cc",
224     &FLAGS_tldflag1, &FLAGS_notldflag1);
225 }
226 using fLI::FLAGS_tldflag1;
227 
228 namespace fLI {
229   static const int32 FLAGS_nonotldflag2 = 23;
230   int32 FLAGS_tldflag2 = FLAGS_nonotldflag2;
231   int32 FLAGS_notldflag2 = FLAGS_nonotldflag2;
232   static FlagRegisterer o_tldflag2(
233     "tldflag2", "int32",
234     "should show up in --helpshort", "gflags_unittest.",
235     &FLAGS_tldflag2, &FLAGS_notldflag2);
236 }
237 using fLI::FLAGS_tldflag2;
238 
239 _START_GOOGLE_NAMESPACE_
240 
241 namespace {
242 
243 
TmpFile(const string & basename)244 static string TmpFile(const string& basename) {
245 #ifdef _MSC_VER
246   return FLAGS_test_tmpdir + "\\" + basename;
247 #else
248   return FLAGS_test_tmpdir + "/" + basename;
249 #endif
250 }
251 
252 // Returns the definition of the --flagfile flag to be used in the tests.
253 // Must be called after ParseCommandLineFlags().
GetFlagFileFlag()254 static const char* GetFlagFileFlag() {
255 #ifdef _MSC_VER
256   static const string flagfile = FLAGS_srcdir + "\\src\\gflags_unittest_flagfile";
257 #else
258   static const string flagfile = FLAGS_srcdir + "/src/gflags_unittest_flagfile";
259 #endif
260   static const string flagfile_flag = string("--flagfile=") + flagfile;
261   return flagfile_flag.c_str();
262 }
263 
264 
265 // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
266 // compiler error iff T1 and T2 are different types.
267 template <typename T1, typename T2>
268 struct CompileAssertTypesEqual;
269 
270 template <typename T>
271 struct CompileAssertTypesEqual<T, T> {
272 };
273 
274 
275 template <typename Expected, typename Actual>
AssertIsType(Actual & x)276 void AssertIsType(Actual& x) {
277   CompileAssertTypesEqual<Expected, Actual>();
278 }
279 
280 // Verify all the flags are the right type.
TEST(FlagTypes,FlagTypes)281 TEST(FlagTypes, FlagTypes) {
282   AssertIsType<bool>(FLAGS_test_bool);
283   AssertIsType<int32>(FLAGS_test_int32);
284   AssertIsType<int64>(FLAGS_test_int64);
285   AssertIsType<uint64>(FLAGS_test_uint64);
286   AssertIsType<double>(FLAGS_test_double);
287   AssertIsType<string>(FLAGS_test_string);
288 }
289 
290 #ifdef GTEST_HAS_DEATH_TEST
291 // Death tests for "help" options.
292 //
293 // The help system automatically calls gflags_exitfunc(1) when you specify any of
294 // the help-related flags ("-helpmatch", "-helpxml") so we can't test
295 // those mainline.
296 
297 // Tests that "-helpmatch" causes the process to die.
TEST(ReadFlagsFromStringDeathTest,HelpMatch)298 TEST(ReadFlagsFromStringDeathTest, HelpMatch) {
299   EXPECT_DEATH(ReadFlagsFromString("-helpmatch=base", GetArgv0(), true),
300                "");
301 }
302 
303 
304 // Tests that "-helpxml" causes the process to die.
TEST(ReadFlagsFromStringDeathTest,HelpXml)305 TEST(ReadFlagsFromStringDeathTest, HelpXml) {
306   EXPECT_DEATH(ReadFlagsFromString("-helpxml", GetArgv0(), true),
307                "");
308 }
309 #endif
310 
311 
312 // A subroutine needed for testing reading flags from a string.
TestFlagString(const string & flags,const string & expected_string,bool expected_bool,int32 expected_int32,double expected_double)313 void TestFlagString(const string& flags,
314                     const string& expected_string,
315                     bool expected_bool,
316                     int32 expected_int32,
317                     double expected_double) {
318   EXPECT_TRUE(ReadFlagsFromString(flags,
319                                   GetArgv0(),
320                                   // errors are fatal
321                                   true));
322 
323   EXPECT_EQ(expected_string, FLAGS_test_string);
324   EXPECT_EQ(expected_bool, FLAGS_test_bool);
325   EXPECT_EQ(expected_int32, FLAGS_test_int32);
326   EXPECT_DOUBLE_EQ(expected_double, FLAGS_test_double);
327 }
328 
329 
330 // Tests reading flags from a string.
TEST(FlagFileTest,ReadFlagsFromString)331 TEST(FlagFileTest, ReadFlagsFromString) {
332   TestFlagString(
333       // Flag string
334       "-test_string=continued\n"
335       "# some comments are in order\n"
336       "# some\n"
337       "  # comments\n"
338       "#are\n"
339       "                  #trickier\n"
340       "# than others\n"
341       "-test_bool=true\n"
342       "     -test_int32=1\n"
343       "-test_double=0.0\n",
344       // Expected values
345       "continued",
346       true,
347       1,
348       0.0);
349 
350   TestFlagString(
351       // Flag string
352       "# let's make sure it can update values\n"
353       "-test_string=initial\n"
354       "-test_bool=false\n"
355       "-test_int32=123\n"
356       "-test_double=123.0\n",
357       // Expected values
358       "initial",
359       false,
360       123,
361       123.0);
362 }
363 
364 // Tests the filename part of the flagfile
TEST(FlagFileTest,FilenamesOurfileLast)365 TEST(FlagFileTest, FilenamesOurfileLast) {
366   FLAGS_test_string = "initial";
367   FLAGS_test_bool = false;
368   FLAGS_test_int32 = -1;
369   FLAGS_test_double = -1.0;
370   TestFlagString(
371       // Flag string
372       "-test_string=continued\n"
373       "# some comments are in order\n"
374       "# some\n"
375       "  # comments\n"
376       "#are\n"
377       "                  #trickier\n"
378       "# than others\n"
379       "not_our_filename\n"
380       "-test_bool=true\n"
381       "     -test_int32=1\n"
382       "gflags_unittest\n"
383       "-test_double=1000.0\n",
384       // Expected values
385       "continued",
386       false,
387       -1,
388       1000.0);
389 }
390 
TEST(FlagFileTest,FilenamesOurfileFirst)391 TEST(FlagFileTest, FilenamesOurfileFirst) {
392   FLAGS_test_string = "initial";
393   FLAGS_test_bool = false;
394   FLAGS_test_int32 = -1;
395   FLAGS_test_double = -1.0;
396   TestFlagString(
397       // Flag string
398       "-test_string=continued\n"
399       "# some comments are in order\n"
400       "# some\n"
401       "  # comments\n"
402       "#are\n"
403       "                  #trickier\n"
404       "# than others\n"
405       "gflags_unittest\n"
406       "-test_bool=true\n"
407       "     -test_int32=1\n"
408       "not_our_filename\n"
409       "-test_double=1000.0\n",
410       // Expected values
411       "continued",
412       true,
413       1,
414       -1.0);
415 }
416 
417 #ifdef HAVE_FNMATCH_H  // otherwise glob isn't supported
TEST(FlagFileTest,FilenamesOurfileGlob)418 TEST(FlagFileTest, FilenamesOurfileGlob) {
419   FLAGS_test_string = "initial";
420   FLAGS_test_bool = false;
421   FLAGS_test_int32 = -1;
422   FLAGS_test_double = -1.0;
423   TestFlagString(
424       // Flag string
425       "-test_string=continued\n"
426       "# some comments are in order\n"
427       "# some\n"
428       "  # comments\n"
429       "#are\n"
430       "                  #trickier\n"
431       "# than others\n"
432       "*flags*\n"
433       "-test_bool=true\n"
434       "     -test_int32=1\n"
435       "flags\n"
436       "-test_double=1000.0\n",
437       // Expected values
438       "continued",
439       true,
440       1,
441       -1.0);
442 }
443 
TEST(FlagFileTest,FilenamesOurfileInBigList)444 TEST(FlagFileTest, FilenamesOurfileInBigList) {
445   FLAGS_test_string = "initial";
446   FLAGS_test_bool = false;
447   FLAGS_test_int32 = -1;
448   FLAGS_test_double = -1.0;
449   TestFlagString(
450       // Flag string
451       "-test_string=continued\n"
452       "# some comments are in order\n"
453       "# some\n"
454       "  # comments\n"
455       "#are\n"
456       "                  #trickier\n"
457       "# than others\n"
458       "*first* *flags* *third*\n"
459       "-test_bool=true\n"
460       "     -test_int32=1\n"
461       "flags\n"
462       "-test_double=1000.0\n",
463       // Expected values
464       "continued",
465       true,
466       1,
467       -1.0);
468 }
469 #endif  // ifdef HAVE_FNMATCH_H
470 
471 // Tests that a failed flag-from-string read keeps flags at default values
TEST(FlagFileTest,FailReadFlagsFromString)472 TEST(FlagFileTest, FailReadFlagsFromString) {
473   FLAGS_test_int32 = 119;
474   string flags("# let's make sure it can update values\n"
475                "-test_string=non_initial\n"
476                "-test_bool=false\n"
477                "-test_int32=123\n"
478                "-test_double=illegal\n");
479 
480   EXPECT_FALSE(ReadFlagsFromString(flags,
481                                    GetArgv0(),
482                                    // errors are fatal
483                                    false));
484 
485   EXPECT_EQ(119, FLAGS_test_int32);
486   EXPECT_EQ("initial", FLAGS_test_string);
487 }
488 
489 // Tests that flags can be set to ordinary values.
TEST(SetFlagValueTest,OrdinaryValues)490 TEST(SetFlagValueTest, OrdinaryValues) {
491   EXPECT_EQ("initial", FLAGS_test_str1);
492 
493   SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT);
494   EXPECT_EQ("second", FLAGS_test_str1);  // set; was default
495 
496   SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT);
497   EXPECT_EQ("second", FLAGS_test_str1);  // already set once
498 
499   FLAGS_test_str1 = "initial";
500   SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT);
501   EXPECT_EQ("initial", FLAGS_test_str1);  // still already set before
502 
503   SetCommandLineOptionWithMode("test_str1", "third", SET_FLAGS_VALUE);
504   EXPECT_EQ("third", FLAGS_test_str1);  // changed value
505 
506   SetCommandLineOptionWithMode("test_str1", "fourth", SET_FLAGS_DEFAULT);
507   EXPECT_EQ("third", FLAGS_test_str1);
508   // value not changed (already set before)
509 
510   EXPECT_EQ("initial", FLAGS_test_str2);
511 
512   SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_DEFAULT);
513   EXPECT_EQ("second", FLAGS_test_str2);  // changed (was default)
514 
515   FLAGS_test_str2 = "extra";
516   EXPECT_EQ("extra", FLAGS_test_str2);
517 
518   FLAGS_test_str2 = "second";
519   SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT);
520   EXPECT_EQ("third", FLAGS_test_str2);  // still changed (was equal to default)
521 
522   SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT);
523   EXPECT_EQ("fourth", FLAGS_test_str2);  // changed (was default)
524 
525   EXPECT_EQ("initial", FLAGS_test_str3);
526 
527   SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT);
528   EXPECT_EQ("second", FLAGS_test_str3);  // changed
529 
530   FLAGS_test_str3 = "third";
531   SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_DEFAULT);
532   EXPECT_EQ("third", FLAGS_test_str3);  // not changed (was set)
533 
534   SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT);
535   EXPECT_EQ("third", FLAGS_test_str3);  // not changed (was set)
536 
537   SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_VALUE);
538   EXPECT_EQ("fourth", FLAGS_test_str3);  // changed value
539 }
540 
541 
542 // Tests that flags can be set to exceptional values.
543 // Note: apparently MINGW doesn't parse inf and nan correctly:
544 //    http://www.mail-archive.com/bug-gnulib@gnu.org/msg09573.html
545 // This url says FreeBSD also has a problem, but I didn't see that.
TEST(SetFlagValueTest,ExceptionalValues)546 TEST(SetFlagValueTest, ExceptionalValues) {
547 #if defined(isinf) && !defined(__MINGW32__)
548   EXPECT_EQ("test_double set to inf\n",
549             SetCommandLineOption("test_double", "inf"));
550   EXPECT_INF(FLAGS_test_double);
551 
552   EXPECT_EQ("test_double set to inf\n",
553             SetCommandLineOption("test_double", "INF"));
554   EXPECT_INF(FLAGS_test_double);
555 #endif
556 
557   // set some bad values
558   EXPECT_EQ("",
559             SetCommandLineOption("test_double", "0.1xxx"));
560   EXPECT_EQ("",
561             SetCommandLineOption("test_double", " "));
562   EXPECT_EQ("",
563             SetCommandLineOption("test_double", ""));
564 #if defined(isinf) && !defined(__MINGW32__)
565   EXPECT_EQ("test_double set to -inf\n",
566             SetCommandLineOption("test_double", "-inf"));
567   EXPECT_INF(FLAGS_test_double);
568   EXPECT_GT(0, FLAGS_test_double);
569 #endif
570 
571 #if defined(isnan) && !defined(__MINGW32__)
572   EXPECT_EQ("test_double set to nan\n",
573             SetCommandLineOption("test_double", "NaN"));
574   EXPECT_NAN(FLAGS_test_double);
575 #endif
576 }
577 
578 // Tests that integer flags can be specified in many ways
TEST(SetFlagValueTest,DifferentRadices)579 TEST(SetFlagValueTest, DifferentRadices) {
580   EXPECT_EQ("test_int32 set to 12\n",
581             SetCommandLineOption("test_int32", "12"));
582 
583   EXPECT_EQ("test_int32 set to 16\n",
584             SetCommandLineOption("test_int32", "0x10"));
585 
586   EXPECT_EQ("test_int32 set to 34\n",
587             SetCommandLineOption("test_int32", "0X22"));
588 
589   // Leading 0 is *not* octal; it's still decimal
590   EXPECT_EQ("test_int32 set to 10\n",
591             SetCommandLineOption("test_int32", "010"));
592 }
593 
594 // Tests what happens when you try to set a flag to an illegal value
TEST(SetFlagValueTest,IllegalValues)595 TEST(SetFlagValueTest, IllegalValues) {
596   FLAGS_test_bool = true;
597   FLAGS_test_int32 = 119;
598   FLAGS_test_int64 = 1191;
599   FLAGS_test_uint64 = 11911;
600 
601   EXPECT_EQ("",
602             SetCommandLineOption("test_bool", "12"));
603 
604   EXPECT_EQ("",
605             SetCommandLineOption("test_int32", "7000000000000"));
606 
607   // TODO(csilvers): uncomment this when we disallow negative numbers for uint64
608 #if 0
609   EXPECT_EQ("",
610             SetCommandLineOption("test_uint64", "-1"));
611 #endif
612 
613   EXPECT_EQ("",
614             SetCommandLineOption("test_int64", "not a number!"));
615 
616   // Test the empty string with each type of input
617   EXPECT_EQ("", SetCommandLineOption("test_bool", ""));
618   EXPECT_EQ("", SetCommandLineOption("test_int32", ""));
619   EXPECT_EQ("", SetCommandLineOption("test_int64", ""));
620   EXPECT_EQ("", SetCommandLineOption("test_uint64", ""));
621   EXPECT_EQ("", SetCommandLineOption("test_double", ""));
622   EXPECT_EQ("test_string set to \n", SetCommandLineOption("test_string", ""));
623 
624   EXPECT_TRUE(FLAGS_test_bool);
625   EXPECT_EQ(119, FLAGS_test_int32);
626   EXPECT_EQ(1191, FLAGS_test_int64);
627   EXPECT_EQ(11911, FLAGS_test_uint64);
628 }
629 
630 
631 // Tests that we only evaluate macro args once
TEST(MacroArgs,EvaluateOnce)632 TEST(MacroArgs, EvaluateOnce) {
633   EXPECT_EQ(13, FLAGS_changeable_var);
634   // Make sure we don't ++ the value somehow, when evaluating the flag.
635   EXPECT_EQ(13, FLAGS_changeable_var);
636   // Make sure the macro only evaluated this var once.
637   EXPECT_EQ(13, changeable_var);
638   // Make sure the actual value and default value are the same
639   SetCommandLineOptionWithMode("changeable_var", "21", SET_FLAG_IF_DEFAULT);
640   EXPECT_EQ(21, FLAGS_changeable_var);
641 }
642 
TEST(MacroArgs,EvaluateOnceBool)643 TEST(MacroArgs, EvaluateOnceBool) {
644   EXPECT_TRUE(FLAGS_changeable_bool_var);
645   EXPECT_TRUE(FLAGS_changeable_bool_var);
646   EXPECT_EQ(8009, changeable_bool_var);
647   SetCommandLineOptionWithMode("changeable_bool_var", "false",
648                                SET_FLAG_IF_DEFAULT);
649   EXPECT_FALSE(FLAGS_changeable_bool_var);
650 }
651 
TEST(MacroArgs,EvaluateOnceStrings)652 TEST(MacroArgs, EvaluateOnceStrings) {
653   EXPECT_EQ("1", FLAGS_changeable_string_var);
654   EXPECT_EQ("1", FLAGS_changeable_string_var);
655   EXPECT_EQ(1, changeable_string_var);
656   SetCommandLineOptionWithMode("changeable_string_var", "different",
657                                SET_FLAG_IF_DEFAULT);
658   EXPECT_EQ("different", FLAGS_changeable_string_var);
659 }
660 
661 // Tests that the FooFromEnv does the right thing
TEST(FromEnvTest,LegalValues)662 TEST(FromEnvTest, LegalValues) {
663   setenv("BOOL_VAL1", "true", 1);
664   setenv("BOOL_VAL2", "false", 1);
665   setenv("BOOL_VAL3", "1", 1);
666   setenv("BOOL_VAL4", "F", 1);
667   EXPECT_TRUE(BoolFromEnv("BOOL_VAL1", false));
668   EXPECT_FALSE(BoolFromEnv("BOOL_VAL2", true));
669   EXPECT_TRUE(BoolFromEnv("BOOL_VAL3", false));
670   EXPECT_FALSE(BoolFromEnv("BOOL_VAL4", true));
671   EXPECT_TRUE(BoolFromEnv("BOOL_VAL_UNKNOWN", true));
672   EXPECT_FALSE(BoolFromEnv("BOOL_VAL_UNKNOWN", false));
673 
674   setenv("INT_VAL1", "1", 1);
675   setenv("INT_VAL2", "-1", 1);
676   EXPECT_EQ(1, Int32FromEnv("INT_VAL1", 10));
677   EXPECT_EQ(-1, Int32FromEnv("INT_VAL2", 10));
678   EXPECT_EQ(10, Int32FromEnv("INT_VAL_UNKNOWN", 10));
679 
680   setenv("INT_VAL3", "1099511627776", 1);
681   EXPECT_EQ(1, Int64FromEnv("INT_VAL1", 20));
682   EXPECT_EQ(-1, Int64FromEnv("INT_VAL2", 20));
683   EXPECT_EQ(1099511627776LL, Int64FromEnv("INT_VAL3", 20));
684   EXPECT_EQ(20, Int64FromEnv("INT_VAL_UNKNOWN", 20));
685 
686   EXPECT_EQ(1, Uint64FromEnv("INT_VAL1", 30));
687   EXPECT_EQ(1099511627776ULL, Uint64FromEnv("INT_VAL3", 30));
688   EXPECT_EQ(30, Uint64FromEnv("INT_VAL_UNKNOWN", 30));
689 
690   // I pick values here that can be easily represented exactly in floating-point
691   setenv("DOUBLE_VAL1", "0.0", 1);
692   setenv("DOUBLE_VAL2", "1.0", 1);
693   setenv("DOUBLE_VAL3", "-1.0", 1);
694   EXPECT_EQ(0.0, DoubleFromEnv("DOUBLE_VAL1", 40.0));
695   EXPECT_EQ(1.0, DoubleFromEnv("DOUBLE_VAL2", 40.0));
696   EXPECT_EQ(-1.0, DoubleFromEnv("DOUBLE_VAL3", 40.0));
697   EXPECT_EQ(40.0, DoubleFromEnv("DOUBLE_VAL_UNKNOWN", 40.0));
698 
699   setenv("STRING_VAL1", "", 1);
700   setenv("STRING_VAL2", "my happy string!", 1);
701   EXPECT_STREQ("", StringFromEnv("STRING_VAL1", "unknown"));
702   EXPECT_STREQ("my happy string!", StringFromEnv("STRING_VAL2", "unknown"));
703   EXPECT_STREQ("unknown", StringFromEnv("STRING_VAL_UNKNOWN", "unknown"));
704 }
705 
706 #ifdef GTEST_HAS_DEATH_TEST
707 // Tests that the FooFromEnv dies on parse-error
TEST(FromEnvDeathTest,IllegalValues)708 TEST(FromEnvDeathTest, IllegalValues) {
709   setenv("BOOL_BAD1", "so true!", 1);
710   setenv("BOOL_BAD2", "", 1);
711   EXPECT_DEATH(BoolFromEnv("BOOL_BAD1", false), "error parsing env variable");
712   EXPECT_DEATH(BoolFromEnv("BOOL_BAD2", true), "error parsing env variable");
713 
714   setenv("INT_BAD1", "one", 1);
715   setenv("INT_BAD2", "100000000000000000", 1);
716   setenv("INT_BAD3", "0xx10", 1);
717   setenv("INT_BAD4", "", 1);
718   EXPECT_DEATH(Int32FromEnv("INT_BAD1", 10), "error parsing env variable");
719   EXPECT_DEATH(Int32FromEnv("INT_BAD2", 10), "error parsing env variable");
720   EXPECT_DEATH(Int32FromEnv("INT_BAD3", 10), "error parsing env variable");
721   EXPECT_DEATH(Int32FromEnv("INT_BAD4", 10), "error parsing env variable");
722 
723   setenv("BIGINT_BAD1", "18446744073709551616000", 1);
724   EXPECT_DEATH(Int64FromEnv("INT_BAD1", 20), "error parsing env variable");
725   EXPECT_DEATH(Int64FromEnv("INT_BAD3", 20), "error parsing env variable");
726   EXPECT_DEATH(Int64FromEnv("INT_BAD4", 20), "error parsing env variable");
727   EXPECT_DEATH(Int64FromEnv("BIGINT_BAD1", 200), "error parsing env variable");
728 
729   setenv("BIGINT_BAD2", "-1", 1);
730   EXPECT_DEATH(Uint64FromEnv("INT_BAD1", 30), "error parsing env variable");
731   EXPECT_DEATH(Uint64FromEnv("INT_BAD3", 30), "error parsing env variable");
732   EXPECT_DEATH(Uint64FromEnv("INT_BAD4", 30), "error parsing env variable");
733   EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD1", 30), "error parsing env variable");
734   // TODO(csilvers): uncomment this when we disallow negative numbers for uint64
735 #if 0
736   EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD2", 30), "error parsing env variable");
737 #endif
738 
739   setenv("DOUBLE_BAD1", "0.0.0", 1);
740   setenv("DOUBLE_BAD2", "", 1);
741   EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD1", 40.0), "error parsing env variable");
742   EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD2", 40.0), "error parsing env variable");
743 }
744 #endif
745 
746 
747 // Tests that FlagSaver can save the states of string flags.
TEST(FlagSaverTest,CanSaveStringFlagStates)748 TEST(FlagSaverTest, CanSaveStringFlagStates) {
749   // 1. Initializes the flags.
750 
751   // State of flag test_str1:
752   //   default value - "initial"
753   //   current value - "initial"
754   //   not set       - true
755 
756   SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_VALUE);
757   // State of flag test_str2:
758   //   default value - "initial"
759   //   current value - "second"
760   //   not set       - false
761 
762   SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT);
763   // State of flag test_str3:
764   //   default value - "second"
765   //   current value - "second"
766   //   not set       - true
767 
768   // 2. Saves the flag states.
769 
770   {
771     FlagSaver fs;
772 
773     // 3. Modifies the flag states.
774 
775     SetCommandLineOptionWithMode("test_str1", "second", SET_FLAGS_VALUE);
776     EXPECT_EQ("second", FLAGS_test_str1);
777     // State of flag test_str1:
778     //   default value - "second"
779     //   current value - "second"
780     //   not set       - true
781 
782     SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT);
783     EXPECT_EQ("second", FLAGS_test_str2);
784     // State of flag test_str2:
785     //   default value - "third"
786     //   current value - "second"
787     //   not set       - false
788 
789     SetCommandLineOptionWithMode("test_str3", "third", SET_FLAGS_VALUE);
790     EXPECT_EQ("third", FLAGS_test_str3);
791     // State of flag test_str1:
792     //   default value - "second"
793     //   current value - "third"
794     //   not set       - false
795 
796     // 4. Restores the flag states.
797   }
798 
799   // 5. Verifies that the states were restored.
800 
801   // Verifies that the value of test_str1 was restored.
802   EXPECT_EQ("initial", FLAGS_test_str1);
803   // Verifies that the "not set" attribute of test_str1 was restored to true.
804   SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT);
805   EXPECT_EQ("second", FLAGS_test_str1);
806 
807   // Verifies that the value of test_str2 was restored.
808   EXPECT_EQ("second", FLAGS_test_str2);
809   // Verifies that the "not set" attribute of test_str2 was restored to false.
810   SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT);
811   EXPECT_EQ("second", FLAGS_test_str2);
812 
813   // Verifies that the value of test_str3 was restored.
814   EXPECT_EQ("second", FLAGS_test_str3);
815   // Verifies that the "not set" attribute of test_str3 was restored to true.
816   SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT);
817   EXPECT_EQ("fourth", FLAGS_test_str3);
818 }
819 
820 
821 // Tests that FlagSaver can save the values of various-typed flags.
TEST(FlagSaverTest,CanSaveVariousTypedFlagValues)822 TEST(FlagSaverTest, CanSaveVariousTypedFlagValues) {
823   // Initializes the flags.
824   FLAGS_test_bool = false;
825   FLAGS_test_int32 = -1;
826   FLAGS_test_int64 = -2;
827   FLAGS_test_uint64 = 3;
828   FLAGS_test_double = 4.0;
829   FLAGS_test_string = "good";
830 
831   // Saves the flag states.
832   {
833     FlagSaver fs;
834 
835     // Modifies the flags.
836     FLAGS_test_bool = true;
837     FLAGS_test_int32 = -5;
838     FLAGS_test_int64 = -6;
839     FLAGS_test_uint64 = 7;
840     FLAGS_test_double = 8.0;
841     FLAGS_test_string = "bad";
842 
843     // Restores the flag states.
844   }
845 
846   // Verifies the flag values were restored.
847   EXPECT_FALSE(FLAGS_test_bool);
848   EXPECT_EQ(-1, FLAGS_test_int32);
849   EXPECT_EQ(-2, FLAGS_test_int64);
850   EXPECT_EQ(3, FLAGS_test_uint64);
851   EXPECT_DOUBLE_EQ(4.0, FLAGS_test_double);
852   EXPECT_EQ("good", FLAGS_test_string);
853 }
854 
TEST(GetAllFlagsTest,BaseTest)855 TEST(GetAllFlagsTest, BaseTest) {
856   vector<CommandLineFlagInfo> flags;
857   GetAllFlags(&flags);
858   bool found_test_bool = false;
859   vector<CommandLineFlagInfo>::const_iterator i;
860   for (i = flags.begin(); i != flags.end(); ++i) {
861     if (i->name == "test_bool") {
862       found_test_bool = true;
863       EXPECT_EQ(i->type, "bool");
864       EXPECT_EQ(i->default_value, "false");
865       EXPECT_EQ(i->flag_ptr, &FLAGS_test_bool);
866       break;
867     }
868   }
869   EXPECT_TRUE(found_test_bool);
870 }
871 
TEST(ShowUsageWithFlagsTest,BaseTest)872 TEST(ShowUsageWithFlagsTest, BaseTest) {
873   // TODO(csilvers): test this by allowing output other than to stdout.
874   // Not urgent since this functionality is tested via
875   // gflags_unittest.sh, though only through use of --help.
876 }
877 
TEST(ShowUsageWithFlagsRestrictTest,BaseTest)878 TEST(ShowUsageWithFlagsRestrictTest, BaseTest) {
879   // TODO(csilvers): test this by allowing output other than to stdout.
880   // Not urgent since this functionality is tested via
881   // gflags_unittest.sh, though only through use of --helpmatch.
882 }
883 
884 // Note: all these argv-based tests depend on SetArgv being called
885 // before ParseCommandLineFlags() in main(), below.
TEST(GetArgvsTest,BaseTest)886 TEST(GetArgvsTest, BaseTest) {
887   vector<string> argvs = GetArgvs();
888   EXPECT_EQ(4, argvs.size());
889   EXPECT_EQ("/test/argv/for/gflags_unittest", argvs[0]);
890   EXPECT_EQ("argv 2", argvs[1]);
891   EXPECT_EQ("3rd argv", argvs[2]);
892   EXPECT_EQ("argv #4", argvs[3]);
893 }
894 
TEST(GetArgvTest,BaseTest)895 TEST(GetArgvTest, BaseTest) {
896   EXPECT_STREQ("/test/argv/for/gflags_unittest "
897                "argv 2 3rd argv argv #4", GetArgv());
898 }
899 
TEST(GetArgv0Test,BaseTest)900 TEST(GetArgv0Test, BaseTest) {
901   EXPECT_STREQ("/test/argv/for/gflags_unittest", GetArgv0());
902 }
903 
TEST(GetArgvSumTest,BaseTest)904 TEST(GetArgvSumTest, BaseTest) {
905   // This number is just the sum of the ASCII values of all the chars
906   // in GetArgv().
907   EXPECT_EQ(4904, GetArgvSum());
908 }
909 
TEST(ProgramInvocationNameTest,BaseTest)910 TEST(ProgramInvocationNameTest, BaseTest) {
911   EXPECT_STREQ("/test/argv/for/gflags_unittest",
912                ProgramInvocationName());
913 }
914 
TEST(ProgramInvocationShortNameTest,BaseTest)915 TEST(ProgramInvocationShortNameTest, BaseTest) {
916   EXPECT_STREQ("gflags_unittest", ProgramInvocationShortName());
917 }
918 
TEST(ProgramUsageTest,BaseTest)919 TEST(ProgramUsageTest, BaseTest) {  // Depends on 1st arg to ParseCommandLineFlags()
920   EXPECT_STREQ("/test/argv/for/gflags_unittest: "
921                "<useless flag> [...]\nDoes something useless.\n",
922                ProgramUsage());
923 }
924 
TEST(GetCommandLineOptionTest,NameExistsAndIsDefault)925 TEST(GetCommandLineOptionTest, NameExistsAndIsDefault) {
926   string value("will be changed");
927   bool r = GetCommandLineOption("test_bool", &value);
928   EXPECT_TRUE(r);
929   EXPECT_EQ("false", value);
930 
931   r = GetCommandLineOption("test_int32", &value);
932   EXPECT_TRUE(r);
933   EXPECT_EQ("-1", value);
934 }
935 
TEST(GetCommandLineOptionTest,NameExistsAndWasAssigned)936 TEST(GetCommandLineOptionTest, NameExistsAndWasAssigned) {
937   FLAGS_test_int32 = 400;
938   string value("will be changed");
939   const bool r = GetCommandLineOption("test_int32", &value);
940   EXPECT_TRUE(r);
941   EXPECT_EQ("400", value);
942 }
943 
TEST(GetCommandLineOptionTest,NameExistsAndWasSet)944 TEST(GetCommandLineOptionTest, NameExistsAndWasSet) {
945   SetCommandLineOption("test_int32", "700");
946   string value("will be changed");
947   const bool r = GetCommandLineOption("test_int32", &value);
948   EXPECT_TRUE(r);
949   EXPECT_EQ("700", value);
950 }
951 
TEST(GetCommandLineOptionTest,NameExistsAndWasNotSet)952 TEST(GetCommandLineOptionTest, NameExistsAndWasNotSet) {
953   // This doesn't set the flag's value, but rather its default value.
954   // is_default is still true, but the 'default' value returned has changed!
955   SetCommandLineOptionWithMode("test_int32", "800", SET_FLAGS_DEFAULT);
956   string value("will be changed");
957   const bool r = GetCommandLineOption("test_int32", &value);
958   EXPECT_TRUE(r);
959   EXPECT_EQ("800", value);
960   EXPECT_TRUE(GetCommandLineFlagInfoOrDie("test_int32").is_default);
961 }
962 
TEST(GetCommandLineOptionTest,NameExistsAndWasConditionallySet)963 TEST(GetCommandLineOptionTest, NameExistsAndWasConditionallySet) {
964   SetCommandLineOptionWithMode("test_int32", "900", SET_FLAG_IF_DEFAULT);
965   string value("will be changed");
966   const bool r = GetCommandLineOption("test_int32", &value);
967   EXPECT_TRUE(r);
968   EXPECT_EQ("900", value);
969 }
970 
TEST(GetCommandLineOptionTest,NameDoesNotExist)971 TEST(GetCommandLineOptionTest, NameDoesNotExist) {
972   string value("will not be changed");
973   const bool r = GetCommandLineOption("test_int3210", &value);
974   EXPECT_FALSE(r);
975   EXPECT_EQ("will not be changed", value);
976 }
977 
TEST(GetCommandLineFlagInfoTest,FlagExists)978 TEST(GetCommandLineFlagInfoTest, FlagExists) {
979   CommandLineFlagInfo info;
980   bool r = GetCommandLineFlagInfo("test_int32", &info);
981   EXPECT_TRUE(r);
982   EXPECT_EQ("test_int32", info.name);
983   EXPECT_EQ("int32", info.type);
984   EXPECT_EQ("", info.description);
985   EXPECT_EQ("-1", info.current_value);
986   EXPECT_EQ("-1", info.default_value);
987   EXPECT_TRUE(info.is_default);
988   EXPECT_FALSE(info.has_validator_fn);
989   EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
990 
991   FLAGS_test_bool = true;
992   r = GetCommandLineFlagInfo("test_bool", &info);
993   EXPECT_TRUE(r);
994   EXPECT_EQ("test_bool", info.name);
995   EXPECT_EQ("bool", info.type);
996   EXPECT_EQ("tests bool-ness", info.description);
997   EXPECT_EQ("true", info.current_value);
998   EXPECT_EQ("false", info.default_value);
999   EXPECT_FALSE(info.is_default);
1000   EXPECT_FALSE(info.has_validator_fn);
1001   EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1002 
1003   FLAGS_test_bool = false;
1004   r = GetCommandLineFlagInfo("test_bool", &info);
1005   EXPECT_TRUE(r);
1006   EXPECT_EQ("test_bool", info.name);
1007   EXPECT_EQ("bool", info.type);
1008   EXPECT_EQ("tests bool-ness", info.description);
1009   EXPECT_EQ("false", info.current_value);
1010   EXPECT_EQ("false", info.default_value);
1011   EXPECT_FALSE(info.is_default);  // value is same, but flag *was* modified
1012   EXPECT_FALSE(info.has_validator_fn);
1013   EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1014 }
1015 
TEST(GetCommandLineFlagInfoTest,FlagDoesNotExist)1016 TEST(GetCommandLineFlagInfoTest, FlagDoesNotExist) {
1017   CommandLineFlagInfo info;
1018   // Set to some random values that GetCommandLineFlagInfo should not change
1019   info.name = "name";
1020   info.type = "type";
1021   info.current_value = "curr";
1022   info.default_value = "def";
1023   info.filename = "/";
1024   info.is_default = false;
1025   info.has_validator_fn = true;
1026   info.flag_ptr = NULL;
1027   bool r = GetCommandLineFlagInfo("test_int3210", &info);
1028   EXPECT_FALSE(r);
1029   EXPECT_EQ("name", info.name);
1030   EXPECT_EQ("type", info.type);
1031   EXPECT_EQ("", info.description);
1032   EXPECT_EQ("curr", info.current_value);
1033   EXPECT_EQ("def", info.default_value);
1034   EXPECT_EQ("/", info.filename);
1035   EXPECT_FALSE(info.is_default);
1036   EXPECT_TRUE(info.has_validator_fn);
1037   EXPECT_EQ(NULL, info.flag_ptr);
1038 }
1039 
TEST(GetCommandLineFlagInfoOrDieTest,FlagExistsAndIsDefault)1040 TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndIsDefault) {
1041   CommandLineFlagInfo info;
1042   info = GetCommandLineFlagInfoOrDie("test_int32");
1043   EXPECT_EQ("test_int32", info.name);
1044   EXPECT_EQ("int32", info.type);
1045   EXPECT_EQ("", info.description);
1046   EXPECT_EQ("-1", info.current_value);
1047   EXPECT_EQ("-1", info.default_value);
1048   EXPECT_TRUE(info.is_default);
1049   EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
1050   info = GetCommandLineFlagInfoOrDie("test_bool");
1051   EXPECT_EQ("test_bool", info.name);
1052   EXPECT_EQ("bool", info.type);
1053   EXPECT_EQ("tests bool-ness", info.description);
1054   EXPECT_EQ("false", info.current_value);
1055   EXPECT_EQ("false", info.default_value);
1056   EXPECT_TRUE(info.is_default);
1057   EXPECT_FALSE(info.has_validator_fn);
1058   EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1059 }
1060 
TEST(GetCommandLineFlagInfoOrDieTest,FlagExistsAndWasAssigned)1061 TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndWasAssigned) {
1062   FLAGS_test_int32 = 400;
1063   CommandLineFlagInfo info;
1064   info = GetCommandLineFlagInfoOrDie("test_int32");
1065   EXPECT_EQ("test_int32", info.name);
1066   EXPECT_EQ("int32", info.type);
1067   EXPECT_EQ("", info.description);
1068   EXPECT_EQ("400", info.current_value);
1069   EXPECT_EQ("-1", info.default_value);
1070   EXPECT_FALSE(info.is_default);
1071   EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
1072   FLAGS_test_bool = true;
1073   info = GetCommandLineFlagInfoOrDie("test_bool");
1074   EXPECT_EQ("test_bool", info.name);
1075   EXPECT_EQ("bool", info.type);
1076   EXPECT_EQ("tests bool-ness", info.description);
1077   EXPECT_EQ("true", info.current_value);
1078   EXPECT_EQ("false", info.default_value);
1079   EXPECT_FALSE(info.is_default);
1080   EXPECT_FALSE(info.has_validator_fn);
1081   EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1082 }
1083 
1084 #ifdef GTEST_HAS_DEATH_TEST
TEST(GetCommandLineFlagInfoOrDieDeathTest,FlagDoesNotExist)1085 TEST(GetCommandLineFlagInfoOrDieDeathTest, FlagDoesNotExist) {
1086   EXPECT_DEATH(GetCommandLineFlagInfoOrDie("test_int3210"),
1087                ".*: flag test_int3210 does not exist");
1088 }
1089 #endif
1090 
1091 
1092 // These are lightly tested because they're deprecated.  Basically,
1093 // the tests are meant to cover how existing users use these functions,
1094 // but not necessarily how new users could use them.
TEST(DeprecatedFunctionsTest,CommandlineFlagsIntoString)1095 TEST(DeprecatedFunctionsTest, CommandlineFlagsIntoString) {
1096   string s = CommandlineFlagsIntoString();
1097   EXPECT_NE(string::npos, s.find("--test_bool="));
1098 }
1099 
TEST(DeprecatedFunctionsTest,AppendFlagsIntoFile)1100 TEST(DeprecatedFunctionsTest, AppendFlagsIntoFile) {
1101   FLAGS_test_int32 = 10;     // just to make the test more interesting
1102   string filename(TmpFile("flagfile"));
1103   unlink(filename.c_str());  // just to be safe
1104   const bool r = AppendFlagsIntoFile(filename, "not the real argv0");
1105   EXPECT_TRUE(r);
1106 
1107   FILE* fp = fopen(filename.c_str(), "r");
1108   EXPECT_TRUE(fp != NULL);
1109   char line[8192];
1110   EXPECT_TRUE(fgets(line, sizeof(line)-1, fp) != NULL);  // get the first line
1111   // First line should be progname.
1112   EXPECT_STREQ("not the real argv0\n", line);
1113 
1114   bool found_bool = false, found_int32 = false;
1115   while (fgets(line, sizeof(line)-1, fp)) {
1116     line[sizeof(line)-1] = '\0';    // just to be safe
1117     if (strcmp(line, "--test_bool=false\n") == 0)
1118       found_bool = true;
1119     if (strcmp(line, "--test_int32=10\n") == 0)
1120       found_int32 = true;
1121   }
1122   EXPECT_TRUE(found_int32);
1123   EXPECT_TRUE(found_bool);
1124   fclose(fp);
1125 }
1126 
TEST(DeprecatedFunctionsTest,ReadFromFlagsFile)1127 TEST(DeprecatedFunctionsTest, ReadFromFlagsFile) {
1128   FLAGS_test_int32 = -10;    // just to make the test more interesting
1129   string filename(TmpFile("flagfile2"));
1130   unlink(filename.c_str());  // just to be safe
1131   bool r = AppendFlagsIntoFile(filename, GetArgv0());
1132   EXPECT_TRUE(r);
1133 
1134   FLAGS_test_int32 = -11;
1135   r = ReadFromFlagsFile(filename, GetArgv0(), true);
1136   EXPECT_TRUE(r);
1137   EXPECT_EQ(-10, FLAGS_test_int32);
1138 }  // unnamed namespace
1139 
TEST(DeprecatedFunctionsTest,ReadFromFlagsFileFailure)1140 TEST(DeprecatedFunctionsTest, ReadFromFlagsFileFailure) {
1141   FLAGS_test_int32 = -20;
1142   string filename(TmpFile("flagfile3"));
1143   FILE* fp = fopen(filename.c_str(), "w");
1144   EXPECT_TRUE(fp != NULL);
1145   // Note the error in the bool assignment below...
1146   fprintf(fp, "%s\n--test_int32=-21\n--test_bool=not_a_bool!\n", GetArgv0());
1147   fclose(fp);
1148 
1149   FLAGS_test_int32 = -22;
1150   const bool r = ReadFromFlagsFile(filename, GetArgv0(), false);
1151   EXPECT_FALSE(r);
1152   EXPECT_EQ(-22, FLAGS_test_int32);   // the -21 from the flagsfile didn't take
1153 }
1154 
TEST(FlagsSetBeforeInitTest,TryFromEnv)1155 TEST(FlagsSetBeforeInitTest, TryFromEnv) {
1156   EXPECT_EQ("pre-set", FLAGS_test_tryfromenv);
1157 }
1158 
1159 // The following test case verifies that ParseCommandLineFlags() and
1160 // ParseCommandLineNonHelpFlags() uses the last definition of a flag
1161 // in case it's defined more than once.
1162 
1163 DEFINE_int32(test_flag, -1, "used for testing gflags.cc");
1164 
1165 // Parses and returns the --test_flag flag.
1166 // If with_help is true, calls ParseCommandLineFlags; otherwise calls
1167 // ParseCommandLineNonHelpFlags.
ParseTestFlag(bool with_help,int argc,const char ** const_argv)1168 int32 ParseTestFlag(bool with_help, int argc, const char** const_argv) {
1169   FlagSaver fs;  // Restores the flags before returning.
1170 
1171   // Makes a copy of the input array s.t. it can be reused
1172   // (ParseCommandLineFlags() will alter the array).
1173   char** const argv_save = new char*[argc + 1];
1174   char** argv = argv_save;
1175   memcpy(argv, const_argv, sizeof(*argv)*(argc + 1));
1176 
1177   if (with_help) {
1178     ParseCommandLineFlags(&argc, &argv, true);
1179   } else {
1180     ParseCommandLineNonHelpFlags(&argc, &argv, true);
1181   }
1182 
1183   delete[] argv_save;
1184   return FLAGS_test_flag;
1185 }
1186 
TEST(ParseCommandLineFlagsUsesLastDefinitionTest,WhenFlagIsDefinedTwiceOnCommandLine)1187 TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
1188      WhenFlagIsDefinedTwiceOnCommandLine) {
1189   const char* argv[] = {
1190     "my_test",
1191     "--test_flag=1",
1192     "--test_flag=2",
1193     NULL,
1194   };
1195 
1196   EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
1197   EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1198 }
1199 
TEST(ParseCommandLineFlagsUsesLastDefinitionTest,WhenFlagIsDefinedTwiceInFlagFile)1200 TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
1201      WhenFlagIsDefinedTwiceInFlagFile) {
1202   const char* argv[] = {
1203     "my_test",
1204     GetFlagFileFlag(),
1205     NULL,
1206   };
1207 
1208   EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
1209   EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1210 }
1211 
TEST(ParseCommandLineFlagsUsesLastDefinitionTest,WhenFlagIsDefinedInCommandLineAndThenFlagFile)1212 TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
1213      WhenFlagIsDefinedInCommandLineAndThenFlagFile) {
1214   const char* argv[] = {
1215     "my_test",
1216     "--test_flag=0",
1217     GetFlagFileFlag(),
1218     NULL,
1219   };
1220 
1221   EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
1222   EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1223 }
1224 
TEST(ParseCommandLineFlagsUsesLastDefinitionTest,WhenFlagIsDefinedInFlagFileAndThenCommandLine)1225 TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
1226      WhenFlagIsDefinedInFlagFileAndThenCommandLine) {
1227   const char* argv[] = {
1228     "my_test",
1229     GetFlagFileFlag(),
1230     "--test_flag=3",
1231     NULL,
1232   };
1233 
1234   EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv));
1235   EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv));
1236 }
1237 
TEST(ParseCommandLineFlagsUsesLastDefinitionTest,WhenFlagIsDefinedInCommandLineAndFlagFileAndThenCommandLine)1238 TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
1239      WhenFlagIsDefinedInCommandLineAndFlagFileAndThenCommandLine) {
1240   const char* argv[] = {
1241     "my_test",
1242     "--test_flag=0",
1243     GetFlagFileFlag(),
1244     "--test_flag=3",
1245     NULL,
1246   };
1247 
1248   EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv));
1249   EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv));
1250 }
1251 
TEST(ParseCommandLineFlagsAndDashArgs,TwoDashArgFirst)1252 TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgFirst) {
1253   const char* argv[] = {
1254     "my_test",
1255     "--",
1256     "--test_flag=0",
1257     NULL,
1258   };
1259 
1260   EXPECT_EQ(-1, ParseTestFlag(true, arraysize(argv) - 1, argv));
1261   EXPECT_EQ(-1, ParseTestFlag(false, arraysize(argv) - 1, argv));
1262 }
1263 
TEST(ParseCommandLineFlagsAndDashArgs,TwoDashArgMiddle)1264 TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgMiddle) {
1265   const char* argv[] = {
1266     "my_test",
1267     "--test_flag=7",
1268     "--",
1269     "--test_flag=0",
1270     NULL,
1271   };
1272 
1273   EXPECT_EQ(7, ParseTestFlag(true, arraysize(argv) - 1, argv));
1274   EXPECT_EQ(7, ParseTestFlag(false, arraysize(argv) - 1, argv));
1275 }
1276 
TEST(ParseCommandLineFlagsAndDashArgs,OneDashArg)1277 TEST(ParseCommandLineFlagsAndDashArgs, OneDashArg) {
1278   const char* argv[] = {
1279     "my_test",
1280     "-",
1281     "--test_flag=0",
1282     NULL,
1283   };
1284 
1285   EXPECT_EQ(0, ParseTestFlag(true, arraysize(argv) - 1, argv));
1286   EXPECT_EQ(0, ParseTestFlag(false, arraysize(argv) - 1, argv));
1287 }
1288 
1289 #ifdef GTEST_HAS_DEATH_TEST
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,FlagIsCompletelyUnknown)1290 TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1291      FlagIsCompletelyUnknown) {
1292   const char* argv[] = {
1293     "my_test",
1294     "--this_flag_does_not_exist",
1295     NULL,
1296   };
1297 
1298   EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1299                "unknown command line flag.*");
1300   EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1301                "unknown command line flag.*");
1302 }
1303 
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,BoolFlagIsCompletelyUnknown)1304 TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1305      BoolFlagIsCompletelyUnknown) {
1306   const char* argv[] = {
1307     "my_test",
1308     "--nothis_flag_does_not_exist",
1309     NULL,
1310   };
1311 
1312   EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1313                "unknown command line flag.*");
1314   EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1315                "unknown command line flag.*");
1316 }
1317 
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,FlagIsNotABool)1318 TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1319      FlagIsNotABool) {
1320   const char* argv[] = {
1321     "my_test",
1322     "--notest_string",
1323     NULL,
1324   };
1325 
1326   EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1327                "boolean value .* specified for .* command line flag");
1328   EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1329                "boolean value .* specified for .* command line flag");
1330 }
1331 #endif
1332 
TEST(ParseCommandLineFlagsWrongFields,DescriptionIsInvalid)1333 TEST(ParseCommandLineFlagsWrongFields,
1334      DescriptionIsInvalid) {
1335   // These must not be automatic variables, since command line flags
1336   // aren't unregistered and gUnit uses FlagSaver to save and restore
1337   // command line flags' values.  If these are on the stack, then when
1338   // later tests attempt to save and restore their values, the stack
1339   // addresses of these variables will be overwritten...  Stack smash!
1340   static bool current_storage;
1341   static bool defvalue_storage;
1342   FlagRegisterer fr("flag_name", "bool", 0, "filename",
1343                     &current_storage, &defvalue_storage);
1344   CommandLineFlagInfo fi;
1345   EXPECT_TRUE(GetCommandLineFlagInfo("flag_name", &fi));
1346   EXPECT_EQ("", fi.description);
1347   EXPECT_EQ(&current_storage, fi.flag_ptr);
1348 }
1349 
ValidateTestFlagIs5(const char * flagname,int32 flagval)1350 static bool ValidateTestFlagIs5(const char* flagname, int32 flagval) {
1351   if (flagval == 5)
1352     return true;
1353   printf("%s isn't 5!\n", flagname);
1354   return false;
1355 }
1356 
ValidateTestFlagIs10(const char * flagname,int32 flagval)1357 static bool ValidateTestFlagIs10(const char* flagname, int32 flagval) {
1358   return flagval == 10;
1359 }
1360 
1361 
TEST(FlagsValidator,ValidFlagViaArgv)1362 TEST(FlagsValidator, ValidFlagViaArgv) {
1363   const char* argv[] = {
1364     "my_test",
1365     "--test_flag=5",
1366     NULL,
1367   };
1368   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1369   EXPECT_EQ(5, ParseTestFlag(true, arraysize(argv) - 1, argv));
1370   // Undo the flag validator setting
1371   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1372 }
1373 
TEST(FlagsValidator,ValidFlagViaSetDefault)1374 TEST(FlagsValidator, ValidFlagViaSetDefault) {
1375   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1376   // SetCommandLineOptionWithMode returns the empty string on error.
1377   EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
1378                                              SET_FLAG_IF_DEFAULT));
1379   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1380 }
1381 
TEST(FlagsValidator,ValidFlagViaSetValue)1382 TEST(FlagsValidator, ValidFlagViaSetValue) {
1383   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1384   FLAGS_test_flag = 100;   // doesn't trigger the validator
1385   // SetCommandLineOptionWithMode returns the empty string on error.
1386   EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
1387                                              SET_FLAGS_VALUE));
1388   EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
1389                                              SET_FLAGS_DEFAULT));
1390   EXPECT_NE("", SetCommandLineOption("test_flag", "5"));
1391   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1392 }
1393 
1394 #ifdef GTEST_HAS_DEATH_TEST
TEST(FlagsValidatorDeathTest,InvalidFlagViaArgv)1395 TEST(FlagsValidatorDeathTest, InvalidFlagViaArgv) {
1396   const char* argv[] = {
1397     "my_test",
1398     "--test_flag=50",
1399     NULL,
1400   };
1401   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1402   EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1403                "ERROR: failed validation of new value '50' for flag 'test_flag'");
1404   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1405 }
1406 #endif
1407 
TEST(FlagsValidator,InvalidFlagViaSetDefault)1408 TEST(FlagsValidator, InvalidFlagViaSetDefault) {
1409   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1410   // SetCommandLineOptionWithMode returns the empty string on error.
1411   EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
1412                                              SET_FLAG_IF_DEFAULT));
1413   EXPECT_EQ(-1, FLAGS_test_flag);   // the setting-to-50 should have failed
1414   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1415 }
1416 
TEST(FlagsValidator,InvalidFlagViaSetValue)1417 TEST(FlagsValidator, InvalidFlagViaSetValue) {
1418   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1419   FLAGS_test_flag = 100;   // doesn't trigger the validator
1420   // SetCommandLineOptionWithMode returns the empty string on error.
1421   EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
1422                                              SET_FLAGS_VALUE));
1423   EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
1424                                              SET_FLAGS_DEFAULT));
1425   EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));
1426   EXPECT_EQ(100, FLAGS_test_flag);   // the setting-to-50 should have failed
1427   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1428 }
1429 
1430 #ifdef GTEST_HAS_DEATH_TEST
TEST(FlagsValidatorDeathTest,InvalidFlagNeverSet)1431 TEST(FlagsValidatorDeathTest, InvalidFlagNeverSet) {
1432   // If a flag keeps its default value, and that default value is
1433   // invalid, we should die at argv-parse time.
1434   const char* argv[] = {
1435     "my_test",
1436     NULL,
1437   };
1438   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1439   EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1440                "ERROR: --test_flag must be set on the commandline");
1441 }
1442 #endif
1443 
TEST(FlagsValidator,InvalidFlagPtr)1444 TEST(FlagsValidator, InvalidFlagPtr) {
1445   int32 dummy;
1446   EXPECT_FALSE(RegisterFlagValidator(NULL, &ValidateTestFlagIs5));
1447   EXPECT_FALSE(RegisterFlagValidator(&dummy, &ValidateTestFlagIs5));
1448 }
1449 
TEST(FlagsValidator,RegisterValidatorTwice)1450 TEST(FlagsValidator, RegisterValidatorTwice) {
1451   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1452   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1453   EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
1454   EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
1455   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1456   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1457   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
1458   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1459 }
1460 
TEST(FlagsValidator,CommandLineFlagInfo)1461 TEST(FlagsValidator, CommandLineFlagInfo) {
1462   CommandLineFlagInfo info;
1463   info = GetCommandLineFlagInfoOrDie("test_flag");
1464   EXPECT_FALSE(info.has_validator_fn);
1465 
1466   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1467   info = GetCommandLineFlagInfoOrDie("test_flag");
1468   EXPECT_TRUE(info.has_validator_fn);
1469 
1470   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1471   info = GetCommandLineFlagInfoOrDie("test_flag");
1472   EXPECT_FALSE(info.has_validator_fn);
1473 }
1474 
TEST(FlagsValidator,FlagSaver)1475 TEST(FlagsValidator, FlagSaver) {
1476   {
1477     FlagSaver fs;
1478     EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1479     EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));  // fails validation
1480   }
1481   EXPECT_NE("", SetCommandLineOption("test_flag", "50"));  // validator is gone
1482 
1483   EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1484   {
1485     FlagSaver fs;
1486     EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
1487     EXPECT_NE("", SetCommandLineOption("test_flag", "50"));  // no validator
1488   }
1489   EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));  // validator is back
1490 }
1491 
1492 
1493 }  // unnamed namespace
1494 
main(int argc,char ** argv)1495 int main(int argc, char **argv) {
1496   // We need to call SetArgv before parsing flags, so our "test" argv will
1497   // win out over this executable's real argv.  That makes running this
1498   // test with a real --help flag kinda annoying, unfortunately.
1499   const char* test_argv[] = { "/test/argv/for/gflags_unittest",
1500                               "argv 2", "3rd argv", "argv #4" };
1501   SetArgv(arraysize(test_argv), test_argv);
1502 
1503   // The first arg is the usage message, also important for testing.
1504   string usage_message = (string(GetArgv0()) +
1505                           ": <useless flag> [...]\nDoes something useless.\n");
1506 
1507   // We test setting tryfromenv manually, and making sure
1508   // ParseCommandLineFlags still evaluates it.
1509   FLAGS_tryfromenv = "test_tryfromenv";
1510   setenv("FLAGS_test_tryfromenv", "pre-set", 1);
1511 
1512   // Modify flag values from declared default value in two ways.
1513   // The recommended way:
1514   SetCommandLineOptionWithMode("changed_bool1", "true", SET_FLAGS_DEFAULT);
1515 
1516   // The non-recommended way:
1517   FLAGS_changed_bool2 = true;
1518 
1519   SetUsageMessage(usage_message.c_str());
1520   SetVersionString("test_version");
1521   ParseCommandLineFlags(&argc, &argv, true);
1522   MakeTmpdir(&FLAGS_test_tmpdir);
1523 
1524   const int exit_status = RUN_ALL_TESTS();
1525   ShutDownCommandLineFlags();
1526   return exit_status;
1527 }
1528 
1529 _END_GOOGLE_NAMESPACE_
1530 
main(int argc,char ** argv)1531 int main(int argc, char** argv) {
1532   return GOOGLE_NAMESPACE::main(argc, argv);
1533 }
1534 
1535