binman: Convert print statements to Python 3
[oweals/u-boot.git] / tools / binman / binman.py
1 #!/usr/bin/env python2
2 # SPDX-License-Identifier: GPL-2.0+
3
4 # Copyright (c) 2016 Google, Inc
5 # Written by Simon Glass <sjg@chromium.org>
6 #
7 # Creates binary images from input files controlled by a description
8 #
9
10 """See README for more information"""
11
12 from __future__ import print_function
13
14 import glob
15 import multiprocessing
16 import os
17 import sys
18 import traceback
19 import unittest
20
21 # Bring in the patman and dtoc libraries
22 our_path = os.path.dirname(os.path.realpath(__file__))
23 for dirname in ['../patman', '../dtoc', '..', '../concurrencytest']:
24     sys.path.insert(0, os.path.join(our_path, dirname))
25
26 # Bring in the libfdt module
27 sys.path.insert(0, 'scripts/dtc/pylibfdt')
28 sys.path.insert(0, os.path.join(our_path,
29                 '../../build-sandbox_spl/scripts/dtc/pylibfdt'))
30
31 import cmdline
32 import command
33 use_concurrent = True
34 try:
35     from concurrencytest import ConcurrentTestSuite, fork_for_tests
36 except:
37     use_concurrent = False
38 import control
39 import test_util
40
41 def RunTests(debug, processes, args):
42     """Run the functional tests and any embedded doctests
43
44     Args:
45         debug: True to enable debugging, which shows a full stack trace on error
46         args: List of positional args provided to binman. This can hold a test
47             name to execute (as in 'binman -t testSections', for example)
48         processes: Number of processes to use to run tests (None=same as #CPUs)
49     """
50     import elf_test
51     import entry_test
52     import fdt_test
53     import ftest
54     import image_test
55     import test
56     import doctest
57
58     result = unittest.TestResult()
59     for module in []:
60         suite = doctest.DocTestSuite(module)
61         suite.run(result)
62
63     sys.argv = [sys.argv[0]]
64     if debug:
65         sys.argv.append('-D')
66     if debug:
67         sys.argv.append('-D')
68
69     # Run the entry tests first ,since these need to be the first to import the
70     # 'entry' module.
71     test_name = args and args[0] or None
72     suite = unittest.TestSuite()
73     loader = unittest.TestLoader()
74     for module in (entry_test.TestEntry, ftest.TestFunctional, fdt_test.TestFdt,
75                    elf_test.TestElf, image_test.TestImage):
76         if test_name:
77             try:
78                 suite.addTests(loader.loadTestsFromName(test_name, module))
79             except AttributeError:
80                 continue
81         else:
82             suite.addTests(loader.loadTestsFromTestCase(module))
83     if use_concurrent and processes != 1:
84         concurrent_suite = ConcurrentTestSuite(suite,
85                 fork_for_tests(processes or multiprocessing.cpu_count()))
86         concurrent_suite.run(result)
87     else:
88         suite.run(result)
89
90     print(result)
91     for test, err in result.errors:
92         print(test.id(), err)
93     for test, err in result.failures:
94         print(err, result.failures)
95     if result.errors or result.failures:
96       print('binman tests FAILED')
97       return 1
98     return 0
99
100 def GetEntryModules(include_testing=True):
101     """Get a set of entry class implementations
102
103     Returns:
104         Set of paths to entry class filenames
105     """
106     glob_list = glob.glob(os.path.join(our_path, 'etype/*.py'))
107     return set([os.path.splitext(os.path.basename(item))[0]
108                 for item in glob_list
109                 if include_testing or '_testing' not in item])
110
111 def RunTestCoverage():
112     """Run the tests and check that we get 100% coverage"""
113     glob_list = GetEntryModules(False)
114     all_set = set([os.path.splitext(os.path.basename(item))[0]
115                    for item in glob_list if '_testing' not in item])
116     test_util.RunTestCoverage('tools/binman/binman.py', None,
117             ['*test*', '*binman.py', 'tools/patman/*', 'tools/dtoc/*'],
118             options.build_dir, all_set)
119
120 def RunBinman(options, args):
121     """Main entry point to binman once arguments are parsed
122
123     Args:
124         options: Command-line options
125         args: Non-option arguments
126     """
127     ret_code = 0
128
129     # For testing: This enables full exception traces.
130     #options.debug = True
131
132     if not options.debug:
133         sys.tracebacklimit = 0
134
135     if options.test:
136         ret_code = RunTests(options.debug, options.processes, args[1:])
137
138     elif options.test_coverage:
139         RunTestCoverage()
140
141     elif options.entry_docs:
142         control.WriteEntryDocs(GetEntryModules())
143
144     else:
145         try:
146             ret_code = control.Binman(options, args)
147         except Exception as e:
148             print('binman: %s' % e)
149             if options.debug:
150                 print()
151                 traceback.print_exc()
152             ret_code = 1
153     return ret_code
154
155
156 if __name__ == "__main__":
157     (options, args) = cmdline.ParseArgs(sys.argv)
158     ret_code = RunBinman(options, args)
159     sys.exit(ret_code)