test_resources.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. import os
  2. import sys
  3. import tempfile
  4. import shutil
  5. import string
  6. import pytest
  7. import pkg_resources
  8. from pkg_resources import (parse_requirements, VersionConflict, parse_version,
  9. Distribution, EntryPoint, Requirement, safe_version, safe_name,
  10. WorkingSet)
  11. packaging = pkg_resources.packaging
  12. def safe_repr(obj, short=False):
  13. """ copied from Python2.7"""
  14. try:
  15. result = repr(obj)
  16. except Exception:
  17. result = object.__repr__(obj)
  18. if not short or len(result) < pkg_resources._MAX_LENGTH:
  19. return result
  20. return result[:pkg_resources._MAX_LENGTH] + ' [truncated]...'
  21. class Metadata(pkg_resources.EmptyProvider):
  22. """Mock object to return metadata as if from an on-disk distribution"""
  23. def __init__(self, *pairs):
  24. self.metadata = dict(pairs)
  25. def has_metadata(self, name):
  26. return name in self.metadata
  27. def get_metadata(self, name):
  28. return self.metadata[name]
  29. def get_metadata_lines(self, name):
  30. return pkg_resources.yield_lines(self.get_metadata(name))
  31. dist_from_fn = pkg_resources.Distribution.from_filename
  32. class TestDistro:
  33. def testCollection(self):
  34. # empty path should produce no distributions
  35. ad = pkg_resources.Environment([], platform=None, python=None)
  36. assert list(ad) == []
  37. assert ad['FooPkg'] == []
  38. ad.add(dist_from_fn("FooPkg-1.3_1.egg"))
  39. ad.add(dist_from_fn("FooPkg-1.4-py2.4-win32.egg"))
  40. ad.add(dist_from_fn("FooPkg-1.2-py2.4.egg"))
  41. # Name is in there now
  42. assert ad['FooPkg']
  43. # But only 1 package
  44. assert list(ad) == ['foopkg']
  45. # Distributions sort by version
  46. assert [dist.version for dist in ad['FooPkg']] == ['1.4','1.3-1','1.2']
  47. # Removing a distribution leaves sequence alone
  48. ad.remove(ad['FooPkg'][1])
  49. assert [dist.version for dist in ad['FooPkg']] == ['1.4','1.2']
  50. # And inserting adds them in order
  51. ad.add(dist_from_fn("FooPkg-1.9.egg"))
  52. assert [dist.version for dist in ad['FooPkg']] == ['1.9','1.4','1.2']
  53. ws = WorkingSet([])
  54. foo12 = dist_from_fn("FooPkg-1.2-py2.4.egg")
  55. foo14 = dist_from_fn("FooPkg-1.4-py2.4-win32.egg")
  56. req, = parse_requirements("FooPkg>=1.3")
  57. # Nominal case: no distros on path, should yield all applicable
  58. assert ad.best_match(req, ws).version == '1.9'
  59. # If a matching distro is already installed, should return only that
  60. ws.add(foo14)
  61. assert ad.best_match(req, ws).version == '1.4'
  62. # If the first matching distro is unsuitable, it's a version conflict
  63. ws = WorkingSet([])
  64. ws.add(foo12)
  65. ws.add(foo14)
  66. with pytest.raises(VersionConflict):
  67. ad.best_match(req, ws)
  68. # If more than one match on the path, the first one takes precedence
  69. ws = WorkingSet([])
  70. ws.add(foo14)
  71. ws.add(foo12)
  72. ws.add(foo14)
  73. assert ad.best_match(req, ws).version == '1.4'
  74. def checkFooPkg(self,d):
  75. assert d.project_name == "FooPkg"
  76. assert d.key == "foopkg"
  77. assert d.version == "1.3.post1"
  78. assert d.py_version == "2.4"
  79. assert d.platform == "win32"
  80. assert d.parsed_version == parse_version("1.3-1")
  81. def testDistroBasics(self):
  82. d = Distribution(
  83. "/some/path",
  84. project_name="FooPkg",version="1.3-1",py_version="2.4",platform="win32"
  85. )
  86. self.checkFooPkg(d)
  87. d = Distribution("/some/path")
  88. assert d.py_version == sys.version[:3]
  89. assert d.platform == None
  90. def testDistroParse(self):
  91. d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg")
  92. self.checkFooPkg(d)
  93. d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg-info")
  94. self.checkFooPkg(d)
  95. def testDistroMetadata(self):
  96. d = Distribution(
  97. "/some/path", project_name="FooPkg", py_version="2.4", platform="win32",
  98. metadata = Metadata(
  99. ('PKG-INFO',"Metadata-Version: 1.0\nVersion: 1.3-1\n")
  100. )
  101. )
  102. self.checkFooPkg(d)
  103. def distRequires(self, txt):
  104. return Distribution("/foo", metadata=Metadata(('depends.txt', txt)))
  105. def checkRequires(self, dist, txt, extras=()):
  106. assert list(dist.requires(extras)) == list(parse_requirements(txt))
  107. def testDistroDependsSimple(self):
  108. for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0":
  109. self.checkRequires(self.distRequires(v), v)
  110. def testResolve(self):
  111. ad = pkg_resources.Environment([])
  112. ws = WorkingSet([])
  113. # Resolving no requirements -> nothing to install
  114. assert list(ws.resolve([], ad)) == []
  115. # Request something not in the collection -> DistributionNotFound
  116. with pytest.raises(pkg_resources.DistributionNotFound):
  117. ws.resolve(parse_requirements("Foo"), ad)
  118. Foo = Distribution.from_filename(
  119. "/foo_dir/Foo-1.2.egg",
  120. metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0"))
  121. )
  122. ad.add(Foo)
  123. ad.add(Distribution.from_filename("Foo-0.9.egg"))
  124. # Request thing(s) that are available -> list to activate
  125. for i in range(3):
  126. targets = list(ws.resolve(parse_requirements("Foo"), ad))
  127. assert targets == [Foo]
  128. list(map(ws.add,targets))
  129. with pytest.raises(VersionConflict):
  130. ws.resolve(parse_requirements("Foo==0.9"), ad)
  131. ws = WorkingSet([]) # reset
  132. # Request an extra that causes an unresolved dependency for "Baz"
  133. with pytest.raises(pkg_resources.DistributionNotFound):
  134. ws.resolve(parse_requirements("Foo[bar]"), ad)
  135. Baz = Distribution.from_filename(
  136. "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))
  137. )
  138. ad.add(Baz)
  139. # Activation list now includes resolved dependency
  140. assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) ==[Foo,Baz]
  141. # Requests for conflicting versions produce VersionConflict
  142. with pytest.raises(VersionConflict) as vc:
  143. ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad)
  144. msg = 'Foo 0.9 is installed but Foo==1.2 is required'
  145. assert vc.value.report() == msg
  146. def testDistroDependsOptions(self):
  147. d = self.distRequires("""
  148. Twisted>=1.5
  149. [docgen]
  150. ZConfig>=2.0
  151. docutils>=0.3
  152. [fastcgi]
  153. fcgiapp>=0.1""")
  154. self.checkRequires(d,"Twisted>=1.5")
  155. self.checkRequires(
  156. d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"]
  157. )
  158. self.checkRequires(
  159. d,"Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"]
  160. )
  161. self.checkRequires(
  162. d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(),
  163. ["docgen","fastcgi"]
  164. )
  165. self.checkRequires(
  166. d,"Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(),
  167. ["fastcgi", "docgen"]
  168. )
  169. with pytest.raises(pkg_resources.UnknownExtra):
  170. d.requires(["foo"])
  171. class TestWorkingSet:
  172. def test_find_conflicting(self):
  173. ws = WorkingSet([])
  174. Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg")
  175. ws.add(Foo)
  176. # create a requirement that conflicts with Foo 1.2
  177. req = next(parse_requirements("Foo<1.2"))
  178. with pytest.raises(VersionConflict) as vc:
  179. ws.find(req)
  180. msg = 'Foo 1.2 is installed but Foo<1.2 is required'
  181. assert vc.value.report() == msg
  182. def test_resolve_conflicts_with_prior(self):
  183. """
  184. A ContextualVersionConflict should be raised when a requirement
  185. conflicts with a prior requirement for a different package.
  186. """
  187. # Create installation where Foo depends on Baz 1.0 and Bar depends on
  188. # Baz 2.0.
  189. ws = WorkingSet([])
  190. md = Metadata(('depends.txt', "Baz==1.0"))
  191. Foo = Distribution.from_filename("/foo_dir/Foo-1.0.egg", metadata=md)
  192. ws.add(Foo)
  193. md = Metadata(('depends.txt', "Baz==2.0"))
  194. Bar = Distribution.from_filename("/foo_dir/Bar-1.0.egg", metadata=md)
  195. ws.add(Bar)
  196. Baz = Distribution.from_filename("/foo_dir/Baz-1.0.egg")
  197. ws.add(Baz)
  198. Baz = Distribution.from_filename("/foo_dir/Baz-2.0.egg")
  199. ws.add(Baz)
  200. with pytest.raises(VersionConflict) as vc:
  201. ws.resolve(parse_requirements("Foo\nBar\n"))
  202. msg = "Baz 1.0 is installed but Baz==2.0 is required by {'Bar'}"
  203. if pkg_resources.PY2:
  204. msg = msg.replace("{'Bar'}", "set(['Bar'])")
  205. assert vc.value.report() == msg
  206. class TestEntryPoints:
  207. def assertfields(self, ep):
  208. assert ep.name == "foo"
  209. assert ep.module_name == "pkg_resources.tests.test_resources"
  210. assert ep.attrs == ("TestEntryPoints",)
  211. assert ep.extras == ("x",)
  212. assert ep.load() is TestEntryPoints
  213. expect = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
  214. assert str(ep) == expect
  215. def setup_method(self, method):
  216. self.dist = Distribution.from_filename(
  217. "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt','[x]')))
  218. def testBasics(self):
  219. ep = EntryPoint(
  220. "foo", "pkg_resources.tests.test_resources", ["TestEntryPoints"],
  221. ["x"], self.dist
  222. )
  223. self.assertfields(ep)
  224. def testParse(self):
  225. s = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
  226. ep = EntryPoint.parse(s, self.dist)
  227. self.assertfields(ep)
  228. ep = EntryPoint.parse("bar baz= spammity[PING]")
  229. assert ep.name == "bar baz"
  230. assert ep.module_name == "spammity"
  231. assert ep.attrs == ()
  232. assert ep.extras == ("ping",)
  233. ep = EntryPoint.parse(" fizzly = wocka:foo")
  234. assert ep.name == "fizzly"
  235. assert ep.module_name == "wocka"
  236. assert ep.attrs == ("foo",)
  237. assert ep.extras == ()
  238. # plus in the name
  239. spec = "html+mako = mako.ext.pygmentplugin:MakoHtmlLexer"
  240. ep = EntryPoint.parse(spec)
  241. assert ep.name == 'html+mako'
  242. reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2"
  243. @pytest.mark.parametrize("reject_spec", reject_specs)
  244. def test_reject_spec(self, reject_spec):
  245. with pytest.raises(ValueError):
  246. EntryPoint.parse(reject_spec)
  247. def test_printable_name(self):
  248. """
  249. Allow any printable character in the name.
  250. """
  251. # Create a name with all printable characters; strip the whitespace.
  252. name = string.printable.strip()
  253. spec = "{name} = module:attr".format(**locals())
  254. ep = EntryPoint.parse(spec)
  255. assert ep.name == name
  256. def checkSubMap(self, m):
  257. assert len(m) == len(self.submap_expect)
  258. for key, ep in pkg_resources.iteritems(self.submap_expect):
  259. assert repr(m.get(key)) == repr(ep)
  260. submap_expect = dict(
  261. feature1=EntryPoint('feature1', 'somemodule', ['somefunction']),
  262. feature2=EntryPoint('feature2', 'another.module', ['SomeClass'], ['extra1','extra2']),
  263. feature3=EntryPoint('feature3', 'this.module', extras=['something'])
  264. )
  265. submap_str = """
  266. # define features for blah blah
  267. feature1 = somemodule:somefunction
  268. feature2 = another.module:SomeClass [extra1,extra2]
  269. feature3 = this.module [something]
  270. """
  271. def testParseList(self):
  272. self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str))
  273. with pytest.raises(ValueError):
  274. EntryPoint.parse_group("x a", "foo=bar")
  275. with pytest.raises(ValueError):
  276. EntryPoint.parse_group("x", ["foo=baz", "foo=bar"])
  277. def testParseMap(self):
  278. m = EntryPoint.parse_map({'xyz':self.submap_str})
  279. self.checkSubMap(m['xyz'])
  280. assert list(m.keys()) == ['xyz']
  281. m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
  282. self.checkSubMap(m['xyz'])
  283. assert list(m.keys()) == ['xyz']
  284. with pytest.raises(ValueError):
  285. EntryPoint.parse_map(["[xyz]", "[xyz]"])
  286. with pytest.raises(ValueError):
  287. EntryPoint.parse_map(self.submap_str)
  288. class TestRequirements:
  289. def testBasics(self):
  290. r = Requirement.parse("Twisted>=1.2")
  291. assert str(r) == "Twisted>=1.2"
  292. assert repr(r) == "Requirement.parse('Twisted>=1.2')"
  293. assert r == Requirement("Twisted", [('>=','1.2')], ())
  294. assert r == Requirement("twisTed", [('>=','1.2')], ())
  295. assert r != Requirement("Twisted", [('>=','2.0')], ())
  296. assert r != Requirement("Zope", [('>=','1.2')], ())
  297. assert r != Requirement("Zope", [('>=','3.0')], ())
  298. assert r != Requirement.parse("Twisted[extras]>=1.2")
  299. def testOrdering(self):
  300. r1 = Requirement("Twisted", [('==','1.2c1'),('>=','1.2')], ())
  301. r2 = Requirement("Twisted", [('>=','1.2'),('==','1.2c1')], ())
  302. assert r1 == r2
  303. assert str(r1) == str(r2)
  304. assert str(r2) == "Twisted==1.2c1,>=1.2"
  305. def testBasicContains(self):
  306. r = Requirement("Twisted", [('>=','1.2')], ())
  307. foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg")
  308. twist11 = Distribution.from_filename("Twisted-1.1.egg")
  309. twist12 = Distribution.from_filename("Twisted-1.2.egg")
  310. assert parse_version('1.2') in r
  311. assert parse_version('1.1') not in r
  312. assert '1.2' in r
  313. assert '1.1' not in r
  314. assert foo_dist not in r
  315. assert twist11 not in r
  316. assert twist12 in r
  317. def testOptionsAndHashing(self):
  318. r1 = Requirement.parse("Twisted[foo,bar]>=1.2")
  319. r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")
  320. assert r1 == r2
  321. assert r1.extras == ("foo","bar")
  322. assert r2.extras == ("bar","foo") # extras are normalized
  323. assert hash(r1) == hash(r2)
  324. assert (
  325. hash(r1)
  326. ==
  327. hash((
  328. "twisted",
  329. packaging.specifiers.SpecifierSet(">=1.2"),
  330. frozenset(["foo","bar"]),
  331. ))
  332. )
  333. def testVersionEquality(self):
  334. r1 = Requirement.parse("foo==0.3a2")
  335. r2 = Requirement.parse("foo!=0.3a4")
  336. d = Distribution.from_filename
  337. assert d("foo-0.3a4.egg") not in r1
  338. assert d("foo-0.3a1.egg") not in r1
  339. assert d("foo-0.3a4.egg") not in r2
  340. assert d("foo-0.3a2.egg") in r1
  341. assert d("foo-0.3a2.egg") in r2
  342. assert d("foo-0.3a3.egg") in r2
  343. assert d("foo-0.3a5.egg") in r2
  344. def testSetuptoolsProjectName(self):
  345. """
  346. The setuptools project should implement the setuptools package.
  347. """
  348. assert (
  349. Requirement.parse('setuptools').project_name == 'setuptools')
  350. # setuptools 0.7 and higher means setuptools.
  351. assert (
  352. Requirement.parse('setuptools == 0.7').project_name == 'setuptools')
  353. assert (
  354. Requirement.parse('setuptools == 0.7a1').project_name == 'setuptools')
  355. assert (
  356. Requirement.parse('setuptools >= 0.7').project_name == 'setuptools')
  357. class TestParsing:
  358. def testEmptyParse(self):
  359. assert list(parse_requirements('')) == []
  360. def testYielding(self):
  361. for inp,out in [
  362. ([], []), ('x',['x']), ([[]],[]), (' x\n y', ['x','y']),
  363. (['x\n\n','y'], ['x','y']),
  364. ]:
  365. assert list(pkg_resources.yield_lines(inp)) == out
  366. def testSplitting(self):
  367. sample = """
  368. x
  369. [Y]
  370. z
  371. a
  372. [b ]
  373. # foo
  374. c
  375. [ d]
  376. [q]
  377. v
  378. """
  379. assert (
  380. list(pkg_resources.split_sections(sample))
  381. ==
  382. [
  383. (None, ["x"]),
  384. ("Y", ["z", "a"]),
  385. ("b", ["c"]),
  386. ("d", []),
  387. ("q", ["v"]),
  388. ]
  389. )
  390. with pytest.raises(ValueError):
  391. list(pkg_resources.split_sections("[foo"))
  392. def testSafeName(self):
  393. assert safe_name("adns-python") == "adns-python"
  394. assert safe_name("WSGI Utils") == "WSGI-Utils"
  395. assert safe_name("WSGI Utils") == "WSGI-Utils"
  396. assert safe_name("Money$$$Maker") == "Money-Maker"
  397. assert safe_name("peak.web") != "peak-web"
  398. def testSafeVersion(self):
  399. assert safe_version("1.2-1") == "1.2.post1"
  400. assert safe_version("1.2 alpha") == "1.2.alpha"
  401. assert safe_version("2.3.4 20050521") == "2.3.4.20050521"
  402. assert safe_version("Money$$$Maker") == "Money-Maker"
  403. assert safe_version("peak.web") == "peak.web"
  404. def testSimpleRequirements(self):
  405. assert (
  406. list(parse_requirements('Twis-Ted>=1.2-1'))
  407. ==
  408. [Requirement('Twis-Ted',[('>=','1.2-1')], ())]
  409. )
  410. assert (
  411. list(parse_requirements('Twisted >=1.2, \ # more\n<2.0'))
  412. ==
  413. [Requirement('Twisted',[('>=','1.2'),('<','2.0')], ())]
  414. )
  415. assert (
  416. Requirement.parse("FooBar==1.99a3")
  417. ==
  418. Requirement("FooBar", [('==','1.99a3')], ())
  419. )
  420. with pytest.raises(ValueError):
  421. Requirement.parse(">=2.3")
  422. with pytest.raises(ValueError):
  423. Requirement.parse("x\\")
  424. with pytest.raises(ValueError):
  425. Requirement.parse("x==2 q")
  426. with pytest.raises(ValueError):
  427. Requirement.parse("X==1\nY==2")
  428. with pytest.raises(ValueError):
  429. Requirement.parse("#")
  430. def testVersionEquality(self):
  431. def c(s1,s2):
  432. p1, p2 = parse_version(s1),parse_version(s2)
  433. assert p1 == p2, (s1,s2,p1,p2)
  434. c('1.2-rc1', '1.2rc1')
  435. c('0.4', '0.4.0')
  436. c('0.4.0.0', '0.4.0')
  437. c('0.4.0-0', '0.4-0')
  438. c('0post1', '0.0post1')
  439. c('0pre1', '0.0c1')
  440. c('0.0.0preview1', '0c1')
  441. c('0.0c1', '0-rc1')
  442. c('1.2a1', '1.2.a.1')
  443. c('1.2.a', '1.2a')
  444. def testVersionOrdering(self):
  445. def c(s1,s2):
  446. p1, p2 = parse_version(s1),parse_version(s2)
  447. assert p1<p2, (s1,s2,p1,p2)
  448. c('2.1','2.1.1')
  449. c('2a1','2b0')
  450. c('2a1','2.1')
  451. c('2.3a1', '2.3')
  452. c('2.1-1', '2.1-2')
  453. c('2.1-1', '2.1.1')
  454. c('2.1', '2.1post4')
  455. c('2.1a0-20040501', '2.1')
  456. c('1.1', '02.1')
  457. c('3.2', '3.2.post0')
  458. c('3.2post1', '3.2post2')
  459. c('0.4', '4.0')
  460. c('0.0.4', '0.4.0')
  461. c('0post1', '0.4post1')
  462. c('2.1.0-rc1','2.1.0')
  463. c('2.1dev','2.1a0')
  464. torture ="""
  465. 0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1
  466. 0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2
  467. 0.77.2-1 0.77.1-1 0.77.0-1
  468. """.split()
  469. for p,v1 in enumerate(torture):
  470. for v2 in torture[p+1:]:
  471. c(v2,v1)
  472. def testVersionBuildout(self):
  473. """
  474. Buildout has a function in it's bootstrap.py that inspected the return
  475. value of parse_version. The new parse_version returns a Version class
  476. which needs to support this behavior, at least for now.
  477. """
  478. def buildout(parsed_version):
  479. _final_parts = '*final-', '*final'
  480. def _final_version(parsed_version):
  481. for part in parsed_version:
  482. if (part[:1] == '*') and (part not in _final_parts):
  483. return False
  484. return True
  485. return _final_version(parsed_version)
  486. assert buildout(parse_version("1.0"))
  487. assert not buildout(parse_version("1.0a1"))
  488. def testVersionIndexable(self):
  489. """
  490. Some projects were doing things like parse_version("v")[0], so we'll
  491. support indexing the same as we support iterating.
  492. """
  493. assert parse_version("1.0")[0] == "00000001"
  494. def testVersionTupleSort(self):
  495. """
  496. Some projects expected to be able to sort tuples against the return
  497. value of parse_version. So again we'll add a warning enabled shim to
  498. make this possible.
  499. """
  500. assert parse_version("1.0") < tuple(parse_version("2.0"))
  501. assert parse_version("1.0") <= tuple(parse_version("2.0"))
  502. assert parse_version("1.0") == tuple(parse_version("1.0"))
  503. assert parse_version("3.0") > tuple(parse_version("2.0"))
  504. assert parse_version("3.0") >= tuple(parse_version("2.0"))
  505. assert parse_version("3.0") != tuple(parse_version("2.0"))
  506. assert not (parse_version("3.0") != tuple(parse_version("3.0")))
  507. def testVersionHashable(self):
  508. """
  509. Ensure that our versions stay hashable even though we've subclassed
  510. them and added some shim code to them.
  511. """
  512. assert (
  513. hash(parse_version("1.0"))
  514. ==
  515. hash(parse_version("1.0"))
  516. )
  517. class TestNamespaces:
  518. def setup_method(self, method):
  519. self._ns_pkgs = pkg_resources._namespace_packages.copy()
  520. self._tmpdir = tempfile.mkdtemp(prefix="tests-setuptools-")
  521. os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
  522. self._prev_sys_path = sys.path[:]
  523. sys.path.append(os.path.join(self._tmpdir, "site-pkgs"))
  524. def teardown_method(self, method):
  525. shutil.rmtree(self._tmpdir)
  526. pkg_resources._namespace_packages = self._ns_pkgs.copy()
  527. sys.path = self._prev_sys_path[:]
  528. @pytest.mark.skipif(os.path.islink(tempfile.gettempdir()),
  529. reason="Test fails when /tmp is a symlink. See #231")
  530. def test_two_levels_deep(self):
  531. """
  532. Test nested namespace packages
  533. Create namespace packages in the following tree :
  534. site-packages-1/pkg1/pkg2
  535. site-packages-2/pkg1/pkg2
  536. Check both are in the _namespace_packages dict and that their __path__
  537. is correct
  538. """
  539. sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
  540. os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
  541. os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
  542. ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
  543. for site in ["site-pkgs", "site-pkgs2"]:
  544. pkg1_init = open(os.path.join(self._tmpdir, site,
  545. "pkg1", "__init__.py"), "w")
  546. pkg1_init.write(ns_str)
  547. pkg1_init.close()
  548. pkg2_init = open(os.path.join(self._tmpdir, site,
  549. "pkg1", "pkg2", "__init__.py"), "w")
  550. pkg2_init.write(ns_str)
  551. pkg2_init.close()
  552. import pkg1
  553. assert "pkg1" in pkg_resources._namespace_packages
  554. # attempt to import pkg2 from site-pkgs2
  555. import pkg1.pkg2
  556. # check the _namespace_packages dict
  557. assert "pkg1.pkg2" in pkg_resources._namespace_packages
  558. assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
  559. # check the __path__ attribute contains both paths
  560. expected = [
  561. os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
  562. os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"),
  563. ]
  564. assert pkg1.pkg2.__path__ == expected