This file is indexed.

/usr/share/pyshared/google/apputils/basetest.py is in python-google-apputils 0.4.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 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
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 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
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
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
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
#!/usr/bin/env python
# Copyright 2010 Google Inc. All Rights Reserved.
#
# 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.

"""Base functionality for google tests.

This module contains base classes and high-level functions for Google-style
tests.
"""

__author__ = 'dborowitz@google.com (Dave Borowitz)'

import collections
import difflib
import getpass
import itertools
import json
import os
import re
import subprocess
import sys
import tempfile
import types
import urlparse

try:
  import faulthandler
except ImportError:
  # //testing/pybase:pybase can't have deps on any extension modules as it
  # is used by code that is executed in such a way it cannot import them. :(
  # We use faulthandler if it is available (either via a user declared dep
  # or from the Python 3.3+ standard library).
  faulthandler = None

# unittest2 is a backport of Python 2.7's unittest for Python 2.6, so
# we don't need it if we are running 2.7 or newer.

if sys.version_info < (2, 7):
  import unittest2 as unittest
else:
  import unittest

from google.apputils import app
import gflags as flags
from google.apputils import shellutil

FLAGS = flags.FLAGS

# ----------------------------------------------------------------------
# Internal functions to extract default flag values from environment.
# ----------------------------------------------------------------------
def _GetDefaultTestRandomSeed():
  random_seed = 301
  value = os.environ.get('TEST_RANDOM_SEED', '')
  try:
    random_seed = int(value)
  except ValueError:
    pass
  return random_seed


def _GetDefaultTestTmpdir():
  tmpdir = os.environ.get('TEST_TMPDIR', '')
  if not tmpdir:
    tmpdir = os.path.join(tempfile.gettempdir(), 'google_apputils_basetest')

  return tmpdir


flags.DEFINE_integer('test_random_seed', _GetDefaultTestRandomSeed(),
                     'Random seed for testing. Some test frameworks may '
                     'change the default value of this flag between runs, so '
                     'it is not appropriate for seeding probabilistic tests.',
                     allow_override=1)
flags.DEFINE_string('test_srcdir',
                    os.environ.get('TEST_SRCDIR', ''),
                    'Root of directory tree where source files live',
                    allow_override=1)
flags.DEFINE_string('test_tmpdir', _GetDefaultTestTmpdir(),
                    'Directory for temporary testing files',
                    allow_override=1)


class BeforeAfterTestCaseMeta(type):

  """Adds setUpTestCase() and tearDownTestCase() methods.

  These may be needed for setup and teardown of shared fixtures usually because
  such fixtures are expensive to setup and teardown (eg Perforce clients).  When
  using such fixtures, care should be taken to keep each test as independent as
  possible (eg via the use of sandboxes).

  Example:

    class MyTestCase(basetest.TestCase):

      __metaclass__ = basetest.BeforeAfterTestCaseMeta

      @classmethod
      def setUpTestCase(cls):
        cls._resource = foo.ReallyExpensiveResource()

      @classmethod
      def tearDownTestCase(cls):
        cls._resource.Destroy()

      def testSomething(self):
        self._resource.Something()
        ...
  """

  _test_loader = unittest.defaultTestLoader

  def __init__(cls, name, bases, dict):
    super(BeforeAfterTestCaseMeta, cls).__init__(name, bases, dict)

    # Notes from mtklein

    # This code can be tricky to think about.  Here are a few things to remember
    # as you read through it.

    # When inheritance is involved, this __init__ is called once on each class
    # in the inheritance chain when that class is defined.  In a typical
    # scenario where a BaseClass inheriting from TestCase declares the
    # __metaclass__ and SubClass inherits from BaseClass, __init__ will be first
    # called with cls=BaseClass when BaseClass is defined, and then called later
    # with cls=SubClass when SubClass is defined.

    # To know when to call setUpTestCase and tearDownTestCase, this class wraps
    # the setUp, tearDown, and test* methods in a TestClass.  We'd like to only
    # wrap those methods in the leaves of the inheritance tree, but we can't
    # know when we're a leaf at wrapping time.  So instead we wrap all the
    # setUp, tearDown, and test* methods, but code them so that we only do the
    # counting we want at the leaves, which we *can* detect when we've got an
    # actual instance to look at --- i.e. self, when a method is running.

    # Because we're wrapping at every level of inheritance, some methods get
    # wrapped multiple times down the inheritance chain; if SubClass were to
    # inherit, say, setUp or testFoo from BaseClass, that method would be
    # wrapped twice, first by BaseClass then by SubClass.  That's OK, because we
    # ensure that the extra code we inject with these wrappers is idempotent.

    # test_names are the test methods this class can see.
    test_names = set(cls._test_loader.getTestCaseNames(cls))

    # Each class keeps a set of the tests it still has to run.  When it's empty,
    # we know we should call tearDownTestCase.  For now, it holds the sentinel
    # value of None, acting as a indication that we need to call setUpTestCase,
    # which fills in the actual tests to run.
    cls.__tests_to_run = None

    # These calls go through and monkeypatch various methods, in no particular
    # order.
    BeforeAfterTestCaseMeta.SetSetUpAttr(cls, test_names)
    BeforeAfterTestCaseMeta.SetTearDownAttr(cls)
    BeforeAfterTestCaseMeta.SetTestMethodAttrs(cls, test_names)
    BeforeAfterTestCaseMeta.SetBeforeAfterTestCaseAttr()

  # Just a little utility function to help with monkey-patching.
  @staticmethod
  def SetMethod(cls, method_name, replacement):
    """Like setattr, but also preserves name, doc, and module metadata."""
    original = getattr(cls, method_name)
    replacement.__name__ = original.__name__
    replacement.__doc__ = original.__doc__
    replacement.__module__ = original.__module__
    setattr(cls, method_name, replacement)

  @staticmethod
  def SetSetUpAttr(cls, test_names):
    """Wraps setUp() with per-class setUp() functionality."""
    # Remember that SetSetUpAttr is eventually called on each class in the
    # inheritance chain.  This line can be subtle because of inheritance.  Say
    # we've got BaseClass that defines setUp, and SubClass inheriting from it
    # that doesn't define setUp.  This method will run twice, and both times
    # cls_setUp will be BaseClass.setUp.  This is one of the tricky cases where
    # setUp will be wrapped multiple times.
    cls_setUp = cls.setUp

    # We create a new setUp method that first checks to see if we need to run
    # setUpTestCase (looking for the __tests_to_run==None flag), and then runs
    # the original setUp method.
    def setUp(self):
      """Function that will encapsulate and replace cls.setUp()."""
      # This line is unassuming but crucial to making this whole system work.
      # It sets leaf to the class of the instance we're currently testing.  That
      # is, leaf is going to be a leaf class.  It's not necessarily the same
      # class as the parameter cls that's being passed in.  For example, in the
      # case above where setUp is in BaseClass, when we instantiate a SubClass
      # and call setUp, we need leaf to be pointing at the class SubClass.
      leaf = self.__class__

      # The reason we want to do this is that it makes sure setUpTestCase is
      # only run once, not once for each class down the inheritance chain.  When
      # multiply-wrapped, this extra code is called multiple times.  In the
      # running example:
      #
      #  1) cls=BaseClass: replace BaseClass' setUp with a wrapped setUp
      #  2) cls=SubClass: set SubClass.setUp to what it thinks was its original
      #     setUp --- the wrapped setUp from 1)
      #
      # So it's double-wrapped, but that's OK.  When we actually call setUp from
      # an instance, we're calling the double-wrapped method.  It sees
      # __tests_to_run is None and fills that in.  Then it calls what it thinks
      # was its original setUp, the singly-wrapped setUp from BaseClass.  The
      # singly-wrapped setUp *skips* the if-statement, as it sees
      # leaf.__tests_to_run is not None now.  It just runs the real, original
      # setUp().

      # test_names is passed in from __init__, and holds all the test cases that
      # cls can see.  In the BaseClass call, that's probably the empty set, and
      # for SubClass it'd have your test methods.

      if leaf.__tests_to_run is None:
        leaf.__tests_to_run = set(test_names)
        self.setUpTestCase()
      cls_setUp(self)

    # Monkeypatch our new setUp method into the place of the original.
    BeforeAfterTestCaseMeta.SetMethod(cls, 'setUp', setUp)

  @staticmethod
  def SetTearDownAttr(cls):
    """Wraps tearDown() with per-class tearDown() functionality."""

    # This is analagous to SetSetUpAttr, except of course it's patching tearDown
    # to run tearDownTestCase when there are no more tests to run.  All the same
    # hairy logic applies.
    cls_tearDown = cls.tearDown

    def tearDown(self):
      """Function that will encapsulate and replace cls.tearDown()."""
      cls_tearDown(self)

      leaf = self.__class__
      # We need to make sure that tearDownTestCase is only run when
      # we're executing this in the leaf class, so we need the
      # explicit leaf == cls check below.
      if (leaf.__tests_to_run is not None
          and not leaf.__tests_to_run
          and leaf == cls):
        leaf.__tests_to_run = None
        self.tearDownTestCase()

    BeforeAfterTestCaseMeta.SetMethod(cls, 'tearDown', tearDown)

  @staticmethod
  def SetTestMethodAttrs(cls, test_names):
    """Makes each test method first remove itself from the remaining set."""
    # This makes each test case remove itself from the set of remaining tests.
    # You might think that this belongs more logically in tearDown, and I'd
    # agree except that tearDown doesn't know what test case it's tearing down!
    # Instead we have the test method itself remove itself before attempting the
    # test.

    # Note that having the test remove itself after running doesn't work, as we
    # never get to 'after running' for tests that fail.

    # Like setUp and tearDown, the test case could conceivably be wrapped
    # twice... but as noted it's an implausible situation to have an actual test
    # defined in a base class.  Just in case, we take the same precaution by
    # looking in only the leaf class' set of __tests_to_run, and using discard()
    # instead of remove() to make the operation idempotent.

    # The closure here makes sure that each new test() function remembers its
    # own values of cls_test and test_name.  Without this, they'd all point to
    # the values from the last iteration of the loop, causing some arbitrary
    # test method to run multiple times and the others never. :(
    def test_closure(cls_test, test_name):
      def test(self, *args, **kargs):
        leaf = self.__class__
        leaf.__tests_to_run.discard(test_name)
        return cls_test(self, *args, **kargs)
      return test

    for test_name in test_names:
      cls_test = getattr(cls, test_name)

      BeforeAfterTestCaseMeta.SetMethod(
          cls, test_name, test_closure(cls_test, test_name))

  @staticmethod
  def SetBeforeAfterTestCaseAttr():
    # This just makes sure every TestCase has a setUpTestCase or
    # tearDownTestCase, so that you can safely define only one or neither of
    # them if you want.
    TestCase.setUpTestCase = lambda self: None
    TestCase.tearDownTestCase = lambda self: None


class TestCase(unittest.TestCase):
  """Extension of unittest.TestCase providing more powerful assertions."""

  maxDiff = 80 * 20

  def __init__(self, methodName='runTest'):
    super(TestCase, self).__init__(methodName)
    self.__recorded_properties = {}

  def shortDescription(self):
    """Format both the test method name and the first line of its docstring.

    If no docstring is given, only returns the method name.

    This method overrides unittest.TestCase.shortDescription(), which
    only returns the first line of the docstring, obscuring the name
    of the test upon failure.

    Returns:
      desc: A short description of a test method.
    """
    desc = str(self)
    # NOTE: super() is used here instead of directly invoking
    # unittest.TestCase.shortDescription(self), because of the
    # following line that occurs later on:
    #       unittest.TestCase = TestCase
    # Because of this, direct invocation of what we think is the
    # superclass will actually cause infinite recursion.
    doc_first_line = super(TestCase, self).shortDescription()
    if doc_first_line is not None:
      desc = '\n'.join((desc, doc_first_line))
    return desc

  def assertSequenceStartsWith(self, prefix, whole, msg=None):
    """An equality assertion for the beginning of ordered sequences.

    If prefix is an empty sequence, it will raise an error unless whole is also
    an empty sequence.

    If prefix is not a sequence, it will raise an error if the first element of
    whole does not match.

    Args:
      prefix: A sequence expected at the beginning of the whole parameter.
      whole: The sequence in which to look for prefix.
      msg: Optional message to append on failure.
    """
    try:
      prefix_len = len(prefix)
    except (TypeError, NotImplementedError):
      prefix = [prefix]
      prefix_len = 1

    try:
      whole_len = len(whole)
    except (TypeError, NotImplementedError):
      self.fail('For whole: len(%s) is not supported, it appears to be type: '
                '%s' % (whole, type(whole)))

    assert prefix_len <= whole_len, (
        'Prefix length (%d) is longer than whole length (%d).' %
        (prefix_len, whole_len))

    if not prefix_len and whole_len:
      self.fail('Prefix length is 0 but whole length is %d: %s' %
                (len(whole), whole))

    try:
      self.assertSequenceEqual(prefix, whole[:prefix_len], msg)
    except AssertionError:
      self.fail(msg or 'prefix: %s not found at start of whole: %s.' %
                (prefix, whole))

  def assertContainsSubset(self, expected_subset, actual_set, msg=None):
    """Checks whether actual iterable is a superset of expected iterable."""
    missing = set(expected_subset) - set(actual_set)
    if not missing:
      return

    missing_msg = 'Missing elements %s\nExpected: %s\nActual: %s' % (
        missing, expected_subset, actual_set)
    if msg:
      msg += ': %s' % missing_msg
    else:
      msg = missing_msg
    self.fail(msg)

  # TODO(user): Provide an assertItemsEqual method when our super class
  # does not provide one.  That method went away in Python 3.2 (renamed
  # to assertCountEqual, or is that different? investigate).

  def assertSameElements(self, expected_seq, actual_seq, msg=None):
    """Assert that two sequences have the same elements (in any order).

    This method, unlike assertItemsEqual, doesn't care about any
    duplicates in the expected and actual sequences.

      >> assertSameElements([1, 1, 1, 0, 0, 0], [0, 1])
      # Doesn't raise an AssertionError

    If possible, you should use assertItemsEqual instead of
    assertSameElements.

    Args:
      expected_seq: A sequence containing elements we are expecting.
      actual_seq: The sequence that we are testing.
      msg: The message to be printed if the test fails.
    """
    # `unittest2.TestCase` used to have assertSameElements, but it was
    # removed in favor of assertItemsEqual. As there's a unit test
    # that explicitly checks this behavior, I am leaving this method
    # alone.
    try:
      expected = dict([(element, None) for element in expected_seq])
      actual = dict([(element, None) for element in actual_seq])
      missing = [element for element in expected if element not in actual]
      unexpected = [element for element in actual if element not in expected]
      missing.sort()
      unexpected.sort()
    except TypeError:
      # Fall back to slower list-compare if any of the objects are
      # not hashable.
      expected = list(expected_seq)
      actual = list(actual_seq)
      expected.sort()
      actual.sort()
      missing, unexpected = _SortedListDifference(expected, actual)
    errors = []
    if missing:
      errors.append('Expected, but missing:\n  %r\n' % missing)
    if unexpected:
      errors.append('Unexpected, but present:\n  %r\n' % unexpected)
    if errors:
      self.fail(msg or ''.join(errors))

  # unittest2.TestCase.assertMulitilineEqual works very similarly, but it
  # has a different error format. However, I find this slightly more readable.
  def assertMultiLineEqual(self, first, second, msg=None):
    """Assert that two multi-line strings are equal."""
    assert isinstance(first, types.StringTypes), (
        'First argument is not a string: %r' % (first,))
    assert isinstance(second, types.StringTypes), (
        'Second argument is not a string: %r' % (second,))

    if first == second:
      return
    if msg:
      failure_message = [msg, ':\n']
    else:
      failure_message = ['\n']
    for line in difflib.ndiff(first.splitlines(True), second.splitlines(True)):
      failure_message.append(line)
      if not line.endswith('\n'):
        failure_message.append('\n')
    raise self.failureException(''.join(failure_message))

  def assertBetween(self, value, minv, maxv, msg=None):
    """Asserts that value is between minv and maxv (inclusive)."""
    if msg is None:
      msg = '"%r" unexpectedly not between "%r" and "%r"' % (value, minv, maxv)
    self.assert_(minv <= value, msg)
    self.assert_(maxv >= value, msg)

  def assertRegexMatch(self, actual_str, regexes, message=None):
    """Asserts that at least one regex in regexes matches str.

    If possible you should use assertRegexpMatches, which is a simpler
    version of this method. assertRegexpMatches takes a single regular
    expression (a string or re compiled object) instead of a list.

    Notes:
    1. This function uses substring matching, i.e. the matching
       succeeds if *any* substring of the error message matches *any*
       regex in the list.  This is more convenient for the user than
       full-string matching.

    2. If regexes is the empty list, the matching will always fail.

    3. Use regexes=[''] for a regex that will always pass.

    4. '.' matches any single character *except* the newline.  To
       match any character, use '(.|\n)'.

    5. '^' matches the beginning of each line, not just the beginning
       of the string.  Similarly, '$' matches the end of each line.

    6. An exception will be thrown if regexes contains an invalid
       regex.

    Args:
      actual_str:  The string we try to match with the items in regexes.
      regexes:  The regular expressions we want to match against str.
        See "Notes" above for detailed notes on how this is interpreted.
      message:  The message to be printed if the test fails.
    """
    if isinstance(regexes, basestring):
      self.fail('regexes is a string; use assertRegexpMatches instead.')
    if not regexes:
      self.fail('No regexes specified.')

    regex_type = type(regexes[0])
    for regex in regexes[1:]:
      if type(regex) is not regex_type:
        self.fail('regexes list must all be the same type.')

    if regex_type is bytes and isinstance(actual_str, unicode):
      regexes = [regex.decode('utf-8') for regex in regexes]
      regex_type = unicode
    elif regex_type is unicode and isinstance(actual_str, bytes):
      regexes = [regex.encode('utf-8') for regex in regexes]
      regex_type = bytes

    if regex_type is unicode:
      regex = u'(?:%s)' % u')|(?:'.join(regexes)
    elif regex_type is bytes:
      regex = b'(?:' + (b')|(?:'.join(regexes)) + b')'
    else:
      self.fail('Only know how to deal with unicode str or bytes regexes.')

    if not re.search(regex, actual_str, re.MULTILINE):
      self.fail(message or ('"%s" does not contain any of these '
                            'regexes: %s.' % (actual_str, regexes)))

  def assertCommandSucceeds(self, command, regexes=(b'',), env=None,
                            close_fds=True):
    """Asserts that a shell command succeeds (i.e. exits with code 0).

    Args:
      command: List or string representing the command to run.
      regexes: List of regular expression byte strings that match success.
      env: Dictionary of environment variable settings.
      close_fds: Whether or not to close all open fd's in the child after
        forking.
    """
    (ret_code, err) = GetCommandStderr(command, env, close_fds)

    # Accommodate code which listed their output regexes w/o the b'' prefix by
    # converting them to bytes for the user.
    if isinstance(regexes[0], unicode):
      regexes = [regex.encode('utf-8') for regex in regexes]

    command_string = GetCommandString(command)
    self.assertEqual(
        ret_code, 0,
        'Running command\n'
        '%s failed with error code %s and message\n'
        '%s' % (
            _QuoteLongString(command_string),
            ret_code,
            _QuoteLongString(err)))
    self.assertRegexMatch(
        err,
        regexes,
        message=(
            'Running command\n'
            '%s failed with error code %s and message\n'
            '%s which matches no regex in %s' % (
                _QuoteLongString(command_string),
                ret_code,
                _QuoteLongString(err),
                regexes)))

  def assertCommandFails(self, command, regexes, env=None, close_fds=True):
    """Asserts a shell command fails and the error matches a regex in a list.

    Args:
      command: List or string representing the command to run.
      regexes: the list of regular expression strings.
      env: Dictionary of environment variable settings.
      close_fds: Whether or not to close all open fd's in the child after
        forking.
    """
    (ret_code, err) = GetCommandStderr(command, env, close_fds)

    # Accommodate code which listed their output regexes w/o the b'' prefix by
    # converting them to bytes for the user.
    if isinstance(regexes[0], unicode):
      regexes = [regex.encode('utf-8') for regex in regexes]

    command_string = GetCommandString(command)
    self.assertNotEqual(
        ret_code, 0,
        'The following command succeeded while expected to fail:\n%s' %
        _QuoteLongString(command_string))
    self.assertRegexMatch(
        err,
        regexes,
        message=(
            'Running command\n'
            '%s failed with error code %s and message\n'
            '%s which matches no regex in %s' % (
                _QuoteLongString(command_string),
                ret_code,
                _QuoteLongString(err),
                regexes)))

  def assertRaisesWithPredicateMatch(self, expected_exception, predicate,
                                     callable_obj, *args,
                                     **kwargs):
    """Asserts that exception is thrown and predicate(exception) is true.

    Args:
      expected_exception: Exception class expected to be raised.
      predicate: Function of one argument that inspects the passed-in exception
        and returns True (success) or False (please fail the test).
      callable_obj: Function to be called.
      args: Extra args.
      kwargs: Extra keyword args.
    """
    try:
      callable_obj(*args, **kwargs)
    except expected_exception as err:
      self.assert_(predicate(err),
                   '%r does not match predicate %r' % (err, predicate))
    else:
      self.fail(expected_exception.__name__ + ' not raised')

  def assertRaisesWithLiteralMatch(self, expected_exception,
                                   expected_exception_message, callable_obj,
                                   *args, **kwargs):
    """Asserts that the message in a raised exception equals the given string.

    Unlike assertRaisesWithRegexpMatch this method takes a literal string, not
    a regular expression.

    Args:
      expected_exception: Exception class expected to be raised.
      expected_exception_message: String message expected in the raised
        exception.  For a raise exception e, expected_exception_message must
        equal str(e).
      callable_obj: Function to be called.
      args: Extra args.
      kwargs: Extra kwargs.
    """
    try:
      callable_obj(*args, **kwargs)
    except expected_exception as err:
      actual_exception_message = str(err)
      self.assert_(expected_exception_message == actual_exception_message,
                   'Exception message does not match.\n'
                   'Expected: %r\n'
                   'Actual: %r' % (expected_exception_message,
                                   actual_exception_message))
    else:
      self.fail(expected_exception.__name__ + ' not raised')

  def assertRaisesWithRegexpMatch(self, expected_exception, expected_regexp,
                                  callable_obj, *args, **kwargs):
    """Asserts that the message in a raised exception matches the given regexp.

    This is just a wrapper around assertRaisesRegexp. Please use
    assertRaisesRegexp instead of assertRaisesWithRegexpMatch.

    Args:
      expected_exception: Exception class expected to be raised.
      expected_regexp: Regexp (re pattern object or string) expected to be
        found in error message.
      callable_obj: Function to be called.
      args: Extra args.
      kwargs: Extra keyword args.
    """
    # TODO(user): this is a good candidate for a global
    # search-and-replace.
    self.assertRaisesRegexp(
        expected_exception,
        expected_regexp,
        callable_obj,
        *args,
        **kwargs)

  def assertContainsInOrder(self, strings, target):
    """Asserts that the strings provided are found in the target in order.

    This may be useful for checking HTML output.

    Args:
      strings: A list of strings, such as [ 'fox', 'dog' ]
      target: A target string in which to look for the strings, such as
        'The quick brown fox jumped over the lazy dog'.
    """
    if not isinstance(strings, list):
      strings = [strings]

    current_index = 0
    last_string = None
    for string in strings:
      index = target.find(str(string), current_index)
      if index == -1 and current_index == 0:
        self.fail("Did not find '%s' in '%s'" %
                  (string, target))
      elif index == -1:
        self.fail("Did not find '%s' after '%s' in '%s'" %
                  (string, last_string, target))
      last_string = string
      current_index = index

  def assertTotallyOrdered(self, *groups):
    """Asserts that total ordering has been implemented correctly.

    For example, say you have a class A that compares only on its attribute x.
    Comparators other than __lt__ are omitted for brevity.

    class A(object):
      def __init__(self, x, y):
        self.x = xio
        self.y = y

      def __hash__(self):
        return hash(self.x)

      def __lt__(self, other):
        try:
          return self.x < other.x
        except AttributeError:
          return NotImplemented

    assertTotallyOrdered will check that instances can be ordered correctly.
    For example,

    self.assertTotallyOrdered(
      [None],  # None should come before everything else.
      [1],     # Integers sort earlier.
      ['foo'],  # As do strings.
      [A(1, 'a')],
      [A(2, 'b')],  # 2 is after 1.
      [A(2, 'c'), A(2, 'd')],  # The second argument is irrelevant.
      [A(3, 'z')])

    Args:
     groups: A list of groups of elements.  Each group of elements is a list
       of objects that are equal.  The elements in each group must be less than
       the elements in the group after it.  For example, these groups are
       totally ordered: [None], [1], [2, 2], [3].
    """

    def CheckOrder(small, big):
      """Ensures small is ordered before big."""
      self.assertFalse(small == big,
                       '%r unexpectedly equals %r' % (small, big))
      self.assertTrue(small != big,
                      '%r unexpectedly equals %r' % (small, big))
      self.assertLess(small, big)
      self.assertFalse(big < small,
                       '%r unexpectedly less than %r' % (big, small))
      self.assertLessEqual(small, big)
      self.assertFalse(big <= small,
                       '%r unexpectedly less than or equal to %r'
                       % (big, small))
      self.assertGreater(big, small)
      self.assertFalse(small > big,
                       '%r unexpectedly greater than %r' % (small, big))
      self.assertGreaterEqual(big, small)
      self.assertFalse(small >= big,
                       '%r unexpectedly greater than or equal to %r'
                       % (small, big))

    def CheckEqual(a, b):
      """Ensures that a and b are equal."""
      self.assertEqual(a, b)
      self.assertFalse(a != b, '%r unexpectedly equals %r' % (a, b))
      self.assertEqual(hash(a), hash(b),
                       'hash %d of %r unexpectedly not equal to hash %d of %r'
                       % (hash(a), a, hash(b), b))
      self.assertFalse(a < b, '%r unexpectedly less than %r' % (a, b))
      self.assertFalse(b < a, '%r unexpectedly less than %r' % (b, a))
      self.assertLessEqual(a, b)
      self.assertLessEqual(b, a)
      self.assertFalse(a > b, '%r unexpectedly greater than %r' % (a, b))
      self.assertFalse(b > a, '%r unexpectedly greater than %r' % (b, a))
      self.assertGreaterEqual(a, b)
      self.assertGreaterEqual(b, a)

    # For every combination of elements, check the order of every pair of
    # elements.
    for elements in itertools.product(*groups):
      elements = list(elements)
      for index, small in enumerate(elements[:-1]):
        for big in elements[index + 1:]:
          CheckOrder(small, big)

    # Check that every element in each group is equal.
    for group in groups:
      for a in group:
        CheckEqual(a, a)
      for a, b in itertools.product(group, group):
        CheckEqual(a, b)

  def assertDictEqual(self, a, b, msg=None):
    """Raises AssertionError if a and b are not equal dictionaries.

    Args:
      a: A dict, the expected value.
      b: A dict, the actual value.
      msg: An optional str, the associated message.

    Raises:
      AssertionError: if the dictionaries are not equal.
    """
    self.assertIsInstance(a, dict, 'First argument is not a dictionary')
    self.assertIsInstance(b, dict, 'Second argument is not a dictionary')

    def Sorted(iterable):
      try:
        return sorted(iterable)  # In 3.3, unordered objects are possible.
      except TypeError:
        return list(iterable)

    if a == b:
      return
    a_items = Sorted(a.iteritems())
    b_items = Sorted(b.iteritems())

    unexpected = []
    missing = []
    different = []

    safe_repr = unittest.util.safe_repr

    def Repr(dikt):
      """Deterministic repr for dict."""
      # Sort the entries based on their repr, not based on their sort order,
      # which will be non-deterministic across executions, for many types.
      entries = sorted((safe_repr(k), safe_repr(v))
                       for k, v in dikt.iteritems())
      return '{%s}' % (', '.join('%s: %s' % pair for pair in entries))

    message = ['%s != %s%s' % (Repr(a), Repr(b), ' (%s)' % msg if msg else '')]

    # The standard library default output confounds lexical difference with
    # value difference; treat them separately.
    for a_key, a_value in a_items:
      if a_key not in b:
        unexpected.append((a_key, a_value))
      elif a_value != b[a_key]:
        different.append((a_key, a_value, b[a_key]))

    if unexpected:
      message.append(
          'Unexpected, but present entries:\n%s' % ''.join(
              '%s: %s\n' % (safe_repr(k), safe_repr(v)) for k, v in unexpected))

    if different:
      message.append(
          'repr() of differing entries:\n%s' % ''.join(
              '%s: %s != %s\n' % (safe_repr(k), safe_repr(a_value),
                                  safe_repr(b_value))
              for k, a_value, b_value in different))

    for b_key, b_value in b_items:
      if b_key not in a:
        missing.append((b_key, b_value))
    if missing:
      message.append(
          'Missing entries:\n%s' % ''.join(
              ('%s: %s\n' % (safe_repr(k), safe_repr(v)) for k, v in missing)))

    raise self.failureException('\n'.join(message))

  def assertUrlEqual(self, a, b):
    """Asserts that urls are equal, ignoring ordering of query params."""
    parsed_a = urlparse.urlparse(a)
    parsed_b = urlparse.urlparse(b)
    self.assertEqual(parsed_a.scheme, parsed_b.scheme)
    self.assertEqual(parsed_a.netloc, parsed_b.netloc)
    self.assertEqual(parsed_a.path, parsed_b.path)
    self.assertEqual(parsed_a.fragment, parsed_b.fragment)
    self.assertEqual(sorted(parsed_a.params.split(';')),
                     sorted(parsed_b.params.split(';')))
    self.assertDictEqual(urlparse.parse_qs(parsed_a.query),
                         urlparse.parse_qs(parsed_b.query))

  def assertSameStructure(self, a, b, aname='a', bname='b', msg=None):
    """Asserts that two values contain the same structural content.

    The two arguments should be data trees consisting of trees of dicts and
    lists. They will be deeply compared by walking into the contents of dicts
    and lists; other items will be compared using the == operator.
    If the two structures differ in content, the failure message will indicate
    the location within the structures where the first difference is found.
    This may be helpful when comparing large structures.

    Args:
      a: The first structure to compare.
      b: The second structure to compare.
      aname: Variable name to use for the first structure in assertion messages.
      bname: Variable name to use for the second structure.
      msg: Additional text to include in the failure message.
    """

    # Accumulate all the problems found so we can report all of them at once
    # rather than just stopping at the first
    problems = []

    _WalkStructureForProblems(a, b, aname, bname, problems)

    # Avoid spamming the user toooo much
    max_problems_to_show = self.maxDiff // 80
    if len(problems) > max_problems_to_show:
      problems = problems[0:max_problems_to_show-1] + ['...']

    if problems:
      failure_message = '; '.join(problems)
      if msg:
        failure_message += (': ' + msg)
      self.fail(failure_message)

  def assertJsonEqual(self, first, second, msg=None):
    """Asserts that the JSON objects defined in two strings are equal.

    A summary of the differences will be included in the failure message
    using assertSameStructure.

    Args:
      first: A string contining JSON to decode and compare to second.
      second: A string contining JSON to decode and compare to first.
      msg: Additional text to include in the failure message.
    """
    try:
      first_structured = json.loads(first)
    except ValueError as e:
      raise ValueError('could not decode first JSON value %s: %s' %
                       (first, e))

    try:
      second_structured = json.loads(second)
    except ValueError as e:
      raise ValueError('could not decode second JSON value %s: %s' %
                       (second, e))

    self.assertSameStructure(first_structured, second_structured,
                             aname='first', bname='second', msg=msg)

  def getRecordedProperties(self):
    """Return any properties that the user has recorded."""
    return self.__recorded_properties

  def recordProperty(self, property_name, property_value):
    """Record an arbitrary property for later use.

    Args:
      property_name: str, name of property to record; must be a valid XML
        attribute name
      property_value: value of property; must be valid XML attribute value
    """
    self.__recorded_properties[property_name] = property_value

  def _getAssertEqualityFunc(self, first, second):
    try:
      return super(TestCase, self)._getAssertEqualityFunc(first, second)
    except AttributeError:
      # This happens if unittest2.TestCase.__init__ was never run. It
      # usually means that somebody created a subclass just for the
      # assertions and has overriden __init__. "assertTrue" is a safe
      # value that will not make __init__ raise a ValueError (this is
      # a bit hacky).
      test_method = getattr(self, '_testMethodName', 'assertTrue')
      super(TestCase, self).__init__(test_method)

    return super(TestCase, self)._getAssertEqualityFunc(first, second)


# This is not really needed here, but some unrelated code calls this
# function.
# TODO(user): sort it out.
def _SortedListDifference(expected, actual):
  """Finds elements in only one or the other of two, sorted input lists.

  Returns a two-element tuple of lists.  The first list contains those
  elements in the "expected" list but not in the "actual" list, and the
  second contains those elements in the "actual" list but not in the
  "expected" list.  Duplicate elements in either input list are ignored.

  Args:
    expected:  The list we expected.
    actual:  The list we actualy got.
  Returns:
    (missing, unexpected)
    missing: items in expected that are not in actual.
    unexpected: items in actual that are not in expected.
  """
  i = j = 0
  missing = []
  unexpected = []
  while True:
    try:
      e = expected[i]
      a = actual[j]
      if e < a:
        missing.append(e)
        i += 1
        while expected[i] == e:
          i += 1
      elif e > a:
        unexpected.append(a)
        j += 1
        while actual[j] == a:
          j += 1
      else:
        i += 1
        try:
          while expected[i] == e:
            i += 1
        finally:
          j += 1
          while actual[j] == a:
            j += 1
    except IndexError:
      missing.extend(expected[i:])
      unexpected.extend(actual[j:])
      break
  return missing, unexpected


# ----------------------------------------------------------------------
# Functions to compare the actual output of a test to the expected
# (golden) output.
#
# Note: We could just replace the sys.stdout and sys.stderr objects,
# but we actually redirect the underlying file objects so that if the
# Python script execs any subprocess, their output will also be
# redirected.
#
# Usage:
#   basetest.CaptureTestStdout()
#   ... do something ...
#   basetest.DiffTestStdout("... path to golden file ...")
# ----------------------------------------------------------------------


class CapturedStream(object):
  """A temporarily redirected output stream."""

  def __init__(self, stream, filename):
    self._stream = stream
    self._fd = stream.fileno()
    self._filename = filename

    # Keep original stream for later
    self._uncaptured_fd = os.dup(self._fd)

    # Open file to save stream to
    cap_fd = os.open(self._filename,
                     os.O_CREAT | os.O_TRUNC | os.O_WRONLY,
                     0600)

    # Send stream to this file
    self._stream.flush()
    os.dup2(cap_fd, self._fd)
    os.close(cap_fd)

  def RestartCapture(self):
    """Resume capturing output to a file (after calling StopCapture)."""
    # Original stream fd
    assert self._uncaptured_fd

    # Append stream to file
    cap_fd = os.open(self._filename,
                     os.O_CREAT | os.O_APPEND | os.O_WRONLY,
                     0600)

    # Send stream to this file
    self._stream.flush()
    os.dup2(cap_fd, self._fd)
    os.close(cap_fd)

  def StopCapture(self):
    """Remove output redirection."""
    self._stream.flush()
    os.dup2(self._uncaptured_fd, self._fd)

  def filename(self):
    return self._filename

  def __del__(self):
    self.StopCapture()
    os.close(self._uncaptured_fd)
    del self._uncaptured_fd


_captured_streams = {}


def _CaptureTestOutput(stream, filename):
  """Redirect an output stream to a file.

  Args:
    stream: Should be sys.stdout or sys.stderr.
    filename: File where output should be stored.
  """
  assert not _captured_streams.has_key(stream)
  _captured_streams[stream] = CapturedStream(stream, filename)


def _DiffTestOutput(stream, golden_filename):
  """Compare ouput of redirected stream to contents of golden file.

  Args:
    stream: Should be sys.stdout or sys.stderr.
    golden_filename: Absolute path to golden file.
  """
  assert _captured_streams.has_key(stream)
  cap = _captured_streams[stream]

  for cap_stream in _captured_streams.itervalues():
    cap_stream.StopCapture()

  try:
    _Diff(cap.filename(), golden_filename)
  finally:
    # remove the current stream
    del _captured_streams[stream]
    # restore other stream capture
    for cap_stream in _captured_streams.itervalues():
      cap_stream.RestartCapture()


# We want to emit exactly one notice to stderr telling the user where to look
# for their stdout or stderr that may have been consumed to aid debugging.
_notified_test_output_path = ''


def _MaybeNotifyAboutTestOutput(outdir):
  global _notified_test_output_path
  if _notified_test_output_path != outdir:
    _notified_test_output_path = outdir
    sys.stderr.write('\nNOTE: Some tests capturing output into: %s\n' % outdir)


# TODO(user): Make CaptureTest* be usable as context managers to easily stop
# capturing at the appropriate time to make debugging failures much easier.


# Public interface
def CaptureTestStdout(outfile=''):
  """Capture the stdout stream to a file until StopCapturing() is called."""
  if not outfile:
    outfile = os.path.join(FLAGS.test_tmpdir, 'captured.out')
    outdir = FLAGS.test_tmpdir
  else:
    outdir = os.path.dirname(outfile)
  _MaybeNotifyAboutTestOutput(outdir)
  _CaptureTestOutput(sys.stdout, outfile)


def CaptureTestStderr(outfile=''):
  """Capture the stderr stream to a file until StopCapturing() is called."""
  if not outfile:
    outfile = os.path.join(FLAGS.test_tmpdir, 'captured.err')
    outdir = FLAGS.test_tmpdir
  else:
    outdir = os.path.dirname(outfile)
  _MaybeNotifyAboutTestOutput(outdir)
  _CaptureTestOutput(sys.stderr, outfile)


def DiffTestStdout(golden):
  _DiffTestOutput(sys.stdout, golden)


def DiffTestStderr(golden):
  _DiffTestOutput(sys.stderr, golden)


def StopCapturing():
  """Stop capturing redirected output.  Debugging sucks if you forget!"""
  while _captured_streams:
    _, cap_stream = _captured_streams.popitem()
    cap_stream.StopCapture()
    del cap_stream


def _WriteTestData(data, filename):
  """Write data into file named filename."""
  fd = os.open(filename, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600)
  if not isinstance(data, (bytes, bytearray)):
    data = data.encode('utf-8')
  os.write(fd, data)
  os.close(fd)


_INT_TYPES = (int, long)  # Sadly there is no types.IntTypes defined for us.


def _WalkStructureForProblems(a, b, aname, bname, problem_list):
  """The recursive comparison behind assertSameStructure."""
  if type(a) != type(b) and not (
      isinstance(a, _INT_TYPES) and isinstance(b, _INT_TYPES)):
    # We do not distinguish between int and long types as 99.99% of Python 2
    # code should never care.  They collapse into a single type in Python 3.
    problem_list.append('%s is a %r but %s is a %r' %
                        (aname, type(a), bname, type(b)))
    # If they have different types there's no point continuing
    return

  if isinstance(a, collections.Mapping):
    for k in a:
      if k in b:
        _WalkStructureForProblems(a[k], b[k],
                                  '%s[%r]' % (aname, k), '%s[%r]' % (bname, k),
                                  problem_list)
      else:
        problem_list.append('%s has [%r] but %s does not' % (aname, k, bname))
    for k in b:
      if k not in a:
        problem_list.append('%s lacks [%r] but %s has it' % (aname, k, bname))

  # Strings are Sequences but we'll just do those with regular !=
  elif isinstance(a, collections.Sequence) and not isinstance(a, basestring):
    minlen = min(len(a), len(b))
    for i in xrange(minlen):
      _WalkStructureForProblems(a[i], b[i],
                                '%s[%d]' % (aname, i), '%s[%d]' % (bname, i),
                                problem_list)
    for i in xrange(minlen, len(a)):
      problem_list.append('%s has [%i] but %s does not' % (aname, i, bname))
    for i in xrange(minlen, len(b)):
      problem_list.append('%s lacks [%i] but %s has it' % (aname, i, bname))

  else:
    if a != b:
      problem_list.append('%s is %r but %s is %r' % (aname, a, bname, b))


class OutputDifferedError(AssertionError):
  pass


class DiffFailureError(Exception):
  pass


def _DiffViaExternalProgram(lhs, rhs, external_diff):
  """Compare two files using an external program; raise if it reports error."""
  # The behavior of this function matches the old _Diff() method behavior
  # when a TEST_DIFF environment variable was set.  A few old things at
  # Google depended on that functionality.
  command = [external_diff, lhs, rhs]
  try:
    subprocess.check_output(command, close_fds=True, stderr=subprocess.STDOUT)
    return True  # No diffs.
  except subprocess.CalledProcessError as error:
    failure_output = error.output
    if error.returncode == 1:
      raise OutputDifferedError('\nRunning %s\n%s\nTest output differed from'
                                ' golden file\n' % (command, failure_output))
  except EnvironmentError as error:
    failure_output = str(error)

  # Running the program failed in some way that wasn't a diff.
  raise DiffFailureError('\nRunning %s\n%s\nFailure diffing test output'
                         ' with golden file\n' % (command, failure_output))


def _Diff(lhs, rhs):
  """Given two pathnames, compare two files.  Raise if they differ."""
  # Some people rely on being able to specify TEST_DIFF in the environment to
  # have tests use their own diff wrapper for use when updating golden data.
  external_diff = os.environ.get('TEST_DIFF')
  if external_diff:
    return _DiffViaExternalProgram(lhs, rhs, external_diff)
  try:
    with open(lhs, 'rt') as lhs_f:
      with open(rhs, 'rt') as rhs_f:
        diff_text = ''.join(
            difflib.unified_diff(lhs_f.readlines(), rhs_f.readlines()))
    if not diff_text:
      return True
    raise OutputDifferedError('\nComparing %s and %s\nTest output differed '
                              'from golden file:\n%s' % (lhs, rhs, diff_text))
  except EnvironmentError as error:
    # Unable to read the files.
    raise DiffFailureError('\nComparing %s and %s\nFailure diffing test output '
                           'with golden file: %s\n' % (lhs, rhs, error))


def DiffTestStringFile(data, golden):
  """Diff data agains a golden file."""
  data_file = os.path.join(FLAGS.test_tmpdir, 'provided.dat')
  _WriteTestData(data, data_file)
  _Diff(data_file, golden)


def DiffTestStrings(data1, data2):
  """Diff two strings."""
  diff_text = ''.join(
      difflib.unified_diff(data1.splitlines(True), data2.splitlines(True)))
  if not diff_text:
    return
  raise OutputDifferedError('\nTest strings differed:\n%s' % diff_text)


def DiffTestFiles(testgen, golden):
  _Diff(testgen, golden)


def GetCommandString(command):
  """Returns an escaped string that can be used as a shell command.

  Args:
    command: List or string representing the command to run.
  Returns:
    A string suitable for use as a shell command.
  """
  if isinstance(command, types.StringTypes):
    return command
  else:
    return shellutil.ShellEscapeList(command)


def GetCommandStderr(command, env=None, close_fds=True):
  """Runs the given shell command and returns a tuple.

  Args:
    command: List or string representing the command to run.
    env: Dictionary of environment variable settings.
    close_fds: Whether or not to close all open fd's in the child after forking.

  Returns:
    Tuple of (exit status, text printed to stdout and stderr by the command).
  """
  if env is None: env = {}
  # Forge needs PYTHON_RUNFILES in order to find the runfiles directory when a
  # Python executable is run by a Python test.  Pass this through from the
  # parent environment if not explicitly defined.
  if os.environ.get('PYTHON_RUNFILES') and not env.get('PYTHON_RUNFILES'):
    env['PYTHON_RUNFILES'] = os.environ['PYTHON_RUNFILES']

  use_shell = isinstance(command, types.StringTypes)
  process = subprocess.Popen(
      command,
      close_fds=close_fds,
      env=env,
      shell=use_shell,
      stderr=subprocess.STDOUT,
      stdout=subprocess.PIPE)
  output = process.communicate()[0]
  exit_status = process.wait()
  return (exit_status, output)


def _QuoteLongString(s):
  """Quotes a potentially multi-line string to make the start and end obvious.

  Args:
    s: A string.

  Returns:
    The quoted string.
  """
  if isinstance(s, (bytes, bytearray)):
    try:
      s = s.decode('utf-8')
    except UnicodeDecodeError:
      s = str(s)
  return ('8<-----------\n' +
          s + '\n' +
          '----------->8\n')


class TestProgramManualRun(unittest.TestProgram):
  """A TestProgram which runs the tests manually."""

  def runTests(self, do_run=False):
    """Run the tests."""
    if do_run:
      unittest.TestProgram.runTests(self)


def main(*args, **kwargs):
  """Executes a set of Python unit tests.

  Usually this function is called without arguments, so the
  unittest.TestProgram instance will get created with the default settings,
  so it will run all test methods of all TestCase classes in the __main__
  module.

  Args:
    args: Positional arguments passed through to unittest.TestProgram.__init__.
    kwargs: Keyword arguments passed through to unittest.TestProgram.__init__.
  """
  _RunInApp(RunTests, args, kwargs)


def _IsInAppMain():
  """Returns True iff app.main or app.really_start is active."""
  f = sys._getframe().f_back
  app_dict = app.__dict__
  while f:
    if f.f_globals is app_dict and f.f_code.co_name in ('run', 'really_start'):
      return True
    f = f.f_back
  return False


class SavedFlag(object):
  """Helper class for saving and restoring a flag value."""

  def __init__(self, flag):
    self.flag = flag
    self.value = flag.value
    self.present = flag.present

  def RestoreFlag(self):
    self.flag.value = self.value
    self.flag.present = self.present




def _RunInApp(function, args, kwargs):
  """Executes a set of Python unit tests, ensuring app.really_start.

  Most users should call basetest.main() instead of _RunInApp.

  _RunInApp calculates argv to be the command-line arguments of this program
  (without the flags), sets the default of FLAGS.alsologtostderr to True,
  then it calls function(argv, args, kwargs), making sure that `function'
  will get called within app.run() or app.really_start(). _RunInApp does this
  by checking whether it is called by either app.run() or
  app.really_start(), or by calling app.really_start() explicitly.

  The reason why app.really_start has to be ensured is to make sure that
  flags are parsed and stripped properly, and other initializations done by
  the app module are also carried out, no matter if basetest.run() is called
  from within or outside app.run().

  If _RunInApp is called from within app.run(), then it will reparse
  sys.argv and pass the result without command-line flags into the argv
  argument of `function'. The reason why this parsing is needed is that
  __main__.main() calls basetest.main() without passing its argv. So the
  only way _RunInApp could get to know the argv without the flags is that
  it reparses sys.argv.

  _RunInApp changes the default of FLAGS.alsologtostderr to True so that the
  test program's stderr will contain all the log messages unless otherwise
  specified on the command-line. This overrides any explicit assignment to
  FLAGS.alsologtostderr by the test program prior to the call to _RunInApp()
  (e.g. in __main__.main).

  Please note that _RunInApp (and the function it calls) is allowed to make
  changes to kwargs.

  Args:
    function: basetest.RunTests or a similar function. It will be called as
        function(argv, args, kwargs) where argv is a list containing the
        elements of sys.argv without the command-line flags.
    args: Positional arguments passed through to unittest.TestProgram.__init__.
    kwargs: Keyword arguments passed through to unittest.TestProgram.__init__.
  """
  if faulthandler:
    try:
      faulthandler.enable()
    except Exception as e:
      sys.stderr.write('faulthandler.enable() failed %r; ignoring.\n' % e)
  if _IsInAppMain():
    # Save command-line flags so the side effects of FLAGS(sys.argv) can be
    # undone.
    saved_flags = dict((f.name, SavedFlag(f))
                       for f in FLAGS.FlagDict().itervalues())

    # Here we'd like to change the default of alsologtostderr from False to
    # True, so the test programs's stderr will contain all the log messages.
    # The desired effect is that if --alsologtostderr is not specified in
    # the command-line, and __main__.main doesn't set FLAGS.logtostderr
    # before calling us (basetest.main), then our changed default takes
    # effect and alsologtostderr becomes True.
    #
    # However, we cannot achive this exact effect, because here we cannot
    # distinguish these situations:
    #
    # A. main.__main__ has changed it to False, it hasn't been specified on
    #    the command-line, and the default was kept as False. We should keep
    #    it as False.
    #
    # B. main.__main__ hasn't changed it, it hasn't been specified on the
    #    command-line, and the default was kept as False. We should change
    #    it to True here.
    #
    # As a workaround, we assume that main.__main__ never changes
    # FLAGS.alsologstderr to False, thus the value of the flag is determined
    # by its default unless the command-line overrides it. We want to change
    # the default to True, and we do it by setting the flag value to True, and
    # letting the command-line override it in FLAGS(sys.argv) below by not
    # restoring it in saved_flag.RestoreFlag().
    if 'alsologtostderr' in saved_flags:
      FLAGS.alsologtostderr = True
      del saved_flags['alsologtostderr']

    # The call FLAGS(sys.argv) parses sys.argv, returns the arguments
    # without the flags, and -- as a side effect -- modifies flag values in
    # FLAGS. We don't want the side effect, because we don't want to
    # override flag changes the program did (e.g. in __main__.main)
    # after the command-line has been parsed. So we have the for loop below
    # to change back flags to their old values.
    argv = FLAGS(sys.argv)
    for saved_flag in saved_flags.itervalues():
      saved_flag.RestoreFlag()


    function(argv, args, kwargs)
  else:
    # Send logging to stderr. Use --alsologtostderr instead of --logtostderr
    # in case tests are reading their own logs.
    if 'alsologtostderr' in FLAGS:
      FLAGS.SetDefault('alsologtostderr', True)

    def Main(argv):
      function(argv, args, kwargs)

    app.really_start(main=Main)


def RunTests(argv, args, kwargs):
  """Executes a set of Python unit tests within app.really_start.

  Most users should call basetest.main() instead of RunTests.

  Please note that RunTests should be called from app.really_start (which is
  called from app.run()). Calling basetest.main() would ensure that.

  Please note that RunTests is allowed to make changes to kwargs.

  Args:
    argv: sys.argv with the command-line flags removed from the front, i.e. the
      argv with which app.run() has called __main__.main.
    args: Positional arguments passed through to unittest.TestProgram.__init__.
    kwargs: Keyword arguments passed through to unittest.TestProgram.__init__.
  """
  test_runner = kwargs.get('testRunner')

  # Make sure tmpdir exists
  if not os.path.isdir(FLAGS.test_tmpdir):
    os.makedirs(FLAGS.test_tmpdir)

  # Run main module setup, if it exists
  main_mod = sys.modules['__main__']
  if hasattr(main_mod, 'setUp') and callable(main_mod.setUp):
    main_mod.setUp()

  # Let unittest.TestProgram.__init__ called by
  # TestProgramManualRun.__init__ do its own argv parsing, e.g. for '-v',
  # on argv, which is sys.argv without the command-line flags.
  kwargs.setdefault('argv', argv)

  try:
    result = None
    test_program = TestProgramManualRun(*args, **kwargs)
    if test_runner:
      test_program.testRunner = test_runner
    else:
      test_program.testRunner = unittest.TextTestRunner(
          verbosity=test_program.verbosity)
    result = test_program.testRunner.run(test_program.test)
  finally:
    # Run main module teardown, if it exists
    if hasattr(main_mod, 'tearDown') and callable(main_mod.tearDown):
      main_mod.tearDown()

  sys.exit(not result.wasSuccessful())