fire_test.py 28.7 KB
1 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 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 411 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 463 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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 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 697 698 699 700 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
# Copyright (C) 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for the fire module."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

import fire
from fire import test_components as tc
from fire import testutils

import mock
import six


class FireTest(testutils.BaseTestCase):

  def testFire(self):
    with mock.patch.object(sys, 'argv', ['progname']):
      fire.Fire(tc.Empty)
      fire.Fire(tc.OldStyleEmpty)
      fire.Fire(tc.WithInit)
    # Test both passing command as a sequence and as a string.
    self.assertEqual(fire.Fire(tc.NoDefaults, command='triple 4'), 12)
    self.assertEqual(fire.Fire(tc.WithDefaults, command=('double', '2')), 4)
    self.assertEqual(fire.Fire(tc.WithDefaults, command=['triple', '4']), 12)
    self.assertEqual(fire.Fire(tc.OldStyleWithDefaults,
                               command=['double', '2']), 4)
    self.assertEqual(fire.Fire(tc.OldStyleWithDefaults,
                               command=['triple', '4']), 12)

  def testFirePositionalCommand(self):
    # Test passing command as a positional argument.
    self.assertEqual(fire.Fire(tc.NoDefaults, 'double 2'), 4)
    self.assertEqual(fire.Fire(tc.NoDefaults, ['double', '2']), 4)

  def testFireInvalidCommandArg(self):
    with self.assertRaises(ValueError):
      # This is not a valid command.
      fire.Fire(tc.WithDefaults, command=10)

  def testFireDefaultName(self):
    with mock.patch.object(sys, 'argv',
                           [os.path.join('python-fire', 'fire',
                                         'base_filename.py')]):
      with self.assertOutputMatches(stdout='SYNOPSIS.*base_filename.py',
                                    stderr=None):
        fire.Fire(tc.Empty)

  def testFireNoArgs(self):
    self.assertEqual(fire.Fire(tc.MixedDefaults, command=['ten']), 10)

  def testFireExceptions(self):
    # Exceptions of Fire are printed to stderr and a FireExit is raised.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.Empty, command=['nomethod'])  # Member doesn't exist.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.NoDefaults, command=['double'])  # Missing argument.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.TypedProperties, command=['delta', 'x'])  # Missing key.

    # Exceptions of the target components are still raised.
    with self.assertRaises(ZeroDivisionError):
      fire.Fire(tc.NumberDefaults, command=['reciprocal', '0.0'])

  def testFireNamedArgs(self):
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['double', '--count', '5']), 10)
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['triple', '--count', '5']), 15)
    self.assertEqual(
        fire.Fire(tc.OldStyleWithDefaults, command=['double', '--count', '5']),
        10)
    self.assertEqual(
        fire.Fire(tc.OldStyleWithDefaults, command=['triple', '--count', '5']),
        15)

  def testFireNamedArgsSingleHyphen(self):
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['double', '-count', '5']), 10)
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['triple', '-count', '5']), 15)
    self.assertEqual(
        fire.Fire(tc.OldStyleWithDefaults, command=['double', '-count', '5']),
        10)
    self.assertEqual(
        fire.Fire(tc.OldStyleWithDefaults, command=['triple', '-count', '5']),
        15)

  def testFireNamedArgsWithEquals(self):
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['double', '--count=5']), 10)
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['triple', '--count=5']), 15)

  def testFireNamedArgsWithEqualsSingleHyphen(self):
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['double', '-count=5']), 10)
    self.assertEqual(fire.Fire(tc.WithDefaults,
                               command=['triple', '-count=5']), 15)

  def testFireAllNamedArgs(self):
    self.assertEqual(fire.Fire(tc.MixedDefaults, command=['sum', '1', '2']), 5)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '--alpha', '1', '2']), 5)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '--beta', '1', '2']), 4)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '1', '--alpha', '2']), 4)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '1', '--beta', '2']), 5)
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['sum', '--alpha', '1', '--beta', '2']), 5)
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['sum', '--beta', '1', '--alpha', '2']), 4)

  def testFireAllNamedArgsOneMissing(self):
    self.assertEqual(fire.Fire(tc.MixedDefaults, command=['sum']), 0)
    self.assertEqual(fire.Fire(tc.MixedDefaults, command=['sum', '1']), 1)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '--alpha', '1']), 1)
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['sum', '--beta', '2']), 4)

  def testFirePartialNamedArgs(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults, command=['identity', '1', '2']), (1, 2))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', '1', '2']), (1, 2))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--beta', '1', '2']), (2, 1))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '1', '--alpha', '2']), (2, 1))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '1', '--beta', '2']), (1, 2))
    self.assertEqual(
        fire.Fire(
            tc.MixedDefaults,
            command=['identity', '--alpha', '1', '--beta', '2']), (1, 2))
    self.assertEqual(
        fire.Fire(
            tc.MixedDefaults,
            command=['identity', '--beta', '1', '--alpha', '2']), (2, 1))

  def testFirePartialNamedArgsOneMissing(self):
    # Errors are written to standard out and a FireExit is raised.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.MixedDefaults,
                command=['identity'])  # Identity needs an arg.

    with self.assertRaisesFireExit(2):
      # Identity needs a value for alpha.
      fire.Fire(tc.MixedDefaults, command=['identity', '--beta', '2'])

    self.assertEqual(
        fire.Fire(tc.MixedDefaults, command=['identity', '1']), (1, '0'))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults, command=['identity', '--alpha', '1']),
        (1, '0'))

  def testFireAnnotatedArgs(self):
    self.assertEqual(fire.Fire(tc.Annotations, command=['double', '5']), 10)
    self.assertEqual(fire.Fire(tc.Annotations, command=['triple', '5']), 15)

  @testutils.skipIf(six.PY2, 'Keyword-only arguments not in Python 2.')
  def testFireKeywordOnlyArgs(self):
    with self.assertRaisesFireExit(2):
      # Keyword arguments must be passed with flag syntax.
      fire.Fire(tc.py3.KeywordOnly, command=['double', '5'])

    self.assertEqual(
        fire.Fire(tc.py3.KeywordOnly, command=['double', '--count', '5']), 10)
    self.assertEqual(
        fire.Fire(tc.py3.KeywordOnly, command=['triple', '--count', '5']), 15)

  def testFireProperties(self):
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['alpha']), True)
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['beta']), (1, 2, 3))

  def testFireRecursion(self):
    self.assertEqual(
        fire.Fire(tc.TypedProperties,
                  command=['charlie', 'double', 'hello']), 'hellohello')
    self.assertEqual(fire.Fire(tc.TypedProperties,
                               command=['charlie', 'triple', 'w']), 'www')

  def testFireVarArgs(self):
    self.assertEqual(
        fire.Fire(tc.VarArgs,
                  command=['cumsums', 'a', 'b', 'c', 'd']),
        ['a', 'ab', 'abc', 'abcd'])
    self.assertEqual(
        fire.Fire(tc.VarArgs, command=['cumsums', '1', '2', '3', '4']),
        [1, 3, 6, 10])

  def testFireVarArgsWithNamedArgs(self):
    self.assertEqual(
        fire.Fire(tc.VarArgs, command=['varchars', '1', '2', 'c', 'd']),
        (1, 2, 'cd'))
    self.assertEqual(
        fire.Fire(tc.VarArgs, command=['varchars', '3', '4', 'c', 'd', 'e']),
        (3, 4, 'cde'))

  def testFireKeywordArgs(self):
    self.assertEqual(
        fire.Fire(
            tc.Kwargs,
            command=['props', '--name', 'David', '--age', '24']),
        {'name': 'David', 'age': 24})
    # Run this test both with a list command and a string command.
    self.assertEqual(
        fire.Fire(
            tc.Kwargs,
            command=['props', '--message',
                     '"This is a message it has -- in it"']),  # Quotes stripped
        {'message': 'This is a message it has -- in it'})
    self.assertEqual(
        fire.Fire(
            tc.Kwargs,
            command=['props', '--message',
                     'This is a message it has -- in it']),
        {'message': 'This is a message it has -- in it'})
    self.assertEqual(
        fire.Fire(
            tc.Kwargs,
            command='props --message "This is a message it has -- in it"'),
        {'message': 'This is a message it has -- in it'})
    self.assertEqual(
        fire.Fire(tc.Kwargs,
                  command=['upper', '--alpha', 'A', '--beta', 'B']),
        'ALPHA BETA')
    self.assertEqual(
        fire.Fire(
            tc.Kwargs,
            command=['upper', '--alpha', 'A', '--beta', 'B', '-', 'lower']),
        'alpha beta')

  def testFireKeywordArgsWithMissingPositionalArgs(self):
    self.assertEqual(
        fire.Fire(tc.Kwargs, command=['run', 'Hello', 'World', '--cell', 'is']),
        ('Hello', 'World', {'cell': 'is'}))
    self.assertEqual(
        fire.Fire(tc.Kwargs, command=['run', 'Hello', '--cell', 'ok']),
        ('Hello', None, {'cell': 'ok'}))

  def testFireObject(self):
    self.assertEqual(
        fire.Fire(tc.WithDefaults(), command=['double', '--count', '5']), 10)
    self.assertEqual(
        fire.Fire(tc.WithDefaults(), command=['triple', '--count', '5']), 15)

  def testFireDict(self):
    component = {
        'double': lambda x=0: 2 * x,
        'cheese': 'swiss',
    }
    self.assertEqual(fire.Fire(component, command=['double', '5']), 10)
    self.assertEqual(fire.Fire(component, command=['cheese']), 'swiss')

  def testFireObjectWithDict(self):
    self.assertEqual(
        fire.Fire(tc.TypedProperties, command=['delta', 'echo']), 'E')
    self.assertEqual(
        fire.Fire(tc.TypedProperties, command=['delta', 'echo', 'lower']), 'e')
    self.assertIsInstance(
        fire.Fire(tc.TypedProperties, command=['delta', 'nest']), dict)
    self.assertEqual(
        fire.Fire(tc.TypedProperties, command=['delta', 'nest', '0']), 'a')

  def testFireSet(self):
    component = tc.simple_set()
    result = fire.Fire(component, command=[])
    self.assertEqual(len(result), 3)

  def testFireFrozenset(self):
    component = tc.simple_frozenset()
    result = fire.Fire(component, command=[])
    self.assertEqual(len(result), 3)

  def testFireList(self):
    component = ['zero', 'one', 'two', 'three']
    self.assertEqual(fire.Fire(component, command=['2']), 'two')
    self.assertEqual(fire.Fire(component, command=['3']), 'three')
    self.assertEqual(fire.Fire(component, command=['-1']), 'three')

  def testFireObjectWithList(self):
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['echo', '0']),
                     'alex')
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['echo', '1']),
                     'bethany')

  def testFireObjectWithTuple(self):
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['fox', '0']),
                     'carry')
    self.assertEqual(fire.Fire(tc.TypedProperties, command=['fox', '1']),
                     'divide')

  def testFireObjectWithListAsObject(self):
    self.assertEqual(
        fire.Fire(tc.TypedProperties, command=['echo', 'count', 'bethany']),
        1)

  def testFireObjectWithTupleAsObject(self):
    self.assertEqual(
        fire.Fire(tc.TypedProperties, command=['fox', 'count', 'divide']),
        1)

  def testFireNoComponent(self):
    self.assertEqual(fire.Fire(command=['tc', 'WithDefaults', 'double', '10']),
                     20)
    last_char = lambda text: text[-1]  # pylint: disable=unused-variable
    self.assertEqual(fire.Fire(command=['last_char', '"Hello"']), 'o')
    self.assertEqual(fire.Fire(command=['last-char', '"World"']), 'd')
    rset = lambda count=0: set(range(count))  # pylint: disable=unused-variable
    self.assertEqual(fire.Fire(command=['rset', '5']), {0, 1, 2, 3, 4})

  def testFireUnderscores(self):
    self.assertEqual(
        fire.Fire(tc.Underscores,
                  command=['underscore-example']), 'fish fingers')
    self.assertEqual(
        fire.Fire(tc.Underscores,
                  command=['underscore_example']), 'fish fingers')

  def testFireUnderscoresInArg(self):
    self.assertEqual(
        fire.Fire(tc.Underscores,
                  command=['underscore-function', 'example']), 'example')
    self.assertEqual(
        fire.Fire(tc.Underscores,
                  command=['underscore_function', '--underscore-arg=score']),
        'score')
    self.assertEqual(
        fire.Fire(tc.Underscores,
                  command=['underscore_function', '--underscore_arg=score']),
        'score')

  def testBoolParsing(self):
    self.assertEqual(fire.Fire(tc.BoolConverter, command=['as-bool', 'True']),
                     True)
    self.assertEqual(
        fire.Fire(tc.BoolConverter, command=['as-bool', 'False']), False)
    self.assertEqual(
        fire.Fire(tc.BoolConverter, command=['as-bool', '--arg=True']), True)
    self.assertEqual(
        fire.Fire(tc.BoolConverter, command=['as-bool', '--arg=False']), False)
    self.assertEqual(fire.Fire(tc.BoolConverter, command=['as-bool', '--arg']),
                     True)
    self.assertEqual(
        fire.Fire(tc.BoolConverter, command=['as-bool', '--noarg']), False)

  def testBoolParsingContinued(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', 'True', 'False']), (True, False))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha=False', '10']), (False, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', '--beta', '10']), (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', '--beta=10']), (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--noalpha', '--beta']), (False, True))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults, command=['identity', '10', '--beta']),
        (10, True))

  def testBoolParsingSingleHyphen(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-alpha=False', '10']), (False, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-alpha', '-beta', '10']), (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-alpha', '-beta=10']), (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-noalpha', '-beta']), (False, True))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-alpha', '-10', '-beta']), (-10, True))

  def testBoolParsingLessExpectedCases(self):
    # Note: Does not return (True, 10).
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', '10']), (10, '0'))
    # To get (True, 10), use one of the following:
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', '--beta=10']),
        (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', 'True', '10']), (True, 10))

    # Note: Does not return (True, '--test') or ('--test', 0).
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.MixedDefaults, command=['identity', '--alpha', '--test'])

    self.assertEqual(
        fire.Fire(
            tc.MixedDefaults,
            command=['identity', '--alpha', 'True', '"--test"']),
        (True, '--test'))
    # To get ('--test', '0'), use one of the following:
    self.assertEqual(fire.Fire(tc.MixedDefaults,
                               command=['identity', '--alpha=--test']),
                     ('--test', '0'))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults, command=r'identity --alpha \"--test\"'),
        ('--test', '0'))

  def testSingleCharFlagParsing(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a']), (True, '0'))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a', '--beta=10']), (True, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a', '-b']), (True, True))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a', '42', '-b']), (42, True))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a', '42', '-b', '10']), (42, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '--alpha', 'True', '-b', '10']),
        (True, 10))
    with self.assertRaisesFireExit(2):
      # This test attempts to use an ambiguous shortcut flag on a function with
      # a naming conflict for the shortcut, triggering a FireError.
      fire.Fire(tc.SimilarArgNames, command=['identity', '-b'])

  def testSingleCharFlagParsingEqualSign(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a=True']), (True, '0'))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a=3', '--beta=10']), (3, 10))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a=False', '-b=15']), (False, 15))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a', '42', '-b=12']), (42, 12))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-a=42', '-b', '10']), (42, 10))

  def testSingleCharFlagParsingExactMatch(self):
    self.assertEqual(
        fire.Fire(tc.SimilarArgNames,
                  command=['identity2', '-a']), (True, None))
    self.assertEqual(
        fire.Fire(tc.SimilarArgNames,
                  command=['identity2', '-a=10']), (10, None))
    self.assertEqual(
        fire.Fire(tc.SimilarArgNames,
                  command=['identity2', '--a']), (True, None))
    self.assertEqual(
        fire.Fire(tc.SimilarArgNames,
                  command=['identity2', '-alpha']), (None, True))
    self.assertEqual(
        fire.Fire(tc.SimilarArgNames,
                  command=['identity2', '-a', '-alpha']), (True, True))

  def testSingleCharFlagParsingCapitalLetter(self):
    self.assertEqual(
        fire.Fire(tc.CapitalizedArgNames,
                  command=['sum', '-D', '5', '-G', '10']), 15)

  def testBoolParsingWithNo(self):
    # In these examples --nothing always refers to the nothing argument:
    def fn1(thing, nothing):
      return thing, nothing

    self.assertEqual(fire.Fire(fn1, command=['--thing', '--nothing']),
                     (True, True))
    self.assertEqual(fire.Fire(fn1, command=['--thing', '--nonothing']),
                     (True, False))

    with self.assertRaisesFireExit(2):
      # In this case nothing=False (since rightmost setting of a flag gets
      # precedence), but it errors because thing has no value.
      fire.Fire(fn1, command=['--nothing', '--nonothing'])

    # In these examples, --nothing sets thing=False:
    def fn2(thing, **kwargs):
      return thing, kwargs
    self.assertEqual(fire.Fire(fn2, command=['--thing']), (True, {}))
    self.assertEqual(fire.Fire(fn2, command=['--nothing']), (False, {}))
    with self.assertRaisesFireExit(2):
      # In this case, nothing=True, but it errors because thing has no value.
      fire.Fire(fn2, command=['--nothing=True'])
    self.assertEqual(fire.Fire(fn2, command=['--nothing', '--nothing=True']),
                     (False, {'nothing': True}))

    def fn3(arg, **kwargs):
      return arg, kwargs
    self.assertEqual(fire.Fire(fn3, command=['--arg=value', '--thing']),
                     ('value', {'thing': True}))
    self.assertEqual(fire.Fire(fn3, command=['--arg=value', '--nothing']),
                     ('value', {'thing': False}))
    self.assertEqual(fire.Fire(fn3, command=['--arg=value', '--nonothing']),
                     ('value', {'nothing': False}))

  def testTraceFlag(self):
    with self.assertRaisesFireExit(0, 'Fire trace:\n'):
      fire.Fire(tc.BoolConverter, command=['as-bool', 'True', '--', '--trace'])
    with self.assertRaisesFireExit(0, 'Fire trace:\n'):
      fire.Fire(tc.BoolConverter, command=['as-bool', 'True', '--', '-t'])
    with self.assertRaisesFireExit(0, 'Fire trace:\n'):
      fire.Fire(tc.BoolConverter, command=['--', '--trace'])

  def testHelpFlag(self):
    with self.assertRaisesFireExit(0):
      fire.Fire(tc.BoolConverter, command=['as-bool', 'True', '--', '--help'])
    with self.assertRaisesFireExit(0):
      fire.Fire(tc.BoolConverter, command=['as-bool', 'True', '--', '-h'])
    with self.assertRaisesFireExit(0):
      fire.Fire(tc.BoolConverter, command=['--', '--help'])

  def testHelpFlagAndTraceFlag(self):
    with self.assertRaisesFireExit(0, 'Fire trace:\n.*SYNOPSIS'):
      fire.Fire(tc.BoolConverter,
                command=['as-bool', 'True', '--', '--help', '--trace'])
    with self.assertRaisesFireExit(0, 'Fire trace:\n.*SYNOPSIS'):
      fire.Fire(tc.BoolConverter, command=['as-bool', 'True', '--', '-h', '-t'])
    with self.assertRaisesFireExit(0, 'Fire trace:\n.*SYNOPSIS'):
      fire.Fire(tc.BoolConverter, command=['--', '-h', '--trace'])

  def testTabCompletionNoName(self):
    completion_script = fire.Fire(tc.NoDefaults, command=['--', '--completion'])
    self.assertIn('double', completion_script)
    self.assertIn('triple', completion_script)

  def testTabCompletion(self):
    completion_script = fire.Fire(
        tc.NoDefaults, command=['--', '--completion'], name='c')
    self.assertIn('double', completion_script)
    self.assertIn('triple', completion_script)

  def testTabCompletionWithDict(self):
    actions = {'multiply': lambda a, b: a * b}
    completion_script = fire.Fire(
        actions, command=['--', '--completion'], name='actCLI')
    self.assertIn('actCLI', completion_script)
    self.assertIn('multiply', completion_script)

  def testBasicSeparator(self):
    # '-' is the default separator.
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '+', '_']), ('+', '_'))
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '_', '+', '-']), ('_', '+'))

    # If we change the separator we can use '-' as an argument.
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['identity', '-', '_', '--', '--separator', '&']),
        ('-', '_'))

    # The separator triggers a function call, but there aren't enough arguments.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.MixedDefaults, command=['identity', '-', '_', '+'])

  def testNonComparable(self):
    """Fire should work with classes that disallow comparisons."""
    # Make sure this test passes both with a string command or a list command.
    self.assertIsInstance(
        fire.Fire(tc.NonComparable, command=''), tc.NonComparable)
    self.assertIsInstance(
        fire.Fire(tc.NonComparable, command=[]), tc.NonComparable)

    # The first separator instantiates the NonComparable object.
    # The second separator causes Fire to check if the separator was necessary.
    self.assertIsInstance(
        fire.Fire(tc.NonComparable, command=['-', '-']), tc.NonComparable)

  def testExtraSeparators(self):
    self.assertEqual(
        fire.Fire(
            tc.ReturnsObj,
            command=['get-obj', 'arg1', 'arg2', '-', '-', 'as-bool', 'True']),
        True)
    self.assertEqual(
        fire.Fire(
            tc.ReturnsObj,
            command=['get-obj', 'arg1', 'arg2', '-', '-', '-', 'as-bool',
                     'True']),
        True)

  def testSeparatorForChaining(self):
    # Without a separator all args are consumed by get_obj.
    self.assertIsInstance(
        fire.Fire(tc.ReturnsObj,
                  command=['get-obj', 'arg1', 'arg2', 'as-bool', 'True']),
        tc.BoolConverter)
    # With a separator only the preceding args are consumed by get_obj.
    self.assertEqual(
        fire.Fire(
            tc.ReturnsObj,
            command=['get-obj', 'arg1', 'arg2', '-', 'as-bool', 'True']), True)
    self.assertEqual(
        fire.Fire(tc.ReturnsObj,
                  command=['get-obj', 'arg1', 'arg2', '&', 'as-bool', 'True',
                           '--', '--separator', '&']),
        True)
    self.assertEqual(
        fire.Fire(tc.ReturnsObj,
                  command=['get-obj', 'arg1', '$$', 'as-bool', 'True', '--',
                           '--separator', '$$']),
        True)

  def testNegativeNumbers(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['sum', '--alpha', '-3', '--beta', '-4']), -11)

  def testFloatForExpectedInt(self):
    self.assertEqual(
        fire.Fire(tc.MixedDefaults,
                  command=['sum', '--alpha', '2.2', '--beta', '3.0']), 8.2)
    self.assertEqual(
        fire.Fire(
            tc.NumberDefaults,
            command=['integer_reciprocal', '--divisor', '5.0']), 0.2)
    self.assertEqual(
        fire.Fire(tc.NumberDefaults, command=['integer_reciprocal', '4.0']),
        0.25)

  def testClassInstantiation(self):
    self.assertIsInstance(fire.Fire(tc.InstanceVars,
                                    command=['--arg1=a1', '--arg2=a2']),
                          tc.InstanceVars)
    with self.assertRaisesFireExit(2):
      # Cannot instantiate a class with positional args.
      fire.Fire(tc.InstanceVars, command=['a1', 'a2'])

  def testTraceErrors(self):
    # Class needs additional value but runs out of args.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars, command=['a1'])
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars, command=['--arg1=a1'])

    # Routine needs additional value but runs out of args.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars, command=['a1', 'a2', '-', 'run', 'b1'])
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars,
                command=['--arg1=a1', '--arg2=a2', '-', 'run b1'])

    # Extra args cannot be consumed.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars,
                command=['a1', 'a2', '-', 'run', 'b1', 'b2', 'b3'])
    with self.assertRaisesFireExit(2):
      fire.Fire(
          tc.InstanceVars,
          command=['--arg1=a1', '--arg2=a2', '-', 'run', 'b1', 'b2', 'b3'])

    # Cannot find member to access.
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars, command=['a1', 'a2', '-', 'jog'])
    with self.assertRaisesFireExit(2):
      fire.Fire(tc.InstanceVars, command=['--arg1=a1', '--arg2=a2', '-', 'jog'])

  def testClassWithDefaultMethod(self):
    self.assertEqual(
        fire.Fire(tc.DefaultMethod, command=['double', '10']), 20
    )

  def testClassWithInvalidProperty(self):
    self.assertEqual(
        fire.Fire(tc.InvalidProperty, command=['double', '10']), 20
    )

  @testutils.skipIf(sys.version_info[0:2] <= (3, 4),
                    'Cannot inspect wrapped signatures in Python 2 or 3.4.')
  def testHelpKwargsDecorator(self):
    # Issue #190, follow the wrapped method instead of crashing.
    with self.assertRaisesFireExit(0):
      fire.Fire(tc.decorated_method, command=['-h'])
    with self.assertRaisesFireExit(0):
      fire.Fire(tc.decorated_method, command=['--help'])


if __name__ == '__main__':
  testutils.main()