aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/test-recipe
blob: 8cb9409a10c7aa1c18c6e9cc10e31dc1f779ae2e (plain)
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
#!/usr/bin/env python

# Copyright (c) 2016, Intel Corporation.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# DESCRIPTION: Will run recipe tests on each provided recipe.
#
# USAGE: recipe-test --recipes <recipe1 recipe2> --tests all
#
# OPTIONS: --recipes <recipe1>
#          --run-tests <test1 test2>| all
#          --list-tests
#
# NOTE: tests are located in lib/oeqa/recipetests
#
# AUTHOR: Daniel Istrate <daniel.alexandrux.istrate@intel.com>
#


import argparse
import logging
import sys
import os
import time
import unittest

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/lib')
import scriptpath
scriptpath.add_bitbake_lib_path()
scriptpath.add_oe_lib_path()

import oeqa.recipetests
from oeqa.utils.commands import get_test_layer, get_bb_var, bitbake, is_recipe_valid
from oeqa.selftest.base import oeSelfTest
import oeqa.utils.ftools as ftools
from oeqa.recipetests.base import RecipeTests


parser = argparse.ArgumentParser()
parser.add_argument('-r', '--recipes', nargs='+', default=False, dest='recipes',
                    help='recipe(s) to run tests against.')
parser.add_argument('-t', '--run-tests', dest='run_tests', default='all', nargs='*',
                    help='Run specified tests.')
parser.add_argument('-l', '--list-tests', required=False,  action='store_true', dest="list_tests", default=False,
                    help='List all available tests.')

if len(sys.argv) < 2:
    parser.print_usage()
    parser.exit(1)

args = parser.parse_args()


def logger_create():
    log_file = 'test-recipe-' + time.strftime("%Y%m%d%H%M%S") + '.log'
    if os.path.exists('test-recipe.log'):
        os.remove('test-recipe.log')
    os.symlink(log_file, 'test-recipe.log')

    log = logging.getLogger("test-recipe")
    log.setLevel(logging.DEBUG)

    fh = logging.FileHandler(filename=log_file, mode='w')
    fh.setLevel(logging.DEBUG)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    log.addHandler(fh)
    log.addHandler(ch)

    return log

log = logger_create()


def preflight_check():

    log.info("Checking that everything is in order before running the tests")

    if not os.environ.get("BUILDDIR"):
        log.error("BUILDDIR isn't set. Did you forget to source your build environment setup script?")
        return False

    builddir = os.environ.get("BUILDDIR")
    if os.getcwd() != builddir:
        log.info("Changing cwd to %s" % builddir)
        os.chdir(builddir)

    if not "meta-selftest" in get_bb_var("BBLAYERS"):
        log.error("You don't seem to have the meta-selftest layer in BBLAYERS")
        return False

    log.info("Running bitbake -p")
    bitbake("-p")

    return True


def add_include():
    builddir = os.environ.get("BUILDDIR")
    if "#include added by test-recipe" \
        not in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
            log.info("Adding: \"include testrecipe.inc\" in local.conf")
            ftools.append_file(os.path.join(builddir, "conf/local.conf"), \
                    "\n#include added by test-recipe\ninclude required.inc\ninclude testrecipe.inc")

    if "#include added by test-recipe" \
        not in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
            log.info("Adding: \"include bblayers.inc\" in bblayers.conf")
            ftools.append_file(os.path.join(builddir, "conf/bblayers.conf"), \
                    "\n#include added by test-recipe\ninclude bblayers.inc")


def remove_include():
    builddir = os.environ.get("BUILDDIR")
    if builddir is None:
        return
    if "#include added by test-recipe" \
        in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
            log.info("Removing the include from local.conf")
            ftools.remove_from_file(os.path.join(builddir, "conf/local.conf"), \
                    "\n#include added by test-recipe\ninclude required.inc\ninclude testrecipe.inc")

    if "#include added by test-recipe" \
        in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
            log.info("Removing the include from bblayers.conf")
            ftools.remove_from_file(os.path.join(builddir, "conf/bblayers.conf"), \
                    "\n#include added by test-recipe\ninclude bblayers.inc")


def remove_inc_files():
    try:
        os.remove(os.path.join(os.environ.get("BUILDDIR"), "conf/testrecipe.inc"))
        for root, _, files in os.walk(get_test_layer()):
            for f in files:
                if f == 'test_recipe.inc':
                    os.remove(os.path.join(root, f))
    except (AttributeError, OSError,) as e:    # AttributeError may happen if BUILDDIR is not set
        pass

    for incl_file in ['conf/bblayers.inc', 'conf/required.inc']:
        try:
            os.remove(os.path.join(os.environ.get("BUILDDIR"), incl_file))
        except:
            pass


def get_tests_from_module(tmod):
    tlist = []

    try:
        import importlib
        modlib = importlib.import_module(tmod)
        for mod in vars(modlib).values():
            if isinstance(mod, type(RecipeTests)) and issubclass(mod, RecipeTests) and mod is not RecipeTests:
                for test in dir(mod):
                    if test.startswith('test_') and callable(vars(mod)[test]):
                        try:
                            test_description = vars(mod)[test].__doc__.split('\n')[0][:60].strip() + '...'
                        except:
                            test_description = None
                        tlist.append((mod.__module__.split('.')[-1], mod.__name__, test, test_description))

    except:
        pass

    return tlist


def list_recipe_tests():
    tmodules = set()
    testlist = []
    prefix = 'oeqa.recipetests.'

    for tpath in oeqa.recipetests.__path__:
        files = sorted([f for f in os.listdir(tpath) if f.endswith('.py') and not
                        f.startswith(('_', '__')) and f != 'base.py'])
        for f in files:
            tmodules.add(prefix + f.rstrip('.py'))

    # Get all the tests from modules
    tmodules = sorted(list(tmodules))

    for tmod in tmodules:
        testlist += get_tests_from_module(tmod)

    print '%-10s\t%-20s\t%-50s\t%-80s' % ('module', 'class', 'name', 'description')
    print '_' * 160
    for t in testlist:
        print '%-10s\t%-20s\t%-50s\t%-80s' % t
    print '_' * 160
    print 'Total found:\t %s' % len(testlist)


def get_recipe_tests(exclusive_modules=[]):
    testslist = []
    prefix = 'oeqa.recipetests.'

    if exclusive_modules != ['all']:
        for mod in exclusive_modules:
            testslist.append(prefix + mod)

    if not testslist:
        for testpath in oeqa.recipetests.__path__:
            files = sorted([f for f in os.listdir(testpath) if f.endswith('.py') and not f.startswith('__') and f != 'base.py'])
            for f in files:
                module = prefix + f[:-3]
                if module not in testslist:
                    testslist.append(module)

    return testslist


def main():

    if args.list_tests:
        list_recipe_tests()
        return 0

    if args.run_tests != 'all' and not args.recipes:
        print 'Please specify the recipe(s) to tests against ( -r or --recipes).'
        return 1

    # Do we want to be able to test multiple recipes?
    if not is_recipe_valid(args.recipes[0]):
        print '"%s" is not a valid recipe. Make sure it shows up in "bitbake -s". Check your spelling.' % args.recipes[0]
        return 1

    if args.run_tests:
        if not preflight_check():
            return 1

        testslist = get_recipe_tests(exclusive_modules=(args.run_tests or []))

        os.environ['TESTRECIPE'] = args.recipes[0]
        log.info('Running tests for recipe "%s" ...' % args.recipes[0])

        suite = unittest.TestSuite()
        loader = unittest.TestLoader()
        loader.sortTestMethodsUsing = None
        runner = unittest.TextTestRunner(verbosity=2, resultclass=StampedResult)
        # we need to do this here, otherwise just loading the tests
        # will take 2 minutes (bitbake -e calls)
        oeSelfTest.testlayer_path = get_test_layer()

        for test in testslist:
            log.info("Loading tests from: %s" % test)
            try:
                suite.addTests(loader.loadTestsFromName(test))
            except AttributeError as e:
                log.error("Failed to import %s" % test)
                log.error(e)
                return 1
        add_include()

        result = runner.run(suite)

        log.info("Finished")

        if result.wasSuccessful():
            return 0
        else:
            return 1


class StampedResult(unittest.TextTestResult):
    """
    Custom TestResult that prints the time when a test starts.  As test-recipe
    can take a long time (ie a few hours) to run, timestamps help us understand
    what tests are taking a long time to execute.
    """
    def startTest(self, test):
        import time
        self.stream.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " - ")
        super(StampedResult, self).startTest(test)

if __name__ == '__main__':

    try:
        ret = main()
    except Exception:
        ret = 1
        import traceback
        traceback.print_exc(5)
    finally:
        remove_include()
        remove_inc_files()
    sys.exit(ret)