test_pkg_resources.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import sys
  4. import tempfile
  5. import os
  6. import zipfile
  7. import datetime
  8. import time
  9. import subprocess
  10. import stat
  11. import distutils.dist
  12. import distutils.command.install_egg_info
  13. from pkg_resources.extern.six.moves import map
  14. import pytest
  15. import pkg_resources
  16. try:
  17. unicode
  18. except NameError:
  19. unicode = str
  20. def timestamp(dt):
  21. """
  22. Return a timestamp for a local, naive datetime instance.
  23. """
  24. try:
  25. return dt.timestamp()
  26. except AttributeError:
  27. # Python 3.2 and earlier
  28. return time.mktime(dt.timetuple())
  29. class EggRemover(unicode):
  30. def __call__(self):
  31. if self in sys.path:
  32. sys.path.remove(self)
  33. if os.path.exists(self):
  34. os.remove(self)
  35. class TestZipProvider(object):
  36. finalizers = []
  37. ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0)
  38. "A reference time for a file modification"
  39. @classmethod
  40. def setup_class(cls):
  41. "create a zip egg and add it to sys.path"
  42. egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)
  43. zip_egg = zipfile.ZipFile(egg, 'w')
  44. zip_info = zipfile.ZipInfo()
  45. zip_info.filename = 'mod.py'
  46. zip_info.date_time = cls.ref_time.timetuple()
  47. zip_egg.writestr(zip_info, 'x = 3\n')
  48. zip_info = zipfile.ZipInfo()
  49. zip_info.filename = 'data.dat'
  50. zip_info.date_time = cls.ref_time.timetuple()
  51. zip_egg.writestr(zip_info, 'hello, world!')
  52. zip_egg.close()
  53. egg.close()
  54. sys.path.append(egg.name)
  55. cls.finalizers.append(EggRemover(egg.name))
  56. @classmethod
  57. def teardown_class(cls):
  58. for finalizer in cls.finalizers:
  59. finalizer()
  60. def test_resource_filename_rewrites_on_change(self):
  61. """
  62. If a previous call to get_resource_filename has saved the file, but
  63. the file has been subsequently mutated with different file of the
  64. same size and modification time, it should not be overwritten on a
  65. subsequent call to get_resource_filename.
  66. """
  67. import mod
  68. manager = pkg_resources.ResourceManager()
  69. zp = pkg_resources.ZipProvider(mod)
  70. filename = zp.get_resource_filename(manager, 'data.dat')
  71. actual = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
  72. assert actual == self.ref_time
  73. f = open(filename, 'w')
  74. f.write('hello, world?')
  75. f.close()
  76. ts = timestamp(self.ref_time)
  77. os.utime(filename, (ts, ts))
  78. filename = zp.get_resource_filename(manager, 'data.dat')
  79. f = open(filename)
  80. assert f.read() == 'hello, world!'
  81. manager.cleanup_resources()
  82. class TestResourceManager(object):
  83. def test_get_cache_path(self):
  84. mgr = pkg_resources.ResourceManager()
  85. path = mgr.get_cache_path('foo')
  86. type_ = str(type(path))
  87. message = "Unexpected type from get_cache_path: " + type_
  88. assert isinstance(path, (unicode, str)), message
  89. class TestIndependence:
  90. """
  91. Tests to ensure that pkg_resources runs independently from setuptools.
  92. """
  93. def test_setuptools_not_imported(self):
  94. """
  95. In a separate Python environment, import pkg_resources and assert
  96. that action doesn't cause setuptools to be imported.
  97. """
  98. lines = (
  99. 'import pkg_resources',
  100. 'import sys',
  101. 'assert "setuptools" not in sys.modules, '
  102. '"setuptools was imported"',
  103. )
  104. cmd = [sys.executable, '-c', '; '.join(lines)]
  105. subprocess.check_call(cmd)
  106. class TestDeepVersionLookupDistutils(object):
  107. @pytest.fixture
  108. def env(self, tmpdir):
  109. """
  110. Create a package environment, similar to a virtualenv,
  111. in which packages are installed.
  112. """
  113. class Environment(str):
  114. pass
  115. env = Environment(tmpdir)
  116. tmpdir.chmod(stat.S_IRWXU)
  117. subs = 'home', 'lib', 'scripts', 'data', 'egg-base'
  118. env.paths = dict(
  119. (dirname, str(tmpdir / dirname))
  120. for dirname in subs
  121. )
  122. list(map(os.mkdir, env.paths.values()))
  123. return env
  124. def create_foo_pkg(self, env, version):
  125. """
  126. Create a foo package installed (distutils-style) to env.paths['lib']
  127. as version.
  128. """
  129. ld = "This package has unicode metadata! ❄"
  130. attrs = dict(name='foo', version=version, long_description=ld)
  131. dist = distutils.dist.Distribution(attrs)
  132. iei_cmd = distutils.command.install_egg_info.install_egg_info(dist)
  133. iei_cmd.initialize_options()
  134. iei_cmd.install_dir = env.paths['lib']
  135. iei_cmd.finalize_options()
  136. iei_cmd.run()
  137. def test_version_resolved_from_egg_info(self, env):
  138. version = '1.11.0.dev0+2329eae'
  139. self.create_foo_pkg(env, version)
  140. # this requirement parsing will raise a VersionConflict unless the
  141. # .egg-info file is parsed (see #419 on BitBucket)
  142. req = pkg_resources.Requirement.parse('foo>=1.9')
  143. dist = pkg_resources.WorkingSet([env.paths['lib']]).find(req)
  144. assert dist.version == version