diff options
Diffstat (limited to 'poky/meta/lib')
34 files changed, 855 insertions, 132 deletions
diff --git a/poky/meta/lib/oe/cve_check.py b/poky/meta/lib/oe/cve_check.py new file mode 100644 index 000000000..ce755f940 --- /dev/null +++ b/poky/meta/lib/oe/cve_check.py @@ -0,0 +1,60 @@ +import collections +import re +import itertools +import functools + +_Version = collections.namedtuple( + "_Version", ["release", "patch_l", "pre_l", "pre_v"] +) + +@functools.total_ordering +class Version(): + + def __init__(self, version, suffix=None): + if str(suffix) == "alphabetical": + version_pattern = r"""r?v?(?:(?P<release>[0-9]+(?:[-\.][0-9]+)*)(?P<patch>[-_\.]?(?P<patch_l>[a-z]))?(?P<pre>[-_\.]?(?P<pre_l>(rc|alpha|beta|pre|preview|dev))[-_\.]?(?P<pre_v>[0-9]+)?)?)(.*)?""" + else: + version_pattern = r"""r?v?(?:(?P<release>[0-9]+(?:[-\.][0-9]+)*)(?P<pre>[-_\.]?(?P<pre_l>(rc|alpha|beta|pre|preview|dev))[-_\.]?(?P<pre_v>[0-9]+)?)?)(.*)?""" + regex = re.compile(r"^\s*" + version_pattern + r"\s*$", re.VERBOSE | re.IGNORECASE) + + match = regex.search(version) + if not match: + raise Exception("Invalid version: '{0}'".format(version)) + + self._version = _Version( + release=tuple(int(i) for i in match.group("release").replace("-",".").split(".")), + patch_l=match.group("patch_l") if str(suffix) == "alphabetical" and match.group("patch_l") else "", + pre_l=match.group("pre_l"), + pre_v=match.group("pre_v") + ) + + self._key = _cmpkey( + self._version.release, + self._version.patch_l, + self._version.pre_l, + self._version.pre_v + ) + + def __eq__(self, other): + if not isinstance(other, Version): + return NotImplemented + return self._key == other._key + + def __gt__(self, other): + if not isinstance(other, Version): + return NotImplemented + return self._key > other._key + +def _cmpkey(release, patch_l, pre_l, pre_v): + # remove leading 0 + _release = tuple( + reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))) + ) + + _patch = patch_l.upper() + + if pre_l is None and pre_v is None: + _pre = float('inf') + else: + _pre = float(pre_v) if pre_v else float('-inf') + return _release, _patch, _pre diff --git a/poky/meta/lib/oe/package_manager/__init__.py b/poky/meta/lib/oe/package_manager/__init__.py index 42225a3b2..8e7128b19 100644 --- a/poky/meta/lib/oe/package_manager/__init__.py +++ b/poky/meta/lib/oe/package_manager/__init__.py @@ -328,7 +328,11 @@ class PackageManager(object, metaclass=ABCMeta): try: bb.note("Installing globbed packages...") cmd = ["oe-pkgdata-util", "-p", pkgdatadir, "list-pkgs", globs] - pkgs = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8") + bb.note('Running %s' % cmd) + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = proc.communicate() + if stderr: bb.note(stderr.decode("utf-8")) + pkgs = stdout.decode("utf-8") self.install(pkgs.split(), attempt_only=True) except subprocess.CalledProcessError as e: # Return code 1 means no packages matched @@ -384,7 +388,10 @@ class PackageManager(object, metaclass=ABCMeta): cmd.extend(['--exclude=' + '|'.join(exclude.split())]) try: bb.note('Running %s' % cmd) - complementary_pkgs = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8") + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = proc.communicate() + if stderr: bb.note(stderr.decode("utf-8")) + complementary_pkgs = stdout.decode("utf-8") complementary_pkgs = set(complementary_pkgs.split()) skip_pkgs = sorted(complementary_pkgs & provided_pkgs) install_pkgs = sorted(complementary_pkgs - provided_pkgs) diff --git a/poky/meta/lib/oe/package_manager/deb/__init__.py b/poky/meta/lib/oe/package_manager/deb/__init__.py index 10ad707c2..7fdfdaa4f 100644 --- a/poky/meta/lib/oe/package_manager/deb/__init__.py +++ b/poky/meta/lib/oe/package_manager/deb/__init__.py @@ -287,7 +287,8 @@ class DpkgPM(OpkgDpkgPM): try: bb.note("Installing the following packages: %s" % ' '.join(pkgs)) - subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT) + output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT) + bb.note(output.decode("utf-8")) except subprocess.CalledProcessError as e: (bb.fatal, bb.warn)[attempt_only]("Unable to install packages. " "Command '%s' returned %d:\n%s" % @@ -343,8 +344,12 @@ class DpkgPM(OpkgDpkgPM): if feed_uris == "": return + sources_conf = os.path.join("%s/etc/apt/sources.list" % self.target_rootfs) + if not os.path.exists(os.path.dirname(sources_conf)): + return + arch_list = [] if feed_archs is None: @@ -362,11 +367,11 @@ class DpkgPM(OpkgDpkgPM): if arch_list: for arch in arch_list: bb.note('Adding dpkg channel at (%s)' % uri) - sources_file.write("deb %s/%s ./\n" % + sources_file.write("deb [trusted=yes] %s/%s ./\n" % (uri, arch)) else: bb.note('Adding dpkg channel at (%s)' % uri) - sources_file.write("deb %s ./\n" % uri) + sources_file.write("deb [trusted=yes] %s ./\n" % uri) def _create_configs(self, archs, base_archs): base_archs = re.sub(r"_", r"-", base_archs) @@ -406,7 +411,7 @@ class DpkgPM(OpkgDpkgPM): with open(os.path.join(self.apt_conf_dir, "sources.list"), "w+") as sources_file: for arch in arch_list: - sources_file.write("deb file:%s/ ./\n" % + sources_file.write("deb [trusted=yes] file:%s/ ./\n" % os.path.join(self.deploy_dir, arch)) base_arch_list = base_archs.split() diff --git a/poky/meta/lib/oe/package_manager/ipk/sdk.py b/poky/meta/lib/oe/package_manager/ipk/sdk.py index 37af0344e..e2ca415c8 100644 --- a/poky/meta/lib/oe/package_manager/ipk/sdk.py +++ b/poky/meta/lib/oe/package_manager/ipk/sdk.py @@ -14,6 +14,12 @@ class PkgSdk(Sdk): def __init__(self, d, manifest_dir=None): super(PkgSdk, self).__init__(d, manifest_dir) + # In sdk_list_installed_packages the call to opkg is hardcoded to + # always use IPKGCONF_TARGET and there's no exposed API to change this + # so simply override IPKGCONF_TARGET to use this separated config file. + ipkgconf_sdk_target = d.getVar("IPKGCONF_SDK_TARGET") + d.setVar("IPKGCONF_TARGET", ipkgconf_sdk_target) + self.target_conf = self.d.getVar("IPKGCONF_TARGET") self.host_conf = self.d.getVar("IPKGCONF_SDK") diff --git a/poky/meta/lib/oe/package_manager/rpm/__init__.py b/poky/meta/lib/oe/package_manager/rpm/__init__.py index 898184442..6df009228 100644 --- a/poky/meta/lib/oe/package_manager/rpm/__init__.py +++ b/poky/meta/lib/oe/package_manager/rpm/__init__.py @@ -33,6 +33,9 @@ class RpmIndexer(Indexer): class RpmSubdirIndexer(RpmIndexer): def write_index(self): bb.note("Generating package index for %s" %(self.deploy_dir)) + # Remove the existing repodata to ensure that we re-generate it no matter what + bb.utils.remove(os.path.join(self.deploy_dir, "repodata"), recurse=True) + self.do_write_index(self.deploy_dir) for entry in os.walk(self.deploy_dir): if os.path.samefile(self.deploy_dir, entry[0]): diff --git a/poky/meta/lib/oe/patch.py b/poky/meta/lib/oe/patch.py index 40755fbb0..fccbedb51 100644 --- a/poky/meta/lib/oe/patch.py +++ b/poky/meta/lib/oe/patch.py @@ -38,15 +38,19 @@ def runcmd(args, dir = None): args = [ pipes.quote(str(arg)) for arg in args ] cmd = " ".join(args) # print("cmd: %s" % cmd) - (exitstatus, output) = subprocess.getstatusoutput(cmd) + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) + stdout, stderr = proc.communicate() + stdout = stdout.decode('utf-8') + stderr = stderr.decode('utf-8') + exitstatus = proc.returncode if exitstatus != 0: - raise CmdError(cmd, exitstatus >> 8, output) - if " fuzz " in output and "Hunk " in output: + raise CmdError(cmd, exitstatus >> 8, "stdout: %s\nstderr: %s" % (stdout, stderr)) + if " fuzz " in stdout and "Hunk " in stdout: # Drop patch fuzz info with header and footer to log file so # insane.bbclass can handle to throw error/warning - bb.note("--- Patch fuzz start ---\n%s\n--- Patch fuzz end ---" % format(output)) + bb.note("--- Patch fuzz start ---\n%s\n--- Patch fuzz end ---" % format(stdout)) - return output + return stdout finally: if dir: @@ -512,7 +516,7 @@ class GitApplyTree(PatchTree): try: shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot] self.gitCommandUserOptions(shellcmd, self.commituser, self.commitemail) - shellcmd += ["am", "-3", "--keep-cr", "-p%s" % patch['strippath']] + shellcmd += ["am", "-3", "--keep-cr", "--no-scissors", "-p%s" % patch['strippath']] return _applypatchhelper(shellcmd, patch, force, reverse, run) except CmdError: # Need to abort the git am, or we'll still be within it at the end diff --git a/poky/meta/lib/oe/path.py b/poky/meta/lib/oe/path.py index 082972457..c8d8ad05b 100644 --- a/poky/meta/lib/oe/path.py +++ b/poky/meta/lib/oe/path.py @@ -320,3 +320,24 @@ def which_wild(pathname, path=None, mode=os.F_OK, *, reverse=False, candidates=F return files +def canonicalize(paths, sep=','): + """Given a string with paths (separated by commas by default), expand + each path using os.path.realpath() and return the resulting paths as a + string (separated using the same separator a the original string). + """ + # Ignore paths containing "$" as they are assumed to be unexpanded bitbake + # variables. Normally they would be ignored, e.g., when passing the paths + # through the shell they would expand to empty strings. However, when they + # are passed through os.path.realpath(), it will cause them to be prefixed + # with the absolute path to the current directory and thus not be empty + # anymore. + # + # Also maintain trailing slashes, as the paths may actually be used as + # prefixes in sting compares later on, where the slashes then are important. + canonical_paths = [] + for path in (paths or '').split(sep): + if '$' not in path: + trailing_slash = path.endswith('/') and '/' or '' + canonical_paths.append(os.path.realpath(path) + trailing_slash) + + return sep.join(canonical_paths) diff --git a/poky/meta/lib/oe/qa.py b/poky/meta/lib/oe/qa.py index ea831b930..e8a854a30 100644 --- a/poky/meta/lib/oe/qa.py +++ b/poky/meta/lib/oe/qa.py @@ -156,6 +156,7 @@ def elf_machine_to_string(machine): """ try: return { + 0x00: "Unset", 0x02: "SPARC", 0x03: "x86", 0x08: "MIPS", diff --git a/poky/meta/lib/oe/rootfs.py b/poky/meta/lib/oe/rootfs.py index 4b747dd0f..249c685dc 100644 --- a/poky/meta/lib/oe/rootfs.py +++ b/poky/meta/lib/oe/rootfs.py @@ -217,6 +217,9 @@ class Rootfs(object, metaclass=ABCMeta): self.progress_reporter.next_stage() if bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", + True, False, self.d) and \ + not bb.utils.contains("IMAGE_FEATURES", + "read-only-rootfs-delayed-postinsts", True, False, self.d): delayed_postinsts = self._get_delayed_postinsts() if delayed_postinsts is not None: diff --git a/poky/meta/lib/oe/sstatesig.py b/poky/meta/lib/oe/sstatesig.py index adfe2e403..84999ee94 100644 --- a/poky/meta/lib/oe/sstatesig.py +++ b/poky/meta/lib/oe/sstatesig.py @@ -552,9 +552,11 @@ def OEOuthashBasic(path, sigfile, task, d): try: update_hash(" %10s" % pwd.getpwuid(s.st_uid).pw_name) update_hash(" %10s" % grp.getgrgid(s.st_gid).gr_name) - except KeyError: + except KeyError as e: bb.warn("KeyError in %s" % path) - raise + msg = ("KeyError: %s\nPath %s is owned by uid %d, gid %d, which doesn't match " + "any user/group on target. This may be due to host contamination." % (e, path, s.st_uid, s.st_gid)) + raise Exception(msg).with_traceback(e.__traceback__) if include_timestamps: update_hash(" %10d" % s.st_mtime) diff --git a/poky/meta/lib/oe/terminal.py b/poky/meta/lib/oe/terminal.py index eb10a6e33..61c2687ef 100644 --- a/poky/meta/lib/oe/terminal.py +++ b/poky/meta/lib/oe/terminal.py @@ -185,7 +185,7 @@ class Custom(Terminal): Terminal.__init__(self, sh_cmd, title, env, d) logger.warning('Custom terminal was started.') else: - logger.debug(1, 'No custom terminal (OE_TERMINAL_CUSTOMCMD) set') + logger.debug('No custom terminal (OE_TERMINAL_CUSTOMCMD) set') raise UnsupportedTerminal('OE_TERMINAL_CUSTOMCMD not set') @@ -216,7 +216,7 @@ def spawn_preferred(sh_cmd, title=None, env=None, d=None): def spawn(name, sh_cmd, title=None, env=None, d=None): """Spawn the specified terminal, by name""" - logger.debug(1, 'Attempting to spawn terminal "%s"', name) + logger.debug('Attempting to spawn terminal "%s"', name) try: terminal = Registry.registry[name] except KeyError: diff --git a/poky/meta/lib/oe/utils.py b/poky/meta/lib/oe/utils.py index 468c76f30..9a2187e36 100644 --- a/poky/meta/lib/oe/utils.py +++ b/poky/meta/lib/oe/utils.py @@ -193,7 +193,7 @@ def parallel_make(d, makeinst=False): return int(v) - return None + return '' def parallel_make_argument(d, fmt, limit=None, makeinst=False): """ diff --git a/poky/meta/lib/oeqa/runtime/cases/ethernet_ip_connman.py b/poky/meta/lib/oeqa/runtime/cases/ethernet_ip_connman.py new file mode 100644 index 000000000..e01061283 --- /dev/null +++ b/poky/meta/lib/oeqa/runtime/cases/ethernet_ip_connman.py @@ -0,0 +1,36 @@ +from oeqa.runtime.case import OERuntimeTestCase +from oeqa.core.decorator.depends import OETestDepends +from oeqa.core.decorator.data import skipIfQemu + +class Ethernet_Test(OERuntimeTestCase): + + def set_ip(self, x): + x = x.split(".") + sample_host_address = '150' + x[3] = sample_host_address + x = '.'.join(x) + return x + + @skipIfQemu('qemuall', 'Test only runs on real hardware') + @OETestDepends(['ssh.SSHTest.test_ssh']) + def test_set_virtual_ip(self): + (status, output) = self.target.run("ifconfig eth0 | grep 'inet ' | awk '{print $2}'") + self.assertEqual(status, 0, msg='Failed to get ip address. Make sure you have an ethernet connection on your device, output: %s' % output) + original_ip = output + virtual_ip = self.set_ip(original_ip) + + (status, output) = self.target.run("ifconfig eth0:1 %s netmask 255.255.255.0 && sleep 2 && ping -c 5 %s && ifconfig eth0:1 down" % (virtual_ip,virtual_ip)) + self.assertEqual(status, 0, msg='Failed to create virtual ip address, output: %s' % output) + + @OETestDepends(['ethernet_ip_connman.Ethernet_Test.test_set_virtual_ip']) + def test_get_ip_from_dhcp(self): + (status, output) = self.target.run("connmanctl services | grep -E '*AO Wired|*AR Wired' | awk '{print $3}'") + self.assertEqual(status, 0, msg='No wired interfaces are detected, output: %s' % output) + wired_interfaces = output + + (status, output) = self.target.run("ip route | grep default | awk '{print $3}'") + self.assertEqual(status, 0, msg='Failed to retrieve the default gateway, output: %s' % output) + default_gateway = output + + (status, output) = self.target.run("connmanctl config %s --ipv4 dhcp && sleep 2 && ping -c 5 %s" % (wired_interfaces,default_gateway)) + self.assertEqual(status, 0, msg='Failed to get dynamic IP address via DHCP in connmand, output: %s' % output)
\ No newline at end of file diff --git a/poky/meta/lib/oeqa/runtime/cases/ptest.py b/poky/meta/lib/oeqa/runtime/cases/ptest.py index a9572c81f..0800f3c27 100644 --- a/poky/meta/lib/oeqa/runtime/cases/ptest.py +++ b/poky/meta/lib/oeqa/runtime/cases/ptest.py @@ -108,4 +108,5 @@ class PtestRunnerTest(OERuntimeTestCase): failmsg = failmsg + "Failed ptests:\n%s" % pprint.pformat(failed_tests) if failmsg: + self.logger.warning("There were failing ptests.") self.fail(failmsg) diff --git a/poky/meta/lib/oeqa/runtime/cases/suspend.py b/poky/meta/lib/oeqa/runtime/cases/suspend.py new file mode 100644 index 000000000..67b6f7e56 --- /dev/null +++ b/poky/meta/lib/oeqa/runtime/cases/suspend.py @@ -0,0 +1,33 @@ +from oeqa.runtime.case import OERuntimeTestCase +from oeqa.core.decorator.depends import OETestDepends +from oeqa.core.decorator.data import skipIfQemu +import threading +import time + +class Suspend_Test(OERuntimeTestCase): + + def test_date(self): + (status, output) = self.target.run('date') + self.assertEqual(status, 0, msg = 'Failed to run date command, output : %s' % output) + + def test_ping(self): + t_thread = threading.Thread(target=self.target.run, args=("ping 8.8.8.8",)) + t_thread.start() + time.sleep(2) + + status, output = self.target.run('pidof ping') + self.target.run('kill -9 %s' % output) + self.assertEqual(status, 0, msg = 'Not able to find process that runs ping, output : %s' % output) + + def set_suspend(self): + (status, output) = self.target.run('sudo rtcwake -m mem -s 10') + self.assertEqual(status, 0, msg = 'Failed to suspends your system to RAM, output : %s' % output) + + @skipIfQemu('qemuall', 'Test only runs on real hardware') + @OETestDepends(['ssh.SSHTest.test_ssh']) + def test_suspend(self): + self.test_date() + self.test_ping() + self.set_suspend() + self.test_date() + self.test_ping() diff --git a/poky/meta/lib/oeqa/runtime/cases/terminal.py b/poky/meta/lib/oeqa/runtime/cases/terminal.py index a268f2688..8fcca99f4 100644 --- a/poky/meta/lib/oeqa/runtime/cases/terminal.py +++ b/poky/meta/lib/oeqa/runtime/cases/terminal.py @@ -10,9 +10,12 @@ class TerminalTest(OERuntimeTestCase): @OEHasPackage(['matchbox-terminal']) @OETestDepends(['ssh.SSHTest.test_ssh']) def test_terminal_running(self): - t_thread = threading.Thread(target=self.target.run, args=('export DISPLAY=:0 && matchbox-terminal',)) + t_thread = threading.Thread(target=self.target.run, args=("export DISPLAY=:0 && matchbox-terminal -e 'sh -c \"uname -a && exec sh\"'",)) t_thread.start() time.sleep(2) + status, output = self.target.run('pidof matchbox-terminal') + number_of_terminal = len(output.split()) + self.assertEqual(number_of_terminal, 1, msg='There should be only one terminal being launched. Number of terminal launched : %s' % number_of_terminal) self.target.run('kill -9 %s' % output) - self.assertEqual(status, 0, msg='Not able to find process that runs terminal.') + self.assertEqual(status, 0, msg='Not able to find process that runs terminal.') diff --git a/poky/meta/lib/oeqa/runtime/cases/usb_hid.py b/poky/meta/lib/oeqa/runtime/cases/usb_hid.py new file mode 100644 index 000000000..3c292cf66 --- /dev/null +++ b/poky/meta/lib/oeqa/runtime/cases/usb_hid.py @@ -0,0 +1,22 @@ +from oeqa.runtime.case import OERuntimeTestCase +from oeqa.core.decorator.depends import OETestDepends +from oeqa.core.decorator.data import skipIfQemu +from oeqa.runtime.decorator.package import OEHasPackage + +class USB_HID_Test(OERuntimeTestCase): + + def keyboard_mouse_simulation(self): + (status, output) = self.target.run('export DISPLAY=:0 && xdotool key F2 && xdotool mousemove 100 100') + return self.assertEqual(status, 0, msg = 'Failed to simulate keyboard/mouse input event, output : %s' % output) + + def set_suspend(self): + (status, output) = self.target.run('sudo rtcwake -m mem -s 10') + return self.assertEqual(status, 0, msg = 'Failed to suspends your system to RAM, output : %s' % output) + + @OEHasPackage(['xdotool']) + @skipIfQemu('qemuall', 'Test only runs on real hardware') + @OETestDepends(['ssh.SSHTest.test_ssh']) + def test_USB_Hid_input(self): + self.keyboard_mouse_simulation() + self.set_suspend() + self.keyboard_mouse_simulation() diff --git a/poky/meta/lib/oeqa/selftest/cases/buildoptions.py b/poky/meta/lib/oeqa/selftest/cases/buildoptions.py index e91f0bd18..3495bee98 100644 --- a/poky/meta/lib/oeqa/selftest/cases/buildoptions.py +++ b/poky/meta/lib/oeqa/selftest/cases/buildoptions.py @@ -38,13 +38,14 @@ class ImageOptionsTests(OESelftestTestCase): p = bb_vars['SYSROOT_DESTDIR'] + bb_vars['bindir'] + "/" + "ccache" self.assertTrue(os.path.isfile(p), msg = "No ccache found (%s)" % p) self.write_config('INHERIT += "ccache"') - self.add_command_to_tearDown('bitbake -c clean m4-native') - bitbake("m4-native -c clean") - bitbake("m4-native -f -c compile") - log_compile = os.path.join(get_bb_var("WORKDIR","m4-native"), "temp/log.do_compile") + recipe = "libgcc-initial" + self.add_command_to_tearDown('bitbake -c clean %s' % recipe) + bitbake("%s -c clean" % recipe) + bitbake("%s -f -c compile" % recipe) + log_compile = os.path.join(get_bb_var("WORKDIR", recipe), "temp/log.do_compile") with open(log_compile, "r") as f: loglines = "".join(f.readlines()) - self.assertIn("ccache", loglines, msg="No match for ccache in m4-native log.do_compile. For further details: %s" % log_compile) + self.assertIn("ccache", loglines, msg="No match for ccache in %s log.do_compile. For further details: %s" % (recipe , log_compile)) def test_read_only_image(self): distro_features = get_bb_var('DISTRO_FEATURES') diff --git a/poky/meta/lib/oeqa/selftest/cases/cve_check.py b/poky/meta/lib/oeqa/selftest/cases/cve_check.py new file mode 100644 index 000000000..3f343a284 --- /dev/null +++ b/poky/meta/lib/oeqa/selftest/cases/cve_check.py @@ -0,0 +1,36 @@ +from oe.cve_check import Version +from oeqa.selftest.case import OESelftestTestCase + +class CVECheck(OESelftestTestCase): + + def test_version_compare(self): + result = Version("100") > Version("99") + self.assertTrue( result, msg="Failed to compare version '100' > '99'") + result = Version("2.3.1") > Version("2.2.3") + self.assertTrue( result, msg="Failed to compare version '2.3.1' > '2.2.3'") + result = Version("2021-01-21") > Version("2020-12-25") + self.assertTrue( result, msg="Failed to compare version '2021-01-21' > '2020-12-25'") + result = Version("1.2-20200910") < Version("1.2-20200920") + self.assertTrue( result, msg="Failed to compare version '1.2-20200910' < '1.2-20200920'") + + result = Version("1.0") >= Version("1.0beta") + self.assertTrue( result, msg="Failed to compare version '1.0' >= '1.0beta'") + result = Version("1.0-rc2") > Version("1.0-rc1") + self.assertTrue( result, msg="Failed to compare version '1.0-rc2' > '1.0-rc1'") + result = Version("1.0.alpha1") < Version("1.0") + self.assertTrue( result, msg="Failed to compare version '1.0.alpha1' < '1.0'") + result = Version("1.0_dev") <= Version("1.0") + self.assertTrue( result, msg="Failed to compare version '1.0_dev' <= '1.0'") + + # ignore "p1" and "p2", so these should be equal + result = Version("1.0p2") == Version("1.0p1") + self.assertTrue( result ,msg="Failed to compare version '1.0p2' to '1.0p1'") + # ignore the "b" and "r" + result = Version("1.0b") == Version("1.0r") + self.assertTrue( result ,msg="Failed to compare version '1.0b' to '1.0r'") + + # consider the trailing alphabet as patched level when comparing + result = Version("1.0b","alphabetical") < Version("1.0r","alphabetical") + self.assertTrue( result ,msg="Failed to compare version with suffix '1.0b' < '1.0r'") + result = Version("1.0b","alphabetical") > Version("1.0","alphabetical") + self.assertTrue( result ,msg="Failed to compare version with suffix '1.0b' > '1.0'") diff --git a/poky/meta/lib/oeqa/selftest/cases/devtool.py b/poky/meta/lib/oeqa/selftest/cases/devtool.py index b8edc8976..3385546e8 100644 --- a/poky/meta/lib/oeqa/selftest/cases/devtool.py +++ b/poky/meta/lib/oeqa/selftest/cases/devtool.py @@ -57,7 +57,7 @@ def setUpModule(): if relpth.endswith('/'): destdir = os.path.join(corecopydir, relpth) # avoid race condition by not copying .pyc files YPBZ#13421,13803 - shutil.copytree(pth, destdir, ignore=ignore_patterns('*.pyc', '__pycache__')) + shutil.copytree(pth, destdir, ignore=shutil.ignore_patterns('*.pyc', '__pycache__')) else: destdir = os.path.join(corecopydir, os.path.dirname(relpth)) bb.utils.mkdirhier(destdir) @@ -697,7 +697,44 @@ class DevtoolModifyTests(DevtoolBase): self.assertTrue(bbclassextended, 'None of these recipes are BBCLASSEXTENDed to native - need to adjust testrecipes list: %s' % ', '.join(testrecipes)) self.assertTrue(inheritnative, 'None of these recipes do "inherit native" - need to adjust testrecipes list: %s' % ', '.join(testrecipes)) + def test_devtool_modify_localfiles_only(self): + # Check preconditions + testrecipe = 'base-files' + src_uri = (get_bb_var('SRC_URI', testrecipe) or '').split() + foundlocalonly = False + correct_symlink = False + for item in src_uri: + if item.startswith('file://'): + if '.patch' not in item: + foundlocalonly = True + else: + foundlocalonly = False + break + self.assertTrue(foundlocalonly, 'This test expects the %s recipe to fetch local files only and it seems that it no longer does' % testrecipe) + # Clean up anything in the workdir/sysroot/sstate cache + bitbake('%s -c cleansstate' % testrecipe) + # Try modifying a recipe + tempdir = tempfile.mkdtemp(prefix='devtoolqa') + self.track_for_cleanup(tempdir) + self.track_for_cleanup(self.workspacedir) + self.add_command_to_tearDown('bitbake -c clean %s' % testrecipe) + self.add_command_to_tearDown('bitbake-layers remove-layer */workspace') + result = runCmd('devtool modify %s -x %s' % (testrecipe, tempdir)) + srcfile = os.path.join(tempdir, 'oe-local-files/share/dot.bashrc') + srclink = os.path.join(tempdir, 'share/dot.bashrc') + self.assertExists(srcfile, 'Extracted source could not be found') + if os.path.islink(srclink) and os.path.exists(srclink) and os.path.samefile(srcfile, srclink): + correct_symlink = True + self.assertTrue(correct_symlink, 'Source symlink to oe-local-files is broken') + matches = glob.glob(os.path.join(self.workspacedir, 'appends', '%s_*.bbappend' % testrecipe)) + self.assertTrue(matches, 'bbappend not created') + # Test devtool status + result = runCmd('devtool status') + self.assertIn(testrecipe, result.output) + self.assertIn(tempdir, result.output) + # Try building + bitbake(testrecipe) def test_devtool_modify_git(self): # Check preconditions diff --git a/poky/meta/lib/oeqa/selftest/cases/fitimage.py b/poky/meta/lib/oeqa/selftest/cases/fitimage.py new file mode 100644 index 000000000..0958036a6 --- /dev/null +++ b/poky/meta/lib/oeqa/selftest/cases/fitimage.py @@ -0,0 +1,365 @@ +# +# SPDX-License-Identifier: MIT +# + +from oeqa.selftest.case import OESelftestTestCase +from oeqa.utils.commands import runCmd, bitbake, get_bb_var, runqemu +import os +import json +import re + +class FitImageTests(OESelftestTestCase): + + def test_fit_image(self): + """ + Summary: Check if FIT image and Image Tree Source (its) are built + and the Image Tree Source has the correct fields. + Expected: 1. fitImage and fitImage-its can be built + 2. The type, load address, entrypoint address and + default values of kernel and ramdisk are as expected + in the Image Tree Source. Not all the fields are tested, + only the key fields that wont vary between different + architectures. + Product: oe-core + Author: Usama Arif <usama.arif@arm.com> + """ + config = """ +# Enable creation of fitImage +KERNEL_IMAGETYPE = "Image" +KERNEL_IMAGETYPES += " fitImage " +KERNEL_CLASSES = " kernel-fitimage " + +# RAM disk variables including load address and entrypoint for kernel and RAM disk +IMAGE_FSTYPES += "cpio.gz" +INITRAMFS_IMAGE = "core-image-minimal" +UBOOT_RD_LOADADDRESS = "0x88000000" +UBOOT_RD_ENTRYPOINT = "0x88000000" +UBOOT_LOADADDRESS = "0x80080000" +UBOOT_ENTRYPOINT = "0x80080000" +FIT_DESC = "A model description" +""" + self.write_config(config) + + # fitImage is created as part of linux recipe + bitbake("virtual/kernel") + + image_type = "core-image-minimal" + deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE') + machine = get_bb_var('MACHINE') + fitimage_its_path = os.path.join(deploy_dir_image, + "fitImage-its-%s-%s-%s" % (image_type, machine, machine)) + fitimage_path = os.path.join(deploy_dir_image, + "fitImage-%s-%s-%s" % (image_type, machine, machine)) + + self.assertTrue(os.path.exists(fitimage_its_path), + "%s image tree source doesn't exist" % (fitimage_its_path)) + self.assertTrue(os.path.exists(fitimage_path), + "%s FIT image doesn't exist" % (fitimage_path)) + + # Check that the type, load address, entrypoint address and default + # values for kernel and ramdisk in Image Tree Source are as expected. + # The order of fields in the below array is important. Not all the + # fields are tested, only the key fields that wont vary between + # different architectures. + its_field_check = [ + 'description = "A model description";', + 'type = "kernel";', + 'load = <0x80080000>;', + 'entry = <0x80080000>;', + 'type = "ramdisk";', + 'load = <0x88000000>;', + 'entry = <0x88000000>;', + 'default = "conf@1";', + 'kernel = "kernel@1";', + 'ramdisk = "ramdisk@1";' + ] + + with open(fitimage_its_path) as its_file: + field_index = 0 + for line in its_file: + if field_index == len(its_field_check): + break + if its_field_check[field_index] in line: + field_index +=1 + + if field_index != len(its_field_check): # if its equal, the test passed + self.assertTrue(field_index == len(its_field_check), + "Fields in Image Tree Source File %s did not match, error in finding %s" + % (fitimage_its_path, its_field_check[field_index])) + + + def test_sign_fit_image(self): + """ + Summary: Check if FIT image and Image Tree Source (its) are created + and signed correctly. + Expected: 1) its and FIT image are built successfully + 2) Scanning the its file indicates signing is enabled + as requested by UBOOT_SIGN_ENABLE (using keys generated + via FIT_GENERATE_KEYS) + 3) Dumping the FIT image indicates signature values + are present (including for images as enabled via + FIT_SIGN_INDIVIDUAL) + 4) Examination of the do_assemble_fitimage runfile/logfile + indicate that UBOOT_MKIMAGE, UBOOT_MKIMAGE_SIGN and + UBOOT_MKIMAGE_SIGN_ARGS are working as expected. + Product: oe-core + Author: Paul Eggleton <paul.eggleton@microsoft.com> based upon + work by Usama Arif <usama.arif@arm.com> + """ + config = """ +# Enable creation of fitImage +MACHINE = "beaglebone-yocto" +KERNEL_IMAGETYPES += " fitImage " +KERNEL_CLASSES = " kernel-fitimage test-mkimage-wrapper " +UBOOT_SIGN_ENABLE = "1" +FIT_GENERATE_KEYS = "1" +UBOOT_SIGN_KEYDIR = "${TOPDIR}/signing-keys" +UBOOT_SIGN_KEYNAME = "oe-selftest" +FIT_SIGN_INDIVIDUAL = "1" +UBOOT_MKIMAGE_SIGN_ARGS = "-c 'a smart comment'" +""" + self.write_config(config) + + # fitImage is created as part of linux recipe + bitbake("virtual/kernel") + + image_type = "core-image-minimal" + deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE') + machine = get_bb_var('MACHINE') + fitimage_its_path = os.path.join(deploy_dir_image, + "fitImage-its-%s" % (machine,)) + fitimage_path = os.path.join(deploy_dir_image, + "fitImage-%s.bin" % (machine,)) + + self.assertTrue(os.path.exists(fitimage_its_path), + "%s image tree source doesn't exist" % (fitimage_its_path)) + self.assertTrue(os.path.exists(fitimage_path), + "%s FIT image doesn't exist" % (fitimage_path)) + + req_itspaths = [ + ['/', 'images', 'kernel@1'], + ['/', 'images', 'kernel@1', 'signature@1'], + ['/', 'images', 'fdt@am335x-boneblack.dtb'], + ['/', 'images', 'fdt@am335x-boneblack.dtb', 'signature@1'], + ['/', 'configurations', 'conf@am335x-boneblack.dtb'], + ['/', 'configurations', 'conf@am335x-boneblack.dtb', 'signature@1'], + ] + + itspath = [] + itspaths = [] + linect = 0 + sigs = {} + with open(fitimage_its_path) as its_file: + linect += 1 + for line in its_file: + line = line.strip() + if line.endswith('};'): + itspath.pop() + elif line.endswith('{'): + itspath.append(line[:-1].strip()) + itspaths.append(itspath[:]) + elif itspath and itspath[-1] == 'signature@1': + itsdotpath = '.'.join(itspath) + if not itsdotpath in sigs: + sigs[itsdotpath] = {} + if not '=' in line or not line.endswith(';'): + self.fail('Unexpected formatting in %s sigs section line %d:%s' % (fitimage_its_path, linect, line)) + key, value = line.split('=', 1) + sigs[itsdotpath][key.rstrip()] = value.lstrip().rstrip(';') + + for reqpath in req_itspaths: + if not reqpath in itspaths: + self.fail('Missing section in its file: %s' % reqpath) + + reqsigvalues_image = { + 'algo': '"sha256,rsa2048"', + 'key-name-hint': '"oe-selftest"', + } + reqsigvalues_config = { + 'algo': '"sha256,rsa2048"', + 'key-name-hint': '"oe-selftest"', + 'sign-images': '"kernel", "fdt"', + } + + for itspath, values in sigs.items(): + if 'conf@' in itspath: + reqsigvalues = reqsigvalues_config + else: + reqsigvalues = reqsigvalues_image + for reqkey, reqvalue in reqsigvalues.items(): + value = values.get(reqkey, None) + if value is None: + self.fail('Missing key "%s" in its file signature section %s' % (reqkey, itspath)) + self.assertEqual(value, reqvalue) + + # Dump the image to see if it really got signed + bitbake("u-boot-tools-native -c addto_recipe_sysroot") + result = runCmd('bitbake -e u-boot-tools-native | grep ^RECIPE_SYSROOT_NATIVE=') + recipe_sysroot_native = result.output.split('=')[1].strip('"') + dumpimage_path = os.path.join(recipe_sysroot_native, 'usr', 'bin', 'dumpimage') + result = runCmd('%s -l %s' % (dumpimage_path, fitimage_path)) + in_signed = None + signed_sections = {} + for line in result.output.splitlines(): + if line.startswith((' Configuration', ' Image')): + in_signed = re.search('\((.*)\)', line).groups()[0] + elif re.match('^ *', line) in (' ', ''): + in_signed = None + elif in_signed: + if not in_signed in signed_sections: + signed_sections[in_signed] = {} + key, value = line.split(':', 1) + signed_sections[in_signed][key.strip()] = value.strip() + self.assertIn('kernel@1', signed_sections) + self.assertIn('fdt@am335x-boneblack.dtb', signed_sections) + self.assertIn('conf@am335x-boneblack.dtb', signed_sections) + for signed_section, values in signed_sections.items(): + value = values.get('Sign algo', None) + self.assertEqual(value, 'sha256,rsa2048:oe-selftest', 'Signature algorithm for %s not expected value' % signed_section) + value = values.get('Sign value', None) + self.assertEqual(len(value), 512, 'Signature value for section %s not expected length' % signed_section) + + # Check for UBOOT_MKIMAGE_SIGN_ARGS + result = runCmd('bitbake -e virtual/kernel | grep ^T=') + tempdir = result.output.split('=', 1)[1].strip().strip('') + result = runCmd('grep "a smart comment" %s/run.do_assemble_fitimage' % tempdir, ignore_status=True) + self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE_SIGN_ARGS value did not get used') + + # Check for evidence of test-mkimage-wrapper class + result = runCmd('grep "### uboot-mkimage wrapper message" %s/log.do_assemble_fitimage' % tempdir, ignore_status=True) + self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE did not work') + result = runCmd('grep "### uboot-mkimage signing wrapper message" %s/log.do_assemble_fitimage' % tempdir, ignore_status=True) + self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE_SIGN did not work') + + def test_initramfs_bundle(self): + """ + Summary: Verifies the content of the initramfs bundle node in the FIT Image Tree Source (its) + The FIT settings are set by the test case. + The machine used is beaglebone-yocto. + Expected: 1. The ITS is generated with initramfs bundle support + 2. All the fields in the kernel node are as expected (matching the + conf settings) + 3. The kernel is included in all the available configurations and + its hash is included in the configuration signature + + Product: oe-core + Author: Abdellatif El Khlifi <abdellatif.elkhlifi@arm.com> + """ + + config = """ +DISTRO="poky" +MACHINE = "beaglebone-yocto" +INITRAMFS_IMAGE_BUNDLE = "1" +INITRAMFS_IMAGE = "core-image-minimal-initramfs" +INITRAMFS_SCRIPTS = "" +UBOOT_MACHINE = "am335x_evm_defconfig" +KERNEL_CLASSES = " kernel-fitimage " +KERNEL_IMAGETYPES = "fitImage" +UBOOT_SIGN_ENABLE = "1" +UBOOT_SIGN_KEYNAME = "beaglebonekey" +UBOOT_SIGN_KEYDIR ?= "${DEPLOY_DIR_IMAGE}" +UBOOT_DTB_BINARY = "u-boot.dtb" +UBOOT_ENTRYPOINT = "0x80000000" +UBOOT_LOADADDRESS = "0x80000000" +UBOOT_DTB_LOADADDRESS = "0x82000000" +UBOOT_ARCH = "arm" +UBOOT_MKIMAGE_DTCOPTS = "-I dts -O dtb -p 2000" +UBOOT_EXTLINUX = "0" +FIT_GENERATE_KEYS = "1" +KERNEL_IMAGETYPE_REPLACEMENT = "zImage" +FIT_HASH_ALG = "sha256" +""" + self.write_config(config) + + # fitImage is created as part of linux recipe + bitbake("virtual/kernel") + + image_type = get_bb_var('INITRAMFS_IMAGE') + deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE') + machine = get_bb_var('MACHINE') + fitimage_its_path = os.path.join(deploy_dir_image, + "fitImage-its-%s-%s-%s" % (image_type, machine, machine)) + fitimage_path = os.path.join(deploy_dir_image,"fitImage") + + self.assertTrue(os.path.exists(fitimage_its_path), + "%s image tree source doesn't exist" % (fitimage_its_path)) + self.assertTrue(os.path.exists(fitimage_path), + "%s FIT image doesn't exist" % (fitimage_path)) + + kernel_load = str(get_bb_var('UBOOT_LOADADDRESS')) + kernel_entry = str(get_bb_var('UBOOT_ENTRYPOINT')) + initramfs_bundle_format = str(get_bb_var('KERNEL_IMAGETYPE_REPLACEMENT')) + uboot_arch = str(get_bb_var('UBOOT_ARCH')) + initramfs_bundle = "arch/" + uboot_arch + "/boot/" + initramfs_bundle_format + ".initramfs" + fit_hash_alg = str(get_bb_var('FIT_HASH_ALG')) + + its_file = open(fitimage_its_path) + + its_lines = [line.strip() for line in its_file.readlines()] + + exp_node_lines = [ + 'kernel@1 {', + 'description = "Linux kernel";', + 'data = /incbin/("' + initramfs_bundle + '");', + 'type = "kernel";', + 'arch = "' + uboot_arch + '";', + 'os = "linux";', + 'compression = "none";', + 'load = <' + kernel_load + '>;', + 'entry = <' + kernel_entry + '>;', + 'hash@1 {', + 'algo = "' + fit_hash_alg +'";', + '};', + '};' + ] + + node_str = exp_node_lines[0] + + test_passed = False + + print ("checking kernel node\n") + + if node_str in its_lines: + node_start_idx = its_lines.index(node_str) + node = its_lines[node_start_idx:(node_start_idx + len(exp_node_lines))] + if node == exp_node_lines: + print("kernel node verified") + else: + self.assertTrue(test_passed == True,"kernel node does not match expectation") + + rx_configs = re.compile("^conf@.*") + its_configs = list(filter(rx_configs.match, its_lines)) + + for cfg_str in its_configs: + cfg_start_idx = its_lines.index(cfg_str) + line_idx = cfg_start_idx + 2 + node_end = False + while node_end == False: + if its_lines[line_idx] == "};" and its_lines[line_idx-1] == "};" : + node_end = True + line_idx = line_idx + 1 + + node = its_lines[cfg_start_idx:line_idx] + print("checking configuration " + cfg_str.rstrip(" {")) + rx_desc_line = re.compile("^description.*1 Linux kernel.*") + if len(list(filter(rx_desc_line.match, node))) != 1: + self.assertTrue(test_passed == True,"kernel keyword not found in the description line") + break + else: + print("kernel keyword found in the description line") + + if 'kernel = "kernel@1";' not in node: + self.assertTrue(test_passed == True,"kernel line not found") + break + else: + print("kernel line found") + + rx_sign_line = re.compile("^sign-images.*kernel.*") + if len(list(filter(rx_sign_line.match, node))) != 1: + self.assertTrue(test_passed == True,"kernel hash not signed") + break + else: + print("kernel hash signed") + + test_passed = True + self.assertTrue(test_passed == True,"Initramfs bundle test success") diff --git a/poky/meta/lib/oeqa/selftest/cases/imagefeatures.py b/poky/meta/lib/oeqa/selftest/cases/imagefeatures.py index 415e0315f..6723a8198 100644 --- a/poky/meta/lib/oeqa/selftest/cases/imagefeatures.py +++ b/poky/meta/lib/oeqa/selftest/cases/imagefeatures.py @@ -264,80 +264,6 @@ PNBLACKLIST[busybox] = "Don't build this" bitbake("--graphviz core-image-sato") - def test_fit_image(self): - """ - Summary: Check if FIT image and Image Tree Source (its) are built - and the Image Tree Source has the correct fields. - Expected: 1. fitImage and fitImage-its can be built - 2. The type, load address, entrypoint address and - default values of kernel and ramdisk are as expected - in the Image Tree Source. Not all the fields are tested, - only the key fields that wont vary between different - architectures. - Product: oe-core - Author: Usama Arif <usama.arif@arm.com> - """ - config = """ -# Enable creation of fitImage -KERNEL_IMAGETYPE = "Image" -KERNEL_IMAGETYPES += " fitImage " -KERNEL_CLASSES = " kernel-fitimage " - -# RAM disk variables including load address and entrypoint for kernel and RAM disk -IMAGE_FSTYPES += "cpio.gz" -INITRAMFS_IMAGE = "core-image-minimal" -UBOOT_RD_LOADADDRESS = "0x88000000" -UBOOT_RD_ENTRYPOINT = "0x88000000" -UBOOT_LOADADDRESS = "0x80080000" -UBOOT_ENTRYPOINT = "0x80080000" -""" - self.write_config(config) - - # fitImage is created as part of linux recipe - bitbake("virtual/kernel") - - image_type = "core-image-minimal" - deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE') - machine = get_bb_var('MACHINE') - fitimage_its_path = os.path.join(deploy_dir_image, - "fitImage-its-%s-%s-%s" % (image_type, machine, machine)) - fitimage_path = os.path.join(deploy_dir_image, - "fitImage-%s-%s-%s" % (image_type, machine, machine)) - - self.assertTrue(os.path.exists(fitimage_its_path), - "%s image tree source doesn't exist" % (fitimage_its_path)) - self.assertTrue(os.path.exists(fitimage_path), - "%s FIT image doesn't exist" % (fitimage_path)) - - # Check that the type, load address, entrypoint address and default - # values for kernel and ramdisk in Image Tree Source are as expected. - # The order of fields in the below array is important. Not all the - # fields are tested, only the key fields that wont vary between - # different architectures. - its_field_check = ['type = "kernel";', - 'load = <0x80080000>;', - 'entry = <0x80080000>;', - 'type = "ramdisk";', - 'load = <0x88000000>;', - 'entry = <0x88000000>;', - 'default = "conf@1";', - 'kernel = "kernel@1";', - 'ramdisk = "ramdisk@1";' - ] - - with open(fitimage_its_path) as its_file: - field_index = 0 - for line in its_file: - if field_index == len(its_field_check): - break - if its_field_check[field_index] in line: - field_index +=1 - - if field_index != len(its_field_check): # if its equal, the test passed - self.assertTrue(field_index == len(its_field_check), - "Fields in Image Tree Source File %s did not match, error in finding %s" - % (fitimage_its_path, its_field_check[field_index])) - def test_image_gen_debugfs(self): """ Summary: Check debugfs generation diff --git a/poky/meta/lib/oeqa/selftest/cases/oelib/elf.py b/poky/meta/lib/oeqa/selftest/cases/oelib/elf.py index d0a28090f..5a5f9b4fd 100644 --- a/poky/meta/lib/oeqa/selftest/cases/oelib/elf.py +++ b/poky/meta/lib/oeqa/selftest/cases/oelib/elf.py @@ -21,6 +21,6 @@ class TestElf(TestCase): self.assertEqual(oe.qa.elf_machine_to_string(0xB7), "AArch64") self.assertEqual(oe.qa.elf_machine_to_string(0xF7), "BPF") - self.assertEqual(oe.qa.elf_machine_to_string(0x00), "Unknown (0)") + self.assertEqual(oe.qa.elf_machine_to_string(0x00), "Unset") self.assertEqual(oe.qa.elf_machine_to_string(0xDEADBEEF), "Unknown (3735928559)") self.assertEqual(oe.qa.elf_machine_to_string("foobar"), "Unknown ('foobar')") diff --git a/poky/meta/lib/oeqa/selftest/cases/package.py b/poky/meta/lib/oeqa/selftest/cases/package.py index 3010b1af4..7166c3991 100644 --- a/poky/meta/lib/oeqa/selftest/cases/package.py +++ b/poky/meta/lib/oeqa/selftest/cases/package.py @@ -168,6 +168,7 @@ class PackageTests(OESelftestTestCase): with runqemu('core-image-minimal') as qemu: for path in [ sysconfdir + "/selftest-chown/file", sysconfdir + "/selftest-chown/dir", - sysconfdir + "/selftest-chown/symlink"]: + sysconfdir + "/selftest-chown/symlink", + sysconfdir + "/selftest-chown/fifotest/fifo"]: if not check_ownership(qemu, "test", "test", path): self.fail('Test ownership %s failed' % path) diff --git a/poky/meta/lib/oeqa/selftest/cases/pkgdata.py b/poky/meta/lib/oeqa/selftest/cases/pkgdata.py index 833a1803b..254abc40c 100644 --- a/poky/meta/lib/oeqa/selftest/cases/pkgdata.py +++ b/poky/meta/lib/oeqa/selftest/cases/pkgdata.py @@ -218,3 +218,9 @@ class OePkgdataUtilTests(OESelftestTestCase): def test_specify_pkgdatadir(self): result = runCmd('oe-pkgdata-util -p %s lookup-pkg zlib' % get_bb_var('PKGDATA_DIR')) self.assertEqual(result.output, 'libz1') + + def test_no_param(self): + result = runCmd('oe-pkgdata-util', ignore_status=True) + self.assertEqual(result.status, 2, "Status different than 2. output: %s" % result.output) + currpos = result.output.find('usage: oe-pkgdata-util') + self.assertTrue(currpos != -1, msg = "Test is Failed. Help is not Displayed in %s" % result.output) diff --git a/poky/meta/lib/oeqa/selftest/cases/pseudo.py b/poky/meta/lib/oeqa/selftest/cases/pseudo.py new file mode 100644 index 000000000..33593d5ce --- /dev/null +++ b/poky/meta/lib/oeqa/selftest/cases/pseudo.py @@ -0,0 +1,27 @@ +# +# SPDX-License-Identifier: MIT +# + +import glob +import os +import shutil +from oeqa.utils.commands import bitbake, get_test_layer +from oeqa.selftest.case import OESelftestTestCase + +class Pseudo(OESelftestTestCase): + + def test_pseudo_pyc_creation(self): + self.write_config("") + + metaselftestpath = get_test_layer() + pycache_path = os.path.join(metaselftestpath, 'lib/__pycache__') + if os.path.exists(pycache_path): + shutil.rmtree(pycache_path) + + bitbake('pseudo-pyc-test -c install') + + test1_pyc_present = len(glob.glob(os.path.join(pycache_path, 'pseudo_pyc_test1.*.pyc'))) + self.assertTrue(test1_pyc_present, 'test1 pyc file missing, should be created outside of pseudo context.') + + test2_pyc_present = len(glob.glob(os.path.join(pycache_path, 'pseudo_pyc_test2.*.pyc'))) + self.assertFalse(test2_pyc_present, 'test2 pyc file present, should not be created in pseudo context.') diff --git a/poky/meta/lib/oeqa/selftest/cases/reproducible.py b/poky/meta/lib/oeqa/selftest/cases/reproducible.py index a7ef33614..deddf6e50 100644 --- a/poky/meta/lib/oeqa/selftest/cases/reproducible.py +++ b/poky/meta/lib/oeqa/selftest/cases/reproducible.py @@ -17,6 +17,71 @@ import stat import os import datetime +# For sample packages, see: +# https://autobuilder.yocto.io/pub/repro-fail/oe-reproducible-20201127-0t7wr_oo/ +# https://autobuilder.yocto.io/pub/repro-fail/oe-reproducible-20201127-4s9ejwyp/ +# https://autobuilder.yocto.io/pub/repro-fail/oe-reproducible-20201127-haiwdlbr/ +# https://autobuilder.yocto.io/pub/repro-fail/oe-reproducible-20201127-hwds3mcl/ +# https://autobuilder.yocto.io/pub/repro-fail/oe-reproducible-20201203-sua0pzvc/ +# (both packages/ and packages-excluded/) +exclude_packages = [ + 'acpica-src', + 'babeltrace2-ptest', + 'bootchart2-doc', + 'cups', + 'cwautomacros', + 'dtc', + 'efivar', + 'epiphany', + 'gcr', + 'git', + 'glide', + 'go-dep', + 'go-helloworld', + 'go-runtime', + 'go_', + 'groff', + 'gst-devtools', + 'gstreamer1.0-python', + 'gtk-doc', + 'igt-gpu-tools', + 'kernel-devsrc', + 'libaprutil', + 'libcap-ng', + 'libhandy-1-src', + 'libid3tag', + 'libproxy', + 'libsecret-dev', + 'libsecret-src', + 'lttng-tools-dbg', + 'lttng-tools-ptest', + 'ltp', + 'meson', + 'ovmf-shell-efi', + 'parted-ptest', + 'perf', + 'python3-cython', + 'qemu', + 'quilt-ptest', + 'rsync', + 'ruby', + 'swig', + 'syslinux-misc', + 'systemd-bootchart', + 'valgrind-ptest', + 'vim', + 'watchdog', + 'xmlto', + 'xorg-minimal-fonts' + ] + +def is_excluded(package): + package_name = os.path.basename(package) + for i in exclude_packages: + if package_name.startswith(i): + return True + return False + MISSING = 'MISSING' DIFFERENT = 'DIFFERENT' SAME = 'SAME' @@ -39,6 +104,7 @@ class PackageCompareResults(object): self.total = [] self.missing = [] self.different = [] + self.different_excluded = [] self.same = [] def add_result(self, r): @@ -46,7 +112,10 @@ class PackageCompareResults(object): if r.status == MISSING: self.missing.append(r) elif r.status == DIFFERENT: - self.different.append(r) + if is_excluded(r.reference): + self.different_excluded.append(r) + else: + self.different.append(r) else: self.same.append(r) @@ -54,10 +123,11 @@ class PackageCompareResults(object): self.total.sort() self.missing.sort() self.different.sort() + self.different_excluded.sort() self.same.sort() def __str__(self): - return 'same=%i different=%i missing=%i total=%i' % (len(self.same), len(self.different), len(self.missing), len(self.total)) + return 'same=%i different=%i different_excluded=%i missing=%i total=%i' % (len(self.same), len(self.different), len(self.different_excluded), len(self.missing), len(self.total)) def compare_file(reference, test, diffutils_sysroot): result = CompareResult() @@ -105,7 +175,7 @@ class DiffoscopeTests(OESelftestTestCase): class ReproducibleTests(OESelftestTestCase): package_classes = ['deb', 'ipk'] - images = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline'] + images = ['core-image-minimal', 'core-image-sato', 'core-image-full-cmdline', 'world'] save_results = False if 'OEQA_DEBUGGING_SAVED_OUTPUT' in os.environ: save_results = os.environ['OEQA_DEBUGGING_SAVED_OUTPUT'] @@ -176,6 +246,12 @@ class ReproducibleTests(OESelftestTestCase): PACKAGE_CLASSES = "{package_classes}" INHIBIT_PACKAGE_STRIP = "1" TMPDIR = "{tmpdir}" + LICENSE_FLAGS_WHITELIST = "commercial" + DISTRO_FEATURES_append = ' systemd pam' + USERADDEXTENSION = "useradd-staticids" + USERADD_ERROR_DYNAMIC = "skip" + USERADD_UID_TABLES += "files/static-passwd" + USERADD_GID_TABLES += "files/static-group" ''').format(package_classes=' '.join('package_%s' % c for c in self.package_classes), tmpdir=tmpdir) @@ -235,6 +311,7 @@ class ReproducibleTests(OESelftestTestCase): self.write_package_list(package_class, 'missing', result.missing) self.write_package_list(package_class, 'different', result.different) + self.write_package_list(package_class, 'different_excluded', result.different_excluded) self.write_package_list(package_class, 'same', result.same) if self.save_results: @@ -242,8 +319,12 @@ class ReproducibleTests(OESelftestTestCase): self.copy_file(d.reference, '/'.join([save_dir, 'packages', strip_topdir(d.reference)])) self.copy_file(d.test, '/'.join([save_dir, 'packages', strip_topdir(d.test)])) + for d in result.different_excluded: + self.copy_file(d.reference, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.reference)])) + self.copy_file(d.test, '/'.join([save_dir, 'packages-excluded', strip_topdir(d.test)])) + if result.missing or result.different: - fails.append("The following %s packages are missing or different: %s" % + fails.append("The following %s packages are missing or different and not in exclusion list: %s" % (c, '\n'.join(r.test for r in (result.missing + result.different)))) # Clean up empty directories diff --git a/poky/meta/lib/oeqa/selftest/cases/runtime_test.py b/poky/meta/lib/oeqa/selftest/cases/runtime_test.py index 7189e4e6c..b20c5b427 100644 --- a/poky/meta/lib/oeqa/selftest/cases/runtime_test.py +++ b/poky/meta/lib/oeqa/selftest/cases/runtime_test.py @@ -276,7 +276,7 @@ class Postinst(OESelftestTestCase): # run_serial()'s status code is useless.' for filename in ("rootfs", "delayed-a", "delayed-b"): status, output = qemu.run_serial("test -f %s && echo found" % os.path.join(targettestdir, filename)) - self.assertEqual(output, "found", "%s was not present on boot" % filename) + self.assertIn("found", output, "%s was not present on boot" % filename) diff --git a/poky/meta/lib/oeqa/selftest/cases/tinfoil.py b/poky/meta/lib/oeqa/selftest/cases/tinfoil.py index 206168ed0..a51c6048d 100644 --- a/poky/meta/lib/oeqa/selftest/cases/tinfoil.py +++ b/poky/meta/lib/oeqa/selftest/cases/tinfoil.py @@ -100,9 +100,11 @@ class TinfoilTests(OESelftestTestCase): eventreceived = False commandcomplete = False start = time.time() - # Wait for 10s in total so we'd detect spurious heartbeat events for example + # Wait for maximum 60s in total so we'd detect spurious heartbeat events for example # The test is IO load sensitive too - while time.time() - start < 10: + while (not (eventreceived == True and commandcomplete == True) + and (time.time() - start < 60)): + # if we received both events (on let's say a good day), we are done event = tinfoil.wait_event(1) if event: if isinstance(event, bb.command.CommandCompleted): diff --git a/poky/meta/lib/oeqa/selftest/cases/wic.py b/poky/meta/lib/oeqa/selftest/cases/wic.py index 714637ec1..2bf5cb9a8 100644 --- a/poky/meta/lib/oeqa/selftest/cases/wic.py +++ b/poky/meta/lib/oeqa/selftest/cases/wic.py @@ -318,6 +318,7 @@ class Wic(WicTestCase): "--image-name=core-image-minimal " "-D -o %s" % self.resultdir) self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct"))) + self.assertEqual(1, len(glob(self.resultdir + "tmp.wic*"))) def test_debug_long(self): """Test --debug option""" @@ -325,6 +326,7 @@ class Wic(WicTestCase): "--image-name=core-image-minimal " "--debug -o %s" % self.resultdir) self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct"))) + self.assertEqual(1, len(glob(self.resultdir + "tmp.wic*"))) def test_skip_build_check_short(self): """Test -s option""" @@ -588,6 +590,9 @@ part / --source rootfs --fstype=ext4 --include-path %s --include-path core-imag def test_permissions(self): """Test permissions are respected""" + # prepare wicenv and rootfs + bitbake('core-image-minimal core-image-minimal-mtdutils -c do_rootfs_wicenv') + oldpath = os.environ['PATH'] os.environ['PATH'] = get_bb_var("PATH", "wic-tools") @@ -621,6 +626,19 @@ part /etc --source rootfs --fstype=ext4 --change-directory=etc res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part)) self.assertEqual(True, files_own_by_root(res.output)) + config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "%s"\n' % wks_file + self.append_config(config) + bitbake('core-image-minimal') + tmpdir = os.path.join(get_bb_var('WORKDIR', 'core-image-minimal'),'build-wic') + + # check each partition for permission + for part in glob(os.path.join(tmpdir, 'temp-*.direct.p*')): + res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part)) + self.assertTrue(files_own_by_root(res.output) + ,msg='Files permission incorrect using wks set "%s"' % test) + + # clean config and result directory for next cases + self.remove_config(config) rmtree(self.resultdir, ignore_errors=True) finally: @@ -990,6 +1008,26 @@ class Wic2(WicTestCase): out = glob(self.resultdir + "%s-*direct" % wksname) self.assertEqual(1, len(out)) + def test_empty_plugin(self): + """Test empty plugin""" + config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_empty_plugin.wks"\n' + self.append_config(config) + self.assertEqual(0, bitbake('core-image-minimal').status) + self.remove_config(config) + + bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE']) + deploy_dir = bb_vars['DEPLOY_DIR_IMAGE'] + machine = bb_vars['MACHINE'] + image_path = os.path.join(deploy_dir, 'core-image-minimal-%s.wic' % machine) + self.assertEqual(True, os.path.exists(image_path)) + + sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools') + + # Fstype column from 'wic ls' should be empty for the second partition + # as listed in test_empty_plugin.wks + result = runCmd("wic ls %s -n %s | awk -F ' ' '{print $1 \" \" $5}' | grep '^2' | wc -w" % (image_path, sysroot)) + self.assertEqual('1', result.output) + @only_for_arch(['i586', 'i686', 'x86_64']) def test_biosplusefi_plugin_qemu(self): """Test biosplusefi plugin in qemu""" diff --git a/poky/meta/lib/oeqa/selftest/context.py b/poky/meta/lib/oeqa/selftest/context.py index dd3609c1d..165992697 100644 --- a/poky/meta/lib/oeqa/selftest/context.py +++ b/poky/meta/lib/oeqa/selftest/context.py @@ -34,7 +34,7 @@ class NonConcurrentTestSuite(unittest.TestSuite): (builddir, newbuilddir) = self.setupfunc("-st", None, self.suite) ret = super().run(result) os.chdir(builddir) - if newbuilddir and ret.wasSuccessful(): + if newbuilddir and ret.wasSuccessful() and self.removefunc: self.removefunc(newbuilddir) def removebuilddir(d): @@ -54,7 +54,7 @@ def removebuilddir(d): bb.utils.prunedir(d, ionice=True) class OESelftestTestContext(OETestContext): - def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None): + def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None, keep_builddir=None): super(OESelftestTestContext, self).__init__(td, logger) self.machines = machines @@ -62,6 +62,11 @@ class OESelftestTestContext(OETestContext): self.config_paths = config_paths self.newbuilddir = newbuilddir + if keep_builddir: + self.removebuilddir = None + else: + self.removebuilddir = removebuilddir + def setup_builddir(self, suffix, selftestdir, suite): builddir = os.environ['BUILDDIR'] if not selftestdir: @@ -119,9 +124,9 @@ class OESelftestTestContext(OETestContext): if processes: from oeqa.core.utils.concurrencytest import ConcurrentTestSuite - return ConcurrentTestSuite(suites, processes, self.setup_builddir, removebuilddir) + return ConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir) else: - return NonConcurrentTestSuite(suites, processes, self.setup_builddir, removebuilddir) + return NonConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir) def runTests(self, processes=None, machine=None, skips=[]): if machine: @@ -179,6 +184,9 @@ class OESelftestTestContextExecutor(OETestContextExecutor): action='append', default=None, help='Exclude all (unhidden) tests that match any of the specified tag(s). (exclude applies before select)') + parser.add_argument('-K', '--keep-builddir', action='store_true', + help='Keep the test build directory even if all tests pass') + parser.add_argument('-B', '--newbuilddir', help='New build directory to use for tests.') parser.add_argument('-v', '--verbose', action='store_true') parser.set_defaults(func=self.run) @@ -236,6 +244,7 @@ class OESelftestTestContextExecutor(OETestContextExecutor): self.tc_kwargs['init']['config_paths']['localconf'] = os.path.join(builddir, "conf/local.conf") self.tc_kwargs['init']['config_paths']['bblayers'] = os.path.join(builddir, "conf/bblayers.conf") self.tc_kwargs['init']['newbuilddir'] = args.newbuilddir + self.tc_kwargs['init']['keep_builddir'] = args.keep_builddir def tag_filter(tags): if args.exclude_tags: diff --git a/poky/meta/lib/oeqa/utils/__init__.py b/poky/meta/lib/oeqa/utils/__init__.py index 70fbe7b55..6d1ec4cb9 100644 --- a/poky/meta/lib/oeqa/utils/__init__.py +++ b/poky/meta/lib/oeqa/utils/__init__.py @@ -43,28 +43,12 @@ def make_logger_bitbake_compatible(logger): import logging """ - Bitbake logger redifines debug() in order to - set a level within debug, this breaks compatibility - with vainilla logging, so we neeed to redifine debug() - method again also add info() method with INFO + 1 level. + We need to raise the log level of the info output so unittest + messages are visible on the console. """ - def _bitbake_log_debug(*args, **kwargs): - lvl = logging.DEBUG - - if isinstance(args[0], int): - lvl = args[0] - msg = args[1] - args = args[2:] - else: - msg = args[0] - args = args[1:] - - logger.log(lvl, msg, *args, **kwargs) - def _bitbake_log_info(msg, *args, **kwargs): logger.log(logging.INFO + 1, msg, *args, **kwargs) - logger.debug = _bitbake_log_debug logger.info = _bitbake_log_info return logger diff --git a/poky/meta/lib/oeqa/utils/commands.py b/poky/meta/lib/oeqa/utils/commands.py index 6c1535ddf..a71c16ab1 100644 --- a/poky/meta/lib/oeqa/utils/commands.py +++ b/poky/meta/lib/oeqa/utils/commands.py @@ -188,7 +188,10 @@ def runCmd(command, ignore_status=False, timeout=None, assert_error=True, sync=T # call sync around the tests to ensure the IO queue doesn't get too large, taking any IO # hit here rather than in bitbake shutdown. if sync: + p = os.environ['PATH'] + os.environ['PATH'] = "/usr/bin:/bin:/usr/sbin:/sbin:" + p os.system("sync") + os.environ['PATH'] = p result.command = command result.status = cmd.status diff --git a/poky/meta/lib/oeqa/utils/package_manager.py b/poky/meta/lib/oeqa/utils/package_manager.py index 362329929..6b67f22fd 100644 --- a/poky/meta/lib/oeqa/utils/package_manager.py +++ b/poky/meta/lib/oeqa/utils/package_manager.py @@ -117,7 +117,7 @@ def extract_packages(d, needed_packages): extract = package.get('extract', True) if extract: - #logger.debug(1, 'Extracting %s' % pkg) + #logger.debug('Extracting %s' % pkg) dst_dir = os.path.join(extracted_path, pkg) # Same package used for more than one test, # don't need to extract again. @@ -130,7 +130,7 @@ def extract_packages(d, needed_packages): shutil.rmtree(pkg_dir) else: - #logger.debug(1, 'Copying %s' % pkg) + #logger.debug('Copying %s' % pkg) _copy_package(d, pkg) def _extract_in_tmpdir(d, pkg): |