blob: b4d4a69b0d8ad87cc17c8f6619bdda1c1b44a600 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Copyright (C) 2013 Intel Corporation
2#
3# Released under the MIT license (see COPYING.MIT)
4
5
6# testimage.bbclass enables testing of qemu images using python unittests.
7# Most of the tests are commands run on target image over ssh.
8# To use it add testimage to global inherit and call your target image with -c testimage
9# You can try it out like this:
10# - first build a qemu core-image-sato
11# - add INHERIT += "testimage" in local.conf
12# - then bitbake core-image-sato -c testimage. That will run a standard suite of tests.
13
14# You can set (or append to) TEST_SUITES in local.conf to select the tests
15# which you want to run for your target.
16# The test names are the module names in meta/lib/oeqa/runtime.
17# Each name in TEST_SUITES represents a required test for the image. (no skipping allowed)
18# Appending "auto" means that it will try to run all tests that are suitable for the image (each test decides that on it's own).
19# Note that order in TEST_SUITES is relevant: tests are run in an order such that
20# tests mentioned in @skipUnlessPassed run before the tests that depend on them,
21# but without such dependencies, tests run in the order in which they are listed
22# in TEST_SUITES.
23#
24# A layer can add its own tests in lib/oeqa/runtime, provided it extends BBPATH as normal in its layer.conf.
25
26# TEST_LOG_DIR contains a command ssh log and may contain infromation about what command is running, output and return codes and for qemu a boot log till login.
27# Booting is handled by this class, and it's not a test in itself.
28# TEST_QEMUBOOT_TIMEOUT can be used to set the maximum time in seconds the launch code will wait for the login prompt.
29
30TEST_LOG_DIR ?= "${WORKDIR}/testimage"
31
32TEST_EXPORT_DIR ?= "${TMPDIR}/testimage/${PN}"
33TEST_EXPORT_ONLY ?= "0"
34
35RPMTESTSUITE = "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'smart rpm', '', d)}"
36
37DEFAULT_TEST_SUITES = "ping auto"
38DEFAULT_TEST_SUITES_pn-core-image-minimal = "ping"
39DEFAULT_TEST_SUITES_pn-core-image-sato = "ping ssh df connman syslog xorg scp vnc date dmesg parselogs ${RPMTESTSUITE} \
40 ${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'python', '', d)}"
41DEFAULT_TEST_SUITES_pn-core-image-sato-sdk = "ping ssh df connman syslog xorg scp vnc date perl ldd gcc kernelmodule dmesg python parselogs ${RPMTESTSUITE}"
42DEFAULT_TEST_SUITES_pn-core-image-lsb-sdk = "ping buildcvs buildiptables buildsudoku connman date df gcc kernelmodule ldd pam parselogs perl python scp ${RPMTESTSUITE} ssh syslog logrotate"
43DEFAULT_TEST_SUITES_pn-meta-toolchain = "auto"
44
45# aarch64 has no graphics
46DEFAULT_TEST_SUITES_remove_aarch64 = "xorg vnc"
47
48#qemumips is too slow for buildsudoku
49DEFAULT_TEST_SUITES_remove_qemumips = "buildsudoku"
50
51TEST_SUITES ?= "${DEFAULT_TEST_SUITES}"
52
53TEST_QEMUBOOT_TIMEOUT ?= "1000"
54TEST_TARGET ?= "qemu"
55TEST_TARGET_IP ?= ""
56TEST_SERVER_IP ?= ""
57
58TESTIMAGEDEPENDS = ""
59TESTIMAGEDEPENDS_qemuall = "qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot"
60
61TESTIMAGELOCK = "${TMPDIR}/testimage.lock"
62TESTIMAGELOCK_qemuall = ""
63
64TESTIMAGE_DUMP_DIR ?= "/tmp/oe-saved-tests/"
65
66testimage_dump_target () {
67 top -bn1
68 ps
69 free
70 df
71 # The next command will export the default gateway IP
72 export DEFAULT_GATEWAY=$(ip route | awk '/default/ { print $3}')
73 ping -c3 $DEFAULT_GATEWAY
74 dmesg
75 netstat -an
76 ip address
77 # Next command will dump logs from /var/log/
78 find /var/log/ -type f 2>/dev/null -exec echo "====================" \; -exec echo {} \; -exec echo "====================" \; -exec cat {} \; -exec echo "" \;
79}
80
81testimage_dump_host () {
82 top -bn1
Patrick Williamsf1e5d692016-03-30 15:21:19 -050083 iostat -x -z -N -d -p ALL 20 2
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 ps -ef
85 free
86 df
87 memstat
88 dmesg
Patrick Williamsf1e5d692016-03-30 15:21:19 -050089 ip -s link
Patrick Williamsc124f4f2015-09-15 14:41:29 -050090 netstat -an
91}
92
93python do_testimage() {
94 testimage_main(d)
95}
96addtask testimage
97do_testimage[nostamp] = "1"
98do_testimage[depends] += "${TESTIMAGEDEPENDS}"
99do_testimage[lockfiles] += "${TESTIMAGELOCK}"
100
101python do_testsdk() {
102 testsdk_main(d)
103}
104addtask testsdk
105do_testsdk[nostamp] = "1"
106do_testsdk[depends] += "${TESTIMAGEDEPENDS}"
107do_testsdk[lockfiles] += "${TESTIMAGELOCK}"
108
109# get testcase list from specified file
110# if path is a relative path, then relative to build/conf/
111def read_testlist(d, fpath):
112 if not os.path.isabs(fpath):
113 builddir = d.getVar("TOPDIR", True)
114 fpath = os.path.join(builddir, "conf", fpath)
115 if not os.path.exists(fpath):
116 bb.fatal("No such manifest file: ", fpath)
117 tcs = []
118 for line in open(fpath).readlines():
119 line = line.strip()
120 if line and not line.startswith("#"):
121 tcs.append(line)
122 return " ".join(tcs)
123
124def get_tests_list(d, type="runtime"):
125 testsuites = []
126 testslist = []
127 manifests = d.getVar("TEST_SUITES_MANIFEST", True)
128 if manifests is not None:
129 manifests = manifests.split()
130 for manifest in manifests:
131 testsuites.extend(read_testlist(d, manifest).split())
132 else:
133 testsuites = d.getVar("TEST_SUITES", True).split()
134 if type == "sdk":
135 testsuites = (d.getVar("TEST_SUITES_SDK", True) or "auto").split()
136 bbpath = d.getVar("BBPATH", True).split(':')
137
138 # This relies on lib/ under each directory in BBPATH being added to sys.path
139 # (as done by default in base.bbclass)
140 for testname in testsuites:
141 if testname != "auto":
142 if testname.startswith("oeqa."):
143 testslist.append(testname)
144 continue
145 found = False
146 for p in bbpath:
147 if os.path.exists(os.path.join(p, 'lib', 'oeqa', type, testname + '.py')):
148 testslist.append("oeqa." + type + "." + testname)
149 found = True
150 break
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500151 elif os.path.exists(os.path.join(p, 'lib', 'oeqa', type, testname.split(".")[0] + '.py')):
152 testslist.append("oeqa." + type + "." + testname)
153 found = True
154 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155 if not found:
156 bb.fatal('Test %s specified in TEST_SUITES could not be found in lib/oeqa/runtime under BBPATH' % testname)
157
158 if "auto" in testsuites:
159 def add_auto_list(path):
160 if not os.path.exists(os.path.join(path, '__init__.py')):
161 bb.fatal('Tests directory %s exists but is missing __init__.py' % path)
162 files = sorted([f for f in os.listdir(path) if f.endswith('.py') and not f.startswith('_')])
163 for f in files:
164 module = 'oeqa.' + type + '.' + f[:-3]
165 if module not in testslist:
166 testslist.append(module)
167
168 for p in bbpath:
169 testpath = os.path.join(p, 'lib', 'oeqa', type)
170 bb.debug(2, 'Searching for tests in %s' % testpath)
171 if os.path.exists(testpath):
172 add_auto_list(testpath)
173
174 return testslist
175
176
177def exportTests(d,tc):
178 import json
179 import shutil
180 import pkgutil
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500181 import re
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500182
183 exportpath = d.getVar("TEST_EXPORT_DIR", True)
184
185 savedata = {}
186 savedata["d"] = {}
187 savedata["target"] = {}
188 savedata["host_dumper"] = {}
189 for key in tc.__dict__:
190 # special cases
191 if key != "d" and key != "target" and key != "host_dumper":
192 savedata[key] = getattr(tc, key)
193 savedata["target"]["ip"] = tc.target.ip or d.getVar("TEST_TARGET_IP", True)
194 savedata["target"]["server_ip"] = tc.target.server_ip or d.getVar("TEST_SERVER_IP", True)
195
196 keys = [ key for key in d.keys() if not key.startswith("_") and not key.startswith("BB") \
197 and not key.startswith("B_pn") and not key.startswith("do_") and not d.getVarFlag(key, "func")]
198 for key in keys:
199 try:
200 savedata["d"][key] = d.getVar(key, True)
201 except bb.data_smart.ExpansionError:
202 # we don't care about those anyway
203 pass
204
205 savedata["host_dumper"]["parent_dir"] = tc.host_dumper.parent_dir
206 savedata["host_dumper"]["cmds"] = tc.host_dumper.cmds
207
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500208 json_file = os.path.join(exportpath, "testdata.json")
209 with open(json_file, "w") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500210 json.dump(savedata, f, skipkeys=True, indent=4, sort_keys=True)
211
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500212 # Replace absolute path with relative in the file
213 exclude_path = os.path.join(d.getVar("COREBASE", True),'meta','lib','oeqa')
214 f1 = open(json_file,'r').read()
215 f2 = open(json_file,'w')
216 m = f1.replace(exclude_path,'oeqa')
217 f2.write(m)
218 f2.close()
219
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500220 # now start copying files
221 # we'll basically copy everything under meta/lib/oeqa, with these exceptions
222 # - oeqa/targetcontrol.py - not needed
223 # - oeqa/selftest - something else
224 # That means:
225 # - all tests from oeqa/runtime defined in TEST_SUITES (including from other layers)
226 # - the contents of oeqa/utils and oeqa/runtime/files
227 # - oeqa/oetest.py and oeqa/runexport.py (this will get copied to exportpath not exportpath/oeqa)
228 # - __init__.py files
229 bb.utils.mkdirhier(os.path.join(exportpath, "oeqa/runtime/files"))
230 bb.utils.mkdirhier(os.path.join(exportpath, "oeqa/utils"))
231 # copy test modules, this should cover tests in other layers too
232 for t in tc.testslist:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500233 if re.search("\w+\.\w+\.test_\S+", t):
234 t = '.'.join(t.split('.')[:3])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235 mod = pkgutil.get_loader(t)
236 shutil.copy2(mod.filename, os.path.join(exportpath, "oeqa/runtime"))
237 # copy __init__.py files
238 oeqadir = pkgutil.get_loader("oeqa").filename
239 shutil.copy2(os.path.join(oeqadir, "__init__.py"), os.path.join(exportpath, "oeqa"))
240 shutil.copy2(os.path.join(oeqadir, "runtime/__init__.py"), os.path.join(exportpath, "oeqa/runtime"))
241 # copy oeqa/oetest.py and oeqa/runexported.py
242 shutil.copy2(os.path.join(oeqadir, "oetest.py"), os.path.join(exportpath, "oeqa"))
243 shutil.copy2(os.path.join(oeqadir, "runexported.py"), exportpath)
244 # copy oeqa/utils/*.py
245 for root, dirs, files in os.walk(os.path.join(oeqadir, "utils")):
246 for f in files:
247 if f.endswith(".py"):
248 shutil.copy2(os.path.join(root, f), os.path.join(exportpath, "oeqa/utils"))
249 # copy oeqa/runtime/files/*
250 for root, dirs, files in os.walk(os.path.join(oeqadir, "runtime/files")):
251 for f in files:
252 shutil.copy2(os.path.join(root, f), os.path.join(exportpath, "oeqa/runtime/files"))
253
254 bb.plain("Exported tests to: %s" % exportpath)
255
256
257def testimage_main(d):
258 import unittest
259 import os
260 import oeqa.runtime
261 import time
262 import signal
263 from oeqa.oetest import loadTests, runTests
264 from oeqa.targetcontrol import get_target_controller
265 from oeqa.utils.dump import get_host_dumper
266
267 pn = d.getVar("PN", True)
268 export = oe.utils.conditional("TEST_EXPORT_ONLY", "1", True, False, d)
269 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR", True))
270 if export:
271 bb.utils.remove(d.getVar("TEST_EXPORT_DIR", True), recurse=True)
272 bb.utils.mkdirhier(d.getVar("TEST_EXPORT_DIR", True))
273
274 # tests in TEST_SUITES become required tests
275 # they won't be skipped even if they aren't suitable for a image (like xorg for minimal)
276 # testslist is what we'll actually pass to the unittest loader
277 testslist = get_tests_list(d)
278 testsrequired = [t for t in d.getVar("TEST_SUITES", True).split() if t != "auto"]
279
280 tagexp = d.getVar("TEST_SUITES_TAGS", True)
281
282 # we need the host dumper in test context
283 host_dumper = get_host_dumper(d)
284
285 # the robot dance
286 target = get_target_controller(d)
287
288 class TestContext(object):
289 def __init__(self):
290 self.d = d
291 self.testslist = testslist
292 self.tagexp = tagexp
293 self.testsrequired = testsrequired
294 self.filesdir = os.path.join(os.path.dirname(os.path.abspath(oeqa.runtime.__file__)),"files")
295 self.target = target
296 self.host_dumper = host_dumper
297 self.imagefeatures = d.getVar("IMAGE_FEATURES", True).split()
298 self.distrofeatures = d.getVar("DISTRO_FEATURES", True).split()
299 manifest = os.path.join(d.getVar("DEPLOY_DIR_IMAGE", True), d.getVar("IMAGE_LINK_NAME", True) + ".manifest")
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500300 nomanifest = d.getVar("IMAGE_NO_MANIFEST", True)
301
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500302 self.sigterm = False
303 self.origsigtermhandler = signal.getsignal(signal.SIGTERM)
304 signal.signal(signal.SIGTERM, self.sigterm_exception)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500305
306 if nomanifest is None or nomanifest != "1":
307 try:
308 with open(manifest) as f:
309 self.pkgmanifest = f.read()
310 except IOError as e:
311 bb.fatal("No package manifest file found. Did you build the image?\n%s" % e)
312 else:
313 self.pkgmanifest = ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314
315 def sigterm_exception(self, signum, stackframe):
316 bb.warn("TestImage received SIGTERM, shutting down...")
317 self.sigterm = True
318 self.target.stop()
319
320 # test context
321 tc = TestContext()
322
323 # this is a dummy load of tests
324 # we are doing that to find compile errors in the tests themselves
325 # before booting the image
326 try:
327 loadTests(tc)
328 except Exception as e:
329 import traceback
330 bb.fatal("Loading tests failed:\n%s" % traceback.format_exc())
331
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500332
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500333 if export:
334 signal.signal(signal.SIGTERM, tc.origsigtermhandler)
335 tc.origsigtermhandler = None
336 exportTests(d,tc)
337 else:
338 target.deploy()
339 try:
340 target.start()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500341 starttime = time.time()
342 result = runTests(tc)
343 stoptime = time.time()
344 if result.wasSuccessful():
345 bb.plain("%s - Ran %d test%s in %.3fs" % (pn, result.testsRun, result.testsRun != 1 and "s" or "", stoptime - starttime))
346 msg = "%s - OK - All required tests passed" % pn
347 skipped = len(result.skipped)
348 if skipped:
349 msg += " (skipped=%d)" % skipped
350 bb.plain(msg)
351 else:
352 raise bb.build.FuncFailed("%s - FAILED - check the task log and the ssh log" % pn )
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500353 finally:
354 signal.signal(signal.SIGTERM, tc.origsigtermhandler)
355 target.stop()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356
357testimage_main[vardepsexclude] =+ "BB_ORIGENV"
358
359
360def testsdk_main(d):
361 import unittest
362 import os
363 import glob
364 import oeqa.runtime
365 import oeqa.sdk
366 import time
367 import subprocess
368 from oeqa.oetest import loadTests, runTests
369
370 pn = d.getVar("PN", True)
371 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR", True))
372
373 # tests in TEST_SUITES become required tests
374 # they won't be skipped even if they aren't suitable.
375 # testslist is what we'll actually pass to the unittest loader
376 testslist = get_tests_list(d, "sdk")
377 testsrequired = [t for t in (d.getVar("TEST_SUITES_SDK", True) or "auto").split() if t != "auto"]
378
379 tcname = d.expand("${SDK_DEPLOY}/${TOOLCHAIN_OUTPUTNAME}.sh")
380 if not os.path.exists(tcname):
381 bb.fatal("The toolchain is not built. Build it before running the tests: 'bitbake <image> -c populate_sdk' .")
382
383 class TestContext(object):
384 def __init__(self):
385 self.d = d
386 self.testslist = testslist
387 self.testsrequired = testsrequired
388 self.filesdir = os.path.join(os.path.dirname(os.path.abspath(oeqa.runtime.__file__)),"files")
389 self.sdktestdir = sdktestdir
390 self.sdkenv = sdkenv
391 self.imagefeatures = d.getVar("IMAGE_FEATURES", True).split()
392 self.distrofeatures = d.getVar("DISTRO_FEATURES", True).split()
393 manifest = d.getVar("SDK_TARGET_MANIFEST", True)
394 try:
395 with open(manifest) as f:
396 self.pkgmanifest = f.read()
397 except IOError as e:
398 bb.fatal("No package manifest file found. Did you build the sdk image?\n%s" % e)
399 hostmanifest = d.getVar("SDK_HOST_MANIFEST", True)
400 try:
401 with open(hostmanifest) as f:
402 self.hostpkgmanifest = f.read()
403 except IOError as e:
404 bb.fatal("No host package manifest file found. Did you build the sdk image?\n%s" % e)
405
406 sdktestdir = d.expand("${WORKDIR}/testimage-sdk/")
407 bb.utils.remove(sdktestdir, True)
408 bb.utils.mkdirhier(sdktestdir)
409 try:
410 subprocess.check_output("cd %s; %s <<EOF\n./tc\nY\nEOF" % (sdktestdir, tcname), shell=True)
411 except subprocess.CalledProcessError as e:
412 bb.fatal("Couldn't install the SDK:\n%s" % e.output)
413
414 try:
415 targets = glob.glob(d.expand(sdktestdir + "/tc/environment-setup-*"))
416 bb.warn(str(targets))
417 for sdkenv in targets:
418 bb.plain("Testing %s" % sdkenv)
419 # test context
420 tc = TestContext()
421
422 # this is a dummy load of tests
423 # we are doing that to find compile errors in the tests themselves
424 # before booting the image
425 try:
426 loadTests(tc, "sdk")
427 except Exception as e:
428 import traceback
429 bb.fatal("Loading tests failed:\n%s" % traceback.format_exc())
430
431
432 starttime = time.time()
433 result = runTests(tc, "sdk")
434 stoptime = time.time()
435 if result.wasSuccessful():
436 bb.plain("%s SDK(%s):%s - Ran %d test%s in %.3fs" % (pn, os.path.basename(tcname), os.path.basename(sdkenv),result.testsRun, result.testsRun != 1 and "s" or "", stoptime - starttime))
437 msg = "%s - OK - All required tests passed" % pn
438 skipped = len(result.skipped)
439 if skipped:
440 msg += " (skipped=%d)" % skipped
441 bb.plain(msg)
442 else:
443 raise bb.build.FuncFailed("%s - FAILED - check the task log and the commands log" % pn )
444 finally:
445 bb.utils.remove(sdktestdir, True)
446
447testsdk_main[vardepsexclude] =+ "BB_ORIGENV"
448