~jamesodhunt/ubuntu/wily/ubuntu-core-upgrader/call-upgrader-directly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# Copyright © 2014-2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------

# --------------------------------------------------------------------
# Terminology:
#
# - "update archive": a fake system-image "ubuntu-hash.tar.xz" tar
#   archive.
# --------------------------------------------------------------------

import tarfile
import tempfile
import unittest
from unittest.mock import patch
import os
import shutil
import sys

from ubuntucoreupgrader.upgrader import (
    tar_generator,
    Upgrader,
    parse_args,
)

base_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(base_dir)

from ubuntucoreupgrader.tests.utils import (
    create_file,
    make_tmp_dir,
    UbuntuCoreUpgraderTestCase,
    )

# file mode to use for creating test directories.
TEST_DIR_MODE = 0o750

CMD_FILE = 'ubuntu_command'


def make_default_options():
    return parse_args([])


class UpgradeTestCase(unittest.TestCase):

    def test_tar_generator_unpack_assets(self):
        tempf = tempfile.TemporaryFile()
        with tarfile.TarFile(fileobj=tempf, mode="w") as tar:

            # special top-level file that should not be unpacked
            tar.add(__file__, "removed")

            tar.add(__file__, "system/bin/true")
            tar.add(__file__, "assets/vmlinuz")
            tar.add(__file__, "assets/initrd.img")
            tar.add(__file__, "unreleated/something")
            tar.add(__file__, "hardware.yaml")

            result = [m.name for m in tar_generator(tar, "cache_dir", [], "/")]
            self.assertEqual(result, ["system/bin/true", "assets/vmlinuz",
                                      "assets/initrd.img", "hardware.yaml"])

    def test_tar_generator_system_files_unpack(self):
        tempf = tempfile.TemporaryFile()
        root_dir = make_tmp_dir()
        cache_dir = make_tmp_dir()

        sys_dir = os.path.join(cache_dir, 'system')

        os.makedirs(os.path.join(root_dir, 'dev'))
        os.makedirs(sys_dir)

        with tarfile.TarFile(fileobj=tempf, mode="w") as tar:
            tar.add(__file__, "assets/vmlinuz")
            tar.add(__file__, "assets/initrd.img")

            device_a = '/dev/null'
            path = (os.path.normpath('{}/{}'.format(sys_dir, device_a)))
            touch_file(path)

            self.assertTrue(os.path.exists(os.path.join(root_dir, device_a)))

            # should not be unpacked as already exists
            tar.add(__file__, "system{}".format(device_a))

            device_b = '/dev/does-not-exist'
            self.assertFalse(os.path.exists(os.path.join(root_dir, device_b)))

            # should be unpacked as does not exist
            tar.add(__file__, "system{}".format(device_b))

            expected = ["assets/vmlinuz", "assets/initrd.img",
                        "dev/does-not-exist"]

            expected_results = [os.path.join(root_dir, file)
                                for file in expected]

            result = [m.name for m in
                      tar_generator(tar, cache_dir, [], root_dir)]

            self.assertEqual(result, expected_results)

        shutil.rmtree(root_dir)
        shutil.rmtree(cache_dir)

    def test_tar_generator_system_files_remove_before_unpack(self):
        """
        Test that the upgrader removes certain files just prior to
        overwriting them via the unpack.
        """

        tempf = tempfile.TemporaryFile()
        root_dir = make_tmp_dir()
        cache_dir = make_tmp_dir()
        sys_dir = os.path.join(cache_dir, 'system')

        os.makedirs(sys_dir)

        file = 'a/file'
        dir = 'a/dir'

        with tarfile.TarFile(fileobj=tempf, mode="w") as tar:

            file_path = os.path.normpath('{}/{}'.format(root_dir, file))
            touch_file(file_path)
            self.assertTrue(os.path.exists(file_path))

            dir_path = os.path.normpath('{}/{}'.format(root_dir, dir))
            os.makedirs(dir_path)
            self.assertTrue(os.path.exists(dir_path))

            tar.add(__file__, "system/{}".format(file))

            expected = [file]
            expected_results = [os.path.join(root_dir, f)
                                for f in expected]

            result = [m.name for m in
                      tar_generator(tar, cache_dir, [], root_dir)]

            self.assertEqual(result, expected_results)

            # file should be removed
            self.assertFalse(os.path.exists(file_path))

            # directory should not be removed
            self.assertTrue(os.path.exists(dir_path))

        shutil.rmtree(root_dir)
        shutil.rmtree(cache_dir)


def touch_file(path):
    '''
    Create an empty file (creating any necessary intermediate
    directories in @path.
    '''
    create_file(path, '')


def make_commands(update_list):
    """
    Convert the specified list of update archives into a list of command
    file commands.
    """
    l = []

    # we don't currently add a mount verb (which would be more
    # realistic) since we can't handle that in the tests.
    # ##l.append('mount system')

    for file in update_list:
        l.append('update {} {}.asc'.format(file, file))

    # we don't currently add an unmount verb (which would be more
    # realistic) since we can't handle that in the tests.
    # ##l.append('unmount system')

    return l


class UbuntuCoreUpgraderObectTestCase(UbuntuCoreUpgraderTestCase):

    def mock_get_cache_dir(self):
        '''
        Mock to allow the tests to control the cache directory location.
        '''
        assert(self.cache_dir)
        self.sys_dir = os.path.join(self.cache_dir, 'system')
        os.makedirs(self.sys_dir, exist_ok=True)
        return self.cache_dir

    def test_create_object(self):
        root_dir = make_tmp_dir()

        file = 'created-regular-file'

        file_path = os.path.join(self.update.system_dir, file)
        create_file(file_path, 'foo bar')

        self.cache_dir = self.update.tmp_dir

        archive = self.update.create_archive(self.TARFILE)
        self.assertTrue(os.path.exists(archive))

        dest = os.path.join(self.cache_dir, os.path.basename(archive))
        touch_file('{}.asc'.format(dest))

        commands = make_commands([self.TARFILE])

        options = make_default_options()

        # XXX: doesn't actually exist, but the option must be set since
        # the upgrader looks for the update archives in the directory
        # where this file is claimed to be.
        options.cmdfile = os.path.join(self.cache_dir, 'ubuntu_command')

        options.root_dir = root_dir

        upgrader = Upgrader(options, commands, [])
        upgrader.get_cache_dir = self.mock_get_cache_dir
        upgrader.MOUNTPOINT_CMD = "true"
        upgrader.run()

        path = os.path.join(root_dir, file)
        self.assertTrue(os.path.exists(path))

        shutil.rmtree(root_dir)

    @patch('ubuntucoreupgrader.upgrader.get_mount_details')
    @patch('ubuntucoreupgrader.upgrader.mount')
    @patch('ubuntucoreupgrader.upgrader.unmount')
    def test_no_format_in_cmd(self, mock_umount, mock_mount,
                              mock_mount_details):

        # If the command file does not contain the format command, mkfs
        # should not be called.
        with patch('ubuntucoreupgrader.upgrader.mkfs') as mock_mkfs:
            args = ['cmdfile']
            options = parse_args(args=args)
            commands = make_commands([self.TARFILE])
            upgrader = Upgrader(options, commands, [])
            upgrader.TIMESTAMP_FILE = '/dev/null'
            upgrader.MOUNTPOINT_CMD = "true"
            upgrader.run()

        # No format command in command file, so should not have been
        # called.
        self.assertFalse(mock_mkfs.called)

    @patch('ubuntucoreupgrader.upgrader.get_mount_details')
    @patch('ubuntucoreupgrader.upgrader.mount')
    @patch('ubuntucoreupgrader.upgrader.unmount')
    def test_format(self, mock_umount, mock_mount, mock_mount_details):
        MOCK_FS_TUPLE = ("device", "fstype", "label")
        mock_mount_details.return_value = MOCK_FS_TUPLE

        # mkfs should be called if the format command is specified in
        # the command file.
        with patch('ubuntucoreupgrader.upgrader.mkfs') as mock_mkfs:
            args = ['cmdfile']
            options = parse_args(args=args)
            commands = make_commands([self.TARFILE])

            # add format command to command file
            commands.insert(0, 'format system')

            upgrader = Upgrader(options, commands, [])
            upgrader.TIMESTAMP_FILE = '/dev/null'
            upgrader.MOUNTPOINT_CMD = "true"
            upgrader.run()

        mock_mkfs.assert_called_with(*MOCK_FS_TUPLE)

if __name__ == "__main__":
    unittest.main()