Commit 3d6b68ae authored by Thomas Koch's avatar Thomas Koch Committed by Guido Günther

tests: Use tempfile.mkdtemp to create temp dirs for tests

This puts test dirs below /tmp which often is a tmpfs.

All tests include the context module which consolidates tmpdir creation
and cleanup, undoes a chdir in teardown and silences log messages.
parent 92edb4ed
......@@ -2,6 +2,8 @@
"""Check if --help works"""
from . import context
import unittest
class TestHelp(unittest.TestCase):
......
......@@ -2,14 +2,17 @@
"""Test L{UpstreamSource}'s tarball unpack"""
from . import context
import os
import shutil
import tarfile
import tempfile
import unittest
import gbp.deb
import gbp.pkg
class TestUnpack:
class TestUnpack(unittest.TestCase):
"""Make sure we unpack gzip and bzip2 archives correctly"""
archive_prefix = "archive"
......@@ -34,17 +37,15 @@ class TestUnpack:
return name, filelist
def setUp(self):
self.dir = tempfile.mkdtemp(prefix='gbp_%s_' % __name__, dir='.')
self.top = os.path.abspath(os.curdir)
os.chdir(self.dir)
self.dir = context.new_tmpdir(__name__)
self.top = context.projectdir
context.chdir(self.dir)
self.archives = {}
for ext in [ "gz", "bz2" ]:
self.archives[ext] = self._create_archive(ext)
def tearDown(self):
os.chdir(self.top)
if not os.getenv("GBP_TESTS_NOCLEAN"):
shutil.rmtree(self.dir)
context.teardown()
def test_upstream_source_type(self):
for (comp, archive) in self.archives.iteritems():
......
......@@ -2,7 +2,10 @@
"""Test L{Changelog}'s guess_version_from_upstream"""
from . import context
import testutils
import unittest
from gbp.scripts import dch
from gbp.deb.changelog import ChangeLog
......
......@@ -2,9 +2,12 @@
"""Test submodule L{GitRepository} submodule methods"""
from . import context
import os
import shutil
import tarfile
import tempfile
import gbp.log
import gbp.git
......@@ -12,7 +15,6 @@ import gbp.command_wrappers
from gbp.scripts import buildpackage
top = None
repo = None
repodir = None
......@@ -29,27 +31,20 @@ class Submodule(object):
def setup():
global repo, repodir, submodules, top, tmpdir
gbp.log.setup(False, False)
top = os.path.abspath(os.curdir)
tmpdir =os.path.join(top,'gbp_%s_repo' % __name__)
os.mkdir(tmpdir)
global repo, repodir, submodules, tmpdir
repodir = os.path.join(tmpdir, 'test_repo')
tmpdir = context.new_tmpdir(__name__)
repodir = tmpdir.join('test_repo')
repo = gbp.git.GitRepository.create(repodir)
for name in submodule_names:
submodules.append(Submodule(name, tmpdir))
submodules.append(Submodule(name, str(tmpdir)))
os.chdir(repodir)
context.chdir(repodir)
def teardown():
os.chdir(top)
if not os.getenv("GBP_TESTS_NOCLEAN") and tmpdir:
shutil.rmtree(tmpdir)
context.teardown()
def test_empty_has_submodules():
"""Test empty repo for submodules"""
......@@ -96,7 +91,7 @@ def test_get_submodules():
def test_dump_tree():
"""Dump the repository and check if files exist"""
dumpdir = os.path.join(tmpdir, "dump")
dumpdir = tmpdir.join("dump")
os.mkdir(dumpdir)
assert buildpackage.dump_tree(repo, dumpdir, "master", True)
assert os.path.exists(os.path.join(dumpdir, testfile_name))
......@@ -108,7 +103,7 @@ def test_create_tarball():
cp = { "Source": "test", "Upstream-Version": "0.1" }
assert buildpackage.git_archive(repo,
cp,
tmpdir,
str(tmpdir),
"HEAD",
"bzip2",
"9",
......@@ -116,7 +111,7 @@ def test_create_tarball():
def test_check_tarfile():
"""Check the contents of the created tarfile"""
t = tarfile.open(os.path.join(tmpdir,"test_0.1.orig.tar.bz2"), 'r:*')
t = tarfile.open(tmpdir.join("test_0.1.orig.tar.bz2"), 'r:*')
files = t.getmembers()
assert "test-0.1/.gitmodules" in [ f.name for f in files ]
assert len(files) == 6
......
......@@ -2,6 +2,8 @@
"""Test tarball compression type detection"""
from . import context
import os
import shutil
import tempfile
......@@ -30,28 +32,28 @@ class MockGitRepository:
class TestDetection(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.tmpdir = context.new_tmpdir(__name__)
self.cp = {'Source': 'source', 'Upstream-Version': '1.2'}
def tearDown(self):
shutil.rmtree(self.tmpdir)
context.teardown()
def test_guess_comp_type_no_pristine_tar_no_orig(self):
repo = MockGitRepository(with_branch=False)
guessed = buildpackage.guess_comp_type(
repo, 'auto', self.cp, self.tmpdir)
repo, 'auto', self.cp, str(self.tmpdir))
self.assertEqual('gzip', guessed)
def test_guess_comp_type_no_pristine_tar_with_orig(self):
open(os.path.join(self.tmpdir, 'source_1.2.orig.tar.bz2'), "w").close()
open(self.tmpdir.join('source_1.2.orig.tar.bz2'), "w").close()
repo = MockGitRepository(with_branch=False)
guessed = buildpackage.guess_comp_type(
repo, 'auto', self.cp, self.tmpdir)
repo, 'auto', self.cp, str(self.tmpdir))
self.assertEqual('bzip2', guessed)
def test_guess_comp_type_no_pristine_tar_with_multiple_origs(self):
open(os.path.join(self.tmpdir, 'source_1.2.orig.tar.gz'), "w").close()
open(os.path.join(self.tmpdir, 'source_1.2.orig.tar.xz'), "w").close()
open(self.tmpdir.join('source_1.2.orig.tar.gz'), "w").close()
open(self.tmpdir.join('source_1.2.orig.tar.xz'), "w").close()
repo = MockGitRepository(with_branch=False)
self.assertRaises(
GbpError,
......@@ -59,21 +61,21 @@ class TestDetection(unittest.TestCase):
repo,
'auto',
self.cp,
self.tmpdir)
str(self.tmpdir))
def test_guess_comp_type_auto_bzip2(self):
subject = 'pristine-tar data for source_1.2-3.orig.tar.bz2'
repo = MockGitRepository(with_branch=True, subject=subject)
guessed = buildpackage.guess_comp_type(
repo, 'auto', self.cp, self.tmpdir)
repo, 'auto', self.cp, str(self.tmpdir))
self.assertEqual("bzip2", guessed)
def test_has_orig_false(self):
self.assertFalse(DebianPkgPolicy.has_orig(orig_file(self.cp, 'gzip'), self.tmpdir))
self.assertFalse(DebianPkgPolicy.has_orig(orig_file(self.cp, 'gzip'), str(self.tmpdir)))
def test_has_orig_true(self):
open(os.path.join(self.tmpdir, 'source_1.2.orig.tar.gz'), "w").close()
self.assertTrue(DebianPkgPolicy.has_orig(orig_file(self.cp, 'gzip'), self.tmpdir))
open(self.tmpdir.join('source_1.2.orig.tar.gz'), "w").close()
self.assertTrue(DebianPkgPolicy.has_orig(orig_file(self.cp, 'gzip'), str(self.tmpdir)))
def test_guess_comp_type_bzip2(self):
repo = MockGitRepository(with_branch=False)
......
......@@ -2,6 +2,8 @@
"""Test the L{UpstreamSource} class"""
from . import context
import glob
import os
import shutil
......@@ -14,8 +16,8 @@ from gbp.pkg import UpstreamSource
class TestDir(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix='gbp_%s_' % __name__, dir='.')
self.upstream_dir = os.path.join(self.tmpdir, 'test-1.0')
self.tmpdir = context.new_tmpdir(__name__)
self.upstream_dir = self.tmpdir.join('test-1.0')
os.mkdir(self.upstream_dir)
def test_directory(self):
......@@ -27,8 +29,7 @@ class TestDir(unittest.TestCase):
self.assertEqual(source.guess_version(), ('test', '1.0'))
def tearDown(self):
if not os.getenv("GBP_TESTS_NOCLEAN"):
shutil.rmtree(self.tmpdir)
context.teardown()
class TestTar(unittest.TestCase):
"""Test if packing tar archives works"""
......@@ -47,28 +48,24 @@ class TestTar(unittest.TestCase):
t.close()
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix='gbp_%s_' % __name__, dir='.')
self.tmpdir = context.new_tmpdir(__name__)
self.source = UpstreamSource(os.path.join(context.projectdir, "gbp"))
def tearDown(self):
if not os.getenv("GBP_TESTS_NOCLEAN"):
shutil.rmtree(self.tmpdir)
context.teardown()
def test_pack_tar(self):
"""Check if packing tar archives works"""
source = UpstreamSource(os.path.abspath("gbp/"))
target = os.path.join(self.tmpdir,
"gbp_0.1.tar.bz2")
repacked = source.pack(target)
target = self.tmpdir.join("gbp_0.1.tar.bz2")
repacked = self.source.pack(target)
self.assertEqual(repacked.is_orig(), True)
self.assertEqual(repacked.is_dir(), False)
self._check_tar(repacked, ["gbp/errors.py", "gbp/__init__.py"])
def test_pack_filtered(self):
"""Check if filtering out files works"""
source = UpstreamSource(os.path.abspath("gbp/"))
target = os.path.join(self.tmpdir,
"gbp_0.1.tar.bz2")
repacked = source.pack(target, ["__init__.py"])
target = self.tmpdir.join("gbp_0.1.tar.bz2")
repacked = self.source.pack(target, ["__init__.py"])
self.assertEqual(repacked.is_orig(), True)
self.assertEqual(repacked.is_dir(), False)
self._check_tar(repacked, ["gbp/errors.py"],
......@@ -78,22 +75,21 @@ class TestTar(unittest.TestCase):
class TestZip(unittest.TestCase):
"""Test if unpacking zip archives works"""
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix='gbp_%s_' % __name__, dir='.')
self.zipfile = os.path.join(self.tmpdir, "gbp-0.1.zip")
z = zipfile.ZipFile(os.path.join(self.tmpdir, "gbp-0.1.zip"), "w")
for f in glob.glob("gbp/*.py"):
self.tmpdir = context.new_tmpdir(__name__)
self.zipfile = self.tmpdir.join("gbp-0.1.zip")
z = zipfile.ZipFile(self.zipfile, "w")
for f in glob.glob(os.path.join(context.projectdir, "gbp/*.py")):
z.write(f, f, zipfile.ZIP_DEFLATED)
z.close()
def tearDown(self):
if not os.getenv("GBP_TESTS_NOCLEAN"):
shutil.rmtree(self.tmpdir)
context.teardown()
def test_unpack(self):
source = UpstreamSource(self.zipfile)
self.assertEqual(source.is_orig(), False)
self.assertEqual(source.is_dir(), False)
self.assertEqual(source.unpacked, None)
source.unpack(self.tmpdir)
source.unpack(str(self.tmpdir))
self.assertNotEqual(source.unpacked, None)
......@@ -2,32 +2,28 @@
"""Test L{FastImport} class"""
from . import context
import os
import shutil
import tempfile
import gbp.log
import gbp.git
repo = None
fastimport = None
tmpdir = None
tf_name = 'testfile'
tl_name = 'a_testlink'
def setup():
global repo, tmpdir
gbp.log.setup(False, False)
top = os.path.abspath(os.curdir)
tmpdir = os.path.join(top,'gbp_%s_repo' % __name__)
os.mkdir(tmpdir)
global repo
repodir = os.path.join(tmpdir, 'test_repo')
repo = gbp.git.GitRepository.create(repodir)
tmpdir = context.new_tmpdir(__name__)
repo = gbp.git.GitRepository.create(tmpdir.join('test_repo'))
def teardown():
if not os.getenv("GBP_TESTS_NOCLEAN") and tmpdir:
shutil.rmtree(tmpdir)
context.teardown()
def test_init_fastimport():
"""Create a fastimport object"""
......
......@@ -2,6 +2,8 @@
"""Test L{Patch} class"""
from . import context
import os
import unittest
......
......@@ -2,6 +2,8 @@
"""Test L{GitRepository}'s write_tree method"""
from . import context
import os
import tests.testutils as testutils
......
......@@ -2,6 +2,8 @@
"""Test L{buildpackage}'s get_upstream_tree method"""
from . import context
import tests.testutils as testutils
import gbp.errors
......
......@@ -2,6 +2,8 @@
"""Test L{gbp.scripts.dch} main"""
from . import context
import unittest
from tests.testutils import DebianGitTestRepo
......@@ -48,7 +50,7 @@ class TestScriptDch(DebianGitTestRepo):
self.upstream_tag = "upstream/%(version)s"
self.top = os.path.abspath(os.path.curdir)
os.mkdir(os.path.join(self.repo.path, "debian"))
os.chdir(self.repo.path)
context.chdir(self.repo.path)
self.add_file("debian/changelog", cl_debian)
self.add_file("debian/control", """Source: test-package\nSection: test\n""")
self.options = ["--upstream-tag=%s" % self.upstream_tag, "--debian-branch=debian",
......@@ -57,7 +59,6 @@ class TestScriptDch(DebianGitTestRepo):
def tearDown(self):
os.chdir(self.top)
DebianGitTestRepo.tearDown(self)
......
......@@ -2,6 +2,8 @@
"""Test L{gbp.deb}"""
from . import context
import os, tempfile, unittest
import gbp.deb
......
......@@ -15,6 +15,8 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Test L{gbp.pq}"""
from . import context
import os
import logging
import unittest
......@@ -32,9 +34,7 @@ class TestApplyAndCommit(testutils.DebianGitTestRepo):
def test_apply_and_commit_patch(self):
"""Test applying a single patch"""
patch = gbp.patch_series.Patch(
os.path.join(os.path.abspath(os.path.curdir),
'tests/data/foo.patch'))
patch = gbp.patch_series.Patch(_patch_path('foo.patch'))
pq.apply_and_commit_patch(self.repo, patch, None)
self.assertIn('foo', self.repo.list_files())
......@@ -42,9 +42,7 @@ class TestApplyAndCommit(testutils.DebianGitTestRepo):
def test_topic(self):
"""Test if setting a topic works"""
patch = gbp.patch_series.Patch(
os.path.join(os.path.abspath(os.path.curdir),
'tests/data/foo.patch'))
patch = gbp.patch_series.Patch(_patch_path('foo.patch'))
pq.apply_and_commit_patch(self.repo, patch, None, topic='foobar')
info = self.repo.get_commit_info('HEAD')
......@@ -56,9 +54,8 @@ class TestApplyAndCommit(testutils.DebianGitTestRepo):
Check if we parse the author from debian control
if it's missing.
"""
patch = gbp.patch_series.Patch(
os.path.join(os.path.abspath(os.path.curdir),
'tests/data/foo.patch'))
patch = gbp.patch_series.Patch(_patch_path('foo.patch'))
# Overwrite data parsed from patch:
patch.author
......@@ -84,9 +81,8 @@ class TestApplySinglePatch(testutils.DebianGitTestRepo):
def test_apply_single_patch(self):
"""Test applying a single patch"""
patch = gbp.patch_series.Patch(
os.path.join(os.path.abspath(os.path.curdir),
'tests/data/foo.patch'))
patch = gbp.patch_series.Patch(_patch_path('foo.patch'))
pq.apply_single_patch(self.repo, 'master', patch, None)
self.assertIn('foo', self.repo.list_files())
......@@ -98,6 +94,9 @@ class TestWritePatch(testutils.DebianGitTestRepo):
testutils.DebianGitTestRepo.setUp(self)
self.add_file('bar', 'bar')
def tearDown(self):
context.teardown()
def test_write_patch(self):
"""Test moving a patch to it's final location"""
......@@ -109,9 +108,9 @@ class TestWritePatch(testutils.DebianGitTestRepo):
self.add_file('foo', 'foo', msg)
# Write it out as patch and check it's existence
d = os.getcwd()
patchfile = self.repo.format_patches('HEAD^', 'HEAD', d)[0]
expected = os.path.join(d, '0001-added-foo.patch')
d = context.new_tmpdir(__name__)
patchfile = self.repo.format_patches('HEAD^', 'HEAD', str(d))[0]
expected = os.path.join(str(d), '0001-added-foo.patch')
self.assertEqual(expected, patchfile)
pq.write_patch(patchfile, self.repo.path, opts)
expected = os.path.join(self.repo.path,
......@@ -129,3 +128,6 @@ class TestWritePatch(testutils.DebianGitTestRepo):
diff = self.repo.diff('master', 'testapply')
# Branches must be identical afterwards
self.assertEqual('', diff)
def _patch_path(name):
return os.path.join(context.projectdir, 'tests/data', name)
......@@ -15,6 +15,8 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Test L{gbp.pq}"""
from . import context
import os
import testutils
import gbp.scripts.import_dscs as import_dscs
......@@ -58,9 +60,8 @@ class TestImportDscs(testutils.DebianGitTestRepo):
"""Test L{gbp.scripts.import_dscs}'s """
def setUp(self):
self.toplevel = os.getcwd()
testutils.DebianGitTestRepo.setUp(self)
os.chdir(self.repo.path)
context.chdir(self.repo.path)
def test_import_success(self):
"""Test importing success with stub"""
......@@ -83,5 +84,5 @@ class TestImportDscs(testutils.DebianGitTestRepo):
def tearDown(self):
testutils.DebianGitTestRepo.tearDown(self)
os.chdir(self.toplevel)
context.teardown()
# this context.py should be included by all tests
# idea from http://kennethreitz.com/repository-structure-and-python.html
import os
import shutil
import sys
import tempfile
sys.path.insert(0, os.path.abspath('..'))
import gbp
import gbp.log
gbp.log.setup(False, False)
# the top or root dir of the git-buildpackage source tree to be used by tests
projectdir = os.path.dirname(os.path.dirname(os.path.abspath(gbp.__file__)))
_chdir_backup = None
_tmpdirs = []
def chdir(dir):
global _chdir_backup
if not _chdir_backup:
_chdir_backup = os.path.abspath(os.curdir)
os.chdir(str(dir))
def new_tmpdir(name):
global _tmpdirs
prefix='gbp_%s_' % name
tmpdir=TmpDir(prefix)
_tmpdirs.append(tmpdir)
return tmpdir
def teardown():
if _chdir_backup:
os.chdir(_chdir_backup)
for tmpdir in _tmpdirs:
tmpdir.rmdir()
del _tmpdirs[:]
class TmpDir(object):
def __init__(self, suffix='', prefix='tmp'):
self.path = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
def rmdir(self):
if self.path and not os.getenv("GBP_TESTS_NOCLEAN"):
shutil.rmtree(self.path)
self.path = None
def __repr__(self):
return self.path
def join(self, *args):
return os.path.join(self.path, *args)
......@@ -3,9 +3,8 @@
"""
Test L{gbp.deb.changelog.ChangeLog}
"""
from . import context
import os
import nose
cl_debian = """git-buildpackage (0.5.32) unstable; urgency=low
......
......@@ -5,6 +5,8 @@ Test L{gbp.config.GbpOptionParser}
Test L{gbp.config.GbpOptionParserDebian}
"""
from . import context
def test_option_parser():
"""
Methods tested:
......
......@@ -4,6 +4,8 @@
Test L{gbp.deb.control.Control}
"""
from . import context
cl_debian = """Source: git-buildpackage
Section: vcs
Priority: optional
......
......@@ -4,6 +4,8 @@
Test L{gbp.git.GitModifier}
"""
from . import context
def test_author():
"""
Methods tested:
......
......@@ -11,20 +11,16 @@ This testcase creates several repositores:
- A mirror of I{repo} below L{mirror_clone_dir} called I{mirror}
"""
from . import context
import os
import gbp.log
gbp.log.setup(color=False, verbose=True)
repo_dir = os.path.abspath(
os.path.join(os.path.curdir, 'gbp_%s_test_repo' % __name__))
bare_dir = os.path.abspath(
os.path.join(os.path.curdir, 'gbp_%s_test_bare' % __name__))
clone_dir = os.path.abspath(
os.path.join(os.path.curdir, 'gbp_%s_test_clone' % __name__))
mirror_clone_dir = os.path.abspath(
os.path.join(os.path.curdir, 'gbp_%s_test_mirror_clone' % __name__))
repo_dir, bare_dir, clone_dir, mirror_clone_dir = map(
lambda x, tmpdir=context.new_tmpdir(__name__): tmpdir.join(x),
['repo', 'bare', 'clone', 'mirror_clone'])
def test_create():
"""
......@@ -539,7 +535,7 @@ def test_pull():
- L{gbp.git.GitRepository.pull}
>>> import gbp.git, os
>>> d = os.path.join(clone_dir, 'gbp_%s_test_repo' % __name__)
>>> d = os.path.join(clone_dir, 'repo')
>>> clone = gbp.git.GitRepository(d)
>>> clone.set_branch('master')
>>> clone.pull()
......@@ -557,7 +553,7 @@ def test_fetch():
- L{gbp.git.GitRepository.remove_remote_repo}
>>> import gbp.git, os
>>> d = os.path.join(clone_dir, 'gbp_%s_test_repo' % __name__)
>>> d = os.path.join(clone_dir, 'repo')
>>> clone = gbp.git.GitRepository(d)
>>> clone.fetch()
>>> clone.push()
......@@ -817,11 +813,7 @@ def test_teardown():
"""
Perform the teardown
>>> import shutil, os
>>> os.getenv("GBP_TESTS_NOCLEAN") or shutil.rmtree(repo_dir)
>>> os.getenv("GBP_TESTS_NOCLEAN") or shutil.rmtree(bare_dir)
>>> os.getenv("GBP_TESTS_NOCLEAN") or shutil.rmtree(mirror_clone_dir)
>>> os.getenv("GBP_TESTS_NOCLEAN") or shutil.rmtree(clone_dir)
>>> context.teardown()
"""
# vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·:
......@@ -15,11 +15,12 @@ This testcase creates this reposity:
"""
from . import context
import os
tmp_dir = os.path.abspath(
os.path.join(os.path.curdir, 'gbp_%s_test' % __name__))
repo_dir = os.path.join(tmp_dir, 'repo')
test_data = os.path.abspath("tests/test_PristineTar_data")
repo_dir = context.new_tmpdir(__name__).join('repo')
test_data = os.path.join(context.projectdir, "tests/test_PristineTar_data")
def test_create():
"""
......@@ -126,8 +127,7 @@ def test_teardown():
"""
Perform the teardown
>>> import shutil, os
>>> os.getenv("GBP_TESTS_NOCLEAN") or shutil.rmtree(tmp_dir)
>>> context.teardown()
"""
# vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·:
# vim: set fileencoding=utf-8 :
from . import context
import os
import shutil
import unittest
......@@ -12,16 +14,13 @@ class DebianGitTestRepo(unittest.TestCase):
"""Scratch repo for a single unit test"""
def setUp(self):
gbp.log.setup(False, False)
top = os.path.abspath(os.path.curdir)
self.tmpdir = os.path.join(top, 'gbp_%s_repo' % __name__)
os.mkdir(self.tmpdir)
self.tmpdir = context.new_tmpdir(__name__)
repodir = os.path.join(self.tmpdir, 'test_repo')
repodir = self.tmpdir.join('test_repo')
self.repo = gbp.deb.git.DebianGitRepository.create(repodir)