context.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # this context.py should be included by all tests
  2. # idea from http://kennethreitz.com/repository-structure-and-python.html
  3. import os
  4. import shutil
  5. import sys
  6. import tempfile
  7. sys.path.insert(0, os.path.abspath('..'))
  8. import gbp
  9. import gbp.log
  10. gbp.log.setup(False, False)
  11. # the top or root dir of the git-buildpackage source tree to be used by tests
  12. projectdir = os.path.dirname(os.path.dirname(os.path.abspath(gbp.__file__)))
  13. _chdir_backup = None
  14. _tmpdirs = []
  15. def chdir(dir):
  16. global _chdir_backup
  17. if not _chdir_backup:
  18. _chdir_backup = os.path.abspath(os.curdir)
  19. os.chdir(str(dir))
  20. def new_tmpdir(name):
  21. global _tmpdirs
  22. prefix='gbp_%s_' % name
  23. tmpdir = TmpDir(prefix)
  24. _tmpdirs.append(tmpdir)
  25. return tmpdir
  26. def teardown():
  27. if _chdir_backup:
  28. os.chdir(_chdir_backup)
  29. for tmpdir in _tmpdirs:
  30. tmpdir.rmdir()
  31. del _tmpdirs[:]
  32. class TmpDir(object):
  33. def __init__(self, suffix='', prefix='tmp'):
  34. self.path = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
  35. def rmdir(self):
  36. if self.path and not os.getenv("GBP_TESTS_NOCLEAN"):
  37. shutil.rmtree(self.path)
  38. self.path = None
  39. def __repr__(self):
  40. return self.path
  41. def join(self, *args):
  42. return os.path.join(self.path, *args)