File: mb_unittest.py

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1344 lines) | stat: -rwxr-xr-x 42,412 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/env python3
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for mb.py."""

import io
import json
import os
import re
import sys
import textwrap
import unittest

sys.path.insert(
    0,
    os.path.abspath(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')))

from mb import mb


# Call has argument input to match subprocess.run
# pylint: disable=redefined-builtin
class FakeMBW(mb.MetaBuildWrapper):
  def __init__(self, win32=False):
    super().__init__()

    # Override vars for test portability.
    if win32:
      self.chromium_src_dir = 'c:\\fake_src'
      self.default_config = 'c:\\fake_src\\tools\\mb\\mb_config.pyl'
      self.default_isolate_map = ('c:\\fake_src\\testing\\buildbot\\'
                                  'gn_isolate_map.pyl')
      self.temp = 'c:\\temp'
      self.platform = 'win32'
      self.executable = 'c:\\python\\python.exe'
      self.sep = '\\'
      self.cwd = 'c:\\fake_src\\out\\Default'
    else:
      self.chromium_src_dir = '/fake_src'
      self.default_config = '/fake_src/tools/mb/mb_config.pyl'
      self.default_isolate_map = '/fake_src/testing/buildbot/gn_isolate_map.pyl'
      self.temp = '/tmp'
      self.platform = 'linux'
      self.executable = '/usr/bin/python'
      self.sep = '/'
      self.cwd = '/fake_src/out/Default'

    self.files = {}
    self.dirs = set()
    self.calls = []
    self.cmds = []
    self.cross_compile = None
    self.out = ''
    self.err = ''
    self.rmdirs = []

  def Exists(self, path):
    abs_path = self._AbsPath(path)
    return (self.files.get(abs_path) is not None or abs_path in self.dirs)

  def ListDir(self, path):
    dir_contents = []
    for f in list(self.files.keys()) + list(self.dirs):
      head, _ = os.path.split(f)
      if head == path:
        dir_contents.append(f)
    return dir_contents

  def MaybeMakeDirectory(self, path):
    abpath = self._AbsPath(path)
    self.dirs.add(abpath)

  def PathJoin(self, *comps):
    return self.sep.join(comps)

  def ReadFile(self, path):
    try:
      return self.files[self._AbsPath(path)]
    except KeyError as e:
      raise IOError('%s not found' % path) from e

  def WriteFile(self, path, contents, force_verbose=False):
    if self.args.dryrun or self.args.verbose or force_verbose:
      self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
    abpath = self._AbsPath(path)
    self.files[abpath] = contents

  def Call(self, cmd, env=None, capture_output=True, input=None):
    # Avoid unused-argument warnings from Pylint
    del env
    del capture_output
    del input
    self.calls.append(cmd)
    if self.cmds:
      return self.cmds.pop(0)
    return 0, '', ''

  def Print(self, *args, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', '\n')
    f = kwargs.get('file', sys.stdout)
    if f == sys.stderr:
      self.err += sep.join(args) + end
    else:
      self.out += sep.join(args) + end

  def TempDir(self):
    tmp_dir = self.temp + self.sep + 'mb_test'
    self.dirs.add(tmp_dir)
    return tmp_dir

  def TempFile(self, mode='w'):
    # Avoid unused-argument warnings from Pylint
    del mode
    return FakeFile(self.files)

  def RemoveFile(self, path):
    abpath = self._AbsPath(path)
    self.files[abpath] = None

  def RemoveDirectory(self, abs_path):
    # Normalize the passed-in path to handle different working directories
    # used during unit testing.
    abs_path = self._AbsPath(abs_path)
    self.rmdirs.append(abs_path)
    files_to_delete = [f for f in self.files if f.startswith(abs_path)]
    for f in files_to_delete:
      self.files[f] = None

  def _AbsPath(self, path):
    if not ((self.platform == 'win32' and path.startswith('c:')) or
            (self.platform != 'win32' and path.startswith('/'))):
      path = self.PathJoin(self.cwd, path)
    if self.sep == '\\':
      return re.sub(r'\\+', r'\\', path)
    return re.sub('/+', '/', path)


class FakeFile:
  def __init__(self, files):
    self.name = '/tmp/file'
    self.buf = ''
    self.files = files

  def write(self, contents):
    self.buf += contents

  def close(self):
    self.files[self.name] = self.buf


TEST_CONFIG = """\
{
  'builder_groups': {
    'chromium': {},
    'fake_builder_group': {
      'fake_args_bot': 'fake_args_bot',
      'fake_args_file': 'args_file_remoteexec',
      'fake_builder': 'rel_bot',
      'fake_debug_builder': 'debug_remoteexec',
      'fake_multi_phase': { 'phase_1': 'phase_1', 'phase_2': 'phase_2'},
    },
  },
  'configs': {
    'args_file_remoteexec': ['fake_args_bot', 'remoteexec'],
    'debug_remoteexec': ['debug', 'remoteexec'],
    'fake_args_bot': ['fake_args_bot'],
    'phase_1': ['rel', 'phase_1'],
    'phase_2': ['rel', 'phase_2'],
    'rel_bot': ['rel', 'remoteexec', 'fake_feature1'],
  },
  'mixins': {
    'debug': {
      'gn_args': 'is_debug=true',
    },
    'fake_args_bot': {
      'args_file': '//build/args/bots/fake_builder_group/fake_args_bot.gn',
    },
    'fake_feature1': {
      'gn_args': 'enable_doom_melon=true',
    },
    'phase_1': {
      'gn_args': 'phase=1',
    },
    'phase_2': {
      'gn_args': 'phase=2',
    },
    'rel': {
      'gn_args': 'is_debug=false dcheck_always_on=false',
    },
    'remoteexec': {
      'gn_args': 'use_remoteexec=true',
    },
  },
}
"""

CONFIG_STARLARK_GN_ARGS = """\
{
  'gn_args_locations_files': [
      '../../infra/config/generated/builders/gn_args_locations.json',
  ],
  'builder_groups': {
  },
  'configs': {
  },
  'mixins': {
  },
}
"""

TEST_GN_ARGS_LOCATIONS_JSON = """\
{
  "chromium": {
    "linux-official": "ci/linux-official/gn-args.json"
  },
  "tryserver.chromium": {
    "linux-official": "try/linux-official/gn-args.json"
  }
}
"""

TEST_GN_ARGS_JSON = """\
{
  "gn_args": {
    "string_arg": "has double quotes",
    "bool_arg_lower_case": true,
    "string_list_arg": ["foo", "bar", "baz"],
    "dict_arg": {
      "string": "foo",
      "bool": true,
      "list": ["foo", "bar", "baz"]
    }
  }
}
"""

TEST_PHASED_GN_ARGS_JSON = """\
{
  "phases": {
    "phase_1": {
      "gn_args": {
        "string_arg": "has double quotes",
        "bool_arg_lower_case": true
      }
    },
    "phase_2": {
      "gn_args": {
        "string_arg": "second phase",
        "bool_arg_lower_case": false
      }
    }
  }
}
"""

TEST_BAD_CONFIG = """\
{
  'configs': {
    'rel_bot_1': ['rel', 'chrome_with_codecs'],
    'rel_bot_2': ['rel', 'bad_nested_config'],
  },
  'builder_groups': {
    'chromium': {
      'a': 'rel_bot_1',
      'b': 'rel_bot_2',
    },
  },
  'mixins': {
    'chrome_with_codecs': {
      'gn_args': 'proprietary_codecs=true',
    },
    'bad_nested_config': {
      'mixins': ['chrome_with_codecs'],
    },
    'rel': {
      'gn_args': 'is_debug=false',
    },
  },
}
"""


TEST_ARGS_FILE_TWICE_CONFIG = """\
{
  'builder_groups': {
    'chromium': {},
    'fake_builder_group': {
      'fake_args_file_twice': 'args_file_twice',
    },
  },
  'configs': {
    'args_file_twice': ['args_file', 'args_file'],
  },
  'mixins': {
    'args_file': {
      'args_file': '//build/args/fake.gn',
    },
  },
}
"""


TEST_DUP_CONFIG = """\
{
  'builder_groups': {
    'chromium': {},
    'fake_builder_group': {
      'fake_builder': 'some_config',
      'other_builder': 'some_other_config',
    },
  },
  'configs': {
    'some_config': ['args_file'],
    'some_other_config': ['args_file'],
  },
  'mixins': {
    'args_file': {
      'args_file': '//build/args/fake.gn',
    },
  },
}
"""

TRYSERVER_CONFIG = """\
{
  'builder_groups': {
    'not_a_tryserver': {
      'fake_builder': 'fake_config',
    },
    'tryserver.chromium.linux': {
      'try_builder': 'fake_config',
    },
    'tryserver.chromium.mac': {
      'try_builder2': 'fake_config',
    },
  },
  'configs': {},
  'mixins': {},
}
"""


def is_win():
  return sys.platform == 'win32'


class UnitTest(unittest.TestCase):
  """Unit tests for mb.py."""
  maxDiff = None

  def fake_mbw(self, files=None, win32=False):
    mbw = FakeMBW(win32=win32)
    mbw.files.setdefault(mbw.default_config, TEST_CONFIG)
    mbw.files.setdefault(
      mbw.ToAbsPath('//testing/buildbot/gn_isolate_map.pyl'),
      '''{
        "foo_unittests": {
          "label": "//foo:foo_unittests",
          "type": "console_test_launcher",
          "args": [],
        },
      }''')
    mbw.files.setdefault(
        mbw.ToAbsPath('//build/args/bots/fake_builder_group/fake_args_bot.gn'),
        'is_debug = false\ndcheck_always_on=false\n')
    mbw.files.setdefault(mbw.ToAbsPath('//tools/mb/rts_banned_suites.json'),
                         '{}')
    if files:
      for path, contents in files.items():
        mbw.files[path] = contents
    return mbw

  def check(self, args, mbw=None, files=None, out=None, err=None, ret=None,
            env=None):
    if not mbw:
      mbw = self.fake_mbw(files)
    prev_env = os.environ.copy()
    try:
      if env:
        os.environ.clear()
        os.environ.update(env)
      actual_ret = mbw.Main(args)
    finally:
      os.environ.clear()
      os.environ.update(prev_env)
    self.assertEqual(
        actual_ret, ret,
        'ret: %s, out: %s, err: %s' % (actual_ret, mbw.out, mbw.err))
    if out is not None:
      self.assertEqual(mbw.out, out)
    if err is not None:
      self.assertEqual(mbw.err, err)
    return mbw

  def path(self, p):
    if is_win():
      return 'c:' + p.replace('/', '\\')
    return p

  def test_analyze(self):
    files = {'/tmp/in.json': '''{\
               "files": ["foo/foo_unittest.cc"],
               "test_targets": ["foo_unittests"],
               "additional_compile_targets": ["all"]
             }''',
             '/tmp/out.json.gn': '''{\
               "status": "Found dependency",
               "compile_targets": ["//foo:foo_unittests"],
               "test_targets": ["//foo:foo_unittests"]
             }'''}

    mbw = self.fake_mbw(files)
    mbw.Call = lambda cmd, env=None, capture_output=True, input='': (0, '', '')

    self.check([
        'analyze', '-c', 'debug_remoteexec', '//out/Default', '/tmp/in.json',
        '/tmp/out.json'
    ],
               mbw=mbw,
               ret=0)
    out = json.loads(mbw.files['/tmp/out.json'])
    self.assertEqual(out, {
      'status': 'Found dependency',
      'compile_targets': ['foo:foo_unittests'],
      'test_targets': ['foo_unittests']
    })

  def test_analyze_optimizes_compile_for_all(self):
    files = {'/tmp/in.json': '''{\
               "files": ["foo/foo_unittest.cc"],
               "test_targets": ["foo_unittests"],
               "additional_compile_targets": ["all"]
             }''',
             '/tmp/out.json.gn': '''{\
               "status": "Found dependency",
               "compile_targets": ["//foo:foo_unittests", "all"],
               "test_targets": ["//foo:foo_unittests"]
             }'''}

    mbw = self.fake_mbw(files)
    mbw.Call = lambda cmd, env=None, capture_output=True, input='': (0, '', '')

    self.check([
        'analyze', '-c', 'debug_remoteexec', '//out/Default', '/tmp/in.json',
        '/tmp/out.json'
    ],
               mbw=mbw,
               ret=0)
    out = json.loads(mbw.files['/tmp/out.json'])

    # check that 'foo_unittests' is not in the compile_targets
    self.assertEqual(['all'], out['compile_targets'])

  def test_analyze_handles_other_toolchains(self):
    files = {'/tmp/in.json': '''{\
               "files": ["foo/foo_unittest.cc"],
               "test_targets": ["foo_unittests"],
               "additional_compile_targets": ["all"]
             }''',
             '/tmp/out.json.gn': '''{\
               "status": "Found dependency",
               "compile_targets": ["//foo:foo_unittests",
                                   "//foo:foo_unittests(bar)"],
               "test_targets": ["//foo:foo_unittests"]
             }'''}

    mbw = self.fake_mbw(files)
    mbw.Call = lambda cmd, env=None, capture_output=True, input='': (0, '', '')

    self.check([
        'analyze', '-c', 'debug_remoteexec', '//out/Default', '/tmp/in.json',
        '/tmp/out.json'
    ],
               mbw=mbw,
               ret=0)
    out = json.loads(mbw.files['/tmp/out.json'])

    # crbug.com/736215: If GN returns a label containing a toolchain,
    # MB (and Ninja) don't know how to handle it; to work around this,
    # we give up and just build everything we were asked to build. The
    # output compile_targets should include all of the input test_targets and
    # additional_compile_targets.
    self.assertEqual(['all', 'foo_unittests'], out['compile_targets'])

  def test_analyze_handles_way_too_many_results(self):
    too_many_files = ', '.join(['"//foo:foo%d"' % i for i in range(40 * 1024)])
    files = {'/tmp/in.json': '''{\
               "files": ["foo/foo_unittest.cc"],
               "test_targets": ["foo_unittests"],
               "additional_compile_targets": ["all"]
             }''',
             '/tmp/out.json.gn': '''{\
               "status": "Found dependency",
               "compile_targets": [''' + too_many_files + '''],
               "test_targets": ["//foo:foo_unittests"]
             }'''}

    mbw = self.fake_mbw(files)
    mbw.Call = lambda cmd, env=None, capture_output=True, input='': (0, '', '')

    self.check([
        'analyze', '-c', 'debug_remoteexec', '//out/Default', '/tmp/in.json',
        '/tmp/out.json'
    ],
               mbw=mbw,
               ret=0)
    out = json.loads(mbw.files['/tmp/out.json'])

    # If GN returns so many compile targets that we might have command-line
    # issues, we should give up and just build everything we were asked to
    # build. The output compile_targets should include all of the input
    # test_targets and additional_compile_targets.
    self.assertEqual(['all', 'foo_unittests'], out['compile_targets'])

  def test_gen(self):
    mbw = self.fake_mbw()
    self.check(['gen', '-c', 'debug_remoteexec', '//out/Default'],
               mbw=mbw,
               ret=0)
    self.assertMultiLineEqual(mbw.files['/fake_src/out/Default/args.gn'],
                              ('is_debug = true\n'
                               'use_remoteexec = true\n'))

    # Make sure we log both what is written to args.gn and the command line.
    self.assertIn('Writing """', mbw.out)
    self.assertIn('/fake_src/buildtools/linux64/gn gen //out/Default --check',
                  mbw.err)

    mbw = self.fake_mbw(win32=True)
    self.check(['gen', '-c', 'debug_remoteexec', '//out/Debug'], mbw=mbw, ret=0)
    self.assertMultiLineEqual(mbw.files['c:\\fake_src\\out\\Debug\\args.gn'],
                              ('is_debug = true\n'
                               'use_remoteexec = true\n'))
    self.assertIn(
        'c:\\fake_src\\buildtools\\win\\gn.exe gen //out/Debug '
        '--check', mbw.err)

    mbw = self.fake_mbw()
    self.check(['gen', '-m', 'fake_builder_group', '-b', 'fake_args_bot',
                '//out/Debug'],
               mbw=mbw, ret=0)
    # TODO: crbug.com/40134852 - This assert is inappropriately failing.
    # self.assertEqual(
    #     mbw.files['/fake_src/out/Debug/args.gn'],
    #     'import("//build/args/bots/fake_builder_group/fake_args_bot.gn")\n')

  def test_gen_args_file_mixins(self):
    mbw = self.fake_mbw()
    self.check(['gen', '-m', 'fake_builder_group', '-b', 'fake_args_file',
                '//out/Debug'], mbw=mbw, ret=0)

    self.assertEqual(
        mbw.files['/fake_src/out/Debug/args.gn'],
        ('import("//build/args/bots/fake_builder_group/fake_args_bot.gn")\n'
         'use_remoteexec = true\n'))

  def test_gen_args_file_twice(self):
    mbw = self.fake_mbw()
    mbw.files[mbw.default_config] = TEST_ARGS_FILE_TWICE_CONFIG
    self.check(['gen', '-m', 'fake_builder_group', '-b', 'fake_args_file_twice',
                '//out/Debug'], mbw=mbw, ret=1)

  def test_gen_fails(self):
    mbw = self.fake_mbw()
    mbw.Call = lambda cmd, env=None, capture_output=True, input='': (1, '', '')
    self.check(['gen', '-c', 'debug_remoteexec', '//out/Default'],
               mbw=mbw,
               ret=1)

  def test_gen_swarming(self):
    files = {
        '/tmp/swarming_targets':
        'base_unittests\n',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }

    mbw = self.fake_mbw(files)

    def fake_call(cmd, env=None, capture_output=True, input=''):
      del cmd
      del env
      del capture_output
      del input
      mbw.files['/fake_src/out/Default/base_unittests.runtime_deps'] = (
          'base_unittests\n')
      return 0, '', ''

    mbw.Call = fake_call

    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '//out/Default'
    ],
               mbw=mbw,
               ret=0)
    self.assertIn('/fake_src/out/Default/base_unittests.isolate', mbw.files)
    self.assertIn('/fake_src/out/Default/base_unittests.isolated.gen.json',
                  mbw.files)

  def test_gen_swarming_script(self):
    files = {
      '/tmp/swarming_targets': 'cc_perftests\n',
      '/fake_src/testing/buildbot/gn_isolate_map.pyl': (
          "{'cc_perftests': {"
          "  'label': '//cc:cc_perftests',"
          "  'type': 'script',"
          "  'script': '/fake_src/out/Default/test_script.py',"
          "}}\n"
      ),
    }
    mbw = self.fake_mbw(files=files)

    def fake_call(cmd, env=None, capture_output=True, input=''):
      del cmd
      del env
      del capture_output
      del input
      mbw.files['/fake_src/out/Default/cc_perftests.runtime_deps'] = (
          'cc_perftests\n')
      return 0, '', ''

    mbw.Call = fake_call

    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '--isolate-map-file',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl', '//out/Default'
    ],
               mbw=mbw,
               ret=0)
    self.assertIn('/fake_src/out/Default/cc_perftests.isolate', mbw.files)
    self.assertIn('/fake_src/out/Default/cc_perftests.isolated.gen.json',
                  mbw.files)

  def test_multiple_isolate_maps(self):
    files = {
        '/tmp/swarming_targets':
        'cc_perftests\n',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'cc_perftests': {"
         "  'label': '//cc:cc_perftests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/testing/buildbot/gn_isolate_map2.pyl':
        ("{'cc_perftests2': {"
         "  'label': '//cc:cc_perftests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }
    mbw = self.fake_mbw(files=files)

    def fake_call(cmd, env=None, capture_output=True, input=''):
      del cmd
      del env
      del capture_output
      del input
      mbw.files['/fake_src/out/Default/cc_perftests.runtime_deps'] = (
          'cc_perftests_fuzzer\n')
      return 0, '', ''

    mbw.Call = fake_call

    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '--isolate-map-file',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl', '--isolate-map-file',
        '/fake_src/testing/buildbot/gn_isolate_map2.pyl', '//out/Default'
    ],
               mbw=mbw,
               ret=0)
    self.assertIn('/fake_src/out/Default/cc_perftests.isolate', mbw.files)
    self.assertIn('/fake_src/out/Default/cc_perftests.isolated.gen.json',
                  mbw.files)

  def test_duplicate_isolate_maps(self):
    files = {
        '/tmp/swarming_targets':
        'cc_perftests\n',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'cc_perftests': {"
         "  'label': '//cc:cc_perftests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/testing/buildbot/gn_isolate_map2.pyl':
        ("{'cc_perftests': {"
         "  'label': '//cc:cc_perftests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        r'c:\\fake_src\out\Default\cc_perftests.exe.runtime_deps':
        ('cc_perftests\n'),
    }
    mbw = self.fake_mbw(files=files, win32=True)
    # Check that passing duplicate targets into mb fails.
    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '--isolate-map-file',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl', '--isolate-map-file',
        '/fake_src/testing/buildbot/gn_isolate_map2.pyl', '//out/Default'
    ],
               mbw=mbw,
               ret=1)

  def test_isolate(self):
    files = {
        '/fake_src/out/Default/toolchain.ninja':
        '',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/out/Default/base_unittests.runtime_deps':
        ('base_unittests\n'),
    }
    self.check([
        'isolate', '-c', 'debug_remoteexec', '//out/Default', 'base_unittests'
    ],
               files=files,
               ret=0)

    # test running isolate on an existing build_dir
    files['/fake_src/out/Default/args.gn'] = 'is_debug = true\n'
    self.check(['isolate', '//out/Default', 'base_unittests'],
               files=files, ret=0)

    self.check(['isolate', '//out/Default', 'base_unittests'],
               files=files, ret=0)

    # Existing build dir that uses a .gni import.
    files['/fake_src/out/Default/args.gn'] = 'import("//import/args.gni")\n'
    files['/fake_src/import/args.gni'] = 'is_debug = true\n'
    self.check(['isolate', '//out/Default', 'base_unittests'],
               files=files,
               ret=0)

  def test_dedup_runtime_deps(self):
    files = {
        '/tmp/swarming_targets':
        'base_unittests\n',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }

    mbw = self.fake_mbw(files)

    def fake_call(cmd, env=None, capture_output=True, input=''):
      del cmd
      del env
      del capture_output
      del input
      mbw.files['/fake_src/out/Default/base_unittests.runtime_deps'] = (
          'base_unittests\n'
          '../../filters/some_filter/\n'
          '../../filters/some_filter/foo\n'
          '../../filters/another_filter/hoo\n')
      return 0, '', ''

    mbw.Call = fake_call

    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '//out/Default'
    ],
               mbw=mbw,
               ret=0)
    self.assertIn('/fake_src/out/Default/base_unittests.isolate', mbw.files)
    files = mbw.files.get('/fake_src/out/Default/base_unittests.isolate')
    self.assertIn('../../filters/some_filter', files)
    self.assertNotIn('../../filters/some_filter/foo', files)
    self.assertIn('../../filters/another_filter/hoo', files)

  def test_gen_isolate_generated_dir(self):
    files = {
        '/tmp/swarming_targets':
        'base_unittests\n',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }

    mbw = self.fake_mbw(files)

    def fake_call(cmd, env=None, capture_output=True, input=''):
      del cmd
      del env
      del capture_output
      del input
      mbw.files['/fake_src/out/Default/base_unittests.runtime_deps'] = (
          'test_data/\n')
      return 0, '', ''

    mbw.Call = fake_call

    self.check([
        'gen', '-c', 'debug_remoteexec', '--swarming-targets-file',
        '/tmp/swarming_targets', '//out/Default'
    ],
               mbw=mbw,
               ret=1)
    expected_err = ('error: gn `data` items may not list generated directories;'
                    ' list files in directory instead for:\n'
                    '//out/Default/test_data/\n')
    self.assertIn(expected_err, mbw.err)

  def test_isolate_dir(self):
    files = {
        '/fake_src/out/Default/toolchain.ninja':
        '',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }
    mbw = self.fake_mbw(files=files)
    mbw.cmds.append((0, '', ''))  # Result of `gn gen`
    mbw.cmds.append((0, '', ''))  # Result of `autoninja`

    # Result of `gn desc runtime_deps`
    mbw.cmds.append((0, 'base_unitests\n../../test_data/\n', ''))
    self.check([
        'isolate', '-c', 'debug_remoteexec', '//out/Default', 'base_unittests'
    ],
               mbw=mbw,
               ret=0)

  def test_isolate_generated_dir(self):
    files = {
        '/fake_src/out/Default/toolchain.ninja':
        '',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
    }
    mbw = self.fake_mbw(files=files)
    mbw.cmds.append((0, '', ''))  # Result of `gn gen`
    mbw.cmds.append((0, '', ''))  # Result of `autoninja`

    # Result of `gn desc runtime_deps`
    mbw.cmds.append((0, 'base_unitests\ntest_data/\n', ''))
    expected_err = ('error: gn `data` items may not list generated directories;'
                    ' list files in directory instead for:\n'
                    '//out/Default/test_data/\n')
    self.check([
        'isolate', '-c', 'debug_remoteexec', '//out/Default', 'base_unittests'
    ],
               mbw=mbw,
               ret=1)
    self.assertEqual(mbw.err[-len(expected_err):], expected_err)

  def test_run(self):
    files = {
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/out/Default/base_unittests.runtime_deps':
        ('base_unittests\n'),
    }
    mbw = self.check(
        [
            'run',
            '-c',
            'debug_remoteexec',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        files=files,
        ret=0,
    )
    # pylint: disable=line-too-long
    self.assertEqual(
        mbw.files['/fake_src/out/Default/base_unittests.isolate'],
          '{"variables": {"command": ["vpython3", "../../testing/test_env.py", "./base_unittests", "--test-launcher-bot-mode", "--asan=0", "--lsan=0", "--msan=0", "--tsan=0", "--cfi-diag=0"], "files": ["../../.vpython3", "../../testing/test_env.py"]}}\n')
    # pylint: enable=line-too-long

    # Check to make sure we're including the relative cwd and the
    # command line in the call to `isolate`.
    self.assertIn(
        'relative-cwd out/Default -- vpython3 '
        '../../testing/test_env.py', mbw.err)

  def test_run_swarmed(self):
    files = {
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/out/Default/base_unittests.runtime_deps':
        ('base_unittests\n'),
        '/fake_src/out/Default/base_unittests.archive.json':
        ('{\"base_unittests\":\"fake_hash\"}'),
        '/fake_src/third_party/depot_tools/cipd_manifest.txt':
        ('# vpython\n'
         '/some/vpython/pkg  git_revision:deadbeef\n'),
    }

    task_json = json.dumps({'tasks': [{'task_id': '00000'}]})
    collect_json = json.dumps({'00000': {'results': {}}})

    mbw = self.fake_mbw(files=files)
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'task.json')] = task_json
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'collect_output.json')] = collect_json
    original_impl = mbw.ToSrcRelPath

    def to_src_rel_path_stub(path):
      if path.endswith('base_unittests.archive.json'):
        return 'base_unittests.archive.json'
      return original_impl(path)

    mbw.ToSrcRelPath = to_src_rel_path_stub

    self.check(
        [
            'run',
            '-s',
            '-c',
            'debug_remoteexec',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        mbw=mbw,
        ret=0,
    )

    # Specify a custom dimension via '-d'.
    mbw = self.fake_mbw(files=files)
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'task.json')] = task_json
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'collect_output.json')] = collect_json
    mbw.ToSrcRelPath = to_src_rel_path_stub
    self.check(
        [
            'run',
            '-s',
            '-c',
            'debug_remoteexec',
            '-d',
            'os',
            'Win7',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        mbw=mbw,
        ret=0,
    )

    # Use the internal swarming server via '--internal'.
    mbw = self.fake_mbw(files=files)
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'task.json')] = task_json
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'collect_output.json')] = collect_json
    mbw.ToSrcRelPath = to_src_rel_path_stub
    self.check(
        [
            'run',
            '-s',
            '--internal',
            '-c',
            'debug_remoteexec',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        mbw=mbw,
        ret=0,
    )

  def test_run_swarmed_task_failure(self):
    files = {
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ("{'base_unittests': {"
         "  'label': '//base:base_unittests',"
         "  'type': 'console_test_launcher',"
         "}}\n"),
        '/fake_src/out/Default/base_unittests.runtime_deps':
        ('base_unittests\n'),
        '/fake_src/out/Default/base_unittests.archive.json':
        ('{\"base_unittests\":\"fake_hash\"}'),
        '/fake_src/third_party/depot_tools/cipd_manifest.txt':
        ('# vpython\n'
         '/some/vpython/pkg  git_revision:deadbeef\n'),
    }

    task_json = json.dumps({'tasks': [{'task_id': '00000'}]})
    collect_json = json.dumps({'00000': {'results': {'exit_code': 1}}})

    mbw = self.fake_mbw(files=files)
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'task.json')] = task_json
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'collect_output.json')] = collect_json
    original_impl = mbw.ToSrcRelPath

    def to_src_rel_path_stub(path):
      if path.endswith('base_unittests.archive.json'):
        return 'base_unittests.archive.json'
      return original_impl(path)

    mbw.ToSrcRelPath = to_src_rel_path_stub

    self.check(
        [
            'run',
            '-s',
            '-c',
            'debug_remoteexec',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        mbw=mbw,
        ret=1,
    )
    mbw = self.fake_mbw(files=files)
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'task.json')] = task_json
    mbw.files[mbw.PathJoin(mbw.TempDir(), 'collect_output.json')] = collect_json
    mbw.ToSrcRelPath = to_src_rel_path_stub
    self.check(
        [
            'run',
            '-s',
            '-c',
            'debug_remoteexec',
            '-d',
            'os',
            'Win7',
            '//out/Default',
            'base_unittests',
            '--force',
        ],
        mbw=mbw,
        ret=1,
    )

  def test_lookup(self):
    self.check(['lookup', '-c', 'debug_remoteexec'],
               ret=0,
               out=('\n'
                    'Writing """\\\n'
                    'is_debug = true\n'
                    'use_remoteexec = true\n'
                    '""" to _path_/args.gn.\n\n'
                    '/fake_src/buildtools/linux64/gn gen _path_\n'))

  def gen_starlark_gn_args_mbw(self, gn_args_json):
    files = {
        self.path('/fake_src/tools/mb/mb_config.pyl'):
        CONFIG_STARLARK_GN_ARGS,
        self.path('/fake_src/tools/mb/../../infra/config/generated/builders/'
                  'gn_args_locations.json'):
        TEST_GN_ARGS_LOCATIONS_JSON,
        self.path('/fake_src/tools/mb/../../infra/config/generated/builders/'
                  'ci/linux-official/gn-args.json'):
        gn_args_json,
    }
    return self.fake_mbw(files=files, win32=is_win())

  def test_lookup_starlark_gn_args(self):
    mbw = self.gen_starlark_gn_args_mbw(TEST_GN_ARGS_JSON)
    expected_out = ('\n'
                    'Writing """\\\n'
                    'bool_arg_lower_case = true\n'
                    'dict_arg = { bool = true\n'
                    'list = [ "foo", "bar", "baz" ]\n'
                    'string = "foo" }\n'
                    'string_arg = "has double quotes"\n'
                    'string_list_arg = [ "foo", "bar", "baz" ]\n'
                    '""" to _path_/args.gn.\n\n')
    if sys.platform == 'win32':
      expected_out += 'c:\\fake_src\\buildtools\\win\\gn.exe gen _path_\n'
    else:
      expected_out += '/fake_src/buildtools/linux64/gn gen _path_\n'
    self.check(['lookup', '-m', 'chromium', '-b', 'linux-official'],
               mbw=mbw,
               ret=0,
               out=expected_out)

  def test_lookup_starlark_gn_args_specified_phase(self):
    mbw = self.gen_starlark_gn_args_mbw(TEST_GN_ARGS_JSON)
    self.check([
        'lookup', '-m', 'chromium', '-b', 'linux-official', '--phase', 'phase_1'
    ],
               mbw=mbw,
               ret=1)
    self.assertIn(
        'MBErr: Must not specify a build --phase '
        'for linux-official on chromium', mbw.err)

  def test_lookup_starlark_phased_gn_args(self):
    mbw = self.gen_starlark_gn_args_mbw(TEST_PHASED_GN_ARGS_JSON)
    expected_out = ('\n'
                    'Writing """\\\n'
                    'bool_arg_lower_case = false\n'
                    'string_arg = "second phase"\n'
                    '""" to _path_/args.gn.\n\n')
    if sys.platform == 'win32':
      expected_out += 'c:\\fake_src\\buildtools\\win\\gn.exe gen _path_\n'
    else:
      expected_out += '/fake_src/buildtools/linux64/gn gen _path_\n'
    self.check([
        'lookup', '-m', 'chromium', '-b', 'linux-official', '--phase', 'phase_2'
    ],
               mbw=mbw,
               ret=0,
               out=expected_out)

  def test_lookup_starlark_phased_gn_args_no_phase(self):
    mbw = self.gen_starlark_gn_args_mbw(TEST_PHASED_GN_ARGS_JSON)
    self.check(['lookup', '-m', 'chromium', '-b', 'linux-official'],
               mbw=mbw,
               ret=1)
    self.assertIn(
        'MBErr: Must specify a build --phase for linux-official on chromium',
        mbw.err)

  def test_lookup_starlark_phased_gn_args_wrong_phase(self):
    mbw = self.gen_starlark_gn_args_mbw(TEST_PHASED_GN_ARGS_JSON)
    self.check([
        'lookup', '-m', 'chromium', '-b', 'linux-official', '--phase', 'phase_3'
    ],
               mbw=mbw,
               ret=1)
    self.assertIn(
        'MBErr: Phase phase_3 doesn\'t exist for linux-official on chromium',
        mbw.err)

  def test_lookup_gn_args_with_non_existent_gn_args_location_file(self):
    files = {
        self.path('/fake_src/tools/mb/mb_config.pyl'):
        textwrap.dedent("""\
            {
              'gn_args_locations_files': [
                '../../infra/config/generated/builders/gn_args_locations.json',
              ],
              'builder_groups': {
                'fake-group': {
                  'fake-builder': 'fake-config',
                },
              },
              'configs': {
                'fake-config': [],
              },
              'mixins': {},
            }
        """)
    }
    mbw = self.fake_mbw(files=files, win32=is_win())
    self.check(['lookup', '-m', 'fake-group', '-b', 'fake-builder'],
               mbw=mbw,
               ret=0)

  def test_quiet_lookup(self):
    self.check(['lookup', '-c', 'debug_remoteexec', '--quiet'],
               ret=0,
               out=('is_debug = true\n'
                    'use_remoteexec = true\n'))

  def test_help(self):
    orig_stdout = sys.stdout
    try:
      sys.stdout = io.StringIO()
      self.assertRaises(SystemExit, self.check, ['-h'])
      self.assertRaises(SystemExit, self.check, ['help'])
      self.assertRaises(SystemExit, self.check, ['help', 'gen'])
    finally:
      sys.stdout = orig_stdout

  def test_multiple_phases(self):
    # Check that not passing a --phase to a multi-phase builder fails.
    mbw = self.check(['lookup', '-m', 'fake_builder_group', '-b',
                      'fake_multi_phase'], ret=1)
    self.assertIn('Must specify a build --phase', mbw.err)

    # Check that passing a --phase to a single-phase builder fails.
    mbw = self.check(['lookup', '-m', 'fake_builder_group', '-b',
                      'fake_builder', '--phase', 'phase_1'], ret=1)
    self.assertIn('Must not specify a build --phase', mbw.err)

    # Check that passing a wrong phase key to a multi-phase builder fails.
    mbw = self.check(['lookup', '-m', 'fake_builder_group', '-b',
                      'fake_multi_phase', '--phase', 'wrong_phase'], ret=1)
    self.assertIn('Phase wrong_phase doesn\'t exist', mbw.err)

    # Check that passing a correct phase key to a multi-phase builder passes.
    mbw = self.check(['lookup', '-m', 'fake_builder_group', '-b',
                      'fake_multi_phase', '--phase', 'phase_1'], ret=0)
    self.assertIn('phase = 1', mbw.out)

    mbw = self.check(['lookup', '-m', 'fake_builder_group', '-b',
                      'fake_multi_phase', '--phase', 'phase_2'], ret=0)
    self.assertIn('phase = 2', mbw.out)

  def test_recursive_lookup(self):
    files = {
        '/fake_src/build/args/fake.gn': (
          'enable_doom_melon = true\n'
          'enable_antidoom_banana = true\n'
        )
    }
    self.check([
        'lookup', '-m', 'fake_builder_group', '-b', 'fake_args_file',
        '--recursive'
    ],
               files=files,
               ret=0,
               out=('dcheck_always_on = false\n'
                    'is_debug = false\n'
                    'use_remoteexec = true\n'))

  def test_train(self):
    mbw = self.fake_mbw()
    temp_dir = mbw.TempDir()
    self.check(['train', '--expectations-dir', temp_dir], mbw=mbw, ret=0)
    self.assertIn(os.path.join(temp_dir, 'fake_builder_group.json'), mbw.files)

  def test_validate(self):
    mbw = self.fake_mbw()
    self.check(['validate'], mbw=mbw, ret=0)

  def test_bad_validate(self):
    mbw = self.fake_mbw()
    mbw.files[mbw.default_config] = TEST_BAD_CONFIG
    self.check(['validate', '-f', mbw.default_config], mbw=mbw, ret=1)

  def test_duplicate_validate(self):
    mbw = self.fake_mbw()
    mbw.files[mbw.default_config] = TEST_DUP_CONFIG
    self.check(['validate'], mbw=mbw, ret=1)
    self.assertIn(
        'Duplicate configs detected. When evaluated fully, the '
        'following configs are all equivalent: \'some_config\', '
        '\'some_other_config\'.', mbw.err)

  def test_good_expectations_validate(self):
    mbw = self.fake_mbw()
    # Train the expectations normally.
    temp_dir = mbw.TempDir()
    self.check(['train', '--expectations-dir', temp_dir], mbw=mbw, ret=0)
    # Immediately validating them should pass.
    self.check(['validate', '--expectations-dir', temp_dir], mbw=mbw, ret=0)

  def test_bad_expectations_validate(self):
    mbw = self.fake_mbw()
    # Train the expectations normally.
    temp_dir = mbw.TempDir()
    self.check(['train', '--expectations-dir', temp_dir], mbw=mbw, ret=0)
    # Remove one of the expectation files.
    mbw.files.pop(os.path.join(temp_dir, 'fake_builder_group.json'))
    # Now validating should fail.
    self.check(['validate', '--expectations-dir', temp_dir], mbw=mbw, ret=1)
    self.assertIn('Expectations out of date', mbw.err)

  def test_build_command_unix(self):
    files = {
        '/fake_src/out/Default/toolchain.ninja':
        '',
        '/fake_src/testing/buildbot/gn_isolate_map.pyl':
        ('{"base_unittests": {'
         '  "label": "//base:base_unittests",'
         '  "type": "console_test_launcher",'
         '  "args": [],'
         '}}\n')
    }

    mbw = self.fake_mbw(files)
    self.check(['run', '//out/Default', 'base_unittests', '--force'],
               mbw=mbw,
               ret=0)
    self.assertIn(['autoninja', '-C', 'out/Default', 'base_unittests'],
                  mbw.calls)

  def test_build_command_windows(self):
    files = {
        'c:\\fake_src\\out\\Default\\toolchain.ninja':
        '',
        'c:\\fake_src\\testing\\buildbot\\gn_isolate_map.pyl':
        ('{"base_unittests": {'
         '  "label": "//base:base_unittests",'
         '  "type": "console_test_launcher",'
         '  "args": [],'
         '}}\n')
    }

    mbw = self.fake_mbw(files, True)
    self.check(['run', '//out/Default', 'base_unittests', '--force'],
               mbw=mbw,
               ret=0)
    self.assertIn(['autoninja.bat', '-C', 'out\\Default', 'base_unittests'],
                  mbw.calls)

  def test_lookup_non_existent_builder_group(self):
    """Ensure correct behavior when non-existent builder group is specified.

    Lookups for builders that don't exist in the config file return a different
    exit code so that they can be distinguished from other errors.
    """
    mbw = self.fake_mbw()
    self.check(
        [
            'lookup', '-m', 'non-existent-builder-group', '-b',
            'non-existent-builder'
        ],
        mbw=mbw,
        ret=2,
    )
    self.assertIn(
        'MBErr: Builder group name "non-existent-builder-group" not found',
        mbw.err)

  def test_lookup_non_existent_builder(self):
    """Ensure correct behavior when non-existent builder is specified.

    Lookups for builders that don't exist in the config file return a different
    exit code so that they can be distinguished from other errors.
    """
    mbw = self.fake_mbw()
    self.check(
        ['lookup', '-m', 'fake_builder_group', '-b', 'non-existent-builder'],
        mbw=mbw,
        ret=2)
    self.assertIn(
        'MBErr: Builder name "non-existent-builder" not found under groups',
        mbw.err)


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