1#
2# Copyright (c) 2015, Intel Corporation.
3#
4# SPDX-License-Identifier: GPL-2.0-only
5#
6# AUTHORS
7# Ed Bartosh <ed.bartosh@linux.intel.com>
8
9"""Test cases for wic."""
10
11import os
12import sys
13import unittest
14import hashlib
15
16from glob import glob
17from shutil import rmtree, copy
18from functools import wraps, lru_cache
19from tempfile import NamedTemporaryFile
20
21from oeqa.selftest.case import OESelftestTestCase
22from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars, runqemu
23
24
25@lru_cache(maxsize=32)
26def get_host_arch(recipe):
27    """A cached call to get_bb_var('HOST_ARCH', <recipe>)"""
28    return get_bb_var('HOST_ARCH', recipe)
29
30
31def only_for_arch(archs, image='core-image-minimal'):
32    """Decorator for wrapping test cases that can be run only for specific target
33    architectures. A list of compatible architectures is passed in `archs`.
34    Current architecture will be determined by parsing bitbake output for
35    `image` recipe.
36    """
37    def wrapper(func):
38        @wraps(func)
39        def wrapped_f(*args, **kwargs):
40            arch = get_host_arch(image)
41            if archs and arch not in archs:
42                raise unittest.SkipTest("Testcase arch dependency not met: %s" % arch)
43            return func(*args, **kwargs)
44        wrapped_f.__name__ = func.__name__
45        return wrapped_f
46    return wrapper
47
48def extract_files(debugfs_output):
49    """
50    extract file names from the output of debugfs -R 'ls -p',
51    which looks like this:
52
53     /2/040755/0/0/.//\n
54     /2/040755/0/0/..//\n
55     /11/040700/0/0/lost+found^M//\n
56     /12/040755/1002/1002/run//\n
57     /13/040755/1002/1002/sys//\n
58     /14/040755/1002/1002/bin//\n
59     /80/040755/1002/1002/var//\n
60     /92/040755/1002/1002/tmp//\n
61    """
62    # NOTE the occasional ^M in file names
63    return [line.split('/')[5].strip() for line in \
64            debugfs_output.strip().split('/\n')]
65
66def files_own_by_root(debugfs_output):
67    for line in debugfs_output.strip().split('/\n'):
68        if line.split('/')[3:5] != ['0', '0']:
69            print(debugfs_output)
70            return False
71    return True
72
73class WicTestCase(OESelftestTestCase):
74    """Wic test class."""
75
76    image_is_ready = False
77    wicenv_cache = {}
78
79    def setUpLocal(self):
80        """This code is executed before each test method."""
81        self.resultdir = self.builddir + "/wic-tmp/"
82        super(WicTestCase, self).setUpLocal()
83
84        # Do this here instead of in setUpClass as the base setUp does some
85        # clean up which can result in the native tools built earlier in
86        # setUpClass being unavailable.
87        if not WicTestCase.image_is_ready:
88            if get_bb_var('USE_NLS') == 'yes':
89                bitbake('wic-tools')
90            else:
91                self.skipTest('wic-tools cannot be built due its (intltool|gettext)-native dependency and NLS disable')
92
93            bitbake('core-image-minimal')
94            bitbake('core-image-minimal-mtdutils')
95            WicTestCase.image_is_ready = True
96
97        rmtree(self.resultdir, ignore_errors=True)
98
99    def tearDownLocal(self):
100        """Remove resultdir as it may contain images."""
101        rmtree(self.resultdir, ignore_errors=True)
102        super(WicTestCase, self).tearDownLocal()
103
104    def _get_image_env_path(self, image):
105        """Generate and obtain the path to <image>.env"""
106        if image not in WicTestCase.wicenv_cache:
107            self.assertEqual(0, bitbake('%s -c do_rootfs_wicenv' % image).status)
108            bb_vars = get_bb_vars(['STAGING_DIR', 'MACHINE'], image)
109            stdir = bb_vars['STAGING_DIR']
110            machine = bb_vars['MACHINE']
111            WicTestCase.wicenv_cache[image] = os.path.join(stdir, machine, 'imgdata')
112        return WicTestCase.wicenv_cache[image]
113
114class Wic(WicTestCase):
115
116    def test_version(self):
117        """Test wic --version"""
118        runCmd('wic --version')
119
120    def test_help(self):
121        """Test wic --help and wic -h"""
122        runCmd('wic --help')
123        runCmd('wic -h')
124
125    def test_createhelp(self):
126        """Test wic create --help"""
127        runCmd('wic create --help')
128
129    def test_listhelp(self):
130        """Test wic list --help"""
131        runCmd('wic list --help')
132
133    def test_help_create(self):
134        """Test wic help create"""
135        runCmd('wic help create')
136
137    def test_help_list(self):
138        """Test wic help list"""
139        runCmd('wic help list')
140
141    def test_help_overview(self):
142        """Test wic help overview"""
143        runCmd('wic help overview')
144
145    def test_help_plugins(self):
146        """Test wic help plugins"""
147        runCmd('wic help plugins')
148
149    def test_help_kickstart(self):
150        """Test wic help kickstart"""
151        runCmd('wic help kickstart')
152
153    def test_list_images(self):
154        """Test wic list images"""
155        runCmd('wic list images')
156
157    def test_list_source_plugins(self):
158        """Test wic list source-plugins"""
159        runCmd('wic list source-plugins')
160
161    def test_listed_images_help(self):
162        """Test wic listed images help"""
163        output = runCmd('wic list images').output
164        imagelist = [line.split()[0] for line in output.splitlines()]
165        for image in imagelist:
166            runCmd('wic list %s help' % image)
167
168    def test_unsupported_subcommand(self):
169        """Test unsupported subcommand"""
170        self.assertNotEqual(0, runCmd('wic unsupported', ignore_status=True).status)
171
172    def test_no_command(self):
173        """Test wic without command"""
174        self.assertEqual(1, runCmd('wic', ignore_status=True).status)
175
176    def test_build_image_name(self):
177        """Test wic create wictestdisk --image-name=core-image-minimal"""
178        cmd = "wic create wictestdisk --image-name=core-image-minimal -o %s" % self.resultdir
179        runCmd(cmd)
180        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
181
182    @only_for_arch(['i586', 'i686', 'x86_64'])
183    def test_gpt_image(self):
184        """Test creation of core-image-minimal with gpt table and UUID boot"""
185        cmd = "wic create directdisk-gpt --image-name core-image-minimal -o %s" % self.resultdir
186        runCmd(cmd)
187        self.assertEqual(1, len(glob(self.resultdir + "directdisk-*.direct")))
188
189    @only_for_arch(['i586', 'i686', 'x86_64'])
190    def test_iso_image(self):
191        """Test creation of hybrid iso image with legacy and EFI boot"""
192        config = 'INITRAMFS_IMAGE = "core-image-minimal-initramfs"\n'\
193                 'MACHINE_FEATURES:append = " efi"\n'\
194                 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
195        self.append_config(config)
196        bitbake('core-image-minimal core-image-minimal-initramfs')
197        self.remove_config(config)
198        cmd = "wic create mkhybridiso --image-name core-image-minimal -o %s" % self.resultdir
199        runCmd(cmd)
200        self.assertEqual(1, len(glob(self.resultdir + "HYBRID_ISO_IMG-*.direct")))
201        self.assertEqual(1, len(glob(self.resultdir + "HYBRID_ISO_IMG-*.iso")))
202
203    @only_for_arch(['i586', 'i686', 'x86_64'])
204    def test_qemux86_directdisk(self):
205        """Test creation of qemux-86-directdisk image"""
206        cmd = "wic create qemux86-directdisk -e core-image-minimal -o %s" % self.resultdir
207        runCmd(cmd)
208        self.assertEqual(1, len(glob(self.resultdir + "qemux86-directdisk-*direct")))
209
210    @only_for_arch(['i586', 'i686', 'x86_64'])
211    def test_mkefidisk(self):
212        """Test creation of mkefidisk image"""
213        cmd = "wic create mkefidisk -e core-image-minimal -o %s" % self.resultdir
214        runCmd(cmd)
215        self.assertEqual(1, len(glob(self.resultdir + "mkefidisk-*direct")))
216
217    @only_for_arch(['i586', 'i686', 'x86_64'])
218    def test_bootloader_config(self):
219        """Test creation of directdisk-bootloader-config image"""
220        config = 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
221        self.append_config(config)
222        bitbake('core-image-minimal')
223        self.remove_config(config)
224        cmd = "wic create directdisk-bootloader-config -e core-image-minimal -o %s" % self.resultdir
225        runCmd(cmd)
226        self.assertEqual(1, len(glob(self.resultdir + "directdisk-bootloader-config-*direct")))
227
228    @only_for_arch(['i586', 'i686', 'x86_64'])
229    def test_systemd_bootdisk(self):
230        """Test creation of systemd-bootdisk image"""
231        config = 'MACHINE_FEATURES:append = " efi"\n'
232        self.append_config(config)
233        bitbake('core-image-minimal')
234        self.remove_config(config)
235        cmd = "wic create systemd-bootdisk -e core-image-minimal -o %s" % self.resultdir
236        runCmd(cmd)
237        self.assertEqual(1, len(glob(self.resultdir + "systemd-bootdisk-*direct")))
238
239    def test_efi_bootpart(self):
240        """Test creation of efi-bootpart image"""
241        cmd = "wic create mkefidisk -e core-image-minimal -o %s" % self.resultdir
242        kimgtype = get_bb_var('KERNEL_IMAGETYPE', 'core-image-minimal')
243        self.append_config('IMAGE_EFI_BOOT_FILES = "%s;kernel"\n' % kimgtype)
244        runCmd(cmd)
245        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
246        images = glob(self.resultdir + "mkefidisk-*.direct")
247        result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
248        self.assertIn("kernel",result.output)
249
250    def test_sdimage_bootpart(self):
251        """Test creation of sdimage-bootpart image"""
252        cmd = "wic create sdimage-bootpart -e core-image-minimal -o %s" % self.resultdir
253        kimgtype = get_bb_var('KERNEL_IMAGETYPE', 'core-image-minimal')
254        self.write_config('IMAGE_BOOT_FILES = "%s"\n' % kimgtype)
255        runCmd(cmd)
256        self.assertEqual(1, len(glob(self.resultdir + "sdimage-bootpart-*direct")))
257
258    @only_for_arch(['i586', 'i686', 'x86_64'])
259    def test_default_output_dir(self):
260        """Test default output location"""
261        for fname in glob("directdisk-*.direct"):
262            os.remove(fname)
263        config = 'DEPENDS:pn-core-image-minimal += "syslinux"\n'
264        self.append_config(config)
265        bitbake('core-image-minimal')
266        self.remove_config(config)
267        cmd = "wic create directdisk -e core-image-minimal"
268        runCmd(cmd)
269        self.assertEqual(1, len(glob("directdisk-*.direct")))
270
271    @only_for_arch(['i586', 'i686', 'x86_64'])
272    def test_build_artifacts(self):
273        """Test wic create directdisk providing all artifacts."""
274        bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
275                              'wic-tools')
276        bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
277                                   'core-image-minimal'))
278        bbvars = {key.lower(): value for key, value in bb_vars.items()}
279        bbvars['resultdir'] = self.resultdir
280        runCmd("wic create directdisk "
281                        "-b %(staging_datadir)s "
282                        "-k %(deploy_dir_image)s "
283                        "-n %(recipe_sysroot_native)s "
284                        "-r %(image_rootfs)s "
285                        "-o %(resultdir)s" % bbvars)
286        self.assertEqual(1, len(glob(self.resultdir + "directdisk-*.direct")))
287
288    def test_compress_gzip(self):
289        """Test compressing an image with gzip"""
290        runCmd("wic create wictestdisk "
291                                   "--image-name core-image-minimal "
292                                   "-c gzip -o %s" % self.resultdir)
293        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.gz")))
294
295    def test_compress_bzip2(self):
296        """Test compressing an image with bzip2"""
297        runCmd("wic create wictestdisk "
298                                   "--image-name=core-image-minimal "
299                                   "-c bzip2 -o %s" % self.resultdir)
300        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.bz2")))
301
302    def test_compress_xz(self):
303        """Test compressing an image with xz"""
304        runCmd("wic create wictestdisk "
305                                   "--image-name=core-image-minimal "
306                                   "--compress-with=xz -o %s" % self.resultdir)
307        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.xz")))
308
309    def test_wrong_compressor(self):
310        """Test how wic breaks if wrong compressor is provided"""
311        self.assertEqual(2, runCmd("wic create wictestdisk "
312                                   "--image-name=core-image-minimal "
313                                   "-c wrong -o %s" % self.resultdir,
314                                   ignore_status=True).status)
315
316    def test_debug_short(self):
317        """Test -D option"""
318        runCmd("wic create wictestdisk "
319                                   "--image-name=core-image-minimal "
320                                   "-D -o %s" % self.resultdir)
321        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
322        self.assertEqual(1, len(glob(self.resultdir + "tmp.wic*")))
323
324    def test_debug_long(self):
325        """Test --debug option"""
326        runCmd("wic create wictestdisk "
327                                   "--image-name=core-image-minimal "
328                                   "--debug -o %s" % self.resultdir)
329        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
330        self.assertEqual(1, len(glob(self.resultdir + "tmp.wic*")))
331
332    def test_skip_build_check_short(self):
333        """Test -s option"""
334        runCmd("wic create wictestdisk "
335                                   "--image-name=core-image-minimal "
336                                   "-s -o %s" % self.resultdir)
337        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
338
339    def test_skip_build_check_long(self):
340        """Test --skip-build-check option"""
341        runCmd("wic create wictestdisk "
342                                   "--image-name=core-image-minimal "
343                                   "--skip-build-check "
344                                   "--outdir %s" % self.resultdir)
345        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
346
347    def test_build_rootfs_short(self):
348        """Test -f option"""
349        runCmd("wic create wictestdisk "
350                                   "--image-name=core-image-minimal "
351                                   "-f -o %s" % self.resultdir)
352        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
353
354    def test_build_rootfs_long(self):
355        """Test --build-rootfs option"""
356        runCmd("wic create wictestdisk "
357                                   "--image-name=core-image-minimal "
358                                   "--build-rootfs "
359                                   "--outdir %s" % self.resultdir)
360        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
361
362    @only_for_arch(['i586', 'i686', 'x86_64'])
363    def test_rootfs_indirect_recipes(self):
364        """Test usage of rootfs plugin with rootfs recipes"""
365        runCmd("wic create directdisk-multi-rootfs "
366                        "--image-name=core-image-minimal "
367                        "--rootfs rootfs1=core-image-minimal "
368                        "--rootfs rootfs2=core-image-minimal "
369                        "--outdir %s" % self.resultdir)
370        self.assertEqual(1, len(glob(self.resultdir + "directdisk-multi-rootfs*.direct")))
371
372    @only_for_arch(['i586', 'i686', 'x86_64'])
373    def test_rootfs_artifacts(self):
374        """Test usage of rootfs plugin with rootfs paths"""
375        bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
376                              'wic-tools')
377        bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
378                                   'core-image-minimal'))
379        bbvars = {key.lower(): value for key, value in bb_vars.items()}
380        bbvars['wks'] = "directdisk-multi-rootfs"
381        bbvars['resultdir'] = self.resultdir
382        runCmd("wic create %(wks)s "
383                        "--bootimg-dir=%(staging_datadir)s "
384                        "--kernel-dir=%(deploy_dir_image)s "
385                        "--native-sysroot=%(recipe_sysroot_native)s "
386                        "--rootfs-dir rootfs1=%(image_rootfs)s "
387                        "--rootfs-dir rootfs2=%(image_rootfs)s "
388                        "--outdir %(resultdir)s" % bbvars)
389        self.assertEqual(1, len(glob(self.resultdir + "%(wks)s-*.direct" % bbvars)))
390
391    def test_exclude_path(self):
392        """Test --exclude-path wks option."""
393
394        oldpath = os.environ['PATH']
395        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
396
397        try:
398            wks_file = 'temp.wks'
399            with open(wks_file, 'w') as wks:
400                rootfs_dir = get_bb_var('IMAGE_ROOTFS', 'core-image-minimal')
401                wks.write("""
402part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path usr
403part /usr --source rootfs --ondisk mmcblk0 --fstype=ext4 --rootfs-dir %s/usr
404part /etc --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path bin/ --rootfs-dir %s/usr"""
405                          % (rootfs_dir, rootfs_dir))
406            runCmd("wic create %s -e core-image-minimal -o %s" \
407                                       % (wks_file, self.resultdir))
408
409            os.remove(wks_file)
410            wicout = glob(self.resultdir + "%s-*direct" % 'temp')
411            self.assertEqual(1, len(wicout))
412
413            wicimg = wicout[0]
414
415            # verify partition size with wic
416            res = runCmd("parted -m %s unit b p 2>/dev/null" % wicimg)
417
418            # parse parted output which looks like this:
419            # BYT;\n
420            # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
421            # 1:0.00MiB:200MiB:200MiB:ext4::;\n
422            partlns = res.output.splitlines()[2:]
423
424            self.assertEqual(3, len(partlns))
425
426            for part in [1, 2, 3]:
427                part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
428                partln = partlns[part-1].split(":")
429                self.assertEqual(7, len(partln))
430                start = int(partln[1].rstrip("B")) / 512
431                length = int(partln[3].rstrip("B")) / 512
432                runCmd("dd if=%s of=%s skip=%d count=%d" %
433                                           (wicimg, part_file, start, length))
434
435            # Test partition 1, should contain the normal root directories, except
436            # /usr.
437            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
438                             os.path.join(self.resultdir, "selftest_img.part1"))
439            files = extract_files(res.output)
440            self.assertIn("etc", files)
441            self.assertNotIn("usr", files)
442
443            # Partition 2, should contain common directories for /usr, not root
444            # directories.
445            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
446                             os.path.join(self.resultdir, "selftest_img.part2"))
447            files = extract_files(res.output)
448            self.assertNotIn("etc", files)
449            self.assertNotIn("usr", files)
450            self.assertIn("share", files)
451
452            # Partition 3, should contain the same as partition 2, including the bin
453            # directory, but not the files inside it.
454            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
455                             os.path.join(self.resultdir, "selftest_img.part3"))
456            files = extract_files(res.output)
457            self.assertNotIn("etc", files)
458            self.assertNotIn("usr", files)
459            self.assertIn("share", files)
460            self.assertIn("bin", files)
461            res = runCmd("debugfs -R 'ls -p bin' %s 2>/dev/null" % \
462                             os.path.join(self.resultdir, "selftest_img.part3"))
463            files = extract_files(res.output)
464            self.assertIn(".", files)
465            self.assertIn("..", files)
466            self.assertEqual(2, len(files))
467
468            for part in [1, 2, 3]:
469                part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
470                os.remove(part_file)
471
472        finally:
473            os.environ['PATH'] = oldpath
474
475    def test_include_path(self):
476        """Test --include-path wks option."""
477
478        oldpath = os.environ['PATH']
479        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
480
481        try:
482            include_path = os.path.join(self.resultdir, 'test-include')
483            os.makedirs(include_path)
484            with open(os.path.join(include_path, 'test-file'), 'w') as t:
485                t.write("test\n")
486            wks_file = os.path.join(include_path, 'temp.wks')
487            with open(wks_file, 'w') as wks:
488                rootfs_dir = get_bb_var('IMAGE_ROOTFS', 'core-image-minimal')
489                wks.write("""
490part /part1 --source rootfs --ondisk mmcblk0 --fstype=ext4
491part /part2 --source rootfs --ondisk mmcblk0 --fstype=ext4 --include-path %s"""
492                          % (include_path))
493            runCmd("wic create %s -e core-image-minimal -o %s" \
494                                       % (wks_file, self.resultdir))
495
496            part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
497            part2 = glob(os.path.join(self.resultdir, 'temp-*.direct.p2'))[0]
498
499            # Test partition 1, should not contain 'test-file'
500            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
501            files = extract_files(res.output)
502            self.assertNotIn('test-file', files)
503            self.assertEqual(True, files_own_by_root(res.output))
504
505            # Test partition 2, should contain 'test-file'
506            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part2))
507            files = extract_files(res.output)
508            self.assertIn('test-file', files)
509            self.assertEqual(True, files_own_by_root(res.output))
510
511        finally:
512            os.environ['PATH'] = oldpath
513
514    def test_include_path_embeded(self):
515        """Test --include-path wks option."""
516
517        oldpath = os.environ['PATH']
518        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
519
520        try:
521            include_path = os.path.join(self.resultdir, 'test-include')
522            os.makedirs(include_path)
523            with open(os.path.join(include_path, 'test-file'), 'w') as t:
524                t.write("test\n")
525            wks_file = os.path.join(include_path, 'temp.wks')
526            with open(wks_file, 'w') as wks:
527                wks.write("""
528part / --source rootfs  --fstype=ext4 --include-path %s --include-path core-image-minimal-mtdutils export/"""
529                          % (include_path))
530            runCmd("wic create %s -e core-image-minimal -o %s" \
531                                       % (wks_file, self.resultdir))
532
533            part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
534
535            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
536            files = extract_files(res.output)
537            self.assertIn('test-file', files)
538            self.assertEqual(True, files_own_by_root(res.output))
539
540            res = runCmd("debugfs -R 'ls -p /export/etc/' %s 2>/dev/null" % (part1))
541            files = extract_files(res.output)
542            self.assertIn('passwd', files)
543            self.assertEqual(True, files_own_by_root(res.output))
544
545        finally:
546            os.environ['PATH'] = oldpath
547
548    def test_include_path_errors(self):
549        """Test --include-path wks option error handling."""
550        wks_file = 'temp.wks'
551
552        # Absolute argument.
553        with open(wks_file, 'w') as wks:
554            wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils /export")
555        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
556                                      % (wks_file, self.resultdir), ignore_status=True).status)
557        os.remove(wks_file)
558
559        # Argument pointing to parent directory.
560        with open(wks_file, 'w') as wks:
561            wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils ././..")
562        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
563                                      % (wks_file, self.resultdir), ignore_status=True).status)
564        os.remove(wks_file)
565
566        # 3 Argument pointing to parent directory.
567        with open(wks_file, 'w') as wks:
568            wks.write("part / --source rootfs --fstype=ext4 --include-path core-image-minimal-mtdutils export/ dummy")
569        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
570                                      % (wks_file, self.resultdir), ignore_status=True).status)
571        os.remove(wks_file)
572
573    def test_exclude_path_errors(self):
574        """Test --exclude-path wks option error handling."""
575        wks_file = 'temp.wks'
576
577        # Absolute argument.
578        with open(wks_file, 'w') as wks:
579            wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path /usr")
580        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
581                                      % (wks_file, self.resultdir), ignore_status=True).status)
582        os.remove(wks_file)
583
584        # Argument pointing to parent directory.
585        with open(wks_file, 'w') as wks:
586            wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path ././..")
587        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
588                                      % (wks_file, self.resultdir), ignore_status=True).status)
589        os.remove(wks_file)
590
591    def test_permissions(self):
592        """Test permissions are respected"""
593
594        # prepare wicenv and rootfs
595        bitbake('core-image-minimal core-image-minimal-mtdutils -c do_rootfs_wicenv')
596
597        oldpath = os.environ['PATH']
598        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
599
600        t_normal = """
601part / --source rootfs --fstype=ext4
602"""
603        t_exclude = """
604part / --source rootfs --fstype=ext4 --exclude-path=home
605"""
606        t_multi = """
607part / --source rootfs --ondisk sda --fstype=ext4
608part /export --source rootfs --rootfs=core-image-minimal-mtdutils --fstype=ext4
609"""
610        t_change = """
611part / --source rootfs --ondisk sda --fstype=ext4 --exclude-path=etc/   
612part /etc --source rootfs --fstype=ext4 --change-directory=etc
613"""
614        tests = [t_normal, t_exclude, t_multi, t_change]
615
616        try:
617            for test in tests:
618                include_path = os.path.join(self.resultdir, 'test-include')
619                os.makedirs(include_path)
620                wks_file = os.path.join(include_path, 'temp.wks')
621                with open(wks_file, 'w') as wks:
622                    wks.write(test)
623                runCmd("wic create %s -e core-image-minimal -o %s" \
624                                       % (wks_file, self.resultdir))
625
626                for part in glob(os.path.join(self.resultdir, 'temp-*.direct.p*')):
627                    res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part))
628                    self.assertEqual(True, files_own_by_root(res.output))
629
630                config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "%s"\n' % wks_file
631                self.append_config(config)
632                bitbake('core-image-minimal')
633                tmpdir = os.path.join(get_bb_var('WORKDIR', 'core-image-minimal'),'build-wic')
634
635                # check each partition for permission
636                for part in glob(os.path.join(tmpdir, 'temp-*.direct.p*')):
637                    res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part))
638                    self.assertTrue(files_own_by_root(res.output)
639                        ,msg='Files permission incorrect using wks set "%s"' % test)
640
641                # clean config and result directory for next cases
642                self.remove_config(config)
643                rmtree(self.resultdir, ignore_errors=True)
644
645        finally:
646            os.environ['PATH'] = oldpath
647
648    def test_change_directory(self):
649        """Test --change-directory wks option."""
650
651        oldpath = os.environ['PATH']
652        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
653
654        try:
655            include_path = os.path.join(self.resultdir, 'test-include')
656            os.makedirs(include_path)
657            wks_file = os.path.join(include_path, 'temp.wks')
658            with open(wks_file, 'w') as wks:
659                wks.write("part /etc --source rootfs --fstype=ext4 --change-directory=etc")
660            runCmd("wic create %s -e core-image-minimal -o %s" \
661                                       % (wks_file, self.resultdir))
662
663            part1 = glob(os.path.join(self.resultdir, 'temp-*.direct.p1'))[0]
664
665            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % (part1))
666            files = extract_files(res.output)
667            self.assertIn('passwd', files)
668
669        finally:
670            os.environ['PATH'] = oldpath
671
672    def test_change_directory_errors(self):
673        """Test --change-directory wks option error handling."""
674        wks_file = 'temp.wks'
675
676        # Absolute argument.
677        with open(wks_file, 'w') as wks:
678            wks.write("part / --source rootfs --fstype=ext4 --change-directory /usr")
679        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
680                                      % (wks_file, self.resultdir), ignore_status=True).status)
681        os.remove(wks_file)
682
683        # Argument pointing to parent directory.
684        with open(wks_file, 'w') as wks:
685            wks.write("part / --source rootfs --fstype=ext4 --change-directory ././..")
686        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
687                                      % (wks_file, self.resultdir), ignore_status=True).status)
688        os.remove(wks_file)
689
690    def test_no_fstab_update(self):
691        """Test --no-fstab-update wks option."""
692
693        oldpath = os.environ['PATH']
694        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
695
696        # Get stock fstab from base-files recipe
697        self.assertEqual(0, bitbake('base-files -c do_install').status)
698        bf_fstab = os.path.join(get_bb_var('D', 'base-files'), 'etc/fstab')
699        self.assertEqual(True, os.path.exists(bf_fstab))
700        bf_fstab_md5sum = runCmd('md5sum %s 2>/dev/null' % bf_fstab).output.split(" ")[0]
701
702        try:
703            no_fstab_update_path = os.path.join(self.resultdir, 'test-no-fstab-update')
704            os.makedirs(no_fstab_update_path)
705            wks_file = os.path.join(no_fstab_update_path, 'temp.wks')
706            with open(wks_file, 'w') as wks:
707                wks.writelines(['part / --source rootfs --fstype=ext4 --label rootfs\n',
708                                'part /mnt/p2 --source rootfs --rootfs-dir=core-image-minimal ',
709                                '--fstype=ext4 --label p2 --no-fstab-update\n'])
710            runCmd("wic create %s -e core-image-minimal -o %s" \
711                                       % (wks_file, self.resultdir))
712
713            part_fstab_md5sum = []
714            for i in range(1, 3):
715                part = glob(os.path.join(self.resultdir, 'temp-*.direct.p') + str(i))[0]
716                part_fstab = runCmd("debugfs -R 'cat etc/fstab' %s 2>/dev/null" % (part))
717                part_fstab_md5sum.append(hashlib.md5((part_fstab.output + "\n\n").encode('utf-8')).hexdigest())
718
719            # '/etc/fstab' in partition 2 should contain the same stock fstab file
720            # as the one installed by the base-file recipe.
721            self.assertEqual(bf_fstab_md5sum, part_fstab_md5sum[1])
722
723            # '/etc/fstab' in partition 1 should contain an updated fstab file.
724            self.assertNotEqual(bf_fstab_md5sum, part_fstab_md5sum[0])
725
726        finally:
727            os.environ['PATH'] = oldpath
728
729    def test_no_fstab_update_errors(self):
730        """Test --no-fstab-update wks option error handling."""
731        wks_file = 'temp.wks'
732
733        # Absolute argument.
734        with open(wks_file, 'w') as wks:
735            wks.write("part / --source rootfs --fstype=ext4 --no-fstab-update /etc")
736        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
737                                      % (wks_file, self.resultdir), ignore_status=True).status)
738        os.remove(wks_file)
739
740        # Argument pointing to parent directory.
741        with open(wks_file, 'w') as wks:
742            wks.write("part / --source rootfs --fstype=ext4 --no-fstab-update ././..")
743        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
744                                      % (wks_file, self.resultdir), ignore_status=True).status)
745        os.remove(wks_file)
746
747    def test_extra_space(self):
748        """Test --extra-space wks option."""
749        extraspace = 1024**3
750        runCmd("wic create wictestdisk "
751                                   "--image-name core-image-minimal "
752                                   "--extra-space %i -o %s" % (extraspace ,self.resultdir))
753        wicout = glob(self.resultdir + "wictestdisk-*.direct")
754        self.assertEqual(1, len(wicout))
755        size = os.path.getsize(wicout[0])
756        self.assertTrue(size > extraspace)
757
758class Wic2(WicTestCase):
759
760    def test_bmap_short(self):
761        """Test generation of .bmap file -m option"""
762        cmd = "wic create wictestdisk -e core-image-minimal -m -o %s" % self.resultdir
763        runCmd(cmd)
764        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
765        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct.bmap")))
766
767    def test_bmap_long(self):
768        """Test generation of .bmap file --bmap option"""
769        cmd = "wic create wictestdisk -e core-image-minimal --bmap -o %s" % self.resultdir
770        runCmd(cmd)
771        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
772        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct.bmap")))
773
774    def test_image_env(self):
775        """Test generation of <image>.env files."""
776        image = 'core-image-minimal'
777        imgdatadir = self._get_image_env_path(image)
778
779        bb_vars = get_bb_vars(['IMAGE_BASENAME', 'WICVARS'], image)
780        basename = bb_vars['IMAGE_BASENAME']
781        self.assertEqual(basename, image)
782        path = os.path.join(imgdatadir, basename) + '.env'
783        self.assertTrue(os.path.isfile(path))
784
785        wicvars = set(bb_vars['WICVARS'].split())
786        # filter out optional variables
787        wicvars = wicvars.difference(('DEPLOY_DIR_IMAGE', 'IMAGE_BOOT_FILES',
788                                      'INITRD', 'INITRD_LIVE', 'ISODIR','INITRAMFS_IMAGE',
789                                      'INITRAMFS_IMAGE_BUNDLE', 'INITRAMFS_LINK_NAME',
790                                      'APPEND', 'IMAGE_EFI_BOOT_FILES'))
791        with open(path) as envfile:
792            content = dict(line.split("=", 1) for line in envfile)
793            # test if variables used by wic present in the .env file
794            for var in wicvars:
795                self.assertTrue(var in content, "%s is not in .env file" % var)
796                self.assertTrue(content[var])
797
798    def test_image_vars_dir_short(self):
799        """Test image vars directory selection -v option"""
800        image = 'core-image-minimal'
801        imgenvdir = self._get_image_env_path(image)
802        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
803
804        runCmd("wic create wictestdisk "
805                                   "--image-name=%s -v %s -n %s -o %s"
806                                   % (image, imgenvdir, native_sysroot,
807                                      self.resultdir))
808        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
809
810    def test_image_vars_dir_long(self):
811        """Test image vars directory selection --vars option"""
812        image = 'core-image-minimal'
813        imgenvdir = self._get_image_env_path(image)
814        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
815
816        runCmd("wic create wictestdisk "
817                                   "--image-name=%s "
818                                   "--vars %s "
819                                   "--native-sysroot %s "
820                                   "--outdir %s"
821                                   % (image, imgenvdir, native_sysroot,
822                                      self.resultdir))
823        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
824
825    @only_for_arch(['i586', 'i686', 'x86_64'])
826    def test_wic_image_type(self):
827        """Test building wic images by bitbake"""
828        config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
829                 'MACHINE_FEATURES:append = " efi"\n'
830        self.append_config(config)
831        self.assertEqual(0, bitbake('wic-image-minimal').status)
832        self.remove_config(config)
833
834        bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE'])
835        deploy_dir = bb_vars['DEPLOY_DIR_IMAGE']
836        machine = bb_vars['MACHINE']
837        prefix = os.path.join(deploy_dir, 'wic-image-minimal-%s.' % machine)
838        # check if we have result image and manifests symlinks
839        # pointing to existing files
840        for suffix in ('wic', 'manifest'):
841            path = prefix + suffix
842            self.assertTrue(os.path.islink(path))
843            self.assertTrue(os.path.isfile(os.path.realpath(path)))
844
845    @only_for_arch(['i586', 'i686', 'x86_64'])
846    def test_qemu(self):
847        """Test wic-image-minimal under qemu"""
848        config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
849                 'MACHINE_FEATURES:append = " efi"\n'
850        self.append_config(config)
851        self.assertEqual(0, bitbake('wic-image-minimal').status)
852        self.remove_config(config)
853
854        with runqemu('wic-image-minimal', ssh=False) as qemu:
855            cmd = "mount | grep '^/dev/' | cut -f1,3 -d ' ' | egrep -c -e '/dev/sda1 /boot' " \
856                  "-e '/dev/root /|/dev/sda2 /' -e '/dev/sda3 /media' -e '/dev/sda4 /mnt'"
857            status, output = qemu.run_serial(cmd)
858            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
859            self.assertEqual(output, '4')
860            cmd = "grep UUID= /etc/fstab"
861            status, output = qemu.run_serial(cmd)
862            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
863            self.assertEqual(output, 'UUID=2c71ef06-a81d-4735-9d3a-379b69c6bdba\t/media\text4\tdefaults\t0\t0')
864
865    @only_for_arch(['i586', 'i686', 'x86_64'])
866    def test_qemu_efi(self):
867        """Test core-image-minimal efi image under qemu"""
868        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "mkefidisk.wks"\n'
869        self.append_config(config)
870        self.assertEqual(0, bitbake('core-image-minimal ovmf').status)
871        self.remove_config(config)
872
873        with runqemu('core-image-minimal', ssh=False,
874                     runqemuparams='ovmf', image_fstype='wic') as qemu:
875            cmd = "grep sda. /proc/partitions  |wc -l"
876            status, output = qemu.run_serial(cmd)
877            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
878            self.assertEqual(output, '3')
879
880    @staticmethod
881    def _make_fixed_size_wks(size):
882        """
883        Create a wks of an image with a single partition. Size of the partition is set
884        using --fixed-size flag. Returns a tuple: (path to wks file, wks image name)
885        """
886        with NamedTemporaryFile("w", suffix=".wks", delete=False) as tempf:
887            wkspath = tempf.name
888            tempf.write("part " \
889                     "--source rootfs --ondisk hda --align 4 --fixed-size %d "
890                     "--fstype=ext4\n" % size)
891
892        return wkspath
893
894    def _get_wic_partitions(self, wkspath, native_sysroot=None, ignore_status=False):
895        p = runCmd("wic create %s -e core-image-minimal -o %s" % (wkspath, self.resultdir),
896                   ignore_status=ignore_status)
897
898        if p.status:
899            return (p, None)
900
901        wksname = os.path.splitext(os.path.basename(wkspath))[0]
902
903        wicout = glob(self.resultdir + "%s-*direct" % wksname)
904
905        if not wicout:
906            return (p, None)
907
908        wicimg = wicout[0]
909
910        if not native_sysroot:
911            native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
912
913        # verify partition size with wic
914        res = runCmd("parted -m %s unit kib p 2>/dev/null" % wicimg,
915                     native_sysroot=native_sysroot)
916
917        # parse parted output which looks like this:
918        # BYT;\n
919        # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
920        # 1:0.00MiB:200MiB:200MiB:ext4::;\n
921        return (p, res.output.splitlines()[2:])
922
923    def test_fixed_size(self):
924        """
925        Test creation of a simple image with partition size controlled through
926        --fixed-size flag
927        """
928        wkspath = Wic2._make_fixed_size_wks(200)
929        _, partlns = self._get_wic_partitions(wkspath)
930        os.remove(wkspath)
931
932        self.assertEqual(partlns, [
933                        "1:4.00kiB:204804kiB:204800kiB:ext4::;",
934                        ])
935
936    def test_fixed_size_error(self):
937        """
938        Test creation of a simple image with partition size controlled through
939        --fixed-size flag. The size of partition is intentionally set to 1MiB
940        in order to trigger an error in wic.
941        """
942        wkspath = Wic2._make_fixed_size_wks(1)
943        p, _ = self._get_wic_partitions(wkspath, ignore_status=True)
944        os.remove(wkspath)
945
946        self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
947
948    def test_offset(self):
949        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
950
951        with NamedTemporaryFile("w", suffix=".wks") as tempf:
952            # Test that partitions are placed at the correct offsets, default KB
953            tempf.write("bootloader --ptable gpt\n" \
954                        "part /    --source rootfs --ondisk hda --offset 32     --fixed-size 100M --fstype=ext4\n" \
955                        "part /bar                 --ondisk hda --offset 102432 --fixed-size 100M --fstype=ext4\n")
956            tempf.flush()
957
958            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
959            self.assertEqual(partlns, [
960                "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
961                "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
962                ])
963
964        with NamedTemporaryFile("w", suffix=".wks") as tempf:
965            # Test that partitions are placed at the correct offsets, same with explicit KB
966            tempf.write("bootloader --ptable gpt\n" \
967                        "part /    --source rootfs --ondisk hda --offset 32K     --fixed-size 100M --fstype=ext4\n" \
968                        "part /bar                 --ondisk hda --offset 102432K --fixed-size 100M --fstype=ext4\n")
969            tempf.flush()
970
971            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
972            self.assertEqual(partlns, [
973                "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
974                "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
975                ])
976
977        with NamedTemporaryFile("w", suffix=".wks") as tempf:
978            # Test that partitions are placed at the correct offsets using MB
979            tempf.write("bootloader --ptable gpt\n" \
980                        "part /    --source rootfs --ondisk hda --offset 32K  --fixed-size 100M --fstype=ext4\n" \
981                        "part /bar                 --ondisk hda --offset 101M --fixed-size 100M --fstype=ext4\n")
982            tempf.flush()
983
984            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
985            self.assertEqual(partlns, [
986                "1:32.0kiB:102432kiB:102400kiB:ext4:primary:;",
987                "2:103424kiB:205824kiB:102400kiB:ext4:primary:;",
988                ])
989
990        with NamedTemporaryFile("w", suffix=".wks") as tempf:
991            # Test that partitions can be placed on a 512 byte sector boundary
992            tempf.write("bootloader --ptable gpt\n" \
993                        "part /    --source rootfs --ondisk hda --offset 65s --fixed-size 99M --fstype=ext4\n" \
994                        "part /bar                 --ondisk hda --offset 102432 --fixed-size 100M --fstype=ext4\n")
995            tempf.flush()
996
997            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
998            self.assertEqual(partlns, [
999                "1:32.5kiB:101408kiB:101376kiB:ext4:primary:;",
1000                "2:102432kiB:204832kiB:102400kiB:ext4:primary:;",
1001                ])
1002
1003        with NamedTemporaryFile("w", suffix=".wks") as tempf:
1004            # Test that a partition can be placed immediately after a MSDOS partition table
1005            tempf.write("bootloader --ptable msdos\n" \
1006                        "part /    --source rootfs --ondisk hda --offset 1s --fixed-size 100M --fstype=ext4\n")
1007            tempf.flush()
1008
1009            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
1010            self.assertEqual(partlns, [
1011                "1:0.50kiB:102400kiB:102400kiB:ext4::;",
1012                ])
1013
1014        with NamedTemporaryFile("w", suffix=".wks") as tempf:
1015            # Test that image creation fails if the partitions would overlap
1016            tempf.write("bootloader --ptable gpt\n" \
1017                        "part /    --source rootfs --ondisk hda --offset 32     --fixed-size 100M --fstype=ext4\n" \
1018                        "part /bar                 --ondisk hda --offset 102431 --fixed-size 100M --fstype=ext4\n")
1019            tempf.flush()
1020
1021            p, _ = self._get_wic_partitions(tempf.name, ignore_status=True)
1022            self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
1023
1024        with NamedTemporaryFile("w", suffix=".wks") as tempf:
1025            # Test that partitions are not allowed to overlap with the booloader
1026            tempf.write("bootloader --ptable gpt\n" \
1027                        "part /    --source rootfs --ondisk hda --offset 8 --fixed-size 100M --fstype=ext4\n")
1028            tempf.flush()
1029
1030            p, _ = self._get_wic_partitions(tempf.name, ignore_status=True)
1031            self.assertNotEqual(p.status, 0, "wic exited successfully when an error was expected:\n%s" % p.output)
1032
1033    def test_extra_space(self):
1034        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
1035
1036        with NamedTemporaryFile("w", suffix=".wks") as tempf:
1037            tempf.write("bootloader --ptable gpt\n" \
1038                        "part /     --source rootfs --ondisk hda --extra-space 200M --fstype=ext4\n")
1039            tempf.flush()
1040
1041            _, partlns = self._get_wic_partitions(tempf.name, native_sysroot)
1042            self.assertEqual(len(partlns), 1)
1043            size = partlns[0].split(':')[3]
1044            self.assertRegex(size, r'^[0-9]+kiB$')
1045            size = int(size[:-3])
1046            self.assertGreaterEqual(size, 204800)
1047
1048    @only_for_arch(['i586', 'i686', 'x86_64'])
1049    def test_rawcopy_plugin_qemu(self):
1050        """Test rawcopy plugin in qemu"""
1051        # build ext4 and then use it for a wic image
1052        config = 'IMAGE_FSTYPES = "ext4"\n'
1053        self.append_config(config)
1054        self.assertEqual(0, bitbake('core-image-minimal').status)
1055        self.remove_config(config)
1056
1057        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_rawcopy_plugin.wks.in"\n'
1058        self.append_config(config)
1059        self.assertEqual(0, bitbake('core-image-minimal-mtdutils').status)
1060        self.remove_config(config)
1061
1062        with runqemu('core-image-minimal-mtdutils', ssh=False, image_fstype='wic') as qemu:
1063            cmd = "grep sda. /proc/partitions  |wc -l"
1064            status, output = qemu.run_serial(cmd)
1065            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1066            self.assertEqual(output, '2')
1067
1068    def test_rawcopy_plugin(self):
1069        """Test rawcopy plugin"""
1070        img = 'core-image-minimal'
1071        machine = get_bb_var('MACHINE', img)
1072        with NamedTemporaryFile("w", suffix=".wks") as wks:
1073            wks.writelines(['part /boot --active --source bootimg-pcbios\n',
1074                            'part / --source rawcopy --sourceparams="file=%s-%s.ext4" --use-uuid\n'\
1075                             % (img, machine),
1076                            'bootloader --timeout=0 --append="console=ttyS0,115200n8"\n'])
1077            wks.flush()
1078            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
1079            runCmd(cmd)
1080            wksname = os.path.splitext(os.path.basename(wks.name))[0]
1081            out = glob(self.resultdir + "%s-*direct" % wksname)
1082            self.assertEqual(1, len(out))
1083
1084    def test_empty_plugin(self):
1085        """Test empty plugin"""
1086        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_empty_plugin.wks"\n'
1087        self.append_config(config)
1088        self.assertEqual(0, bitbake('core-image-minimal').status)
1089        self.remove_config(config)
1090
1091        bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE'])
1092        deploy_dir = bb_vars['DEPLOY_DIR_IMAGE']
1093        machine = bb_vars['MACHINE']
1094        image_path = os.path.join(deploy_dir, 'core-image-minimal-%s.wic' % machine)
1095        self.assertEqual(True, os.path.exists(image_path))
1096
1097        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1098
1099        # Fstype column from 'wic ls' should be empty for the second partition
1100        # as listed in test_empty_plugin.wks
1101        result = runCmd("wic ls %s -n %s | awk -F ' ' '{print $1 \" \" $5}' | grep '^2' | wc -w" % (image_path, sysroot))
1102        self.assertEqual('1', result.output)
1103
1104    @only_for_arch(['i586', 'i686', 'x86_64'])
1105    def test_biosplusefi_plugin_qemu(self):
1106        """Test biosplusefi plugin in qemu"""
1107        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_biosplusefi_plugin.wks"\nMACHINE_FEATURES:append = " efi"\n'
1108        self.append_config(config)
1109        self.assertEqual(0, bitbake('core-image-minimal').status)
1110        self.remove_config(config)
1111
1112        with runqemu('core-image-minimal', ssh=False, image_fstype='wic') as qemu:
1113            # Check that we have ONLY two /dev/sda* partitions (/boot and /)
1114            cmd = "grep sda. /proc/partitions | wc -l"
1115            status, output = qemu.run_serial(cmd)
1116            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1117            self.assertEqual(output, '2')
1118            # Check that /dev/sda1 is /boot and that either /dev/root OR /dev/sda2 is /
1119            cmd = "mount | grep '^/dev/' | cut -f1,3 -d ' ' | egrep -c -e '/dev/sda1 /boot' -e '/dev/root /|/dev/sda2 /'"
1120            status, output = qemu.run_serial(cmd)
1121            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1122            self.assertEqual(output, '2')
1123            # Check that /boot has EFI bootx64.efi (required for EFI)
1124            cmd = "ls /boot/EFI/BOOT/bootx64.efi | wc -l"
1125            status, output = qemu.run_serial(cmd)
1126            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1127            self.assertEqual(output, '1')
1128            # Check that "BOOTABLE" flag is set on boot partition (required for PC-Bios)
1129            # Trailing "cat" seems to be required; otherwise run_serial() sends back echo of the input command
1130            cmd = "fdisk -l /dev/sda | grep /dev/sda1 | awk {print'$2'} | cat"
1131            status, output = qemu.run_serial(cmd)
1132            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1133            self.assertEqual(output, '*')
1134
1135    @only_for_arch(['i586', 'i686', 'x86_64'])
1136    def test_biosplusefi_plugin(self):
1137        """Test biosplusefi plugin"""
1138        # Wic generation below may fail depending on the order of the unittests
1139        # This is because bootimg-pcbios (that bootimg-biosplusefi uses) generate its MBR inside STAGING_DATADIR directory
1140        #    which may or may not exists depending on what was built already
1141        # If an image hasn't been built yet, directory ${STAGING_DATADIR}/syslinux won't exists and _get_bootimg_dir()
1142        #   will raise with "Couldn't find correct bootimg_dir"
1143        # The easiest way to work-around this issue is to make sure we already built an image here, hence the bitbake call
1144        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "test_biosplusefi_plugin.wks"\nMACHINE_FEATURES:append = " efi"\n'
1145        self.append_config(config)
1146        self.assertEqual(0, bitbake('core-image-minimal').status)
1147        self.remove_config(config)
1148
1149        img = 'core-image-minimal'
1150        with NamedTemporaryFile("w", suffix=".wks") as wks:
1151            wks.writelines(['part /boot --active --source bootimg-biosplusefi --sourceparams="loader=grub-efi"\n',
1152                            'part / --source rootfs --fstype=ext4 --align 1024 --use-uuid\n'\
1153                            'bootloader --timeout=0 --append="console=ttyS0,115200n8"\n'])
1154            wks.flush()
1155            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
1156            runCmd(cmd)
1157            wksname = os.path.splitext(os.path.basename(wks.name))[0]
1158            out = glob(self.resultdir + "%s-*.direct" % wksname)
1159            self.assertEqual(1, len(out))
1160
1161    @only_for_arch(['i586', 'i686', 'x86_64'])
1162    def test_efi_plugin_unified_kernel_image_qemu(self):
1163        """Test efi plugin's Unified Kernel Image feature in qemu"""
1164        config = 'IMAGE_FSTYPES = "wic"\n'\
1165                 'INITRAMFS_IMAGE = "core-image-minimal-initramfs"\n'\
1166                 'WKS_FILE = "test_efi_plugin.wks"\n'\
1167                 'MACHINE_FEATURES:append = " efi"\n'
1168        self.append_config(config)
1169        self.assertEqual(0, bitbake('core-image-minimal core-image-minimal-initramfs ovmf').status)
1170        self.remove_config(config)
1171
1172        with runqemu('core-image-minimal', ssh=False,
1173                     runqemuparams='ovmf', image_fstype='wic') as qemu:
1174            # Check that /boot has EFI bootx64.efi (required for EFI)
1175            cmd = "ls /boot/EFI/BOOT/bootx64.efi | wc -l"
1176            status, output = qemu.run_serial(cmd)
1177            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1178            self.assertEqual(output, '1')
1179            # Check that /boot has EFI/Linux/linux.efi (required for Unified Kernel Images auto detection)
1180            cmd = "ls /boot/EFI/Linux/linux.efi | wc -l"
1181            status, output = qemu.run_serial(cmd)
1182            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1183            self.assertEqual(output, '1')
1184            # Check that /boot doesn't have loader/entries/boot.conf (Unified Kernel Images are auto detected by the bootloader)
1185            cmd = "ls /boot/loader/entries/boot.conf 2&>/dev/null | wc -l"
1186            status, output = qemu.run_serial(cmd)
1187            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1188            self.assertEqual(output, '0')
1189
1190    def test_fs_types(self):
1191        """Test filesystem types for empty and not empty partitions"""
1192        img = 'core-image-minimal'
1193        with NamedTemporaryFile("w", suffix=".wks") as wks:
1194            wks.writelines(['part ext2   --fstype ext2     --source rootfs\n',
1195                            'part btrfs  --fstype btrfs    --source rootfs --size 40M\n',
1196                            'part squash --fstype squashfs --source rootfs\n',
1197                            'part swap   --fstype swap --size 1M\n',
1198                            'part emptyvfat   --fstype vfat   --size 1M\n',
1199                            'part emptymsdos  --fstype msdos  --size 1M\n',
1200                            'part emptyext2   --fstype ext2   --size 1M\n',
1201                            'part emptybtrfs  --fstype btrfs  --size 150M\n'])
1202            wks.flush()
1203            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
1204            runCmd(cmd)
1205            wksname = os.path.splitext(os.path.basename(wks.name))[0]
1206            out = glob(self.resultdir + "%s-*direct" % wksname)
1207            self.assertEqual(1, len(out))
1208
1209    def test_kickstart_parser(self):
1210        """Test wks parser options"""
1211        with NamedTemporaryFile("w", suffix=".wks") as wks:
1212            wks.writelines(['part / --fstype ext3 --source rootfs --system-id 0xFF '\
1213                            '--overhead-factor 1.2 --size 100k\n'])
1214            wks.flush()
1215            cmd = "wic create %s -e core-image-minimal -o %s" % (wks.name, self.resultdir)
1216            runCmd(cmd)
1217            wksname = os.path.splitext(os.path.basename(wks.name))[0]
1218            out = glob(self.resultdir + "%s-*direct" % wksname)
1219            self.assertEqual(1, len(out))
1220
1221    def test_image_bootpart_globbed(self):
1222        """Test globbed sources with image-bootpart plugin"""
1223        img = "core-image-minimal"
1224        cmd = "wic create sdimage-bootpart -e %s -o %s" % (img, self.resultdir)
1225        config = 'IMAGE_BOOT_FILES = "%s*"' % get_bb_var('KERNEL_IMAGETYPE', img)
1226        self.append_config(config)
1227        runCmd(cmd)
1228        self.remove_config(config)
1229        self.assertEqual(1, len(glob(self.resultdir + "sdimage-bootpart-*direct")))
1230
1231    def test_sparse_copy(self):
1232        """Test sparse_copy with FIEMAP and SEEK_HOLE filemap APIs"""
1233        libpath = os.path.join(get_bb_var('COREBASE'), 'scripts', 'lib', 'wic')
1234        sys.path.insert(0, libpath)
1235        from  filemap import FilemapFiemap, FilemapSeek, sparse_copy, ErrorNotSupp
1236        with NamedTemporaryFile("w", suffix=".wic-sparse") as sparse:
1237            src_name = sparse.name
1238            src_size = 1024 * 10
1239            sparse.truncate(src_size)
1240            # write one byte to the file
1241            with open(src_name, 'r+b') as sfile:
1242                sfile.seek(1024 * 4)
1243                sfile.write(b'\x00')
1244            dest = sparse.name + '.out'
1245            # copy src file to dest using different filemap APIs
1246            for api in (FilemapFiemap, FilemapSeek, None):
1247                if os.path.exists(dest):
1248                    os.unlink(dest)
1249                try:
1250                    sparse_copy(sparse.name, dest, api=api)
1251                except ErrorNotSupp:
1252                    continue # skip unsupported API
1253                dest_stat = os.stat(dest)
1254                self.assertEqual(dest_stat.st_size, src_size)
1255                # 8 blocks is 4K (physical sector size)
1256                self.assertEqual(dest_stat.st_blocks, 8)
1257            os.unlink(dest)
1258
1259    def test_wic_ls(self):
1260        """Test listing image content using 'wic ls'"""
1261        runCmd("wic create wictestdisk "
1262                                   "--image-name=core-image-minimal "
1263                                   "-D -o %s" % self.resultdir)
1264        images = glob(self.resultdir + "wictestdisk-*.direct")
1265        self.assertEqual(1, len(images))
1266
1267        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1268
1269        # list partitions
1270        result = runCmd("wic ls %s -n %s" % (images[0], sysroot))
1271        self.assertEqual(3, len(result.output.split('\n')))
1272
1273        # list directory content of the first partition
1274        result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
1275        self.assertEqual(6, len(result.output.split('\n')))
1276
1277    def test_wic_cp(self):
1278        """Test copy files and directories to the the wic image."""
1279        runCmd("wic create wictestdisk "
1280                                   "--image-name=core-image-minimal "
1281                                   "-D -o %s" % self.resultdir)
1282        images = glob(self.resultdir + "wictestdisk-*.direct")
1283        self.assertEqual(1, len(images))
1284
1285        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1286
1287        # list directory content of the first partition
1288        result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
1289        self.assertEqual(6, len(result.output.split('\n')))
1290
1291        with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
1292            testfile.write("test")
1293
1294            # copy file to the partition
1295            runCmd("wic cp %s %s:1/ -n %s" % (testfile.name, images[0], sysroot))
1296
1297            # check if file is there
1298            result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
1299            self.assertEqual(7, len(result.output.split('\n')))
1300            self.assertTrue(os.path.basename(testfile.name) in result.output)
1301
1302            # prepare directory
1303            testdir = os.path.join(self.resultdir, 'wic-test-cp-dir')
1304            testsubdir = os.path.join(testdir, 'subdir')
1305            os.makedirs(os.path.join(testsubdir))
1306            copy(testfile.name, testdir)
1307
1308            # copy directory to the partition
1309            runCmd("wic cp %s %s:1/ -n %s" % (testdir, images[0], sysroot))
1310
1311            # check if directory is there
1312            result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
1313            self.assertEqual(8, len(result.output.split('\n')))
1314            self.assertTrue(os.path.basename(testdir) in result.output)
1315
1316            # copy the file from the partition and check if it success
1317            dest = '%s-cp' % testfile.name
1318            runCmd("wic cp %s:1/%s %s -n %s" % (images[0],
1319                    os.path.basename(testfile.name), dest, sysroot))
1320            self.assertTrue(os.path.exists(dest))
1321
1322
1323    def test_wic_rm(self):
1324        """Test removing files and directories from the the wic image."""
1325        runCmd("wic create mkefidisk "
1326                                   "--image-name=core-image-minimal "
1327                                   "-D -o %s" % self.resultdir)
1328        images = glob(self.resultdir + "mkefidisk-*.direct")
1329        self.assertEqual(1, len(images))
1330
1331        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1332
1333        # list directory content of the first partition
1334        result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
1335        self.assertIn('\nBZIMAGE        ', result.output)
1336        self.assertIn('\nEFI          <DIR>     ', result.output)
1337
1338        # remove file
1339        runCmd("wic rm %s:1/bzimage -n %s" % (images[0], sysroot))
1340
1341        # remove directory
1342        runCmd("wic rm %s:1/efi -n %s" % (images[0], sysroot))
1343
1344        # check if they're removed
1345        result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
1346        self.assertNotIn('\nBZIMAGE        ', result.output)
1347        self.assertNotIn('\nEFI          <DIR>     ', result.output)
1348
1349    def test_mkfs_extraopts(self):
1350        """Test wks option --mkfs-extraopts for empty and not empty partitions"""
1351        img = 'core-image-minimal'
1352        with NamedTemporaryFile("w", suffix=".wks") as wks:
1353            wks.writelines(
1354                ['part ext2   --fstype ext2     --source rootfs --mkfs-extraopts "-D -F -i 8192"\n',
1355                 "part btrfs  --fstype btrfs    --source rootfs --size 40M --mkfs-extraopts='--quiet'\n",
1356                 'part squash --fstype squashfs --source rootfs --mkfs-extraopts "-no-sparse -b 4096"\n',
1357                 'part emptyvfat   --fstype vfat   --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
1358                 'part emptymsdos  --fstype msdos  --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
1359                 'part emptyext2   --fstype ext2   --size 1M --mkfs-extraopts "-D -F -i 8192"\n',
1360                 'part emptybtrfs  --fstype btrfs  --size 100M --mkfs-extraopts "--mixed -K"\n'])
1361            wks.flush()
1362            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
1363            runCmd(cmd)
1364            wksname = os.path.splitext(os.path.basename(wks.name))[0]
1365            out = glob(self.resultdir + "%s-*direct" % wksname)
1366            self.assertEqual(1, len(out))
1367
1368    def test_expand_mbr_image(self):
1369        """Test wic write --expand command for mbr image"""
1370        # build an image
1371        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "directdisk.wks"\n'
1372        self.append_config(config)
1373        self.assertEqual(0, bitbake('core-image-minimal').status)
1374
1375        # get path to the image
1376        bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE'])
1377        deploy_dir = bb_vars['DEPLOY_DIR_IMAGE']
1378        machine = bb_vars['MACHINE']
1379        image_path = os.path.join(deploy_dir, 'core-image-minimal-%s.wic' % machine)
1380
1381        self.remove_config(config)
1382
1383        try:
1384            # expand image to 1G
1385            new_image_path = None
1386            with NamedTemporaryFile(mode='wb', suffix='.wic.exp',
1387                                    dir=deploy_dir, delete=False) as sparse:
1388                sparse.truncate(1024 ** 3)
1389                new_image_path = sparse.name
1390
1391            sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1392            cmd = "wic write -n %s --expand 1:0 %s %s" % (sysroot, image_path, new_image_path)
1393            runCmd(cmd)
1394
1395            # check if partitions are expanded
1396            orig = runCmd("wic ls %s -n %s" % (image_path, sysroot))
1397            exp = runCmd("wic ls %s -n %s" % (new_image_path, sysroot))
1398            orig_sizes = [int(line.split()[3]) for line in orig.output.split('\n')[1:]]
1399            exp_sizes = [int(line.split()[3]) for line in exp.output.split('\n')[1:]]
1400            self.assertEqual(orig_sizes[0], exp_sizes[0]) # first partition is not resized
1401            self.assertTrue(orig_sizes[1] < exp_sizes[1])
1402
1403            # Check if all free space is partitioned
1404            result = runCmd("%s/usr/sbin/sfdisk -F %s" % (sysroot, new_image_path))
1405            self.assertTrue("0 B, 0 bytes, 0 sectors" in result.output)
1406
1407            bb.utils.rename(image_path, image_path + '.bak')
1408            bb.utils.rename(new_image_path, image_path)
1409
1410            # Check if it boots in qemu
1411            with runqemu('core-image-minimal', ssh=False) as qemu:
1412                cmd = "ls /etc/"
1413                status, output = qemu.run_serial('true')
1414                self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
1415        finally:
1416            if os.path.exists(new_image_path):
1417                os.unlink(new_image_path)
1418            if os.path.exists(image_path + '.bak'):
1419                bb.utils.rename(image_path + '.bak', image_path)
1420
1421    def test_wic_ls_ext(self):
1422        """Test listing content of the ext partition using 'wic ls'"""
1423        runCmd("wic create wictestdisk "
1424                                   "--image-name=core-image-minimal "
1425                                   "-D -o %s" % self.resultdir)
1426        images = glob(self.resultdir + "wictestdisk-*.direct")
1427        self.assertEqual(1, len(images))
1428
1429        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1430
1431        # list directory content of the second ext4 partition
1432        result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1433        self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(
1434                            set(line.split()[-1] for line in result.output.split('\n') if line)))
1435
1436    def test_wic_cp_ext(self):
1437        """Test copy files and directories to the ext partition."""
1438        runCmd("wic create wictestdisk "
1439                                   "--image-name=core-image-minimal "
1440                                   "-D -o %s" % self.resultdir)
1441        images = glob(self.resultdir + "wictestdisk-*.direct")
1442        self.assertEqual(1, len(images))
1443
1444        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1445
1446        # list directory content of the ext4 partition
1447        result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1448        dirs = set(line.split()[-1] for line in result.output.split('\n') if line)
1449        self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(dirs))
1450
1451        with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
1452            testfile.write("test")
1453
1454            # copy file to the partition
1455            runCmd("wic cp %s %s:2/ -n %s" % (testfile.name, images[0], sysroot))
1456
1457            # check if file is there
1458            result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1459            newdirs = set(line.split()[-1] for line in result.output.split('\n') if line)
1460            self.assertEqual(newdirs.difference(dirs), set([os.path.basename(testfile.name)]))
1461
1462            # check if the file to copy is in the partition
1463            result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
1464            self.assertTrue('fstab' in [line.split()[-1] for line in result.output.split('\n') if line])
1465
1466            # copy file from the partition, replace the temporary file content with it and
1467            # check for the file size to validate the copy
1468            runCmd("wic cp %s:2/etc/fstab %s -n %s" % (images[0], testfile.name, sysroot))
1469            self.assertTrue(os.stat(testfile.name).st_size > 0)
1470
1471
1472    def test_wic_rm_ext(self):
1473        """Test removing files from the ext partition."""
1474        runCmd("wic create mkefidisk "
1475                                   "--image-name=core-image-minimal "
1476                                   "-D -o %s" % self.resultdir)
1477        images = glob(self.resultdir + "mkefidisk-*.direct")
1478        self.assertEqual(1, len(images))
1479
1480        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1481
1482        # list directory content of the /etc directory on ext4 partition
1483        result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
1484        self.assertTrue('fstab' in [line.split()[-1] for line in result.output.split('\n') if line])
1485
1486        # remove file
1487        runCmd("wic rm %s:2/etc/fstab -n %s" % (images[0], sysroot))
1488
1489        # check if it's removed
1490        result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
1491        self.assertTrue('fstab' not in [line.split()[-1] for line in result.output.split('\n') if line])
1492
1493        # remove non-empty directory
1494        runCmd("wic rm -r %s:2/etc/ -n %s" % (images[0], sysroot))
1495
1496        # check if it's removed
1497        result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1498        self.assertTrue('etc' not in [line.split()[-1] for line in result.output.split('\n') if line])
1499