test_archive_util.py 9.38 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4
"""Tests for distutils.archive_util."""
import unittest
import os
5
import sys
6
import tarfile
7
from os.path import splitdrive
8
import warnings
9

10
from distutils import archive_util
11
from distutils.archive_util import (check_archive_formats, make_tarball,
12 13
                                    make_zipfile, make_archive,
                                    ARCHIVE_FORMATS)
14
from distutils.spawn import find_executable, spawn
15
from distutils.tests import support
16
from test.support import check_warnings, run_unittest, patch
17 18 19 20 21 22 23

try:
    import zipfile
    ZIP_SUPPORT = True
except ImportError:
    ZIP_SUPPORT = find_executable('zip')

24 25 26 27 28 29
try:
    import zlib
    ZLIB_SUPPORT = True
except ImportError:
    ZLIB_SUPPORT = False

30 31 32 33 34 35 36 37 38 39 40 41
def can_fs_encode(filename):
    """
    Return True if the filename can be saved in the file system.
    """
    if os.path.supports_unicode_filenames:
        return True
    try:
        filename.encode(sys.getfilesystemencoding())
    except UnicodeEncodeError:
        return False
    return True

42

43
class ArchiveUtilTestCase(support.TempdirManager,
44
                          support.LoggingSilencer,
45 46
                          unittest.TestCase):

47
    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
48
    def test_make_tarball(self):
49 50 51
        self._make_tarball('archive')

    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
52 53
    @unittest.skipUnless(can_fs_encode('årchiv'),
        'File system cannot handle this filename')
54 55 56 57 58 59 60
    def test_make_tarball_latin1(self):
        """
        Mirror test_make_tarball, except filename contains latin characters.
        """
        self._make_tarball('årchiv') # note this isn't a real word

    @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
61 62
    @unittest.skipUnless(can_fs_encode('のアーカイブ'),
        'File system cannot handle this filename')
63 64 65 66 67 68 69 70
    def test_make_tarball_extended(self):
        """
        Mirror test_make_tarball, except filename contains extended
        characters outside the latin charset.
        """
        self._make_tarball('のアーカイブ') # japanese for archive

    def _make_tarball(self, target_name):
71 72 73 74
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')
75 76
        os.mkdir(os.path.join(tmpdir, 'sub'))
        self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
77 78

        tmpdir2 = self.mkdtemp()
79 80 81
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "Source and target should be on same drive")

82
        base_name = os.path.join(tmpdir2, target_name)
83 84 85 86 87

        # working with relative paths to avoid tar warnings
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
88
            make_tarball(splitdrive(base_name)[1], '.')
89 90
        finally:
            os.chdir(old_dir)
91 92 93

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
94
        self.assertTrue(os.path.exists(tarball))
95 96

        # trying an uncompressed one
97
        base_name = os.path.join(tmpdir2, target_name)
98 99 100
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
101
            make_tarball(splitdrive(base_name)[1], '.', compress=None)
102 103
        finally:
            os.chdir(old_dir)
104
        tarball = base_name + '.tar'
105
        self.assertTrue(os.path.exists(tarball))
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    def _tarinfo(self, path):
        tar = tarfile.open(path)
        try:
            names = tar.getnames()
            names.sort()
            return tuple(names)
        finally:
            tar.close()

    def _create_files(self):
        # creating something to tar
        tmpdir = self.mkdtemp()
        dist = os.path.join(tmpdir, 'dist')
        os.mkdir(dist)
        self.write_file([dist, 'file1'], 'xxx')
        self.write_file([dist, 'file2'], 'xxx')
        os.mkdir(os.path.join(dist, 'sub'))
        self.write_file([dist, 'sub', 'file3'], 'xxx')
        os.mkdir(os.path.join(dist, 'sub2'))
        tmpdir2 = self.mkdtemp()
        base_name = os.path.join(tmpdir2, 'archive')
        return tmpdir, tmpdir2, base_name

130 131 132
    @unittest.skipUnless(find_executable('tar') and find_executable('gzip')
                         and ZLIB_SUPPORT,
                         'Need the tar, gzip and zlib command to run')
133 134 135 136 137 138 139 140 141 142 143
    def test_tarfile_vs_tar(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
144
        self.assertTrue(os.path.exists(tarball))
145 146 147

        # now create another tarball using `tar`
        tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
148 149
        tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
        gzip_cmd = ['gzip', '-f9', 'archive2.tar']
150 151 152
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
153 154
            spawn(tar_cmd)
            spawn(gzip_cmd)
155 156 157
        finally:
            os.chdir(old_dir)

158
        self.assertTrue(os.path.exists(tarball2))
159
        # let's compare both tarballs
160
        self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
161 162 163 164 165 166 167 168 169 170

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
171
        self.assertTrue(os.path.exists(tarball))
172 173 174 175 176 177 178 179 180 181

        # now for a dry_run
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist', compress=None, dry_run=True)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
182
        self.assertTrue(os.path.exists(tarball))
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

    @unittest.skipUnless(find_executable('compress'),
                         'The compress program is required')
    def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
199
        self.assertTrue(os.path.exists(tarball))
200
        self.assertEqual(len(w.warnings), 1)
201 202 203 204 205 206 207 208 209 210 211 212

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
213
        self.assertTrue(not os.path.exists(tarball))
214
        self.assertEqual(len(w.warnings), 1)
215

216 217
    @unittest.skipUnless(ZIP_SUPPORT and ZLIB_SUPPORT,
                         'Need zip and zlib support to run')
218
    def test_make_zipfile(self):
219 220 221 222 223 224 225 226 227 228 229
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')

        tmpdir2 = self.mkdtemp()
        base_name = os.path.join(tmpdir2, 'archive')
        make_zipfile(base_name, tmpdir)

        # check if the compressed tarball was created
        tarball = base_name + '.zip'
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        self.assertTrue(os.path.exists(tarball))

    @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
    def test_make_zipfile_no_zlib(self):
        patch(self, archive_util.zipfile, 'zlib', None)  # force zlib ImportError

        called = []
        zipfile_class = zipfile.ZipFile
        def fake_zipfile(*a, **kw):
            if kw.get('compression', None) == zipfile.ZIP_STORED:
                called.append((a, kw))
            return zipfile_class(*a, **kw)

        patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)

        # create something to tar and compress
        tmpdir, tmpdir2, base_name = self._create_files()
        make_zipfile(base_name, tmpdir)

        tarball = base_name + '.zip'
        self.assertEqual(called,
                         [((tarball, "w"), {'compression': zipfile.ZIP_STORED})])
        self.assertTrue(os.path.exists(tarball))
253 254

    def test_check_archive_formats(self):
255 256 257
        self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']),
                         'xxx')
        self.assertEqual(check_archive_formats(['gztar', 'zip']), None)
258 259 260 261 262 263

    def test_make_archive(self):
        tmpdir = self.mkdtemp()
        base_name = os.path.join(tmpdir, 'archive')
        self.assertRaises(ValueError, make_archive, base_name, 'xxx')

264 265 266 267 268 269 270 271 272 273
    def test_make_archive_cwd(self):
        current_dir = os.getcwd()
        def _breaks(*args, **kw):
            raise RuntimeError()
        ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
        try:
            try:
                make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
            except:
                pass
274
            self.assertEqual(os.getcwd(), current_dir)
275 276 277
        finally:
            del ARCHIVE_FORMATS['xxx']

278 279 280 281
def test_suite():
    return unittest.makeSuite(ArchiveUtilTestCase)

if __name__ == "__main__":
282
    run_unittest(test_suite())