#!/usr/bin/env python

# Copyright (c) 2007, Google Inc.
# 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.

"Unittest for flags.py module"

__pychecker__ = "no-local" # for unittest


import sys
import os
import shutil
import unittest

# We use the name 'flags' internally in this test, for historical reasons.
# Don't do this yourself! :-)  Just do 'import gflags; FLAGS=gflags.FLAGS; etc'
import gflags as flags
FLAGS=flags.FLAGS

def MultiLineEqual(expected_help, help):
  """Returns True if expected_help == help.  Otherwise returns False
  and logs the difference in a human-readable way.
  """
  if help == expected_help:
    return True
  
  print "Error: FLAGS.MainModuleHelp() didn't return the expected result."
  print "Got:"
  print help
  print "[End of got]"

  help_lines = help.split('\n')
  expected_help_lines = expected_help.split('\n')

  num_help_lines = len(help_lines)
  num_expected_help_lines = len(expected_help_lines)

  if num_help_lines != num_expected_help_lines:
    print "Number of help lines = %d, expected %d" % (
        num_help_lines, num_expected_help_lines)

  num_to_match = min(num_help_lines, num_expected_help_lines)

  for i in range(num_to_match):
    if help_lines[i] != expected_help_lines[i]:
      print "One discrepancy: Got:"
      print help_lines[i]
      print "Expected:"
      print expected_help_lines[i]
      break
  else:
    # If we got here, found no discrepancy, print first new line.
    if num_help_lines > num_expected_help_lines:
      print "New help line:"
      print help_lines[num_expected_help_lines]
    elif num_expected_help_lines > num_help_lines:
      print "Missing expected help line:"
      print expected_help_lines[num_help_lines]
    else:
      print "Bug in this test -- discrepancy detected but not found."

  return False


class FlagsUnitTest(unittest.TestCase):
  "Flags Unit Test"

  def test_flags(self):

    ##############################################
    # Test normal usage with no (expected) errors.

    # Define flags
    number_test_framework_flags = len(FLAGS.RegisteredFlags())
    repeatHelp = "how many times to repeat (0-5)"
    flags.DEFINE_integer("repeat", 4, repeatHelp,
                         lower_bound=0, short_name='r')
    flags.DEFINE_string("name", "Bob", "namehelp")
    flags.DEFINE_boolean("debug", 0, "debughelp")
    flags.DEFINE_boolean("q", 1, "quiet mode")
    flags.DEFINE_boolean("quack", 0, "superstring of 'q'")
    flags.DEFINE_boolean("noexec", 1, "boolean flag with no as prefix")
    flags.DEFINE_integer("x", 3, "how eXtreme to be")
    flags.DEFINE_integer("l", 0x7fffffff00000000L, "how long to be")
    flags.DEFINE_list('letters', 'a,b,c', "a list of letters")
    flags.DEFINE_enum("kwery", None, ['who', 'what', 'why', 'where', 'when'],
                      "?")

    # Specify number of flags defined above.  The short_name defined
    # for 'repeat' counts as an extra flag.
    number_defined_flags = 10 + 1
    self.assertEqual(len(FLAGS.RegisteredFlags()),
                         number_defined_flags + number_test_framework_flags)

    assert FLAGS.repeat == 4, "integer default values not set:" + FLAGS.repeat
    assert FLAGS.name == 'Bob', "default values not set:" + FLAGS.name
    assert FLAGS.debug == 0, "boolean default values not set:" + FLAGS.debug
    assert FLAGS.q == 1, "boolean default values not set:" + FLAGS.q
    assert FLAGS.x == 3, "integer default values not set:" + FLAGS.x
    assert FLAGS.l == 0x7fffffff00000000L, ("integer default values not set:"
                                            + FLAGS.l)
    assert FLAGS.letters == ['a', 'b', 'c'], "list default values not set:" \
      + FLAGS.letters
    assert FLAGS.kwery is None, ("enum default None value not set:"
                                  + FLAGS.kwery)

    flag_values = FLAGS.FlagValuesDict()
    assert flag_values['repeat'] == 4
    assert flag_values['name'] == 'Bob'
    assert flag_values['debug'] == 0
    assert flag_values['r'] == 4       # short for of repeat
    assert flag_values['q'] == 1
    assert flag_values['quack'] == 0
    assert flag_values['x'] == 3
    assert flag_values['l'] == 0x7fffffff00000000L
    assert flag_values['letters'] == ['a', 'b', 'c']
    assert flag_values['kwery'] is None

    # Verify string form of defaults
    assert FLAGS['repeat'].default_as_str == "'4'"
    assert FLAGS['name'].default_as_str == "'Bob'"
    assert FLAGS['debug'].default_as_str == "'false'"
    assert FLAGS['q'].default_as_str == "'true'"
    assert FLAGS['quack'].default_as_str == "'false'"
    assert FLAGS['noexec'].default_as_str == "'true'"
    assert FLAGS['x'].default_as_str == "'3'"
    assert FLAGS['l'].default_as_str == "'9223372032559808512'"
    assert FLAGS['letters'].default_as_str == "'a,b,c'"

    # Verify that the iterator for flags yields all the keys
    keys = list(FLAGS)
    keys.sort()
    reg_flags = FLAGS.RegisteredFlags()
    reg_flags.sort()
    self.assertEqual(keys, reg_flags)

    # Parse flags
    # .. empty command line
    argv = ('./program',)
    argv = FLAGS(argv)
    assert len(argv) == 1, "wrong number of arguments pulled"
    assert argv[0]=='./program', "program name not preserved"

    # .. non-empty command line
    argv = ('./program', '--debug', '--name=Bob', '-q', '--x=8')
    argv = FLAGS(argv)
    assert len(argv) == 1, "wrong number of arguments pulled"
    assert argv[0]=='./program', "program name not preserved"
    assert FLAGS['debug'].present == 1
    FLAGS['debug'].present = 0 # Reset
    assert FLAGS['name'].present == 1
    FLAGS['name'].present = 0 # Reset
    assert FLAGS['q'].present == 1
    FLAGS['q'].present = 0 # Reset
    assert FLAGS['x'].present == 1
    FLAGS['x'].present = 0 # Reset

    # Flags list
    self.assertEqual(len(FLAGS.RegisteredFlags()),
                     number_defined_flags + number_test_framework_flags)
    assert 'name' in FLAGS.RegisteredFlags()
    assert 'debug' in FLAGS.RegisteredFlags()
    assert 'repeat' in FLAGS.RegisteredFlags()
    assert 'r' in FLAGS.RegisteredFlags()
    assert 'q' in FLAGS.RegisteredFlags()
    assert 'quack' in FLAGS.RegisteredFlags()
    assert 'x' in FLAGS.RegisteredFlags()
    assert 'l' in FLAGS.RegisteredFlags()
    assert 'letters' in FLAGS.RegisteredFlags()

    # has_key
    assert FLAGS.has_key('name')
    assert not FLAGS.has_key('name2')
    assert 'name' in FLAGS