1#!/usr/bin/env python
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# Copyright (c) 2015, Intel Corporation.
6# All rights reserved.
7#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License version 2 as
10# published by the Free Software Foundation.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License along
18# with this program; if not, write to the Free Software Foundation, Inc.,
19# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20#
21# AUTHORS
22# Ed Bartosh <ed.bartosh@linux.intel.com>
23
24"""Test cases for wic."""
25
26import os
27import sys
28import unittest
29
30from glob import glob
31from shutil import rmtree, copy
32from functools import wraps, lru_cache
33from tempfile import NamedTemporaryFile
34
35from oeqa.selftest.case import OESelftestTestCase
36from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars, runqemu
37from oeqa.core.decorator.oeid import OETestID
38
39
40@lru_cache(maxsize=32)
41def get_host_arch(recipe):
42    """A cached call to get_bb_var('HOST_ARCH', <recipe>)"""
43    return get_bb_var('HOST_ARCH', recipe)
44
45
46def only_for_arch(archs, image='core-image-minimal'):
47    """Decorator for wrapping test cases that can be run only for specific target
48    architectures. A list of compatible architectures is passed in `archs`.
49    Current architecture will be determined by parsing bitbake output for
50    `image` recipe.
51    """
52    def wrapper(func):
53        @wraps(func)
54        def wrapped_f(*args, **kwargs):
55            arch = get_host_arch(image)
56            if archs and arch not in archs:
57                raise unittest.SkipTest("Testcase arch dependency not met: %s" % arch)
58            return func(*args, **kwargs)
59        wrapped_f.__name__ = func.__name__
60        return wrapped_f
61    return wrapper
62
63
64class Wic(OESelftestTestCase):
65    """Wic test class."""
66
67    resultdir = "/var/tmp/wic.oe-selftest/"
68    image_is_ready = False
69    native_sysroot = None
70    wicenv_cache = {}
71
72    def setUpLocal(self):
73        """This code is executed before each test method."""
74        super(Wic, self).setUpLocal()
75        if not self.native_sysroot:
76            Wic.native_sysroot = get_bb_var('STAGING_DIR_NATIVE', 'wic-tools')
77
78        # Do this here instead of in setUpClass as the base setUp does some
79        # clean up which can result in the native tools built earlier in
80        # setUpClass being unavailable.
81        if not Wic.image_is_ready:
82            if get_bb_var('USE_NLS') == 'yes':
83                bitbake('wic-tools')
84            else:
85                self.skipTest('wic-tools cannot be built due its (intltool|gettext)-native dependency and NLS disable')
86
87            bitbake('core-image-minimal')
88            Wic.image_is_ready = True
89
90        rmtree(self.resultdir, ignore_errors=True)
91
92    def tearDownLocal(self):
93        """Remove resultdir as it may contain images."""
94        rmtree(self.resultdir, ignore_errors=True)
95        super(Wic, self).tearDownLocal()
96
97    @OETestID(1552)
98    def test_version(self):
99        """Test wic --version"""
100        self.assertEqual(0, runCmd('wic --version').status)
101
102    @OETestID(1208)
103    def test_help(self):
104        """Test wic --help and wic -h"""
105        self.assertEqual(0, runCmd('wic --help').status)
106        self.assertEqual(0, runCmd('wic -h').status)
107
108    @OETestID(1209)
109    def test_createhelp(self):
110        """Test wic create --help"""
111        self.assertEqual(0, runCmd('wic create --help').status)
112
113    @OETestID(1210)
114    def test_listhelp(self):
115        """Test wic list --help"""
116        self.assertEqual(0, runCmd('wic list --help').status)
117
118    @OETestID(1553)
119    def test_help_create(self):
120        """Test wic help create"""
121        self.assertEqual(0, runCmd('wic help create').status)
122
123    @OETestID(1554)
124    def test_help_list(self):
125        """Test wic help list"""
126        self.assertEqual(0, runCmd('wic help list').status)
127
128    @OETestID(1215)
129    def test_help_overview(self):
130        """Test wic help overview"""
131        self.assertEqual(0, runCmd('wic help overview').status)
132
133    @OETestID(1216)
134    def test_help_plugins(self):
135        """Test wic help plugins"""
136        self.assertEqual(0, runCmd('wic help plugins').status)
137
138    @OETestID(1217)
139    def test_help_kickstart(self):
140        """Test wic help kickstart"""
141        self.assertEqual(0, runCmd('wic help kickstart').status)
142
143    @OETestID(1555)
144    def test_list_images(self):
145        """Test wic list images"""
146        self.assertEqual(0, runCmd('wic list images').status)
147
148    @OETestID(1556)
149    def test_list_source_plugins(self):
150        """Test wic list source-plugins"""
151        self.assertEqual(0, runCmd('wic list source-plugins').status)
152
153    @OETestID(1557)
154    def test_listed_images_help(self):
155        """Test wic listed images help"""
156        output = runCmd('wic list images').output
157        imagelist = [line.split()[0] for line in output.splitlines()]
158        for image in imagelist:
159            self.assertEqual(0, runCmd('wic list %s help' % image).status)
160
161    @OETestID(1213)
162    def test_unsupported_subcommand(self):
163        """Test unsupported subcommand"""
164        self.assertNotEqual(0, runCmd('wic unsupported', ignore_status=True).status)
165
166    @OETestID(1214)
167    def test_no_command(self):
168        """Test wic without command"""
169        self.assertEqual(1, runCmd('wic', ignore_status=True).status)
170
171    @OETestID(1211)
172    def test_build_image_name(self):
173        """Test wic create wictestdisk --image-name=core-image-minimal"""
174        cmd = "wic create wictestdisk --image-name=core-image-minimal -o %s" % self.resultdir
175        self.assertEqual(0, runCmd(cmd).status)
176        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
177
178    @OETestID(1157)
179    @only_for_arch(['i586', 'i686', 'x86_64'])
180    def test_gpt_image(self):
181        """Test creation of core-image-minimal with gpt table and UUID boot"""
182        cmd = "wic create directdisk-gpt --image-name core-image-minimal -o %s" % self.resultdir
183        self.assertEqual(0, runCmd(cmd).status)
184        self.assertEqual(1, len(glob(self.resultdir + "directdisk-*.direct")))
185
186    @OETestID(1346)
187    @only_for_arch(['i586', 'i686', 'x86_64'])
188    def test_iso_image(self):
189        """Test creation of hybrid iso image with legacy and EFI boot"""
190        config = 'INITRAMFS_IMAGE = "core-image-minimal-initramfs"\n'\
191                 'MACHINE_FEATURES_append = " efi"\n'\
192                 'DEPENDS_pn-core-image-minimal += "syslinux"\n'
193        self.append_config(config)
194        bitbake('core-image-minimal')
195        self.remove_config(config)
196        cmd = "wic create mkhybridiso --image-name core-image-minimal -o %s" % self.resultdir
197        self.assertEqual(0, runCmd(cmd).status)
198        self.assertEqual(1, len(glob(self.resultdir + "HYBRID_ISO_IMG-*.direct")))
199        self.assertEqual(1, len(glob(self.resultdir + "HYBRID_ISO_IMG-*.iso")))
200
201    @OETestID(1348)
202    @only_for_arch(['i586', 'i686', 'x86_64'])
203    def test_qemux86_directdisk(self):
204        """Test creation of qemux-86-directdisk image"""
205        cmd = "wic create qemux86-directdisk -e core-image-minimal -o %s" % self.resultdir
206        self.assertEqual(0, runCmd(cmd).status)
207        self.assertEqual(1, len(glob(self.resultdir + "qemux86-directdisk-*direct")))
208
209    @OETestID(1350)
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        self.assertEqual(0, runCmd(cmd).status)
215        self.assertEqual(1, len(glob(self.resultdir + "mkefidisk-*direct")))
216
217    @OETestID(1385)
218    @only_for_arch(['i586', 'i686', 'x86_64'])
219    def test_bootloader_config(self):
220        """Test creation of directdisk-bootloader-config image"""
221        config = 'DEPENDS_pn-core-image-minimal += "syslinux"\n'
222        self.append_config(config)
223        bitbake('core-image-minimal')
224        self.remove_config(config)
225        cmd = "wic create directdisk-bootloader-config -e core-image-minimal -o %s" % self.resultdir
226        self.assertEqual(0, runCmd(cmd).status)
227        self.assertEqual(1, len(glob(self.resultdir + "directdisk-bootloader-config-*direct")))
228
229    @OETestID(1560)
230    @only_for_arch(['i586', 'i686', 'x86_64'])
231    def test_systemd_bootdisk(self):
232        """Test creation of systemd-bootdisk image"""
233        config = 'MACHINE_FEATURES_append = " efi"\n'
234        self.append_config(config)
235        bitbake('core-image-minimal')
236        self.remove_config(config)
237        cmd = "wic create systemd-bootdisk -e core-image-minimal -o %s" % self.resultdir
238        self.assertEqual(0, runCmd(cmd).status)
239        self.assertEqual(1, len(glob(self.resultdir + "systemd-bootdisk-*direct")))
240
241    @OETestID(1561)
242    def test_sdimage_bootpart(self):
243        """Test creation of sdimage-bootpart image"""
244        cmd = "wic create sdimage-bootpart -e core-image-minimal -o %s" % self.resultdir
245        kimgtype = get_bb_var('KERNEL_IMAGETYPE', 'core-image-minimal')
246        self.write_config('IMAGE_BOOT_FILES = "%s"\n' % kimgtype)
247        self.assertEqual(0, runCmd(cmd).status)
248        self.assertEqual(1, len(glob(self.resultdir + "sdimage-bootpart-*direct")))
249
250    @OETestID(1562)
251    @only_for_arch(['i586', 'i686', 'x86_64'])
252    def test_default_output_dir(self):
253        """Test default output location"""
254        for fname in glob("directdisk-*.direct"):
255            os.remove(fname)
256        config = 'DEPENDS_pn-core-image-minimal += "syslinux"\n'
257        self.append_config(config)
258        bitbake('core-image-minimal')
259        self.remove_config(config)
260        cmd = "wic create directdisk -e core-image-minimal"
261        self.assertEqual(0, runCmd(cmd).status)
262        self.assertEqual(1, len(glob("directdisk-*.direct")))
263
264    @OETestID(1212)
265    @only_for_arch(['i586', 'i686', 'x86_64'])
266    def test_build_artifacts(self):
267        """Test wic create directdisk providing all artifacts."""
268        bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
269                              'wic-tools')
270        bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
271                                   'core-image-minimal'))
272        bbvars = {key.lower(): value for key, value in bb_vars.items()}
273        bbvars['resultdir'] = self.resultdir
274        status = runCmd("wic create directdisk "
275                        "-b %(staging_datadir)s "
276                        "-k %(deploy_dir_image)s "
277                        "-n %(recipe_sysroot_native)s "
278                        "-r %(image_rootfs)s "
279                        "-o %(resultdir)s" % bbvars).status
280        self.assertEqual(0, status)
281        self.assertEqual(1, len(glob(self.resultdir + "directdisk-*.direct")))
282
283    @OETestID(1264)
284    def test_compress_gzip(self):
285        """Test compressing an image with gzip"""
286        self.assertEqual(0, runCmd("wic create wictestdisk "
287                                   "--image-name core-image-minimal "
288                                   "-c gzip -o %s" % self.resultdir).status)
289        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.gz")))
290
291    @OETestID(1265)
292    def test_compress_bzip2(self):
293        """Test compressing an image with bzip2"""
294        self.assertEqual(0, runCmd("wic create wictestdisk "
295                                   "--image-name=core-image-minimal "
296                                   "-c bzip2 -o %s" % self.resultdir).status)
297        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.bz2")))
298
299    @OETestID(1266)
300    def test_compress_xz(self):
301        """Test compressing an image with xz"""
302        self.assertEqual(0, runCmd("wic create wictestdisk "
303                                   "--image-name=core-image-minimal "
304                                   "--compress-with=xz -o %s" % self.resultdir).status)
305        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct.xz")))
306
307    @OETestID(1267)
308    def test_wrong_compressor(self):
309        """Test how wic breaks if wrong compressor is provided"""
310        self.assertEqual(2, runCmd("wic create wictestdisk "
311                                   "--image-name=core-image-minimal "
312                                   "-c wrong -o %s" % self.resultdir,
313                                   ignore_status=True).status)
314
315    @OETestID(1558)
316    def test_debug_short(self):
317        """Test -D option"""
318        self.assertEqual(0, runCmd("wic create wictestdisk "
319                                   "--image-name=core-image-minimal "
320                                   "-D -o %s" % self.resultdir).status)
321        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
322
323    @OETestID(1658)
324    def test_debug_long(self):
325        """Test --debug option"""
326        self.assertEqual(0, runCmd("wic create wictestdisk "
327                                   "--image-name=core-image-minimal "
328                                   "--debug -o %s" % self.resultdir).status)
329        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
330
331    @OETestID(1563)
332    def test_skip_build_check_short(self):
333        """Test -s option"""
334        self.assertEqual(0, runCmd("wic create wictestdisk "
335                                   "--image-name=core-image-minimal "
336                                   "-s -o %s" % self.resultdir).status)
337        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
338
339    @OETestID(1671)
340    def test_skip_build_check_long(self):
341        """Test --skip-build-check option"""
342        self.assertEqual(0, runCmd("wic create wictestdisk "
343                                   "--image-name=core-image-minimal "
344                                   "--skip-build-check "
345                                   "--outdir %s" % self.resultdir).status)
346        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
347
348    @OETestID(1564)
349    def test_build_rootfs_short(self):
350        """Test -f option"""
351        self.assertEqual(0, runCmd("wic create wictestdisk "
352                                   "--image-name=core-image-minimal "
353                                   "-f -o %s" % self.resultdir).status)
354        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
355
356    @OETestID(1656)
357    def test_build_rootfs_long(self):
358        """Test --build-rootfs option"""
359        self.assertEqual(0, runCmd("wic create wictestdisk "
360                                   "--image-name=core-image-minimal "
361                                   "--build-rootfs "
362                                   "--outdir %s" % self.resultdir).status)
363        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*.direct")))
364
365    @OETestID(1268)
366    @only_for_arch(['i586', 'i686', 'x86_64'])
367    def test_rootfs_indirect_recipes(self):
368        """Test usage of rootfs plugin with rootfs recipes"""
369        status = runCmd("wic create directdisk-multi-rootfs "
370                        "--image-name=core-image-minimal "
371                        "--rootfs rootfs1=core-image-minimal "
372                        "--rootfs rootfs2=core-image-minimal "
373                        "--outdir %s" % self.resultdir).status
374        self.assertEqual(0, status)
375        self.assertEqual(1, len(glob(self.resultdir + "directdisk-multi-rootfs*.direct")))
376
377    @OETestID(1269)
378    @only_for_arch(['i586', 'i686', 'x86_64'])
379    def test_rootfs_artifacts(self):
380        """Test usage of rootfs plugin with rootfs paths"""
381        bb_vars = get_bb_vars(['STAGING_DATADIR', 'RECIPE_SYSROOT_NATIVE'],
382                              'wic-tools')
383        bb_vars.update(get_bb_vars(['DEPLOY_DIR_IMAGE', 'IMAGE_ROOTFS'],
384                                   'core-image-minimal'))
385        bbvars = {key.lower(): value for key, value in bb_vars.items()}
386        bbvars['wks'] = "directdisk-multi-rootfs"
387        bbvars['resultdir'] = self.resultdir
388        status = runCmd("wic create %(wks)s "
389                        "--bootimg-dir=%(staging_datadir)s "
390                        "--kernel-dir=%(deploy_dir_image)s "
391                        "--native-sysroot=%(recipe_sysroot_native)s "
392                        "--rootfs-dir rootfs1=%(image_rootfs)s "
393                        "--rootfs-dir rootfs2=%(image_rootfs)s "
394                        "--outdir %(resultdir)s" % bbvars).status
395        self.assertEqual(0, status)
396        self.assertEqual(1, len(glob(self.resultdir + "%(wks)s-*.direct" % bbvars)))
397
398    @OETestID(1661)
399    def test_exclude_path(self):
400        """Test --exclude-path wks option."""
401
402        oldpath = os.environ['PATH']
403        os.environ['PATH'] = get_bb_var("PATH", "wic-tools")
404
405        try:
406            wks_file = 'temp.wks'
407            with open(wks_file, 'w') as wks:
408                rootfs_dir = get_bb_var('IMAGE_ROOTFS', 'core-image-minimal')
409                wks.write("""
410part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path usr
411part /usr --source rootfs --ondisk mmcblk0 --fstype=ext4 --rootfs-dir %s/usr
412part /etc --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path bin/ --rootfs-dir %s/usr"""
413                          % (rootfs_dir, rootfs_dir))
414            self.assertEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
415                                       % (wks_file, self.resultdir)).status)
416
417            os.remove(wks_file)
418            wicout = glob(self.resultdir + "%s-*direct" % 'temp')
419            self.assertEqual(1, len(wicout))
420
421            wicimg = wicout[0]
422
423            # verify partition size with wic
424            res = runCmd("parted -m %s unit b p 2>/dev/null" % wicimg)
425            self.assertEqual(0, res.status)
426
427            # parse parted output which looks like this:
428            # BYT;\n
429            # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
430            # 1:0.00MiB:200MiB:200MiB:ext4::;\n
431            partlns = res.output.splitlines()[2:]
432
433            self.assertEqual(3, len(partlns))
434
435            for part in [1, 2, 3]:
436                part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
437                partln = partlns[part-1].split(":")
438                self.assertEqual(7, len(partln))
439                start = int(partln[1].rstrip("B")) / 512
440                length = int(partln[3].rstrip("B")) / 512
441                self.assertEqual(0, runCmd("dd if=%s of=%s skip=%d count=%d" %
442                                           (wicimg, part_file, start, length)).status)
443
444            def extract_files(debugfs_output):
445                """
446                extract file names from the output of debugfs -R 'ls -p',
447                which looks like this:
448
449                 /2/040755/0/0/.//\n
450                 /2/040755/0/0/..//\n
451                 /11/040700/0/0/lost+found^M//\n
452                 /12/040755/1002/1002/run//\n
453                 /13/040755/1002/1002/sys//\n
454                 /14/040755/1002/1002/bin//\n
455                 /80/040755/1002/1002/var//\n
456                 /92/040755/1002/1002/tmp//\n
457                """
458                # NOTE the occasional ^M in file names
459                return [line.split('/')[5].strip() for line in \
460                        debugfs_output.strip().split('/\n')]
461
462            # Test partition 1, should contain the normal root directories, except
463            # /usr.
464            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
465                             os.path.join(self.resultdir, "selftest_img.part1"))
466            self.assertEqual(0, res.status)
467            files = extract_files(res.output)
468            self.assertIn("etc", files)
469            self.assertNotIn("usr", files)
470
471            # Partition 2, should contain common directories for /usr, not root
472            # directories.
473            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
474                             os.path.join(self.resultdir, "selftest_img.part2"))
475            self.assertEqual(0, res.status)
476            files = extract_files(res.output)
477            self.assertNotIn("etc", files)
478            self.assertNotIn("usr", files)
479            self.assertIn("share", files)
480
481            # Partition 3, should contain the same as partition 2, including the bin
482            # directory, but not the files inside it.
483            res = runCmd("debugfs -R 'ls -p' %s 2>/dev/null" % \
484                             os.path.join(self.resultdir, "selftest_img.part3"))
485            self.assertEqual(0, res.status)
486            files = extract_files(res.output)
487            self.assertNotIn("etc", files)
488            self.assertNotIn("usr", files)
489            self.assertIn("share", files)
490            self.assertIn("bin", files)
491            res = runCmd("debugfs -R 'ls -p bin' %s 2>/dev/null" % \
492                             os.path.join(self.resultdir, "selftest_img.part3"))
493            self.assertEqual(0, res.status)
494            files = extract_files(res.output)
495            self.assertIn(".", files)
496            self.assertIn("..", files)
497            self.assertEqual(2, len(files))
498
499            for part in [1, 2, 3]:
500                part_file = os.path.join(self.resultdir, "selftest_img.part%d" % part)
501                os.remove(part_file)
502
503        finally:
504            os.environ['PATH'] = oldpath
505
506    @OETestID(1662)
507    def test_exclude_path_errors(self):
508        """Test --exclude-path wks option error handling."""
509        wks_file = 'temp.wks'
510
511        # Absolute argument.
512        with open(wks_file, 'w') as wks:
513            wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path /usr")
514        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
515                                      % (wks_file, self.resultdir), ignore_status=True).status)
516        os.remove(wks_file)
517
518        # Argument pointing to parent directory.
519        with open(wks_file, 'w') as wks:
520            wks.write("part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --exclude-path ././..")
521        self.assertNotEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
522                                      % (wks_file, self.resultdir), ignore_status=True).status)
523        os.remove(wks_file)
524
525    @OETestID(1496)
526    def test_bmap_short(self):
527        """Test generation of .bmap file -m option"""
528        cmd = "wic create wictestdisk -e core-image-minimal -m -o %s" % self.resultdir
529        status = runCmd(cmd).status
530        self.assertEqual(0, status)
531        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
532        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct.bmap")))
533
534    @OETestID(1655)
535    def test_bmap_long(self):
536        """Test generation of .bmap file --bmap option"""
537        cmd = "wic create wictestdisk -e core-image-minimal --bmap -o %s" % self.resultdir
538        status = runCmd(cmd).status
539        self.assertEqual(0, status)
540        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
541        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct.bmap")))
542
543    def _get_image_env_path(self, image):
544        """Generate and obtain the path to <image>.env"""
545        if image not in self.wicenv_cache:
546            self.assertEqual(0, bitbake('%s -c do_rootfs_wicenv' % image).status)
547            bb_vars = get_bb_vars(['STAGING_DIR', 'MACHINE'], image)
548            stdir = bb_vars['STAGING_DIR']
549            machine = bb_vars['MACHINE']
550            self.wicenv_cache[image] = os.path.join(stdir, machine, 'imgdata')
551        return self.wicenv_cache[image]
552
553    @OETestID(1347)
554    def test_image_env(self):
555        """Test generation of <image>.env files."""
556        image = 'core-image-minimal'
557        imgdatadir = self._get_image_env_path(image)
558
559        bb_vars = get_bb_vars(['IMAGE_BASENAME', 'WICVARS'], image)
560        basename = bb_vars['IMAGE_BASENAME']
561        self.assertEqual(basename, image)
562        path = os.path.join(imgdatadir, basename) + '.env'
563        self.assertTrue(os.path.isfile(path))
564
565        wicvars = set(bb_vars['WICVARS'].split())
566        # filter out optional variables
567        wicvars = wicvars.difference(('DEPLOY_DIR_IMAGE', 'IMAGE_BOOT_FILES',
568                                      'INITRD', 'INITRD_LIVE', 'ISODIR'))
569        with open(path) as envfile:
570            content = dict(line.split("=", 1) for line in envfile)
571            # test if variables used by wic present in the .env file
572            for var in wicvars:
573                self.assertTrue(var in content, "%s is not in .env file" % var)
574                self.assertTrue(content[var])
575
576    @OETestID(1559)
577    def test_image_vars_dir_short(self):
578        """Test image vars directory selection -v option"""
579        image = 'core-image-minimal'
580        imgenvdir = self._get_image_env_path(image)
581        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
582
583        self.assertEqual(0, runCmd("wic create wictestdisk "
584                                   "--image-name=%s -v %s -n %s -o %s"
585                                   % (image, imgenvdir, native_sysroot,
586                                      self.resultdir)).status)
587        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
588
589    @OETestID(1665)
590    def test_image_vars_dir_long(self):
591        """Test image vars directory selection --vars option"""
592        image = 'core-image-minimal'
593        imgenvdir = self._get_image_env_path(image)
594        native_sysroot = get_bb_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
595
596        self.assertEqual(0, runCmd("wic create wictestdisk "
597                                   "--image-name=%s "
598                                   "--vars %s "
599                                   "--native-sysroot %s "
600                                   "--outdir %s"
601                                   % (image, imgenvdir, native_sysroot,
602                                      self.resultdir)).status)
603        self.assertEqual(1, len(glob(self.resultdir + "wictestdisk-*direct")))
604
605    @OETestID(1351)
606    @only_for_arch(['i586', 'i686', 'x86_64'])
607    def test_wic_image_type(self):
608        """Test building wic images by bitbake"""
609        config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
610                 'MACHINE_FEATURES_append = " efi"\n'
611        self.append_config(config)
612        self.assertEqual(0, bitbake('wic-image-minimal').status)
613        self.remove_config(config)
614
615        bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE'])
616        deploy_dir = bb_vars['DEPLOY_DIR_IMAGE']
617        machine = bb_vars['MACHINE']
618        prefix = os.path.join(deploy_dir, 'wic-image-minimal-%s.' % machine)
619        # check if we have result image and manifests symlinks
620        # pointing to existing files
621        for suffix in ('wic', 'manifest'):
622            path = prefix + suffix
623            self.assertTrue(os.path.islink(path))
624            self.assertTrue(os.path.isfile(os.path.realpath(path)))
625
626    @OETestID(1424)
627    @only_for_arch(['i586', 'i686', 'x86_64'])
628    def test_qemu(self):
629        """Test wic-image-minimal under qemu"""
630        config = 'IMAGE_FSTYPES += "wic"\nWKS_FILE = "wic-image-minimal"\n'\
631                 'MACHINE_FEATURES_append = " efi"\n'
632        self.append_config(config)
633        self.assertEqual(0, bitbake('wic-image-minimal').status)
634        self.remove_config(config)
635
636        with runqemu('wic-image-minimal', ssh=False) as qemu:
637            cmd = "mount |grep '^/dev/' | cut -f1,3 -d ' ' | sort"
638            status, output = qemu.run_serial(cmd)
639            self.assertEqual(output, '/dev/root /\r\n/dev/sda1 /boot\r\n/dev/sda3 /media\r\n/dev/sda4 /mnt')
640            cmd = "grep UUID= /etc/fstab"
641            status, output = qemu.run_serial(cmd)
642            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
643            self.assertEqual(output, 'UUID=2c71ef06-a81d-4735-9d3a-379b69c6bdba\t/media\text4\tdefaults\t0\t0')
644
645    @only_for_arch(['i586', 'i686', 'x86_64'])
646    @OETestID(1852)
647    def test_qemu_efi(self):
648        """Test core-image-minimal efi image under qemu"""
649        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "mkefidisk.wks"\n'
650        self.append_config(config)
651        self.assertEqual(0, bitbake('core-image-minimal ovmf').status)
652        self.remove_config(config)
653
654        with runqemu('core-image-minimal', ssh=False,
655                     runqemuparams='ovmf', image_fstype='wic') as qemu:
656            cmd = "grep sda. /proc/partitions  |wc -l"
657            status, output = qemu.run_serial(cmd)
658            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
659            self.assertEqual(output, '3')
660
661    @staticmethod
662    def _make_fixed_size_wks(size):
663        """
664        Create a wks of an image with a single partition. Size of the partition is set
665        using --fixed-size flag. Returns a tuple: (path to wks file, wks image name)
666        """
667        with NamedTemporaryFile("w", suffix=".wks", delete=False) as tempf:
668            wkspath = tempf.name
669            tempf.write("part " \
670                     "--source rootfs --ondisk hda --align 4 --fixed-size %d "
671                     "--fstype=ext4\n" % size)
672        wksname = os.path.splitext(os.path.basename(wkspath))[0]
673
674        return wkspath, wksname
675
676    @OETestID(1847)
677    def test_fixed_size(self):
678        """
679        Test creation of a simple image with partition size controlled through
680        --fixed-size flag
681        """
682        wkspath, wksname = Wic._make_fixed_size_wks(200)
683
684        self.assertEqual(0, runCmd("wic create %s -e core-image-minimal -o %s" \
685                                   % (wkspath, self.resultdir)).status)
686        os.remove(wkspath)
687        wicout = glob(self.resultdir + "%s-*direct" % wksname)
688        self.assertEqual(1, len(wicout))
689
690        wicimg = wicout[0]
691
692        # verify partition size with wic
693        res = runCmd("parted -m %s unit mib p 2>/dev/null" % wicimg,
694                     ignore_status=True,
695                     native_sysroot=self.native_sysroot)
696        self.assertEqual(0, res.status)
697
698        # parse parted output which looks like this:
699        # BYT;\n
700        # /var/tmp/wic/build/tmpfwvjjkf_-201611101222-hda.direct:200MiB:file:512:512:msdos::;\n
701        # 1:0.00MiB:200MiB:200MiB:ext4::;\n
702        partlns = res.output.splitlines()[2:]
703
704        self.assertEqual(1, len(partlns))
705        self.assertEqual("1:0.00MiB:200MiB:200MiB:ext4::;", partlns[0])
706
707    @OETestID(1848)
708    def test_fixed_size_error(self):
709        """
710        Test creation of a simple image with partition size controlled through
711        --fixed-size flag. The size of partition is intentionally set to 1MiB
712        in order to trigger an error in wic.
713        """
714        wkspath, wksname = Wic._make_fixed_size_wks(1)
715
716        self.assertEqual(1, runCmd("wic create %s -e core-image-minimal -o %s" \
717                                   % (wkspath, self.resultdir), ignore_status=True).status)
718        os.remove(wkspath)
719        wicout = glob(self.resultdir + "%s-*direct" % wksname)
720        self.assertEqual(0, len(wicout))
721
722    @only_for_arch(['i586', 'i686', 'x86_64'])
723    @OETestID(1854)
724    def test_rawcopy_plugin_qemu(self):
725        """Test rawcopy plugin in qemu"""
726        # build ext4 and wic images
727        for fstype in ("ext4", "wic"):
728            config = 'IMAGE_FSTYPES = "%s"\nWKS_FILE = "test_rawcopy_plugin.wks.in"\n' % fstype
729            self.append_config(config)
730            self.assertEqual(0, bitbake('core-image-minimal').status)
731            self.remove_config(config)
732
733        with runqemu('core-image-minimal', ssh=False, image_fstype='wic') as qemu:
734            cmd = "grep sda. /proc/partitions  |wc -l"
735            status, output = qemu.run_serial(cmd)
736            self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
737            self.assertEqual(output, '2')
738
739    @OETestID(1853)
740    def test_rawcopy_plugin(self):
741        """Test rawcopy plugin"""
742        img = 'core-image-minimal'
743        machine = get_bb_var('MACHINE', img)
744        with NamedTemporaryFile("w", suffix=".wks") as wks:
745            wks.writelines(['part /boot --active --source bootimg-pcbios\n',
746                            'part / --source rawcopy --sourceparams="file=%s-%s.ext4" --use-uuid\n'\
747                             % (img, machine),
748                            'bootloader --timeout=0 --append="console=ttyS0,115200n8"\n'])
749            wks.flush()
750            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
751            self.assertEqual(0, runCmd(cmd).status)
752            wksname = os.path.splitext(os.path.basename(wks.name))[0]
753            out = glob(self.resultdir + "%s-*direct" % wksname)
754            self.assertEqual(1, len(out))
755
756    @OETestID(1849)
757    def test_fs_types(self):
758        """Test filesystem types for empty and not empty partitions"""
759        img = 'core-image-minimal'
760        with NamedTemporaryFile("w", suffix=".wks") as wks:
761            wks.writelines(['part ext2   --fstype ext2     --source rootfs\n',
762                            'part btrfs  --fstype btrfs    --source rootfs --size 40M\n',
763                            'part squash --fstype squashfs --source rootfs\n',
764                            'part swap   --fstype swap --size 1M\n',
765                            'part emptyvfat   --fstype vfat   --size 1M\n',
766                            'part emptymsdos  --fstype msdos  --size 1M\n',
767                            'part emptyext2   --fstype ext2   --size 1M\n',
768                            'part emptybtrfs  --fstype btrfs  --size 100M\n'])
769            wks.flush()
770            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
771            self.assertEqual(0, runCmd(cmd).status)
772            wksname = os.path.splitext(os.path.basename(wks.name))[0]
773            out = glob(self.resultdir + "%s-*direct" % wksname)
774            self.assertEqual(1, len(out))
775
776    @OETestID(1851)
777    def test_kickstart_parser(self):
778        """Test wks parser options"""
779        with NamedTemporaryFile("w", suffix=".wks") as wks:
780            wks.writelines(['part / --fstype ext3 --source rootfs --system-id 0xFF '\
781                            '--overhead-factor 1.2 --size 100k\n'])
782            wks.flush()
783            cmd = "wic create %s -e core-image-minimal -o %s" % (wks.name, self.resultdir)
784            self.assertEqual(0, runCmd(cmd).status)
785            wksname = os.path.splitext(os.path.basename(wks.name))[0]
786            out = glob(self.resultdir + "%s-*direct" % wksname)
787            self.assertEqual(1, len(out))
788
789    @OETestID(1850)
790    def test_image_bootpart_globbed(self):
791        """Test globbed sources with image-bootpart plugin"""
792        img = "core-image-minimal"
793        cmd = "wic create sdimage-bootpart -e %s -o %s" % (img, self.resultdir)
794        config = 'IMAGE_BOOT_FILES = "%s*"' % get_bb_var('KERNEL_IMAGETYPE', img)
795        self.append_config(config)
796        self.assertEqual(0, runCmd(cmd).status)
797        self.remove_config(config)
798        self.assertEqual(1, len(glob(self.resultdir + "sdimage-bootpart-*direct")))
799
800    @OETestID(1855)
801    def test_sparse_copy(self):
802        """Test sparse_copy with FIEMAP and SEEK_HOLE filemap APIs"""
803        libpath = os.path.join(get_bb_var('COREBASE'), 'scripts', 'lib', 'wic')
804        sys.path.insert(0, libpath)
805        from  filemap import FilemapFiemap, FilemapSeek, sparse_copy, ErrorNotSupp
806        with NamedTemporaryFile("w", suffix=".wic-sparse") as sparse:
807            src_name = sparse.name
808            src_size = 1024 * 10
809            sparse.truncate(src_size)
810            # write one byte to the file
811            with open(src_name, 'r+b') as sfile:
812                sfile.seek(1024 * 4)
813                sfile.write(b'\x00')
814            dest = sparse.name + '.out'
815            # copy src file to dest using different filemap APIs
816            for api in (FilemapFiemap, FilemapSeek, None):
817                if os.path.exists(dest):
818                    os.unlink(dest)
819                try:
820                    sparse_copy(sparse.name, dest, api=api)
821                except ErrorNotSupp:
822                    continue # skip unsupported API
823                dest_stat = os.stat(dest)
824                self.assertEqual(dest_stat.st_size, src_size)
825                # 8 blocks is 4K (physical sector size)
826                self.assertEqual(dest_stat.st_blocks, 8)
827            os.unlink(dest)
828
829    @OETestID(1857)
830    def test_wic_ls(self):
831        """Test listing image content using 'wic ls'"""
832        self.assertEqual(0, runCmd("wic create wictestdisk "
833                                   "--image-name=core-image-minimal "
834                                   "-D -o %s" % self.resultdir).status)
835        images = glob(self.resultdir + "wictestdisk-*.direct")
836        self.assertEqual(1, len(images))
837
838        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
839
840        # list partitions
841        result = runCmd("wic ls %s -n %s" % (images[0], sysroot))
842        self.assertEqual(0, result.status)
843        self.assertEqual(3, len(result.output.split('\n')))
844
845        # list directory content of the first partition
846        result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
847        self.assertEqual(0, result.status)
848        self.assertEqual(6, len(result.output.split('\n')))
849
850    @OETestID(1856)
851    def test_wic_cp(self):
852        """Test copy files and directories to the the wic image."""
853        self.assertEqual(0, runCmd("wic create wictestdisk "
854                                   "--image-name=core-image-minimal "
855                                   "-D -o %s" % self.resultdir).status)
856        images = glob(self.resultdir + "wictestdisk-*.direct")
857        self.assertEqual(1, len(images))
858
859        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
860
861        # list directory content of the first partition
862        result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
863        self.assertEqual(0, result.status)
864        self.assertEqual(6, len(result.output.split('\n')))
865
866        with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
867            testfile.write("test")
868
869            # copy file to the partition
870            result = runCmd("wic cp %s %s:1/ -n %s" % (testfile.name, images[0], sysroot))
871            self.assertEqual(0, result.status)
872
873            # check if file is there
874            result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
875            self.assertEqual(0, result.status)
876            self.assertEqual(7, len(result.output.split('\n')))
877            self.assertTrue(os.path.basename(testfile.name) in result.output)
878
879            # prepare directory
880            testdir = os.path.join(self.resultdir, 'wic-test-cp-dir')
881            testsubdir = os.path.join(testdir, 'subdir')
882            os.makedirs(os.path.join(testsubdir))
883            copy(testfile.name, testdir)
884
885            # copy directory to the partition
886            result = runCmd("wic cp %s %s:1/ -n %s" % (testdir, images[0], sysroot))
887            self.assertEqual(0, result.status)
888
889            # check if directory is there
890            result = runCmd("wic ls %s:1/ -n %s" % (images[0], sysroot))
891            self.assertEqual(0, result.status)
892            self.assertEqual(8, len(result.output.split('\n')))
893            self.assertTrue(os.path.basename(testdir) in result.output)
894
895    @OETestID(1858)
896    def test_wic_rm(self):
897        """Test removing files and directories from the the wic image."""
898        self.assertEqual(0, runCmd("wic create mkefidisk "
899                                   "--image-name=core-image-minimal "
900                                   "-D -o %s" % self.resultdir).status)
901        images = glob(self.resultdir + "mkefidisk-*.direct")
902        self.assertEqual(1, len(images))
903
904        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
905
906        # list directory content of the first partition
907        result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
908        self.assertEqual(0, result.status)
909        self.assertIn('\nBZIMAGE        ', result.output)
910        self.assertIn('\nEFI          <DIR>     ', result.output)
911
912        # remove file
913        result = runCmd("wic rm %s:1/bzimage -n %s" % (images[0], sysroot))
914        self.assertEqual(0, result.status)
915
916        # remove directory
917        result = runCmd("wic rm %s:1/efi -n %s" % (images[0], sysroot))
918        self.assertEqual(0, result.status)
919
920        # check if they're removed
921        result = runCmd("wic ls %s:1 -n %s" % (images[0], sysroot))
922        self.assertEqual(0, result.status)
923        self.assertNotIn('\nBZIMAGE        ', result.output)
924        self.assertNotIn('\nEFI          <DIR>     ', result.output)
925
926    @OETestID(1922)
927    def test_mkfs_extraopts(self):
928        """Test wks option --mkfs-extraopts for empty and not empty partitions"""
929        img = 'core-image-minimal'
930        with NamedTemporaryFile("w", suffix=".wks") as wks:
931            wks.writelines(
932                ['part ext2   --fstype ext2     --source rootfs --mkfs-extraopts "-D -F -i 8192"\n',
933                 "part btrfs  --fstype btrfs    --source rootfs --size 40M --mkfs-extraopts='--quiet'\n",
934                 'part squash --fstype squashfs --source rootfs --mkfs-extraopts "-no-sparse -b 4096"\n',
935                 'part emptyvfat   --fstype vfat   --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
936                 'part emptymsdos  --fstype msdos  --size 1M --mkfs-extraopts "-S 1024 -s 64"\n',
937                 'part emptyext2   --fstype ext2   --size 1M --mkfs-extraopts "-D -F -i 8192"\n',
938                 'part emptybtrfs  --fstype btrfs  --size 100M --mkfs-extraopts "--mixed -K"\n'])
939            wks.flush()
940            cmd = "wic create %s -e %s -o %s" % (wks.name, img, self.resultdir)
941            self.assertEqual(0, runCmd(cmd).status)
942            wksname = os.path.splitext(os.path.basename(wks.name))[0]
943            out = glob(self.resultdir + "%s-*direct" % wksname)
944            self.assertEqual(1, len(out))
945
946    def test_expand_mbr_image(self):
947        """Test wic write --expand command for mbr image"""
948        # build an image
949        config = 'IMAGE_FSTYPES = "wic"\nWKS_FILE = "directdisk.wks"\n'
950        self.append_config(config)
951        self.assertEqual(0, bitbake('core-image-minimal').status)
952
953        # get path to the image
954        bb_vars = get_bb_vars(['DEPLOY_DIR_IMAGE', 'MACHINE'])
955        deploy_dir = bb_vars['DEPLOY_DIR_IMAGE']
956        machine = bb_vars['MACHINE']
957        image_path = os.path.join(deploy_dir, 'core-image-minimal-%s.wic' % machine)
958
959        self.remove_config(config)
960
961        try:
962            # expand image to 1G
963            new_image_path = None
964            with NamedTemporaryFile(mode='wb', suffix='.wic.exp',
965                                    dir=deploy_dir, delete=False) as sparse:
966                sparse.truncate(1024 ** 3)
967                new_image_path = sparse.name
968
969            sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
970            cmd = "wic write -n %s --expand 1:0 %s %s" % (sysroot, image_path, new_image_path)
971            self.assertEqual(0, runCmd(cmd).status)
972
973            # check if partitions are expanded
974            orig = runCmd("wic ls %s -n %s" % (image_path, sysroot))
975            exp = runCmd("wic ls %s -n %s" % (new_image_path, sysroot))
976            orig_sizes = [int(line.split()[3]) for line in orig.output.split('\n')[1:]]
977            exp_sizes = [int(line.split()[3]) for line in exp.output.split('\n')[1:]]
978            self.assertEqual(orig_sizes[0], exp_sizes[0]) # first partition is not resized
979            self.assertTrue(orig_sizes[1] < exp_sizes[1])
980
981            # Check if all free space is partitioned
982            result = runCmd("%s/usr/sbin/sfdisk -F %s" % (sysroot, new_image_path))
983            self.assertTrue("0 B, 0 bytes, 0 sectors" in result.output)
984
985            os.rename(image_path, image_path + '.bak')
986            os.rename(new_image_path, image_path)
987
988            # Check if it boots in qemu
989            with runqemu('core-image-minimal', ssh=False) as qemu:
990                cmd = "ls /etc/"
991                status, output = qemu.run_serial('true')
992                self.assertEqual(1, status, 'Failed to run command "%s": %s' % (cmd, output))
993        finally:
994            if os.path.exists(new_image_path):
995                os.unlink(new_image_path)
996            if os.path.exists(image_path + '.bak'):
997                os.rename(image_path + '.bak', image_path)
998
999    def test_wic_ls_ext(self):
1000        """Test listing content of the ext partition using 'wic ls'"""
1001        self.assertEqual(0, runCmd("wic create wictestdisk "
1002                                   "--image-name=core-image-minimal "
1003                                   "-D -o %s" % self.resultdir).status)
1004        images = glob(self.resultdir + "wictestdisk-*.direct")
1005        self.assertEqual(1, len(images))
1006
1007        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1008
1009        # list directory content of the second ext4 partition
1010        result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1011        self.assertEqual(0, result.status)
1012        self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(
1013                            set(line.split()[-1] for line in result.output.split('\n') if line)))
1014
1015    def test_wic_cp_ext(self):
1016        """Test copy files and directories to the ext partition."""
1017        self.assertEqual(0, runCmd("wic create wictestdisk "
1018                                   "--image-name=core-image-minimal "
1019                                   "-D -o %s" % self.resultdir).status)
1020        images = glob(self.resultdir + "wictestdisk-*.direct")
1021        self.assertEqual(1, len(images))
1022
1023        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1024
1025        # list directory content of the ext4 partition
1026        result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1027        self.assertEqual(0, result.status)
1028        dirs = set(line.split()[-1] for line in result.output.split('\n') if line)
1029        self.assertTrue(set(['bin', 'home', 'proc', 'usr', 'var', 'dev', 'lib', 'sbin']).issubset(dirs))
1030
1031        with NamedTemporaryFile("w", suffix=".wic-cp") as testfile:
1032            testfile.write("test")
1033
1034            # copy file to the partition
1035            result = runCmd("wic cp %s %s:2/ -n %s" % (testfile.name, images[0], sysroot))
1036            self.assertEqual(0, result.status)
1037
1038            # check if file is there
1039            result = runCmd("wic ls %s:2/ -n %s" % (images[0], sysroot))
1040            self.assertEqual(0, result.status)
1041            newdirs = set(line.split()[-1] for line in result.output.split('\n') if line)
1042            self.assertEqual(newdirs.difference(dirs), set([os.path.basename(testfile.name)]))
1043
1044    def test_wic_rm_ext(self):
1045        """Test removing files from the ext partition."""
1046        self.assertEqual(0, runCmd("wic create mkefidisk "
1047                                   "--image-name=core-image-minimal "
1048                                   "-D -o %s" % self.resultdir).status)
1049        images = glob(self.resultdir + "mkefidisk-*.direct")
1050        self.assertEqual(1, len(images))
1051
1052        sysroot = get_bb_var('RECIPE_SYSROOT_NATIVE', 'wic-tools')
1053
1054        # list directory content of the /etc directory on ext4 partition
1055        result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
1056        self.assertEqual(0, result.status)
1057        self.assertTrue('fstab' in [line.split()[-1] for line in result.output.split('\n') if line])
1058
1059        # remove file
1060        result = runCmd("wic rm %s:2/etc/fstab -n %s" % (images[0], sysroot))
1061        self.assertEqual(0, result.status)
1062
1063        # check if it's removed
1064        result = runCmd("wic ls %s:2/etc/ -n %s" % (images[0], sysroot))
1065        self.assertEqual(0, result.status)
1066        self.assertTrue('fstab' not in [line.split()[-1] for line in result.output.split('\n') if line])
1067