test_package.py 11.2 KB
Newer Older
Oz Linden's avatar
Oz Linden committed
1
2
# $LicenseInfo:firstyear=2010&license=mit$
# Copyright (c) 2010, Linden Research, Inc.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
Oz Linden's avatar
Oz Linden committed
21
# $/LicenseInfo$
22
23
24
#
# Integration test to exercise the archive packaging
#
25

26
27
import os
import sys
28
import logging
29
import re
30
import shutil
Andrew A. de Laix's avatar
Andrew A. de Laix committed
31
import tarfile
Oz Linden's avatar
Oz Linden committed
32
import tempfile
33
import unittest
Oz Linden's avatar
Oz Linden committed
34
from zipfile import ZipFile
35
from string import Template
36

Andrew A. de Laix's avatar
Andrew A. de Laix committed
37
38
import autobuild.autobuild_tool_package as package
from autobuild import configfile
39
from autobuild import common
Signal Linden's avatar
Signal Linden committed
40
from .basetest import BaseTest, ExpectError, CaptureStdout, clean_dir, clean_file
41
        
42

43
44
45
46
47
48
49
50
# ****************************************************************************
#   TODO
# - Test for specific --build-dir (new select_directories() mechanism)
# - Test packaging from configuration-specific build directory
# - Test packaging from --all configurations
# - Test packaging from build directory(ies) for specified --configuration(s)
# ****************************************************************************

51
logger=logging.getLogger("autobuild.test_package")
52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
class PackageOptions(object):
    def __init__(self, data_dir):
        self.addrsize=common.DEFAULT_ADDRSIZE
        self.clean_only=True
        self.check_license=False
        self.dry_run=False
        self.all=False
        self.configurations=None
        self.platform=None
        self.results_file=None
        self.archive_filename=None
        self.archive_format=None
        self.select_dir=None
        self.autobuild_filename=os.path.join(data_dir, "autobuild-package-config.xml")
Oz Linden's avatar
Oz Linden committed
67

68
class TestPackaging(BaseTest):
69
    def setUp(self):
70
        BaseTest.setUp(self)
71
72
73
74
75
76
        self.temp_dir = tempfile.mkdtemp()
        # Copy our data_dir to temp_dir because loading a config file may
        # cause it to be updated and resaved.
        orig_data_dir = os.path.join(self.this_dir, "data")
        self.data_dir = os.path.join(self.temp_dir, "data")
        shutil.copytree(orig_data_dir, self.data_dir)
Oz Linden's avatar
Oz Linden committed
77
        self.config_path = os.path.join(self.data_dir, "autobuild-package-config.xml")
Andrew A. de Laix's avatar
Andrew A. de Laix committed
78
        self.config = configfile.ConfigurationDescription(self.config_path)
79
        self.platform = 'common'
Oz Linden's avatar
Oz Linden committed
80
        self.tar_basename = os.path.join(self.data_dir, "test1-1.0-common-123456")
81
        self.tar_name = self.tar_basename + ".tar.zst"
Andrew A. de Laix's avatar
Andrew A. de Laix committed
82
        self.zip_name = self.tar_basename + ".zip"
83
84
        self.expected_files=['include/file1','LICENSES/test1.txt','autobuild-package.xml']
        self.expected_files.sort()
85
86
        self.saved_dir=os.getcwd()
        os.chdir(os.path.join(self.temp_dir, "data"))
87

88
89
90
91
92
93
94
95
96
    def instantiateTemplate(self, source_name, dest_name, changes):
        template_file=open(source_name,'r')
        template=Template(template_file.read())
        template_file.close()
        modified=template.substitute(changes)
        dest=open(dest_name,'w')
        dest.write(modified)
        dest.close()

97
    def tearDown(self):
98
        os.chdir(self.saved_dir)
99
100
101
        clean_dir(self.temp_dir)
        BaseTest.tearDown(self)

102
    def tar_has_expected(self,tar):
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        try:
            from cStringIO import StringIO as BIO
        except ImportError: # python 3
            from io import BytesIO as BIO

        try:
            import lzma
        except ImportError:
            from backports import lzma

        filedata = None
        with lzma.open(tar, "r") as f:
            filedata = f.read()
            f.close()

        file_in = BIO(filedata)
        tarball = tarfile.open(fileobj=file_in, mode="r")
120
121
        packaged_files=tarball.getnames()
        packaged_files.sort()
Signal Linden's avatar
Signal Linden committed
122
        self.assertEqual(packaged_files, self.expected_files)
123
124
125
126
127
128
        tarball.close()

    def zip_has_expected(self,zip):
        zip_file = ZipFile(zip,'r')
        packaged_files=zip_file.namelist()
        packaged_files.sort()
Signal Linden's avatar
Signal Linden committed
129
        self.assertEqual(packaged_files, self.expected_files)
130
        zip_file.close()
131

Andrew A. de Laix's avatar
Andrew A. de Laix committed
132
    def test_package(self):
133
        logger.setLevel(logging.DEBUG)
134
        package.package(self.config, self.config.get_build_directory(None, 'common'), 'common', archive_format='txz')
135
        assert os.path.exists(self.tar_name), "%s does not exist" % self.tar_name
136
137
        self.tar_has_expected(self.tar_name)

138
    def test_results(self):
139
        raise unittest.SkipTest("This test is extremely flakey")
140
141
142
        logger.setLevel(logging.DEBUG)
        results_output=tempfile.mktemp()
        package.package(self.config, self.config.get_build_directory(None, 'common'), 
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                        'common', archive_format='txz', results_file=results_output)
        expected_results_regex = '''\
{
    "autobuild_package_clean": "true",
    "autobuild_package_filename": "%s",
    "autobuild_package_md5": "%s",
    "autobuild_package_metadata": "%s",
    "autobuild_package_name": "%s",
    "autobuild_package_sha256": "%s",
    "autobuild_package_sha3_256": "%s",
    "autobuild_package_sha3_384": "%s",
    "autobuild_package_version": "%s"
}
$''' % (re.escape(os.path.basename(self.tar_name)), "[0-9a-f]{32}", re.escape(os.path.join(self.data_dir, "package-test", "autobuild-package.xml")), 'test1',
       "[0-9a-f]{64}", "[0-9a-f]{64}",  "[0-9a-f]{96}", re.escape("1.0"))
158
159
160
161
162
163
164
        expected=re.compile(expected_results_regex, flags=re.MULTILINE)
        assert os.path.exists(results_output), "results file not found: %s" % results_output
        actual_results = open(results_output,'r').read()
        assert expected.match(actual_results), \
          "\n!!! expected regex:\n%s\n!!! actual result:\n%s" % (expected_results_regex, actual_results)
        clean_file(results_output)

165
166
167
168
169
170
171
172
173
    def test_package_other_version(self):
        # read the existing metadata file and update stored package version
        build_directory = self.config.get_build_directory(None, 'common')
        metadata_filename = os.path.join(build_directory,
                                         configfile.PACKAGE_METADATA_FILE)
        metadata = configfile.MetadataDescription(metadata_filename)
        metadata.package_description.version = "2.3"
        metadata.save()
        # okay, now use that to build package
174
        package.package(self.config, build_directory, 'common', archive_format='txz')
175
176
177
178
179
180
181
182
183
        # should have used updated package version in tarball name
        expected_tar_name = self.tar_name.replace("-1.0-", "-2.3-")
        if not os.path.exists(expected_tar_name):
            if os.path.exists(self.tar_name):
                raise AssertionError("package built %s instead of %s" %
                                     (self.tar_name, expected_tar_name))
            raise AssertionError("package built neither %s nor %s" %
                                 (self.tar_name, expected_tar_name))

Andrew A. de Laix's avatar
Andrew A. de Laix committed
184
    def test_autobuild_package(self):
Oz Linden's avatar
Oz Linden committed
185
186
187
188
        with CaptureStdout() as stream:
            self.autobuild("package",
                           "--config-file=" + self.config_path,
                           "-p", "common")
189
        assert os.path.exists(self.tar_name), "%s does not exist" % self.tar_name
190
        self.tar_has_expected(self.tar_name)
191
        self.remove(self.tar_name)
192
193
194
        self.autobuild("package",
                       "--config-file=" + self.config_path,
                       "--archive-format=zip",
195
                       "-p", "common")
196
        assert os.path.exists(self.zip_name), "%s does not exist" % self.zip_name
197
198
199
        self.zip_has_expected(self.zip_name)
        self.remove(self.zip_name)

200
201
        self.autobuild("package",
                       "--config-file=" + self.config_path,
202
                       "-p", "common",
203
                       "--dry-run")
204
205
206
        assert not os.path.exists(self.zip_name), "%s created by dry run" % self.zip_name
        assert not os.path.exists(self.tar_name), "%s created by dry run" % self.tar_name

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    def test_disallowed_paths(self):
        self.options = PackageOptions(self.data_dir)
        config_template=os.path.join(self.data_dir,"autobuild-package-disallowedpath-config.xml")
        # earlier tests establish the 'common' platform
        # clear that out so that this test uses both the current and common
        del os.environ['AUTOBUILD_PLATFORM']
        del os.environ['AUTOBUILD_PLATFORM_OVERRIDE']
        common.Platform=None
        self.platform=common.get_current_platform()
        logger.debug("platform "+self.platform)
        self.options.platform=self.platform
        platform_config=self.platform+"-autobuild-package-disallowedpath-config.xml"
        self.instantiateTemplate(config_template
                                ,platform_config
                                ,{'PLATFORM':self.platform})
        self.options.autobuild_filename = platform_config
223
224
225
226
        # it's hard to come up with a root path (such as /etc/passwd) that will be on all platforms
        # so we use "/" here; if you use some /etc/passwd, you get a different exception
        # (No files matched manifest specifiers) when the file does not exist
        badpaths=["include/../include/file1","include/../file2","../package-test/include/file1","include/..","/"]
227
228
229
230
        with ExpectError("Absolute paths or paths with parent directory elements are not allowed:\n  "+'\n  '.join(sorted(badpaths))+"\n",
                         "Bad paths not detected"):
            package.AutobuildTool().run(self.options)

231
232
    def test_package_missing(self):
        self.options = PackageOptions(self.data_dir)
233
        config_template=os.path.join(self.data_dir,"autobuild-package-missing-config.xml")
234
235
236
237
238
239
240
241
242
243
244
245
246
        # earlier tests establish the 'common' platform
        # clear that out so that this test uses both the current and common
        del os.environ['AUTOBUILD_PLATFORM']
        del os.environ['AUTOBUILD_PLATFORM_OVERRIDE']
        common.Platform=None
        self.platform=common.get_current_platform()
        logger.debug("platform "+self.platform)
        self.options.platform=self.platform
        platform_config=self.platform+"-autobuild-package-missing-config.xml"
        self.instantiateTemplate(config_template
                                ,platform_config
                                ,{'PLATFORM':self.platform})
        self.options.autobuild_filename = platform_config
247
        with ExpectError("No files matched manifest specifiers:\n"+'\n'.join(["missing/\\*.txt","not_there.txt"]),
248
249
250
251
                         "Missing files not detected"):
            package.AutobuildTool().run(self.options)


252
253
if __name__ == '__main__':
    unittest.main()