test.py 25.6 KB
Newer Older
1
# SPDX-License-Identifier: GPL-2.0+
2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2012 The Chromium OS Authors.
#

import os
import shutil
import sys
import tempfile
import time
import unittest

# Bring in the patman libraries
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(our_path, '../patman'))

S
Simon Glass 已提交
16 17 18 19 20
from buildman import board
from buildman import bsettings
from buildman import builder
from buildman import control
from buildman import toolchain
21
import commit
S
Simon Glass 已提交
22
import command
23
import terminal
24
import test_util
25
import tools
26

27 28
use_network = True

29 30 31 32 33 34 35 36 37 38
settings_data = '''
# Buildman settings file

[toolchain]
main: /usr/sbin

[toolchain-alias]
x86: i386 x86_64
'''

39 40 41 42 43 44 45 46
migration = '''===================== WARNING ======================
This board does not use CONFIG_DM. CONFIG_DM will be
compulsory starting with the v2020.01 release.
Failure to update may result in board removal.
See doc/driver-model/migration.rst for more info.
====================================================
'''

47 48 49 50
errors = [
    '''main.c: In function 'main_loop':
main.c:260:6: warning: unused variable 'joe' [-Wunused-variable]
''',
51
    '''main.c: In function 'main_loop2':
52 53 54 55 56 57
main.c:295:2: error: 'fred' undeclared (first use in this function)
main.c:295:2: note: each undeclared identifier is reported only once for each function it appears in
make[1]: *** [main.o] Error 1
make: *** [common/libcommon.o] Error 2
Make failed
''',
S
Simon Glass 已提交
58 59 60
    '''arch/arm/dts/socfpga_arria10_socdk_sdmmc.dtb: Warning \
(avoid_unnecessary_addr_size): /clocks: unnecessary #address-cells/#size-cells \
without "ranges" or child "reg" property
61 62 63 64 65 66 67 68 69
''',
    '''powerpc-linux-ld: warning: dot moved backwards before `.bss'
powerpc-linux-ld: warning: dot moved backwards before `.bss'
powerpc-linux-ld: u-boot: section .text lma 0xfffc0000 overlaps previous sections
powerpc-linux-ld: u-boot: section .rodata lma 0xfffef3ec overlaps previous sections
powerpc-linux-ld: u-boot: section .reloc lma 0xffffa400 overlaps previous sections
powerpc-linux-ld: u-boot: section .data lma 0xffffcd38 overlaps previous sections
powerpc-linux-ld: u-boot: section .u_boot_cmd lma 0xffffeb40 overlaps previous sections
powerpc-linux-ld: u-boot: section .bootpg lma 0xfffff198 overlaps previous sections
70 71 72 73 74 75 76 77 78 79 80 81 82 83
''',
   '''In file included from %(basedir)sarch/sandbox/cpu/cpu.c:9:0:
%(basedir)sarch/sandbox/include/asm/state.h:44:0: warning: "xxxx" redefined [enabled by default]
%(basedir)sarch/sandbox/include/asm/state.h:43:0: note: this is the location of the previous definition
%(basedir)sarch/sandbox/cpu/cpu.c: In function 'do_reset':
%(basedir)sarch/sandbox/cpu/cpu.c:27:1: error: unknown type name 'blah'
%(basedir)sarch/sandbox/cpu/cpu.c:28:12: error: expected declaration specifiers or '...' before numeric constant
make[2]: *** [arch/sandbox/cpu/cpu.o] Error 1
make[1]: *** [arch/sandbox/cpu] Error 2
make[1]: *** Waiting for unfinished jobs....
In file included from %(basedir)scommon/board_f.c:55:0:
%(basedir)sarch/sandbox/include/asm/state.h:44:0: warning: "xxxx" redefined [enabled by default]
%(basedir)sarch/sandbox/include/asm/state.h:43:0: note: this is the location of the previous definition
make: *** [sub-make] Error 2
84 85 86 87 88 89
'''
]


# hash, subject, return code, list of errors/warnings
commits = [
90
    ['1234', 'upstream/master, migration warning', 0, []],
91 92 93 94
    ['5678', 'Second commit, a warning', 0, errors[0:1]],
    ['9012', 'Third commit, error', 1, errors[0:2]],
    ['3456', 'Fourth commit, warning', 0, [errors[0], errors[2]]],
    ['7890', 'Fifth commit, link errors', 1, [errors[0], errors[3]]],
95
    ['abcd', 'Sixth commit, fixes all errors', 0, []],
96 97
    ['ef01', 'Seventh commit, fix migration, check directory suppression', 1,
     [errors[4]]],
98 99 100
]

boards = [
101 102 103
    ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 1', 'board0',  ''],
    ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 2', 'board1', ''],
    ['Active', 'powerpc', 'powerpc', '', 'Tester', 'PowerPC board 1', 'board2', ''],
S
Simon Glass 已提交
104
    ['Active', 'powerpc', 'mpc83xx', '', 'Tester', 'PowerPC board 2', 'board3', ''],
105
    ['Active', 'sandbox', 'sandbox', '', 'Tester', 'Sandbox board', 'board4', ''],
106 107
]

108 109
BASE_DIR = 'base'

110 111
OUTCOME_OK, OUTCOME_WARN, OUTCOME_ERR = range(3)

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
class Options:
    """Class that holds build options"""
    pass

class TestBuild(unittest.TestCase):
    """Test buildman

    TODO: Write tests for the rest of the functionality
    """
    def setUp(self):
        # Set up commits to build
        self.commits = []
        sequence = 0
        for commit_info in commits:
            comm = commit.Commit(commit_info[0])
            comm.subject = commit_info[1]
            comm.return_code = commit_info[2]
            comm.error_list = commit_info[3]
130 131
            if sequence < 6:
                 comm.error_list += [migration]
132 133 134 135 136 137 138 139 140 141
            comm.sequence = sequence
            sequence += 1
            self.commits.append(comm)

        # Set up boards to build
        self.boards = board.Boards()
        for brd in boards:
            self.boards.AddBoard(board.Board(*brd))
        self.boards.SelectBoards([])

142 143 144 145
        # Add some test settings
        bsettings.Setup(None)
        bsettings.AddFile(settings_data)

146 147 148 149 150 151 152
        # Set up the toolchains
        self.toolchains = toolchain.Toolchains()
        self.toolchains.Add('arm-linux-gcc', test=False)
        self.toolchains.Add('sparc-linux-gcc', test=False)
        self.toolchains.Add('powerpc-linux-gcc', test=False)
        self.toolchains.Add('gcc', test=False)

153 154 155 156
        # Avoid sending any output
        terminal.SetPrintTestMode()
        self._col = terminal.Color()

157 158 159 160 161 162
        self.base_dir = tempfile.mkdtemp()
        if not os.path.isdir(self.base_dir):
            os.mkdir(self.base_dir)

    def tearDown(self):
        shutil.rmtree(self.base_dir)
163

164
    def Make(self, commit, brd, stage, *args, **kwargs):
165 166 167 168 169 170
        result = command.CommandResult()
        boardnum = int(brd.target[-1])
        result.return_code = 0
        result.stderr = ''
        result.stdout = ('This is the test output for board %s, commit %s' %
                (brd.target, commit.hash))
171 172
        if ((boardnum >= 1 and boardnum >= commit.sequence) or
                boardnum == 4 and commit.sequence == 6):
173
            result.return_code = commit.return_code
174
            result.stderr = (''.join(commit.error_list)
175
                % {'basedir' : self.base_dir + '/.bm-work/00/'})
176 177
        elif commit.sequence < 6:
            result.stderr = migration
178 179 180 181

        result.combined = result.stdout + result.stderr
        return result

182
    def assertSummary(self, text, arch, plus, boards, outcome=OUTCOME_ERR):
183
        col = self._col
184 185
        expected_colour = (col.GREEN if outcome == OUTCOME_OK else
                           col.YELLOW if outcome == OUTCOME_WARN else col.RED)
186 187
        expect = '%10s: ' % arch
        # TODO(sjg@chromium.org): If plus is '', we shouldn't need this
188
        expect += ' ' + col.Color(expected_colour, plus)
189 190 191 192 193
        expect += '  '
        for board in boards:
            expect += col.Color(expected_colour, ' %s' % board)
        self.assertEqual(text, expect)

194 195
    def _SetupTest(self, echo_lines=False, **kwdisplay_args):
        """Set up the test by running a build and summary
196

197 198 199 200 201 202 203 204
        Args:
            echo_lines: True to echo lines to the terminal to aid test
                development
            kwdisplay_args: Dict of arguemnts to pass to
                Builder.SetDisplayOptions()

        Returns:
            Iterator containing the output lines, each a PrintLine() object
205
        """
206
        build = builder.Builder(self.toolchains, self.base_dir, None, 1, 2,
207 208 209 210
                                checkout=False, show_unknown=False)
        build.do_make = self.Make
        board_selected = self.boards.GetSelectedDict()

211 212
        # Build the boards for the pre-defined commits and warnings/errors
        # associated with each. This calls our Make() to inject the fake output.
213 214
        build.BuildBoards(self.commits, board_selected, keep_outputs=False,
                          verbose=False)
215 216 217 218 219 220
        lines = terminal.GetPrintTestLines()
        count = 0
        for line in lines:
            if line.text.strip():
                count += 1

221 222 223
        # We should get two starting messages, an update for every commit built
        # and a summary message
        self.assertEqual(count, len(commits) * len(boards) + 3)
224
        build.SetDisplayOptions(**kwdisplay_args);
S
Simon Glass 已提交
225
        build.ShowSummary(self.commits, board_selected)
226 227 228 229
        if echo_lines:
            terminal.EchoPrintTestLines()
        return iter(terminal.GetPrintTestLines())

230 231 232
    def _CheckOutput(self, lines, list_error_boards=False,
                     filter_dtb_warnings=False,
                     filter_migration_warnings=False):
233
        """Check for expected output from the build summary
234

235 236
        Args:
            lines: Iterator containing the lines returned from the summary
237 238
            list_error_boards: Adjust the check for output produced with the
               --list-error-boards flag
239 240
            filter_dtb_warnings: Adjust the check for output produced with the
               --filter-dtb-warnings flag
241
        """
242
        def add_line_prefix(prefix, boards, error_str, colour):
243 244 245 246 247 248 249
            """Add a prefix to each line of a string

            The training \n in error_str is removed before processing

            Args:
                prefix: String prefix to add
                error_str: Error string containing the lines
250 251
                colour: Expected colour for the line. Note that the board list,
                    if present, always appears in magenta
252 253 254 255 256

            Returns:
                New string where each line has the prefix added
            """
            lines = error_str.strip().splitlines()
257 258 259 260 261 262 263 264 265 266
            new_lines = []
            for line in lines:
                if boards:
                    expect = self._col.Color(colour, prefix + '(')
                    expect += self._col.Color(self._col.MAGENTA, boards,
                                              bright=False)
                    expect += self._col.Color(colour, ') %s' % line)
                else:
                    expect = self._col.Color(colour, prefix + line)
                new_lines.append(expect)
267 268
            return '\n'.join(new_lines)

269 270 271
        col = terminal.Color()
        boards01234 = ('board0 board1 board2 board3 board4'
                       if list_error_boards else '')
272 273 274
        boards1234 = 'board1 board2 board3 board4' if list_error_boards else ''
        boards234 = 'board2 board3 board4' if list_error_boards else ''
        boards34 = 'board3 board4' if list_error_boards else ''
275 276
        boards4 = 'board4' if list_error_boards else ''

277
        # Upstream commit: migration warnings only
278
        self.assertEqual(next(lines).text, '01: %s' % commits[0][1])
279

280 281 282 283 284 285 286 287 288 289 290
        if not filter_migration_warnings:
            self.assertSummary(next(lines).text, 'arm', 'w+',
                               ['board0', 'board1'], outcome=OUTCOME_WARN)
            self.assertSummary(next(lines).text, 'powerpc', 'w+',
                               ['board2', 'board3'], outcome=OUTCOME_WARN)
            self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
                               outcome=OUTCOME_WARN)

            self.assertEqual(next(lines).text,
                add_line_prefix('+', boards01234, migration, col.RED))

291
        # Second commit: all archs should fail with warnings
292
        self.assertEqual(next(lines).text, '02: %s' % commits[1][1])
293

294 295 296 297 298 299 300
        if filter_migration_warnings:
            self.assertSummary(next(lines).text, 'arm', 'w+',
                               ['board1'], outcome=OUTCOME_WARN)
            self.assertSummary(next(lines).text, 'powerpc', 'w+',
                               ['board2', 'board3'], outcome=OUTCOME_WARN)
            self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
                               outcome=OUTCOME_WARN)
301 302

        # Second commit: The warnings should be listed
303 304
        self.assertEqual(next(lines).text,
            add_line_prefix('w+', boards1234, errors[0], col.YELLOW))
305

306
        # Third commit: Still fails
307
        self.assertEqual(next(lines).text, '03: %s' % commits[2][1])
308 309 310
        if filter_migration_warnings:
            self.assertSummary(next(lines).text, 'arm', '',
                               ['board1'], outcome=OUTCOME_OK)
311 312 313
        self.assertSummary(next(lines).text, 'powerpc', '+',
                           ['board2', 'board3'])
        self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
314

315
        # Expect a compiler error
316 317
        self.assertEqual(next(lines).text,
                         add_line_prefix('+', boards234, errors[1], col.RED))
318

319
        # Fourth commit: Compile errors are fixed, just have warning for board3
320
        self.assertEqual(next(lines).text, '04: %s' % commits[3][1])
321 322 323 324 325 326 327 328 329 330 331 332
        if filter_migration_warnings:
            expect = '%10s: ' % 'powerpc'
            expect += ' ' + col.Color(col.GREEN, '')
            expect += '  '
            expect += col.Color(col.GREEN, ' %s' % 'board2')
            expect += ' ' + col.Color(col.YELLOW, 'w+')
            expect += '  '
            expect += col.Color(col.YELLOW, ' %s' % 'board3')
            self.assertEqual(next(lines).text, expect)
        else:
            self.assertSummary(next(lines).text, 'powerpc', 'w+',
                               ['board2', 'board3'], outcome=OUTCOME_WARN)
333
        self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
334
                               outcome=OUTCOME_WARN)
335 336

        # Compile error fixed
337 338
        self.assertEqual(next(lines).text,
                         add_line_prefix('-', boards234, errors[1], col.GREEN))
339

340 341 342 343
        if not filter_dtb_warnings:
            self.assertEqual(
                next(lines).text,
                add_line_prefix('w+', boards34, errors[2], col.YELLOW))
344

345
        # Fifth commit
346
        self.assertEqual(next(lines).text, '05: %s' % commits[4][1])
347 348 349
        if filter_migration_warnings:
            self.assertSummary(next(lines).text, 'powerpc', '', ['board3'],
                               outcome=OUTCOME_OK)
350
        self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
351 352 353 354

        # The second line of errors[3] is a duplicate, so buildman will drop it
        expect = errors[3].rstrip().split('\n')
        expect = [expect[0]] + expect[2:]
355
        expect = '\n'.join(expect)
356 357
        self.assertEqual(next(lines).text,
                         add_line_prefix('+', boards4, expect, col.RED))
358

359 360 361 362
        if not filter_dtb_warnings:
            self.assertEqual(
                next(lines).text,
                add_line_prefix('w-', boards34, errors[2], col.CYAN))
363

364
        # Sixth commit
365
        self.assertEqual(next(lines).text, '06: %s' % commits[5][1])
366 367 368 369 370 371
        if filter_migration_warnings:
            self.assertSummary(next(lines).text, 'sandbox', '', ['board4'],
                               outcome=OUTCOME_OK)
        else:
            self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
                               outcome=OUTCOME_WARN)
372 373 374 375

        # The second line of errors[3] is a duplicate, so buildman will drop it
        expect = errors[3].rstrip().split('\n')
        expect = [expect[0]] + expect[2:]
376
        expect = '\n'.join(expect)
377 378 379 380
        self.assertEqual(next(lines).text,
                         add_line_prefix('-', boards4, expect, col.GREEN))
        self.assertEqual(next(lines).text,
                         add_line_prefix('w-', boards4, errors[0], col.CYAN))
381

382
        # Seventh commit
383
        self.assertEqual(next(lines).text, '07: %s' % commits[6][1])
384 385 386 387 388 389 390 391
        if filter_migration_warnings:
            self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
        else:
            self.assertSummary(next(lines).text, 'arm', '', ['board0', 'board1'],
                               outcome=OUTCOME_OK)
            self.assertSummary(next(lines).text, 'powerpc', '',
                               ['board2', 'board3'], outcome=OUTCOME_OK)
            self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
392 393 394 395

        # Pick out the correct error lines
        expect_str = errors[4].rstrip().replace('%(basedir)s', '').split('\n')
        expect = expect_str[3:8] + [expect_str[-1]]
396
        expect = '\n'.join(expect)
397 398 399 400 401
        if not filter_migration_warnings:
            self.assertEqual(
                next(lines).text,
                add_line_prefix('-', boards01234, migration, col.GREEN))

402 403
        self.assertEqual(next(lines).text,
                         add_line_prefix('+', boards4, expect, col.RED))
404 405 406

        # Now the warnings lines
        expect = [expect_str[0]] + expect_str[10:12] + [expect_str[9]]
407
        expect = '\n'.join(expect)
408 409
        self.assertEqual(next(lines).text,
                         add_line_prefix('w+', boards4, expect, col.YELLOW))
410

411 412 413 414 415 416
    def testOutput(self):
        """Test basic builder operation and output

        This does a line-by-line verification of the summary output.
        """
        lines = self._SetupTest(show_errors=True)
417 418
        self._CheckOutput(lines, list_error_boards=False,
                          filter_dtb_warnings=False)
419 420 421 422 423 424 425

    def testErrorBoards(self):
        """Test output with --list-error-boards

        This does a line-by-line verification of the summary output.
        """
        lines = self._SetupTest(show_errors=True, list_error_boards=True)
426
        self._CheckOutput(lines, list_error_boards=True)
427 428 429 430 431 432 433

    def testFilterDtb(self):
        """Test output with --filter-dtb-warnings

        This does a line-by-line verification of the summary output.
        """
        lines = self._SetupTest(show_errors=True, filter_dtb_warnings=True)
434 435 436 437 438 439 440 441 442 443
        self._CheckOutput(lines, filter_dtb_warnings=True)

    def testFilterMigration(self):
        """Test output with --filter-migration-warnings

        This does a line-by-line verification of the summary output.
        """
        lines = self._SetupTest(show_errors=True,
                                filter_migration_warnings=True)
        self._CheckOutput(lines, filter_migration_warnings=True)
444

445 446 447 448 449 450 451
    def _testGit(self):
        """Test basic builder operation by building a branch"""
        options = Options()
        options.git = os.getcwd()
        options.summary = False
        options.jobs = None
        options.dry_run = False
452
        #options.git = os.path.join(self.base_dir, 'repo')
453 454 455 456 457 458 459 460 461 462 463 464 465
        options.branch = 'test-buildman'
        options.force_build = False
        options.list_tool_chains = False
        options.count = -1
        options.git_dir = None
        options.threads = None
        options.show_unknown = False
        options.quick = False
        options.show_errors = False
        options.keep_outputs = False
        args = ['tegra20']
        control.DoBuildman(options, args)

466 467 468
    def testBoardSingle(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['sandbox']),
469
                         ({'all': ['board4'], 'sandbox': ['board4']}, []))
470 471 472 473

    def testBoardArch(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['arm']),
474 475
                         ({'all': ['board0', 'board1'],
                          'arm': ['board0', 'board1']}, []))
476 477 478 479

    def testBoardArchSingle(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['arm sandbox']),
480
                         ({'sandbox': ['board4'],
S
Simon Glass 已提交
481
                          'all': ['board0', 'board1', 'board4'],
482
                          'arm': ['board0', 'board1']}, []))
S
Simon Glass 已提交
483

484 485 486 487

    def testBoardArchSingleMultiWord(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['arm', 'sandbox']),
488 489 490
                         ({'sandbox': ['board4'],
                          'all': ['board0', 'board1', 'board4'],
                          'arm': ['board0', 'board1']}, []))
491 492 493 494

    def testBoardSingleAnd(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['Tester & arm']),
495 496
                         ({'Tester&arm': ['board0', 'board1'],
                           'all': ['board0', 'board1']}, []))
497 498 499 500 501 502

    def testBoardTwoAnd(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['Tester', '&', 'arm',
                                                   'Tester' '&', 'powerpc',
                                                   'sandbox']),
503
                         ({'sandbox': ['board4'],
S
Simon Glass 已提交
504 505 506
                          'all': ['board0', 'board1', 'board2', 'board3',
                                  'board4'],
                          'Tester&powerpc': ['board2', 'board3'],
507
                          'Tester&arm': ['board0', 'board1']}, []))
508 509 510

    def testBoardAll(self):
        """Test single board selection"""
S
Simon Glass 已提交
511
        self.assertEqual(self.boards.SelectBoards([]),
512 513
                         ({'all': ['board0', 'board1', 'board2', 'board3',
                                  'board4']}, []))
514 515 516 517

    def testBoardRegularExpression(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['T.*r&^Po']),
518 519
                         ({'all': ['board2', 'board3'],
                          'T.*r&^Po': ['board2', 'board3']}, []))
520 521 522 523 524

    def testBoardDuplicate(self):
        """Test single board selection"""
        self.assertEqual(self.boards.SelectBoards(['sandbox sandbox',
                                                   'sandbox']),
525
                         ({'all': ['board4'], 'sandbox': ['board4']}, []))
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
    def CheckDirs(self, build, dirname):
        self.assertEqual('base%s' % dirname, build._GetOutputDir(1))
        self.assertEqual('base%s/fred' % dirname,
                         build.GetBuildDir(1, 'fred'))
        self.assertEqual('base%s/fred/done' % dirname,
                         build.GetDoneFile(1, 'fred'))
        self.assertEqual('base%s/fred/u-boot.sizes' % dirname,
                         build.GetFuncSizesFile(1, 'fred', 'u-boot'))
        self.assertEqual('base%s/fred/u-boot.objdump' % dirname,
                         build.GetObjdumpFile(1, 'fred', 'u-boot'))
        self.assertEqual('base%s/fred/err' % dirname,
                         build.GetErrFile(1, 'fred'))

    def testOutputDir(self):
        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
                                checkout=False, show_unknown=False)
        build.commits = self.commits
        build.commit_count = len(self.commits)
        subject = self.commits[1].subject.translate(builder.trans_valid_chars)
        dirname ='/%02d_of_%02d_g%s_%s' % (2, build.commit_count, commits[1][0],
                                           subject[:20])
        self.CheckDirs(build, dirname)

    def testOutputDirCurrent(self):
        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
                                checkout=False, show_unknown=False)
        build.commits = None
        build.commit_count = 0
        self.CheckDirs(build, '/current')
555

556 557 558 559 560 561 562 563
    def testOutputDirNoSubdirs(self):
        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
                                checkout=False, show_unknown=False,
                                no_subdirs=True)
        build.commits = None
        build.commit_count = 0
        self.CheckDirs(build, '')

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    def testToolchainAliases(self):
        self.assertTrue(self.toolchains.Select('arm') != None)
        with self.assertRaises(ValueError):
            self.toolchains.Select('no-arch')
        with self.assertRaises(ValueError):
            self.toolchains.Select('x86')

        self.toolchains = toolchain.Toolchains()
        self.toolchains.Add('x86_64-linux-gcc', test=False)
        self.assertTrue(self.toolchains.Select('x86') != None)

        self.toolchains = toolchain.Toolchains()
        self.toolchains.Add('i386-linux-gcc', test=False)
        self.assertTrue(self.toolchains.Select('x86') != None)

579 580
    def testToolchainDownload(self):
        """Test that we can download toolchains"""
581
        if use_network:
582 583
            with test_util.capture_sys_output() as (stdout, stderr):
                url = self.toolchains.LocateArchUrl('arm')
584 585
            self.assertRegexpMatches(url, 'https://www.kernel.org/pub/tools/'
                    'crosstool/files/bin/x86_64/.*/'
586
                    'x86_64-gcc-.*-nolibc[-_]arm-.*linux-gnueabi.tar.xz')
587

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    def testGetEnvArgs(self):
        """Test the GetEnvArgs() function"""
        tc = self.toolchains.Select('arm')
        self.assertEqual('arm-linux-',
                         tc.GetEnvArgs(toolchain.VAR_CROSS_COMPILE))
        self.assertEqual('', tc.GetEnvArgs(toolchain.VAR_PATH))
        self.assertEqual('arm',
                         tc.GetEnvArgs(toolchain.VAR_ARCH))
        self.assertEqual('', tc.GetEnvArgs(toolchain.VAR_MAKE_ARGS))

        self.toolchains.Add('/path/to/x86_64-linux-gcc', test=False)
        tc = self.toolchains.Select('x86')
        self.assertEqual('/path/to',
                         tc.GetEnvArgs(toolchain.VAR_PATH))
        tc.override_toolchain = 'clang'
        self.assertEqual('HOSTCC=clang CC=clang',
                         tc.GetEnvArgs(toolchain.VAR_MAKE_ARGS))

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    def testPrepareOutputSpace(self):
        def _Touch(fname):
            tools.WriteFile(os.path.join(base_dir, fname), b'')

        base_dir = tempfile.mkdtemp()

        # Add various files that we want removed and left alone
        to_remove = ['01_of_22_g0982734987_title', '102_of_222_g92bf_title',
                     '01_of_22_g2938abd8_title']
        to_leave = ['something_else', '01-something.patch', '01_of_22_another']
        for name in to_remove + to_leave:
            _Touch(name)

        build = builder.Builder(self.toolchains, base_dir, None, 1, 2)
        build.commits = self.commits
        build.commit_count = len(commits)
        result = set(build._GetOutputSpaceRemovals())
        expected = set([os.path.join(base_dir, f) for f in to_remove])
        self.assertEqual(expected, result)
625

626 627
if __name__ == "__main__":
    unittest.main()