1import unittest
2import os
3import datetime
4
5from infra.builder import Builder
6from infra.emulator import Emulator
7
8BASIC_TOOLCHAIN_CONFIG = \
9    """
10    BR2_arm=y
11    BR2_TOOLCHAIN_EXTERNAL=y
12    BR2_TOOLCHAIN_EXTERNAL_BOOTLIN=y
13    BR2_TOOLCHAIN_EXTERNAL_BOOTLIN_ARMV5_EABI_GLIBC_STABLE=y
14    """
15
16MINIMAL_CONFIG = \
17    """
18    BR2_INIT_NONE=y
19    BR2_SYSTEM_BIN_SH_NONE=y
20    # BR2_PACKAGE_BUSYBOX is not set
21    # BR2_TARGET_ROOTFS_TAR is not set
22    """
23
24
25class BRConfigTest(unittest.TestCase):
26    """Test up to the configure stage."""
27    config = None
28    br2_external = list()
29    downloaddir = None
30    outputdir = None
31    logtofile = True
32    keepbuilds = False
33    jlevel = 0
34    timeout_multiplier = 1
35
36    def __init__(self, names):
37        super(BRConfigTest, self).__init__(names)
38        self.testname = self.__class__.__name__
39        self.builddir = self.outputdir and os.path.join(self.outputdir, self.testname)
40        self.config += '\nBR2_DL_DIR="{}"\n'.format(self.downloaddir)
41        self.config += "\nBR2_JLEVEL={}\n".format(self.jlevel)
42
43    def show_msg(self, msg):
44        print("{} {:40s} {}".format(datetime.datetime.now().strftime("%H:%M:%S"),
45                                    self.testname, msg))
46
47    def setUp(self):
48        self.show_msg("Starting")
49        self.b = Builder(self.config, self.builddir, self.logtofile, self.jlevel)
50
51        if not self.keepbuilds:
52            self.b.delete()
53
54        if not self.b.is_finished():
55            self.b.configure(make_extra_opts=["BR2_EXTERNAL={}".format(":".join(self.br2_external))])
56
57    def tearDown(self):
58        self.show_msg("Cleaning up")
59        if self.b and not self.keepbuilds:
60            self.b.delete()
61
62
63class BRTest(BRConfigTest):
64    """Test up to the build stage and instantiate an emulator."""
65    def __init__(self, names):
66        super(BRTest, self).__init__(names)
67        self.emulator = None
68
69    def setUp(self):
70        super(BRTest, self).setUp()
71        if not self.b.is_finished():
72            self.show_msg("Building")
73            self.b.build()
74            self.show_msg("Building done")
75
76        self.emulator = Emulator(self.builddir, self.downloaddir,
77                                 self.logtofile, self.timeout_multiplier)
78
79    def tearDown(self):
80        if self.emulator:
81            self.emulator.stop()
82        super(BRTest, self).tearDown()
83
84    # Run the given 'cmd' with a 'timeout' on the target and
85    # assert that the command succeeded; on error, print the
86    # faulty command and its output
87    def assertRunOk(self, cmd, timeout=-1):
88        out, exit_code = self.emulator.run(cmd, timeout)
89        self.assertEqual(
90            exit_code,
91            0,
92            "\nFailed to run: {}\noutput was:\n{}".format(cmd, '  '+'\n  '.join(out))
93        )
94