Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(232)

Side by Side Diff: tools/nixysa/third_party/gflags-1.0/src/gflags_unittest-main.cc

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

Powered by Google App Engine
This is Rietveld 408576698