gflags_unittest.cc 50.6 KB
Newer Older
1
// Copyright (c) 2005, Google Inc.
Craig Silverstein's avatar
Craig Silverstein committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// ---
//
// For now, this unit test does not cover all features of
33
// gflags.cc
Craig Silverstein's avatar
Craig Silverstein committed
34

35
#include "config_for_unittests.h"
36 37 38
#include <gflags/gflags.h>

#include <math.h>       // for isinf() and isnan()
Craig Silverstein's avatar
Craig Silverstein committed
39
#include <stdio.h>
40
#include <stdlib.h>
Craig Silverstein's avatar
Craig Silverstein committed
41
#include <string.h>
42 43 44
#ifdef GFLAGS_HAVE_UNISTD_H
#  include <unistd.h>   // for unlink()
#endif
Craig Silverstein's avatar
Craig Silverstein committed
45 46
#include <vector>
#include <string>
47 48 49
#include "util.h"
TEST_INIT
EXPECT_DEATH_INIT
50

51 52
// I don't actually use this header file, but #include it under the
// old location to make sure that the include-header-forwarding
53 54
// works.  But don't bother on windows; the windows port is so new
// it never had the old location-names.
55
#ifndef _MSC_VER
56 57
#include <gflags/gflags_completions.h>
void (*unused_fn)() = &GFLAGS_NAMESPACE::HandleCommandLineCompletions;
58
#endif
Craig Silverstein's avatar
Craig Silverstein committed
59

60 61
using std::string;
using std::vector;
62 63 64 65 66 67
using GFLAGS_NAMESPACE::int32;
using GFLAGS_NAMESPACE::FlagRegisterer;
using GFLAGS_NAMESPACE::StringFromEnv;
using GFLAGS_NAMESPACE::RegisterFlagValidator;
using GFLAGS_NAMESPACE::CommandLineFlagInfo;
using GFLAGS_NAMESPACE::GetAllFlags;
Craig Silverstein's avatar
Craig Silverstein committed
68

69 70
DEFINE_string(test_tmpdir, "", "Dir we use for temp files");
DEFINE_string(srcdir, StringFromEnv("SRCDIR", "."), "Source-dir root, needed to find gflags_unittest_flagfile");
Craig Silverstein's avatar
Craig Silverstein committed
71

72 73
DECLARE_string(tryfromenv);   // in gflags.cc

Craig Silverstein's avatar
Craig Silverstein committed
74
DEFINE_bool(test_bool, false, "tests bool-ness");
Craig Silverstein's avatar
Craig Silverstein committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
DEFINE_int32(test_int32, -1, "");
DEFINE_int64(test_int64, -2, "");
DEFINE_uint64(test_uint64, 2, "");
DEFINE_double(test_double, -1.0, "");
DEFINE_string(test_string, "initial", "");

//
// The below ugliness gets some additional code coverage in the -helpxml
// and -helpmatch test cases having to do with string lengths and formatting
//
DEFINE_bool(test_bool_with_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_quite_long_name,
            false,
            "extremely_extremely_extremely_extremely_extremely_extremely_extremely_extremely_long_meaning");

DEFINE_string(test_str1, "initial", "");
DEFINE_string(test_str2, "initial", "");
DEFINE_string(test_str3, "initial", "");

// This is used to test setting tryfromenv manually
DEFINE_string(test_tryfromenv, "initial", "");

96 97 98 99 100 101 102 103
// Don't try this at home!
static int changeable_var = 12;
DEFINE_int32(changeable_var, ++changeable_var, "");

static int changeable_bool_var = 8008;
DEFINE_bool(changeable_bool_var, ++changeable_bool_var == 8009, "");

static int changeable_string_var = 0;
104
static string ChangeableString() {
105
  char r[] = {static_cast<char>('0' + ++changeable_string_var), '\0'};
106 107 108 109
  return r;
}
DEFINE_string(changeable_string_var, ChangeableString(), "");

Craig Silverstein's avatar
Craig Silverstein committed
110
// These are never used in this unittest, but can be used by
111 112
// gflags_unittest.sh when it needs to specify flags
// that are legal for gflags_unittest but don't need to
Craig Silverstein's avatar
Craig Silverstein committed
113 114 115 116 117 118 119 120
// be a particular value.
DEFINE_bool(unused_bool, true, "unused bool-ness");
DEFINE_int32(unused_int32, -1001, "");
DEFINE_int64(unused_int64, -2001, "");
DEFINE_uint64(unused_uint64, 2000, "");
DEFINE_double(unused_double, -1000.0, "");
DEFINE_string(unused_string, "unused", "");

121 122 123
// These flags are used by gflags_unittest.sh
DEFINE_bool(changed_bool1, false, "changed");
DEFINE_bool(changed_bool2, false, "changed");
Craig Silverstein's avatar
Craig Silverstein committed
124 125 126 127 128 129 130 131 132 133 134 135 136
DEFINE_bool(long_helpstring, false,
            "This helpstring goes on forever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever and ever and ever and ever and ever and ever and ever and "
            "ever.  This is the end of a long helpstring");

137

138 139
static bool AlwaysFail(const char* flag, bool value) { return value == false; }
DEFINE_bool(always_fail, false, "will fail to validate when you set it");
140
DEFINE_validator(always_fail, AlwaysFail);
141

142
// See the comment by GetAllFlags in gflags.h
143 144 145 146
static bool DeadlockIfCantLockInValidators(const char* flag, bool value) {
  if (!value) {
    return true;
  }
147
  vector<CommandLineFlagInfo> dummy;
148 149 150 151 152 153 154
  GetAllFlags(&dummy);
  return true;
}
DEFINE_bool(deadlock_if_cant_lock,
            false,
            "will deadlock if set to true and "
            "if locking of registry in validators fails.");
155
DEFINE_validator(deadlock_if_cant_lock, DeadlockIfCantLockInValidators);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

#define MAKEFLAG(x) DEFINE_int32(test_flag_num##x, x, "Test flag")

// Define 10 flags
#define MAKEFLAG10(x)                           \
  MAKEFLAG(x##0);                               \
  MAKEFLAG(x##1);                               \
  MAKEFLAG(x##2);                               \
  MAKEFLAG(x##3);                               \
  MAKEFLAG(x##4);                               \
  MAKEFLAG(x##5);                               \
  MAKEFLAG(x##6);                               \
  MAKEFLAG(x##7);                               \
  MAKEFLAG(x##8);                               \
  MAKEFLAG(x##9)

// Define 100 flags
#define MAKEFLAG100(x)                          \
  MAKEFLAG10(x##0);                             \
  MAKEFLAG10(x##1);                             \
  MAKEFLAG10(x##2);                             \
  MAKEFLAG10(x##3);                             \
  MAKEFLAG10(x##4);                             \
  MAKEFLAG10(x##5);                             \
  MAKEFLAG10(x##6);                             \
  MAKEFLAG10(x##7);                             \
  MAKEFLAG10(x##8);                             \
  MAKEFLAG10(x##9)

// Define a bunch of command-line flags.  Each occurrence of the MAKEFLAG100
// macro defines 100 integer flags.  This lets us test the effect of having
// many flags on startup time.
MAKEFLAG100(1);
MAKEFLAG100(2);
MAKEFLAG100(3);
MAKEFLAG100(4);
MAKEFLAG100(5);
MAKEFLAG100(6);
MAKEFLAG100(7);
MAKEFLAG100(8);
MAKEFLAG100(9);
MAKEFLAG100(10);
MAKEFLAG100(11);
MAKEFLAG100(12);
MAKEFLAG100(13);
MAKEFLAG100(14);
MAKEFLAG100(15);

#undef MAKEFLAG100
#undef MAKEFLAG10
#undef MAKEFLAG
207

208
// This is a pseudo-flag -- we want to register a flag with a filename
209 210 211 212 213 214 215 216 217
// at the top level, but there is no way to do this except by faking
// the filename.
namespace fLI {
  static const int32 FLAGS_nonotldflag1 = 12;
  int32 FLAGS_tldflag1 = FLAGS_nonotldflag1;
  int32 FLAGS_notldflag1 = FLAGS_nonotldflag1;
  static FlagRegisterer o_tldflag1(
    "tldflag1", "int32",
    "should show up in --helpshort", "gflags_unittest.cc",
Craig Silverstein's avatar
Craig Silverstein committed
218
    &FLAGS_tldflag1, &FLAGS_notldflag1);
219 220 221 222 223 224 225 226 227 228
}
using fLI::FLAGS_tldflag1;

namespace fLI {
  static const int32 FLAGS_nonotldflag2 = 23;
  int32 FLAGS_tldflag2 = FLAGS_nonotldflag2;
  int32 FLAGS_notldflag2 = FLAGS_nonotldflag2;
  static FlagRegisterer o_tldflag2(
    "tldflag2", "int32",
    "should show up in --helpshort", "gflags_unittest.",
Craig Silverstein's avatar
Craig Silverstein committed
229
    &FLAGS_tldflag2, &FLAGS_notldflag2);
230 231 232
}
using fLI::FLAGS_tldflag2;

233
namespace GFLAGS_NAMESPACE {
Craig Silverstein's avatar
Craig Silverstein committed
234

235
namespace {
Craig Silverstein's avatar
Craig Silverstein committed
236 237


238 239 240 241 242 243 244 245 246
static string TmpFile(const string& basename) {
#ifdef _MSC_VER
  return FLAGS_test_tmpdir + "\\" + basename;
#else
  return FLAGS_test_tmpdir + "/" + basename;
#endif
}

// Returns the definition of the --flagfile flag to be used in the tests.
247
// Must be called after ParseCommandLineFlags().
248 249
static const char* GetFlagFileFlag() {
#ifdef _MSC_VER
250
  static const string flagfile = FLAGS_srcdir + "\\gflags_unittest_flagfile";
251
#else
252
  static const string flagfile = FLAGS_srcdir + "/gflags_unittest_flagfile";
253 254 255 256 257 258
#endif
  static const string flagfile_flag = string("--flagfile=") + flagfile;
  return flagfile_flag.c_str();
}


259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
// compiler error iff T1 and T2 are different types.
template <typename T1, typename T2>
struct CompileAssertTypesEqual;

template <typename T>
struct CompileAssertTypesEqual<T, T> {
};


template <typename Expected, typename Actual>
void AssertIsType(Actual& x) {
  CompileAssertTypesEqual<Expected, Actual>();
}

// Verify all the flags are the right type.
TEST(FlagTypes, FlagTypes) {
  AssertIsType<bool>(FLAGS_test_bool);
  AssertIsType<int32>(FLAGS_test_int32);
  AssertIsType<int64>(FLAGS_test_int64);
  AssertIsType<uint64>(FLAGS_test_uint64);
  AssertIsType<double>(FLAGS_test_double);
  AssertIsType<string>(FLAGS_test_string);
}

284
#ifdef GTEST_HAS_DEATH_TEST
Craig Silverstein's avatar
Craig Silverstein committed
285 286
// Death tests for "help" options.
//
287
// The help system automatically calls gflags_exitfunc(1) when you specify any of
Craig Silverstein's avatar
Craig Silverstein committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
// the help-related flags ("-helpmatch", "-helpxml") so we can't test
// those mainline.

// Tests that "-helpmatch" causes the process to die.
TEST(ReadFlagsFromStringDeathTest, HelpMatch) {
  EXPECT_DEATH(ReadFlagsFromString("-helpmatch=base", GetArgv0(), true),
               "");
}


// Tests that "-helpxml" causes the process to die.
TEST(ReadFlagsFromStringDeathTest, HelpXml) {
  EXPECT_DEATH(ReadFlagsFromString("-helpxml", GetArgv0(), true),
               "");
}
303
#endif
Craig Silverstein's avatar
Craig Silverstein committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410


// A subroutine needed for testing reading flags from a string.
void TestFlagString(const string& flags,
                    const string& expected_string,
                    bool expected_bool,
                    int32 expected_int32,
                    double expected_double) {
  EXPECT_TRUE(ReadFlagsFromString(flags,
                                  GetArgv0(),
                                  // errors are fatal
                                  true));

  EXPECT_EQ(expected_string, FLAGS_test_string);
  EXPECT_EQ(expected_bool, FLAGS_test_bool);
  EXPECT_EQ(expected_int32, FLAGS_test_int32);
  EXPECT_DOUBLE_EQ(expected_double, FLAGS_test_double);
}


// Tests reading flags from a string.
TEST(FlagFileTest, ReadFlagsFromString) {
  TestFlagString(
      // Flag string
      "-test_string=continued\n"
      "# some comments are in order\n"
      "# some\n"
      "  # comments\n"
      "#are\n"
      "                  #trickier\n"
      "# than others\n"
      "-test_bool=true\n"
      "     -test_int32=1\n"
      "-test_double=0.0\n",
      // Expected values
      "continued",
      true,
      1,
      0.0);

  TestFlagString(
      // Flag string
      "# let's make sure it can update values\n"
      "-test_string=initial\n"
      "-test_bool=false\n"
      "-test_int32=123\n"
      "-test_double=123.0\n",
      // Expected values
      "initial",
      false,
      123,
      123.0);
}

// Tests the filename part of the flagfile
TEST(FlagFileTest, FilenamesOurfileLast) {
  FLAGS_test_string = "initial";
  FLAGS_test_bool = false;
  FLAGS_test_int32 = -1;
  FLAGS_test_double = -1.0;
  TestFlagString(
      // Flag string
      "-test_string=continued\n"
      "# some comments are in order\n"
      "# some\n"
      "  # comments\n"
      "#are\n"
      "                  #trickier\n"
      "# than others\n"
      "not_our_filename\n"
      "-test_bool=true\n"
      "     -test_int32=1\n"
      "gflags_unittest\n"
      "-test_double=1000.0\n",
      // Expected values
      "continued",
      false,
      -1,
      1000.0);
}

TEST(FlagFileTest, FilenamesOurfileFirst) {
  FLAGS_test_string = "initial";
  FLAGS_test_bool = false;
  FLAGS_test_int32 = -1;
  FLAGS_test_double = -1.0;
  TestFlagString(
      // Flag string
      "-test_string=continued\n"
      "# some comments are in order\n"
      "# some\n"
      "  # comments\n"
      "#are\n"
      "                  #trickier\n"
      "# than others\n"
      "gflags_unittest\n"
      "-test_bool=true\n"
      "     -test_int32=1\n"
      "not_our_filename\n"
      "-test_double=1000.0\n",
      // Expected values
      "continued",
      true,
      1,
      -1.0);
}

411
#if HAVE_FNMATCH_H  // otherwise glob isn't supported
Craig Silverstein's avatar
Craig Silverstein committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
TEST(FlagFileTest, FilenamesOurfileGlob) {
  FLAGS_test_string = "initial";
  FLAGS_test_bool = false;
  FLAGS_test_int32 = -1;
  FLAGS_test_double = -1.0;
  TestFlagString(
      // Flag string
      "-test_string=continued\n"
      "# some comments are in order\n"
      "# some\n"
      "  # comments\n"
      "#are\n"
      "                  #trickier\n"
      "# than others\n"
      "*flags*\n"
      "-test_bool=true\n"
      "     -test_int32=1\n"
      "flags\n"
      "-test_double=1000.0\n",
      // Expected values
      "continued",
      true,
      1,
      -1.0);
}

TEST(FlagFileTest, FilenamesOurfileInBigList) {
  FLAGS_test_string = "initial";
  FLAGS_test_bool = false;
  FLAGS_test_int32 = -1;
  FLAGS_test_double = -1.0;
  TestFlagString(
      // Flag string
      "-test_string=continued\n"
      "# some comments are in order\n"
      "# some\n"
      "  # comments\n"
      "#are\n"
      "                  #trickier\n"
      "# than others\n"
      "*first* *flags* *third*\n"
      "-test_bool=true\n"
      "     -test_int32=1\n"
      "flags\n"
      "-test_double=1000.0\n",
      // Expected values
      "continued",
      true,
      1,
      -1.0);
}
463
#endif  // ifdef HAVE_FNMATCH_H
Craig Silverstein's avatar
Craig Silverstein committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

// Tests that a failed flag-from-string read keeps flags at default values
TEST(FlagFileTest, FailReadFlagsFromString) {
  FLAGS_test_int32 = 119;
  string flags("# let's make sure it can update values\n"
               "-test_string=non_initial\n"
               "-test_bool=false\n"
               "-test_int32=123\n"
               "-test_double=illegal\n");

  EXPECT_FALSE(ReadFlagsFromString(flags,
                                   GetArgv0(),
                                   // errors are fatal
                                   false));

  EXPECT_EQ(119, FLAGS_test_int32);
  EXPECT_EQ("initial", FLAGS_test_string);
}

// Tests that flags can be set to ordinary values.
TEST(SetFlagValueTest, OrdinaryValues) {
  EXPECT_EQ("initial", FLAGS_test_str1);

  SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str1);  // set; was default

  SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str1);  // already set once

  FLAGS_test_str1 = "initial";
  SetCommandLineOptionWithMode("test_str1", "third", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("initial", FLAGS_test_str1);  // still already set before

  SetCommandLineOptionWithMode("test_str1", "third", SET_FLAGS_VALUE);
  EXPECT_EQ("third", FLAGS_test_str1);  // changed value

  SetCommandLineOptionWithMode("test_str1", "fourth", SET_FLAGS_DEFAULT);
  EXPECT_EQ("third", FLAGS_test_str1);
  // value not changed (already set before)

  EXPECT_EQ("initial", FLAGS_test_str2);

  SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str2);  // changed (was default)

  FLAGS_test_str2 = "extra";
  EXPECT_EQ("extra", FLAGS_test_str2);

  FLAGS_test_str2 = "second";
  SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT);
  EXPECT_EQ("third", FLAGS_test_str2);  // still changed (was equal to default)

  SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("fourth", FLAGS_test_str2);  // changed (was default)

  EXPECT_EQ("initial", FLAGS_test_str3);

  SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str3);  // changed

  FLAGS_test_str3 = "third";
  SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_DEFAULT);
  EXPECT_EQ("third", FLAGS_test_str3);  // not changed (was set)

  SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("third", FLAGS_test_str3);  // not changed (was set)

  SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAGS_VALUE);
  EXPECT_EQ("fourth", FLAGS_test_str3);  // changed value
}


// Tests that flags can be set to exceptional values.
537 538 539
// Note: apparently MINGW doesn't parse inf and nan correctly:
//    http://www.mail-archive.com/bug-gnulib@gnu.org/msg09573.html
// This url says FreeBSD also has a problem, but I didn't see that.
Craig Silverstein's avatar
Craig Silverstein committed
540
TEST(SetFlagValueTest, ExceptionalValues) {
541
#if defined(isinf) && !defined(__MINGW32__)
Craig Silverstein's avatar
Craig Silverstein committed
542 543
  EXPECT_EQ("test_double set to inf\n",
            SetCommandLineOption("test_double", "inf"));
544
  EXPECT_INF(FLAGS_test_double);
Craig Silverstein's avatar
Craig Silverstein committed
545 546 547

  EXPECT_EQ("test_double set to inf\n",
            SetCommandLineOption("test_double", "INF"));
548
  EXPECT_INF(FLAGS_test_double);
549
#endif
Craig Silverstein's avatar
Craig Silverstein committed
550 551 552 553 554 555 556 557

  // set some bad values
  EXPECT_EQ("",
            SetCommandLineOption("test_double", "0.1xxx"));
  EXPECT_EQ("",
            SetCommandLineOption("test_double", " "));
  EXPECT_EQ("",
            SetCommandLineOption("test_double", ""));
558
#if defined(isinf) && !defined(__MINGW32__)
Craig Silverstein's avatar
Craig Silverstein committed
559 560
  EXPECT_EQ("test_double set to -inf\n",
            SetCommandLineOption("test_double", "-inf"));
561
  EXPECT_INF(FLAGS_test_double);
Craig Silverstein's avatar
Craig Silverstein committed
562
  EXPECT_GT(0, FLAGS_test_double);
563
#endif
Craig Silverstein's avatar
Craig Silverstein committed
564

565
#if defined(isnan) && !defined(__MINGW32__)
Craig Silverstein's avatar
Craig Silverstein committed
566 567
  EXPECT_EQ("test_double set to nan\n",
            SetCommandLineOption("test_double", "NaN"));
568
  EXPECT_NAN(FLAGS_test_double);
569
#endif
Craig Silverstein's avatar
Craig Silverstein committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
}

// Tests that integer flags can be specified in many ways
TEST(SetFlagValueTest, DifferentRadices) {
  EXPECT_EQ("test_int32 set to 12\n",
            SetCommandLineOption("test_int32", "12"));

  EXPECT_EQ("test_int32 set to 16\n",
            SetCommandLineOption("test_int32", "0x10"));

  EXPECT_EQ("test_int32 set to 34\n",
            SetCommandLineOption("test_int32", "0X22"));

  // Leading 0 is *not* octal; it's still decimal
  EXPECT_EQ("test_int32 set to 10\n",
            SetCommandLineOption("test_int32", "010"));
}

// Tests what happens when you try to set a flag to an illegal value
TEST(SetFlagValueTest, IllegalValues) {
  FLAGS_test_bool = true;
  FLAGS_test_int32 = 119;
  FLAGS_test_int64 = 1191;
  FLAGS_test_uint64 = 11911;

  EXPECT_EQ("",
            SetCommandLineOption("test_bool", "12"));

  EXPECT_EQ("",
            SetCommandLineOption("test_int32", "7000000000000"));

  EXPECT_EQ("",
            SetCommandLineOption("test_uint64", "-1"));

  EXPECT_EQ("",
            SetCommandLineOption("test_int64", "not a number!"));

  // Test the empty string with each type of input
  EXPECT_EQ("", SetCommandLineOption("test_bool", ""));
  EXPECT_EQ("", SetCommandLineOption("test_int32", ""));
  EXPECT_EQ("", SetCommandLineOption("test_int64", ""));
  EXPECT_EQ("", SetCommandLineOption("test_uint64", ""));
  EXPECT_EQ("", SetCommandLineOption("test_double", ""));
  EXPECT_EQ("test_string set to \n", SetCommandLineOption("test_string", ""));

615
  EXPECT_TRUE(FLAGS_test_bool);
Craig Silverstein's avatar
Craig Silverstein committed
616 617 618 619 620 621
  EXPECT_EQ(119, FLAGS_test_int32);
  EXPECT_EQ(1191, FLAGS_test_int64);
  EXPECT_EQ(11911, FLAGS_test_uint64);
}


622 623 624 625 626 627 628 629 630 631 632 633 634
// Tests that we only evaluate macro args once
TEST(MacroArgs, EvaluateOnce) {
  EXPECT_EQ(13, FLAGS_changeable_var);
  // Make sure we don't ++ the value somehow, when evaluating the flag.
  EXPECT_EQ(13, FLAGS_changeable_var);
  // Make sure the macro only evaluated this var once.
  EXPECT_EQ(13, changeable_var);
  // Make sure the actual value and default value are the same
  SetCommandLineOptionWithMode("changeable_var", "21", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ(21, FLAGS_changeable_var);
}

TEST(MacroArgs, EvaluateOnceBool) {
635 636
  EXPECT_TRUE(FLAGS_changeable_bool_var);
  EXPECT_TRUE(FLAGS_changeable_bool_var);
637 638 639
  EXPECT_EQ(8009, changeable_bool_var);
  SetCommandLineOptionWithMode("changeable_bool_var", "false",
                               SET_FLAG_IF_DEFAULT);
640
  EXPECT_FALSE(FLAGS_changeable_bool_var);
641 642 643 644 645 646 647 648 649 650 651
}

TEST(MacroArgs, EvaluateOnceStrings) {
  EXPECT_EQ("1", FLAGS_changeable_string_var);
  EXPECT_EQ("1", FLAGS_changeable_string_var);
  EXPECT_EQ(1, changeable_string_var);
  SetCommandLineOptionWithMode("changeable_string_var", "different",
                               SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("different", FLAGS_changeable_string_var);
}

Craig Silverstein's avatar
Craig Silverstein committed
652 653 654 655 656 657
// Tests that the FooFromEnv does the right thing
TEST(FromEnvTest, LegalValues) {
  setenv("BOOL_VAL1", "true", 1);
  setenv("BOOL_VAL2", "false", 1);
  setenv("BOOL_VAL3", "1", 1);
  setenv("BOOL_VAL4", "F", 1);
658 659 660 661 662 663
  EXPECT_TRUE(BoolFromEnv("BOOL_VAL1", false));
  EXPECT_FALSE(BoolFromEnv("BOOL_VAL2", true));
  EXPECT_TRUE(BoolFromEnv("BOOL_VAL3", false));
  EXPECT_FALSE(BoolFromEnv("BOOL_VAL4", true));
  EXPECT_TRUE(BoolFromEnv("BOOL_VAL_UNKNOWN", true));
  EXPECT_FALSE(BoolFromEnv("BOOL_VAL_UNKNOWN", false));
Craig Silverstein's avatar
Craig Silverstein committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696

  setenv("INT_VAL1", "1", 1);
  setenv("INT_VAL2", "-1", 1);
  EXPECT_EQ(1, Int32FromEnv("INT_VAL1", 10));
  EXPECT_EQ(-1, Int32FromEnv("INT_VAL2", 10));
  EXPECT_EQ(10, Int32FromEnv("INT_VAL_UNKNOWN", 10));

  setenv("INT_VAL3", "1099511627776", 1);
  EXPECT_EQ(1, Int64FromEnv("INT_VAL1", 20));
  EXPECT_EQ(-1, Int64FromEnv("INT_VAL2", 20));
  EXPECT_EQ(1099511627776LL, Int64FromEnv("INT_VAL3", 20));
  EXPECT_EQ(20, Int64FromEnv("INT_VAL_UNKNOWN", 20));

  EXPECT_EQ(1, Uint64FromEnv("INT_VAL1", 30));
  EXPECT_EQ(1099511627776ULL, Uint64FromEnv("INT_VAL3", 30));
  EXPECT_EQ(30, Uint64FromEnv("INT_VAL_UNKNOWN", 30));

  // I pick values here that can be easily represented exactly in floating-point
  setenv("DOUBLE_VAL1", "0.0", 1);
  setenv("DOUBLE_VAL2", "1.0", 1);
  setenv("DOUBLE_VAL3", "-1.0", 1);
  EXPECT_EQ(0.0, DoubleFromEnv("DOUBLE_VAL1", 40.0));
  EXPECT_EQ(1.0, DoubleFromEnv("DOUBLE_VAL2", 40.0));
  EXPECT_EQ(-1.0, DoubleFromEnv("DOUBLE_VAL3", 40.0));
  EXPECT_EQ(40.0, DoubleFromEnv("DOUBLE_VAL_UNKNOWN", 40.0));

  setenv("STRING_VAL1", "", 1);
  setenv("STRING_VAL2", "my happy string!", 1);
  EXPECT_STREQ("", StringFromEnv("STRING_VAL1", "unknown"));
  EXPECT_STREQ("my happy string!", StringFromEnv("STRING_VAL2", "unknown"));
  EXPECT_STREQ("unknown", StringFromEnv("STRING_VAL_UNKNOWN", "unknown"));
}

697
#ifdef GTEST_HAS_DEATH_TEST
Craig Silverstein's avatar
Craig Silverstein committed
698
// Tests that the FooFromEnv dies on parse-error
699
TEST(FromEnvDeathTest, IllegalValues) {
700
  setenv("BOOL_BAD1", "so true!", 1);
Craig Silverstein's avatar
Craig Silverstein committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
  setenv("BOOL_BAD2", "", 1);
  EXPECT_DEATH(BoolFromEnv("BOOL_BAD1", false), "error parsing env variable");
  EXPECT_DEATH(BoolFromEnv("BOOL_BAD2", true), "error parsing env variable");

  setenv("INT_BAD1", "one", 1);
  setenv("INT_BAD2", "100000000000000000", 1);
  setenv("INT_BAD3", "0xx10", 1);
  setenv("INT_BAD4", "", 1);
  EXPECT_DEATH(Int32FromEnv("INT_BAD1", 10), "error parsing env variable");
  EXPECT_DEATH(Int32FromEnv("INT_BAD2", 10), "error parsing env variable");
  EXPECT_DEATH(Int32FromEnv("INT_BAD3", 10), "error parsing env variable");
  EXPECT_DEATH(Int32FromEnv("INT_BAD4", 10), "error parsing env variable");

  setenv("BIGINT_BAD1", "18446744073709551616000", 1);
  EXPECT_DEATH(Int64FromEnv("INT_BAD1", 20), "error parsing env variable");
  EXPECT_DEATH(Int64FromEnv("INT_BAD3", 20), "error parsing env variable");
  EXPECT_DEATH(Int64FromEnv("INT_BAD4", 20), "error parsing env variable");
  EXPECT_DEATH(Int64FromEnv("BIGINT_BAD1", 200), "error parsing env variable");

  setenv("BIGINT_BAD2", "-1", 1);
  EXPECT_DEATH(Uint64FromEnv("INT_BAD1", 30), "error parsing env variable");
  EXPECT_DEATH(Uint64FromEnv("INT_BAD3", 30), "error parsing env variable");
  EXPECT_DEATH(Uint64FromEnv("INT_BAD4", 30), "error parsing env variable");
  EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD1", 30), "error parsing env variable");
  // TODO(csilvers): uncomment this when we disallow negative numbers for uint64
#if 0
  EXPECT_DEATH(Uint64FromEnv("BIGINT_BAD2", 30), "error parsing env variable");
#endif

  setenv("DOUBLE_BAD1", "0.0.0", 1);
  setenv("DOUBLE_BAD2", "", 1);
  EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD1", 40.0), "error parsing env variable");
  EXPECT_DEATH(DoubleFromEnv("DOUBLE_BAD2", 40.0), "error parsing env variable");
}
735 736
#endif

Craig Silverstein's avatar
Craig Silverstein committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

// Tests that FlagSaver can save the states of string flags.
TEST(FlagSaverTest, CanSaveStringFlagStates) {
  // 1. Initializes the flags.

  // State of flag test_str1:
  //   default value - "initial"
  //   current value - "initial"
  //   not set       - true

  SetCommandLineOptionWithMode("test_str2", "second", SET_FLAGS_VALUE);
  // State of flag test_str2:
  //   default value - "initial"
  //   current value - "second"
  //   not set       - false

  SetCommandLineOptionWithMode("test_str3", "second", SET_FLAGS_DEFAULT);
  // State of flag test_str3:
  //   default value - "second"
  //   current value - "second"
  //   not set       - true

  // 2. Saves the flag states.

  {
    FlagSaver fs;

    // 3. Modifies the flag states.

    SetCommandLineOptionWithMode("test_str1", "second", SET_FLAGS_VALUE);
    EXPECT_EQ("second", FLAGS_test_str1);
    // State of flag test_str1:
    //   default value - "second"
    //   current value - "second"
    //   not set       - true

    SetCommandLineOptionWithMode("test_str2", "third", SET_FLAGS_DEFAULT);
    EXPECT_EQ("second", FLAGS_test_str2);
    // State of flag test_str2:
    //   default value - "third"
    //   current value - "second"
    //   not set       - false

    SetCommandLineOptionWithMode("test_str3", "third", SET_FLAGS_VALUE);
    EXPECT_EQ("third", FLAGS_test_str3);
    // State of flag test_str1:
    //   default value - "second"
    //   current value - "third"
    //   not set       - false

    // 4. Restores the flag states.
  }

  // 5. Verifies that the states were restored.

  // Verifies that the value of test_str1 was restored.
  EXPECT_EQ("initial", FLAGS_test_str1);
  // Verifies that the "not set" attribute of test_str1 was restored to true.
  SetCommandLineOptionWithMode("test_str1", "second", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str1);

  // Verifies that the value of test_str2 was restored.
  EXPECT_EQ("second", FLAGS_test_str2);
  // Verifies that the "not set" attribute of test_str2 was restored to false.
  SetCommandLineOptionWithMode("test_str2", "fourth", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("second", FLAGS_test_str2);

  // Verifies that the value of test_str3 was restored.
  EXPECT_EQ("second", FLAGS_test_str3);
  // Verifies that the "not set" attribute of test_str3 was restored to true.
  SetCommandLineOptionWithMode("test_str3", "fourth", SET_FLAG_IF_DEFAULT);
  EXPECT_EQ("fourth", FLAGS_test_str3);
}


// Tests that FlagSaver can save the values of various-typed flags.
TEST(FlagSaverTest, CanSaveVariousTypedFlagValues) {
  // Initializes the flags.
  FLAGS_test_bool = false;
  FLAGS_test_int32 = -1;
  FLAGS_test_int64 = -2;
  FLAGS_test_uint64 = 3;
  FLAGS_test_double = 4.0;
  FLAGS_test_string = "good";

  // Saves the flag states.
  {
    FlagSaver fs;

    // Modifies the flags.
    FLAGS_test_bool = true;
    FLAGS_test_int32 = -5;
    FLAGS_test_int64 = -6;
    FLAGS_test_uint64 = 7;
    FLAGS_test_double = 8.0;
    FLAGS_test_string = "bad";

    // Restores the flag states.
  }

  // Verifies the flag values were restored.
  EXPECT_FALSE(FLAGS_test_bool);
  EXPECT_EQ(-1, FLAGS_test_int32);
  EXPECT_EQ(-2, FLAGS_test_int64);
  EXPECT_EQ(3, FLAGS_test_uint64);
  EXPECT_DOUBLE_EQ(4.0, FLAGS_test_double);
  EXPECT_EQ("good", FLAGS_test_string);
}

TEST(GetAllFlagsTest, BaseTest) {
  vector<CommandLineFlagInfo> flags;
  GetAllFlags(&flags);
  bool found_test_bool = false;
  vector<CommandLineFlagInfo>::const_iterator i;
  for (i = flags.begin(); i != flags.end(); ++i) {
    if (i->name == "test_bool") {
      found_test_bool = true;
      EXPECT_EQ(i->type, "bool");
      EXPECT_EQ(i->default_value, "false");
Craig Silverstein's avatar
Craig Silverstein committed
856
      EXPECT_EQ(i->flag_ptr, &FLAGS_test_bool);
Craig Silverstein's avatar
Craig Silverstein committed
857 858 859
      break;
    }
  }
860
  EXPECT_TRUE(found_test_bool);
Craig Silverstein's avatar
Craig Silverstein committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
}

TEST(ShowUsageWithFlagsTest, BaseTest) {
  // TODO(csilvers): test this by allowing output other than to stdout.
  // Not urgent since this functionality is tested via
  // gflags_unittest.sh, though only through use of --help.
}

TEST(ShowUsageWithFlagsRestrictTest, BaseTest) {
  // TODO(csilvers): test this by allowing output other than to stdout.
  // Not urgent since this functionality is tested via
  // gflags_unittest.sh, though only through use of --helpmatch.
}

// Note: all these argv-based tests depend on SetArgv being called
876
// before ParseCommandLineFlags() in main(), below.
Craig Silverstein's avatar
Craig Silverstein committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
TEST(GetArgvsTest, BaseTest) {
  vector<string> argvs = GetArgvs();
  EXPECT_EQ(4, argvs.size());
  EXPECT_EQ("/test/argv/for/gflags_unittest", argvs[0]);
  EXPECT_EQ("argv 2", argvs[1]);
  EXPECT_EQ("3rd argv", argvs[2]);
  EXPECT_EQ("argv #4", argvs[3]);
}

TEST(GetArgvTest, BaseTest) {
  EXPECT_STREQ("/test/argv/for/gflags_unittest "
               "argv 2 3rd argv argv #4", GetArgv());
}

TEST(GetArgv0Test, BaseTest) {
  EXPECT_STREQ("/test/argv/for/gflags_unittest", GetArgv0());
}

TEST(GetArgvSumTest, BaseTest) {
  // This number is just the sum of the ASCII values of all the chars
  // in GetArgv().
  EXPECT_EQ(4904, GetArgvSum());
}

TEST(ProgramInvocationNameTest, BaseTest) {
  EXPECT_STREQ("/test/argv/for/gflags_unittest",
               ProgramInvocationName());
}

TEST(ProgramInvocationShortNameTest, BaseTest) {
  EXPECT_STREQ("gflags_unittest", ProgramInvocationShortName());
}

910
TEST(ProgramUsageTest, BaseTest) {  // Depends on 1st arg to ParseCommandLineFlags()
Craig Silverstein's avatar
Craig Silverstein committed
911 912 913 914 915 916 917
  EXPECT_STREQ("/test/argv/for/gflags_unittest: "
               "<useless flag> [...]\nDoes something useless.\n",
               ProgramUsage());
}

TEST(GetCommandLineOptionTest, NameExistsAndIsDefault) {
  string value("will be changed");
918
  bool r = GetCommandLineOption("test_bool", &value);
919
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
920 921
  EXPECT_EQ("false", value);

922
  r = GetCommandLineOption("test_int32", &value);
923
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
924 925 926 927 928 929
  EXPECT_EQ("-1", value);
}

TEST(GetCommandLineOptionTest, NameExistsAndWasAssigned) {
  FLAGS_test_int32 = 400;
  string value("will be changed");
930
  const bool r = GetCommandLineOption("test_int32", &value);
931
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
932 933 934 935 936 937
  EXPECT_EQ("400", value);
}

TEST(GetCommandLineOptionTest, NameExistsAndWasSet) {
  SetCommandLineOption("test_int32", "700");
  string value("will be changed");
938
  const bool r = GetCommandLineOption("test_int32", &value);
939
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
940 941 942 943 944 945 946 947
  EXPECT_EQ("700", value);
}

TEST(GetCommandLineOptionTest, NameExistsAndWasNotSet) {
  // This doesn't set the flag's value, but rather its default value.
  // is_default is still true, but the 'default' value returned has changed!
  SetCommandLineOptionWithMode("test_int32", "800", SET_FLAGS_DEFAULT);
  string value("will be changed");
948
  const bool r = GetCommandLineOption("test_int32", &value);
949
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
950
  EXPECT_EQ("800", value);
951
  EXPECT_TRUE(GetCommandLineFlagInfoOrDie("test_int32").is_default);
Craig Silverstein's avatar
Craig Silverstein committed
952 953 954 955 956
}

TEST(GetCommandLineOptionTest, NameExistsAndWasConditionallySet) {
  SetCommandLineOptionWithMode("test_int32", "900", SET_FLAG_IF_DEFAULT);
  string value("will be changed");
957
  const bool r = GetCommandLineOption("test_int32", &value);
958
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
959 960 961 962 963
  EXPECT_EQ("900", value);
}

TEST(GetCommandLineOptionTest, NameDoesNotExist) {
  string value("will not be changed");
964
  const bool r = GetCommandLineOption("test_int3210", &value);
965
  EXPECT_FALSE(r);
Craig Silverstein's avatar
Craig Silverstein committed
966 967 968 969 970 971
  EXPECT_EQ("will not be changed", value);
}

TEST(GetCommandLineFlagInfoTest, FlagExists) {
  CommandLineFlagInfo info;
  bool r = GetCommandLineFlagInfo("test_int32", &info);
972
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
973 974 975
  EXPECT_EQ("test_int32", info.name);
  EXPECT_EQ("int32", info.type);
  EXPECT_EQ("", info.description);
976
  EXPECT_EQ("-1", info.current_value);
Craig Silverstein's avatar
Craig Silverstein committed
977
  EXPECT_EQ("-1", info.default_value);
978 979
  EXPECT_TRUE(info.is_default);
  EXPECT_FALSE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
980
  EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
981 982

  FLAGS_test_bool = true;
Craig Silverstein's avatar
Craig Silverstein committed
983
  r = GetCommandLineFlagInfo("test_bool", &info);
984
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
985 986 987
  EXPECT_EQ("test_bool", info.name);
  EXPECT_EQ("bool", info.type);
  EXPECT_EQ("tests bool-ness", info.description);
988
  EXPECT_EQ("true", info.current_value);
Craig Silverstein's avatar
Craig Silverstein committed
989
  EXPECT_EQ("false", info.default_value);
990 991
  EXPECT_FALSE(info.is_default);
  EXPECT_FALSE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
992
  EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
993 994 995

  FLAGS_test_bool = false;
  r = GetCommandLineFlagInfo("test_bool", &info);
996
  EXPECT_TRUE(r);
997 998 999 1000 1001
  EXPECT_EQ("test_bool", info.name);
  EXPECT_EQ("bool", info.type);
  EXPECT_EQ("tests bool-ness", info.description);
  EXPECT_EQ("false", info.current_value);
  EXPECT_EQ("false", info.default_value);
1002 1003
  EXPECT_FALSE(info.is_default);  // value is same, but flag *was* modified
  EXPECT_FALSE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
1004
  EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
Craig Silverstein's avatar
Craig Silverstein committed
1005 1006 1007 1008
}

TEST(GetCommandLineFlagInfoTest, FlagDoesNotExist) {
  CommandLineFlagInfo info;
1009 1010 1011 1012 1013 1014 1015
  // Set to some random values that GetCommandLineFlagInfo should not change
  info.name = "name";
  info.type = "type";
  info.current_value = "curr";
  info.default_value = "def";
  info.filename = "/";
  info.is_default = false;
1016
  info.has_validator_fn = true;
Craig Silverstein's avatar
Craig Silverstein committed
1017
  info.flag_ptr = NULL;
Craig Silverstein's avatar
Craig Silverstein committed
1018
  bool r = GetCommandLineFlagInfo("test_int3210", &info);
1019
  EXPECT_FALSE(r);
1020 1021 1022 1023 1024 1025
  EXPECT_EQ("name", info.name);
  EXPECT_EQ("type", info.type);
  EXPECT_EQ("", info.description);
  EXPECT_EQ("curr", info.current_value);
  EXPECT_EQ("def", info.default_value);
  EXPECT_EQ("/", info.filename);
1026 1027
  EXPECT_FALSE(info.is_default);
  EXPECT_TRUE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
1028
  EXPECT_EQ(NULL, info.flag_ptr);
Craig Silverstein's avatar
Craig Silverstein committed
1029 1030
}

1031 1032 1033 1034 1035 1036
TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndIsDefault) {
  CommandLineFlagInfo info;
  info = GetCommandLineFlagInfoOrDie("test_int32");
  EXPECT_EQ("test_int32", info.name);
  EXPECT_EQ("int32", info.type);
  EXPECT_EQ("", info.description);
1037
  EXPECT_EQ("-1", info.current_value);
1038
  EXPECT_EQ("-1", info.default_value);
1039
  EXPECT_TRUE(info.is_default);
Craig Silverstein's avatar
Craig Silverstein committed
1040
  EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
1041 1042 1043 1044
  info = GetCommandLineFlagInfoOrDie("test_bool");
  EXPECT_EQ("test_bool", info.name);
  EXPECT_EQ("bool", info.type);
  EXPECT_EQ("tests bool-ness", info.description);
1045
  EXPECT_EQ("false", info.current_value);
1046
  EXPECT_EQ("false", info.default_value);
1047 1048
  EXPECT_TRUE(info.is_default);
  EXPECT_FALSE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
1049
  EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1050 1051 1052 1053 1054 1055 1056 1057 1058
}

TEST(GetCommandLineFlagInfoOrDieTest, FlagExistsAndWasAssigned) {
  FLAGS_test_int32 = 400;
  CommandLineFlagInfo info;
  info = GetCommandLineFlagInfoOrDie("test_int32");
  EXPECT_EQ("test_int32", info.name);
  EXPECT_EQ("int32", info.type);
  EXPECT_EQ("", info.description);
1059
  EXPECT_EQ("400", info.current_value);
1060
  EXPECT_EQ("-1", info.default_value);
1061
  EXPECT_FALSE(info.is_default);
Craig Silverstein's avatar
Craig Silverstein committed
1062
  EXPECT_EQ(&FLAGS_test_int32, info.flag_ptr);
1063 1064 1065 1066 1067
  FLAGS_test_bool = true;
  info = GetCommandLineFlagInfoOrDie("test_bool");
  EXPECT_EQ("test_bool", info.name);
  EXPECT_EQ("bool", info.type);
  EXPECT_EQ("tests bool-ness", info.description);
1068
  EXPECT_EQ("true", info.current_value);
1069
  EXPECT_EQ("false", info.default_value);
1070 1071
  EXPECT_FALSE(info.is_default);
  EXPECT_FALSE(info.has_validator_fn);
Craig Silverstein's avatar
Craig Silverstein committed
1072
  EXPECT_EQ(&FLAGS_test_bool, info.flag_ptr);
1073 1074
}

1075
#ifdef GTEST_HAS_DEATH_TEST
1076
TEST(GetCommandLineFlagInfoOrDieDeathTest, FlagDoesNotExist) {
1077 1078 1079
  EXPECT_DEATH(GetCommandLineFlagInfoOrDie("test_int3210"),
               ".*: flag test_int3210 does not exist");
}
1080
#endif
1081

Craig Silverstein's avatar
Craig Silverstein committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

// These are lightly tested because they're deprecated.  Basically,
// the tests are meant to cover how existing users use these functions,
// but not necessarily how new users could use them.
TEST(DeprecatedFunctionsTest, CommandlineFlagsIntoString) {
  string s = CommandlineFlagsIntoString();
  EXPECT_NE(string::npos, s.find("--test_bool="));
}

TEST(DeprecatedFunctionsTest, AppendFlagsIntoFile) {
  FLAGS_test_int32 = 10;     // just to make the test more interesting
1093
  string filename(TmpFile("flagfile"));
Craig Silverstein's avatar
Craig Silverstein committed
1094 1095
  unlink(filename.c_str());  // just to be safe
  const bool r = AppendFlagsIntoFile(filename, "not the real argv0");
1096
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
1097

1098 1099
  FILE* fp;
  EXPECT_EQ(0, SafeFOpen(&fp, filename.c_str(), "r"));
Craig Silverstein's avatar
Craig Silverstein committed
1100 1101
  EXPECT_TRUE(fp != NULL);
  char line[8192];
1102 1103
  EXPECT_TRUE(fgets(line, sizeof(line)-1, fp) != NULL);  // get the first line
  // First line should be progname.
Craig Silverstein's avatar
Craig Silverstein committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  EXPECT_STREQ("not the real argv0\n", line);

  bool found_bool = false, found_int32 = false;
  while (fgets(line, sizeof(line)-1, fp)) {
    line[sizeof(line)-1] = '\0';    // just to be safe
    if (strcmp(line, "--test_bool=false\n") == 0)
      found_bool = true;
    if (strcmp(line, "--test_int32=10\n") == 0)
      found_int32 = true;
  }
1114 1115
  EXPECT_TRUE(found_int32);
  EXPECT_TRUE(found_bool);
Craig Silverstein's avatar
Craig Silverstein committed
1116 1117 1118 1119 1120
  fclose(fp);
}

TEST(DeprecatedFunctionsTest, ReadFromFlagsFile) {
  FLAGS_test_int32 = -10;    // just to make the test more interesting
1121
  string filename(TmpFile("flagfile2"));
Craig Silverstein's avatar
Craig Silverstein committed
1122 1123
  unlink(filename.c_str());  // just to be safe
  bool r = AppendFlagsIntoFile(filename, GetArgv0());
1124
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
1125 1126 1127

  FLAGS_test_int32 = -11;
  r = ReadFromFlagsFile(filename, GetArgv0(), true);
1128
  EXPECT_TRUE(r);
Craig Silverstein's avatar
Craig Silverstein committed
1129
  EXPECT_EQ(-10, FLAGS_test_int32);
1130
}  // unnamed namespace
Craig Silverstein's avatar
Craig Silverstein committed
1131 1132 1133

TEST(DeprecatedFunctionsTest, ReadFromFlagsFileFailure) {
  FLAGS_test_int32 = -20;
1134
  string filename(TmpFile("flagfile3"));
1135 1136
  FILE* fp;
  EXPECT_EQ(0, SafeFOpen(&fp, filename.c_str(), "w"));
Craig Silverstein's avatar
Craig Silverstein committed
1137 1138 1139 1140 1141 1142 1143
  EXPECT_TRUE(fp != NULL);
  // Note the error in the bool assignment below...
  fprintf(fp, "%s\n--test_int32=-21\n--test_bool=not_a_bool!\n", GetArgv0());
  fclose(fp);

  FLAGS_test_int32 = -22;
  const bool r = ReadFromFlagsFile(filename, GetArgv0(), false);
1144
  EXPECT_FALSE(r);
Craig Silverstein's avatar
Craig Silverstein committed
1145 1146 1147
  EXPECT_EQ(-22, FLAGS_test_int32);   // the -21 from the flagsfile didn't take
}

1148
TEST(FlagsSetBeforeInitTest, TryFromEnv) {
Craig Silverstein's avatar
Craig Silverstein committed
1149 1150 1151
  EXPECT_EQ("pre-set", FLAGS_test_tryfromenv);
}

1152 1153 1154 1155
// The following test case verifies that ParseCommandLineFlags() and
// ParseCommandLineNonHelpFlags() uses the last definition of a flag
// in case it's defined more than once.

1156
DEFINE_int32(test_flag, -1, "used for testing gflags.cc");
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

// Parses and returns the --test_flag flag.
// If with_help is true, calls ParseCommandLineFlags; otherwise calls
// ParseCommandLineNonHelpFlags.
int32 ParseTestFlag(bool with_help, int argc, const char** const_argv) {
  FlagSaver fs;  // Restores the flags before returning.

  // Makes a copy of the input array s.t. it can be reused
  // (ParseCommandLineFlags() will alter the array).
  char** const argv_save = new char*[argc + 1];
  char** argv = argv_save;
  memcpy(argv, const_argv, sizeof(*argv)*(argc + 1));

  if (with_help) {
    ParseCommandLineFlags(&argc, &argv, true);
  } else {
    ParseCommandLineNonHelpFlags(&argc, &argv, true);
  }

  delete[] argv_save;
  return FLAGS_test_flag;
}

TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
     WhenFlagIsDefinedTwiceOnCommandLine) {
  const char* argv[] = {
    "my_test",
    "--test_flag=1",
    "--test_flag=2",
    NULL,
  };

1189 1190
  EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
}

TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
     WhenFlagIsDefinedTwiceInFlagFile) {
  const char* argv[] = {
    "my_test",
    GetFlagFileFlag(),
    NULL,
  };

1201 1202
  EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
}

TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
     WhenFlagIsDefinedInCommandLineAndThenFlagFile) {
  const char* argv[] = {
    "my_test",
    "--test_flag=0",
    GetFlagFileFlag(),
    NULL,
  };

1214 1215
  EXPECT_EQ(2, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(2, ParseTestFlag(false, arraysize(argv) - 1, argv));
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
}

TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
     WhenFlagIsDefinedInFlagFileAndThenCommandLine) {
  const char* argv[] = {
    "my_test",
    GetFlagFileFlag(),
    "--test_flag=3",
    NULL,
  };

1227 1228
  EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv));
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
}

TEST(ParseCommandLineFlagsUsesLastDefinitionTest,
     WhenFlagIsDefinedInCommandLineAndFlagFileAndThenCommandLine) {
  const char* argv[] = {
    "my_test",
    "--test_flag=0",
    GetFlagFileFlag(),
    "--test_flag=3",
    NULL,
  };

1241 1242
  EXPECT_EQ(3, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(3, ParseTestFlag(false, arraysize(argv) - 1, argv));
1243 1244
}

1245 1246 1247 1248 1249 1250 1251 1252
TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgFirst) {
  const char* argv[] = {
    "my_test",
    "--",
    "--test_flag=0",
    NULL,
  };

1253 1254
  EXPECT_EQ(-1, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(-1, ParseTestFlag(false, arraysize(argv) - 1, argv));
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
}

TEST(ParseCommandLineFlagsAndDashArgs, TwoDashArgMiddle) {
  const char* argv[] = {
    "my_test",
    "--test_flag=7",
    "--",
    "--test_flag=0",
    NULL,
  };

1266 1267
  EXPECT_EQ(7, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(7, ParseTestFlag(false, arraysize(argv) - 1, argv));
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
}

TEST(ParseCommandLineFlagsAndDashArgs, OneDashArg) {
  const char* argv[] = {
    "my_test",
    "-",
    "--test_flag=0",
    NULL,
  };

1278 1279
  EXPECT_EQ(0, ParseTestFlag(true, arraysize(argv) - 1, argv));
  EXPECT_EQ(0, ParseTestFlag(false, arraysize(argv) - 1, argv));
1280 1281
}

1282
#ifdef GTEST_HAS_DEATH_TEST
1283
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1284 1285 1286 1287 1288 1289 1290
     FlagIsCompletelyUnknown) {
  const char* argv[] = {
    "my_test",
    "--this_flag_does_not_exist",
    NULL,
  };

1291
  EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1292
               "unknown command line flag.*");
1293
  EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1294 1295 1296
               "unknown command line flag.*");
}

1297
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1298 1299 1300 1301 1302 1303 1304
     BoolFlagIsCompletelyUnknown) {
  const char* argv[] = {
    "my_test",
    "--nothis_flag_does_not_exist",
    NULL,
  };

1305
  EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1306
               "unknown command line flag.*");
1307
  EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1308 1309 1310
               "unknown command line flag.*");
}

1311
TEST(ParseCommandLineFlagsUnknownFlagDeathTest,
1312 1313 1314 1315 1316 1317 1318
     FlagIsNotABool) {
  const char* argv[] = {
    "my_test",
    "--notest_string",
    NULL,
  };

1319
  EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1320
               "boolean value .* specified for .* command line flag");
1321
  EXPECT_DEATH(ParseTestFlag(false, arraysize(argv) - 1, argv),
1322 1323
               "boolean value .* specified for .* command line flag");
}
1324
#endif
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

TEST(ParseCommandLineFlagsWrongFields,
     DescriptionIsInvalid) {
  // These must not be automatic variables, since command line flags
  // aren't unregistered and gUnit uses FlagSaver to save and restore
  // command line flags' values.  If these are on the stack, then when
  // later tests attempt to save and restore their values, the stack
  // addresses of these variables will be overwritten...  Stack smash!
  static bool current_storage;
  static bool defvalue_storage;
  FlagRegisterer fr("flag_name", "bool", 0, "filename",
Craig Silverstein's avatar
Craig Silverstein committed
1336
                    &current_storage, &defvalue_storage);
1337 1338 1339
  CommandLineFlagInfo fi;
  EXPECT_TRUE(GetCommandLineFlagInfo("flag_name", &fi));
  EXPECT_EQ("", fi.description);
Craig Silverstein's avatar
Craig Silverstein committed
1340
  EXPECT_EQ(&current_storage, fi.flag_ptr);
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
}

static bool ValidateTestFlagIs5(const char* flagname, int32 flagval) {
  if (flagval == 5)
    return true;
  printf("%s isn't 5!\n", flagname);
  return false;
}

static bool ValidateTestFlagIs10(const char* flagname, int32 flagval) {
  return flagval == 10;
}


TEST(FlagsValidator, ValidFlagViaArgv) {
  const char* argv[] = {
    "my_test",
    "--test_flag=5",
    NULL,
  };
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1362
  EXPECT_EQ(5, ParseTestFlag(true, arraysize(argv) - 1, argv));
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
  // Undo the flag validator setting
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

TEST(FlagsValidator, ValidFlagViaSetDefault) {
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  // SetCommandLineOptionWithMode returns the empty string on error.
  EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
                                             SET_FLAG_IF_DEFAULT));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

TEST(FlagsValidator, ValidFlagViaSetValue) {
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  FLAGS_test_flag = 100;   // doesn't trigger the validator
  // SetCommandLineOptionWithMode returns the empty string on error.
  EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
                                             SET_FLAGS_VALUE));
  EXPECT_NE("", SetCommandLineOptionWithMode("test_flag", "5",
                                             SET_FLAGS_DEFAULT));
  EXPECT_NE("", SetCommandLineOption("test_flag", "5"));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

1387
#ifdef GTEST_HAS_DEATH_TEST
1388
TEST(FlagsValidatorDeathTest, InvalidFlagViaArgv) {
1389 1390 1391 1392 1393 1394
  const char* argv[] = {
    "my_test",
    "--test_flag=50",
    NULL,
  };
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1395
  EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1396 1397 1398
               "ERROR: failed validation of new value '50' for flag 'test_flag'");
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}
1399
#endif
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

TEST(FlagsValidator, InvalidFlagViaSetDefault) {
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  // SetCommandLineOptionWithMode returns the empty string on error.
  EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
                                             SET_FLAG_IF_DEFAULT));
  EXPECT_EQ(-1, FLAGS_test_flag);   // the setting-to-50 should have failed
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

TEST(FlagsValidator, InvalidFlagViaSetValue) {
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  FLAGS_test_flag = 100;   // doesn't trigger the validator
  // SetCommandLineOptionWithMode returns the empty string on error.
  EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
                                             SET_FLAGS_VALUE));
  EXPECT_EQ("", SetCommandLineOptionWithMode("test_flag", "50",
                                             SET_FLAGS_DEFAULT));
  EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));
  EXPECT_EQ(100, FLAGS_test_flag);   // the setting-to-50 should have failed
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

1423
#ifdef GTEST_HAS_DEATH_TEST
1424
TEST(FlagsValidatorDeathTest, InvalidFlagNeverSet) {
1425 1426 1427 1428 1429 1430 1431
  // If a flag keeps its default value, and that default value is
  // invalid, we should die at argv-parse time.
  const char* argv[] = {
    "my_test",
    NULL,
  };
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1432
  EXPECT_DEATH(ParseTestFlag(true, arraysize(argv) - 1, argv),
1433 1434
               "ERROR: --test_flag must be set on the commandline");
}
1435
#endif
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471

TEST(FlagsValidator, InvalidFlagPtr) {
  int32 dummy;
  EXPECT_FALSE(RegisterFlagValidator(NULL, &ValidateTestFlagIs5));
  EXPECT_FALSE(RegisterFlagValidator(&dummy, &ValidateTestFlagIs5));
}

TEST(FlagsValidator, RegisterValidatorTwice) {
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
  EXPECT_FALSE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs10));
  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
}

TEST(FlagsValidator, CommandLineFlagInfo) {
  CommandLineFlagInfo info;
  info = GetCommandLineFlagInfoOrDie("test_flag");
  EXPECT_FALSE(info.has_validator_fn);

  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  info = GetCommandLineFlagInfoOrDie("test_flag");
  EXPECT_TRUE(info.has_validator_fn);

  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
  info = GetCommandLineFlagInfoOrDie("test_flag");
  EXPECT_FALSE(info.has_validator_fn);
}

TEST(FlagsValidator, FlagSaver) {
  {
    FlagSaver fs;
    EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
1472
    EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));  // fails validation
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
  }
  EXPECT_NE("", SetCommandLineOption("test_flag", "50"));  // validator is gone

  EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, &ValidateTestFlagIs5));
  {
    FlagSaver fs;
    EXPECT_TRUE(RegisterFlagValidator(&FLAGS_test_flag, NULL));
    EXPECT_NE("", SetCommandLineOption("test_flag", "50"));  // no validator
  }
  EXPECT_EQ("", SetCommandLineOption("test_flag", "50"));  // validator is back
}


1486 1487 1488
}  // unnamed namespace

int main(int argc, char **argv) {
1489 1490 1491 1492 1493

  // Run unit tests only if called without arguments, otherwise this program
  // is used by an "external" usage test
  const bool run_tests = (argc == 1);

1494
  // We need to call SetArgv before parsing flags, so our "test" argv will
Craig Silverstein's avatar
Craig Silverstein committed
1495 1496 1497 1498
  // win out over this executable's real argv.  That makes running this
  // test with a real --help flag kinda annoying, unfortunately.
  const char* test_argv[] = { "/test/argv/for/gflags_unittest",
                              "argv 2", "3rd argv", "argv #4" };
1499
  SetArgv(arraysize(test_argv), test_argv);
Craig Silverstein's avatar
Craig Silverstein committed
1500 1501 1502 1503 1504

  // The first arg is the usage message, also important for testing.
  string usage_message = (string(GetArgv0()) +
                          ": <useless flag> [...]\nDoes something useless.\n");

1505 1506
  // We test setting tryfromenv manually, and making sure
  // ParseCommandLineFlags still evaluates it.
Craig Silverstein's avatar
Craig Silverstein committed
1507 1508 1509
  FLAGS_tryfromenv = "test_tryfromenv";
  setenv("FLAGS_test_tryfromenv", "pre-set", 1);

1510 1511 1512
  // Modify flag values from declared default value in two ways.
  // The recommended way:
  SetCommandLineOptionWithMode("changed_bool1", "true", SET_FLAGS_DEFAULT);
1513

1514 1515 1516
  // The non-recommended way:
  FLAGS_changed_bool2 = true;

Craig Silverstein's avatar
Craig Silverstein committed
1517
  SetUsageMessage(usage_message.c_str());
1518
  SetVersionString("test_version");
Craig Silverstein's avatar
Craig Silverstein committed
1519
  ParseCommandLineFlags(&argc, &argv, true);
1520
  MakeTmpdir(&FLAGS_test_tmpdir);
Craig Silverstein's avatar
Craig Silverstein committed
1521

1522 1523 1524 1525 1526
  int exit_status = 0;
  if (run_tests) {
	  fprintf(stdout, "Running the unit tests now...\n\n"); fflush(stdout);
	  exit_status = RUN_ALL_TESTS();
  } else fprintf(stderr, "\n\nPASS\n");
1527 1528
  ShutDownCommandLineFlags();
  return exit_status;
Craig Silverstein's avatar
Craig Silverstein committed
1529 1530
}

1531
} // GFLAGS_NAMESPACE
Craig Silverstein's avatar
Craig Silverstein committed
1532 1533

int main(int argc, char** argv) {
1534
  return GFLAGS_NAMESPACE::main(argc, argv);
Craig Silverstein's avatar
Craig Silverstein committed
1535
}
1536