test_resources.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. from __future__ import unicode_literals
  2. import os
  3. import sys
  4. import string
  5. from pkg_resources.extern.six.moves import map
  6. import pytest
  7. from pkg_resources.extern import packaging
  8. import pkg_resources
  9. from pkg_resources import (parse_requirements, VersionConflict, parse_version,
  10. Distribution, EntryPoint, Requirement, safe_version, safe_name,
  11. WorkingSet)
  12. class Metadata(pkg_resources.EmptyProvider):
  13. """Mock object to return metadata as if from an on-disk distribution"""
  14. def __init__(self, *pairs):
  15. self.metadata = dict(pairs)
  16. def has_metadata(self, name):
  17. return name in self.metadata
  18. def get_metadata(self, name):
  19. return self.metadata[name]
  20. def get_metadata_lines(self, name):
  21. return pkg_resources.yield_lines(self.get_metadata(name))
  22. dist_from_fn = pkg_resources.Distribution.from_filename
  23. class TestDistro:
  24. def testCollection(self):
  25. # empty path should produce no distributions
  26. ad = pkg_resources.Environment([], platform=None, python=None)
  27. assert list(ad) == []
  28. assert ad['FooPkg'] == []
  29. ad.add(dist_from_fn("FooPkg-1.3_1.egg"))
  30. ad.add(dist_from_fn("FooPkg-1.4-py2.4-win32.egg"))
  31. ad.add(dist_from_fn("FooPkg-1.2-py2.4.egg"))
  32. # Name is in there now
  33. assert ad['FooPkg']
  34. # But only 1 package
  35. assert list(ad) == ['foopkg']
  36. # Distributions sort by version
  37. assert [dist.version for dist in ad['FooPkg']] == ['1.4','1.3-1','1.2']
  38. # Removing a distribution leaves sequence alone
  39. ad.remove(ad['FooPkg'][1])
  40. assert [dist.version for dist in ad['FooPkg']] == ['1.4','1.2']
  41. # And inserting adds them in order
  42. ad.add(dist_from_fn("FooPkg-1.9.egg"))
  43. assert [dist.version for dist in ad['FooPkg']] == ['1.9','1.4','1.2']
  44. ws = WorkingSet([])
  45. foo12 = dist_from_fn("FooPkg-1.2-py2.4.egg")
  46. foo14 = dist_from_fn("FooPkg-1.4-py2.4-win32.egg")
  47. req, = parse_requirements("FooPkg>=1.3")
  48. # Nominal case: no distros on path, should yield all applicable
  49. assert ad.best_match(req, ws).version == '1.9'
  50. # If a matching distro is already installed, should return only that
  51. ws.add(foo14)
  52. assert ad.best_match(req, ws).version == '1.4'
  53. # If the first matching distro is unsuitable, it's a version conflict
  54. ws = WorkingSet([])
  55. ws.add(foo12)
  56. ws.add(foo14)
  57. with pytest.raises(VersionConflict):
  58. ad.best_match(req, ws)
  59. # If more than one match on the path, the first one takes precedence
  60. ws = WorkingSet([])
  61. ws.add(foo14)
  62. ws.add(foo12)
  63. ws.add(foo14)
  64. assert ad.best_match(req, ws).version == '1.4'
  65. def checkFooPkg(self,d):
  66. assert d.project_name == "FooPkg"
  67. assert d.key == "foopkg"
  68. assert d.version == "1.3.post1"
  69. assert d.py_version == "2.4"
  70. assert d.platform == "win32"
  71. assert d.parsed_version == parse_version("1.3-1")
  72. def testDistroBasics(self):
  73. d = Distribution(
  74. "/some/path",
  75. project_name="FooPkg",version="1.3-1",py_version="2.4",platform="win32"
  76. )
  77. self.checkFooPkg(d)
  78. d = Distribution("/some/path")
  79. assert d.py_version == sys.version[:3]
  80. assert d.platform == None
  81. def testDistroParse(self):
  82. d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg")
  83. self.checkFooPkg(d)
  84. d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg-info")
  85. self.checkFooPkg(d)
  86. def testDistroMetadata(self):
  87. d = Distribution(
  88. "/some/path", project_name="FooPkg", py_version="2.4", platform="win32",
  89. metadata = Metadata(
  90. ('PKG-INFO',"Metadata-Version: 1.0\nVersion: 1.3-1\n")
  91. )
  92. )
  93. self.checkFooPkg(d)
  94. def distRequires(self, txt):
  95. return Distribution("/foo", metadata=Metadata(('depends.txt', txt)))
  96. def checkRequires(self, dist, txt, extras=()):
  97. assert list(dist.requires(extras)) == list(parse_requirements(txt))
  98. def testDistroDependsSimple(self):
  99. for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0":
  100. self.checkRequires(self.distRequires(v), v)
  101. def testResolve(self):
  102. ad = pkg_resources.Environment([])
  103. ws = WorkingSet([])
  104. # Resolving no requirements -> nothing to install
  105. assert list(ws.resolve([], ad)) == []
  106. # Request something not in the collection -> DistributionNotFound
  107. with pytest.raises(pkg_resources.DistributionNotFound):
  108. ws.resolve(parse_requirements("Foo"), ad)
  109. Foo = Distribution.from_filename(
  110. "/foo_dir/Foo-1.2.egg",
  111. metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0"))
  112. )
  113. ad.add(Foo)
  114. ad.add(Distribution.from_filename("Foo-0.9.egg"))
  115. # Request thing(s) that are available -> list to activate
  116. for i in range(3):
  117. targets = list(ws.resolve(parse_requirements("Foo"), ad))
  118. assert targets == [Foo]
  119. list(map(ws.add, targets))
  120. with pytest.raises(VersionConflict):
  121. ws.resolve(parse_requirements("Foo==0.9"), ad)
  122. ws = WorkingSet([]) # reset
  123. # Request an extra that causes an unresolved dependency for "Baz"
  124. with pytest.raises(pkg_resources.DistributionNotFound):
  125. ws.resolve(parse_requirements("Foo[bar]"), ad)
  126. Baz = Distribution.from_filename(
  127. "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))
  128. )
  129. ad.add(Baz)
  130. # Activation list now includes resolved dependency
  131. assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) ==[Foo,Baz]
  132. # Requests for conflicting versions produce VersionConflict
  133. with pytest.raises(VersionConflict) as vc:
  134. ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad)
  135. msg = 'Foo 0.9 is installed but Foo==1.2 is required'
  136. assert vc.value.report() == msg
  137. def test_environment_marker_evaluation_negative(self):
  138. """Environment markers are evaluated at resolution time."""
  139. ad = pkg_resources.Environment([])
  140. ws = WorkingSet([])
  141. res = ws.resolve(parse_requirements("Foo;python_version<'2'"), ad)
  142. assert list(res) == []
  143. def test_environment_marker_evaluation_positive(self):
  144. ad = pkg_resources.Environment([])
  145. ws = WorkingSet([])
  146. Foo = Distribution.from_filename("/foo_dir/Foo-1.2.dist-info")
  147. ad.add(Foo)
  148. res = ws.resolve(parse_requirements("Foo;python_version>='2'"), ad)
  149. assert list(res) == [Foo]
  150. def test_environment_marker_evaluation_called(self):
  151. """
  152. If one package foo requires bar without any extras,
  153. markers should pass for bar without extras.
  154. """
  155. parent_req, = parse_requirements("foo")
  156. req, = parse_requirements("bar;python_version>='2'")
  157. req_extras = pkg_resources._ReqExtras({req: parent_req.extras})
  158. assert req_extras.markers_pass(req)
  159. parent_req, = parse_requirements("foo[]")
  160. req, = parse_requirements("bar;python_version>='2'")
  161. req_extras = pkg_resources._ReqExtras({req: parent_req.extras})
  162. assert req_extras.markers_pass(req)
  163. def test_marker_evaluation_with_extras(self):
  164. """Extras are also evaluated as markers at resolution time."""
  165. ad = pkg_resources.Environment([])
  166. ws = WorkingSet([])
  167. # Metadata needs to be native strings due to cStringIO behaviour in
  168. # 2.6, so use str().
  169. Foo = Distribution.from_filename(
  170. "/foo_dir/Foo-1.2.dist-info",
  171. metadata=Metadata(("METADATA", str("Provides-Extra: baz\n"
  172. "Requires-Dist: quux; extra=='baz'")))
  173. )
  174. ad.add(Foo)
  175. assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo]
  176. quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")
  177. ad.add(quux)
  178. res = list(ws.resolve(parse_requirements("Foo[baz]"), ad))
  179. assert res == [Foo,quux]
  180. def test_marker_evaluation_with_multiple_extras(self):
  181. ad = pkg_resources.Environment([])
  182. ws = WorkingSet([])
  183. # Metadata needs to be native strings due to cStringIO behaviour in
  184. # 2.6, so use str().
  185. Foo = Distribution.from_filename(
  186. "/foo_dir/Foo-1.2.dist-info",
  187. metadata=Metadata(("METADATA", str("Provides-Extra: baz\n"
  188. "Requires-Dist: quux; extra=='baz'\n"
  189. "Provides-Extra: bar\n"
  190. "Requires-Dist: fred; extra=='bar'\n")))
  191. )
  192. ad.add(Foo)
  193. quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")
  194. ad.add(quux)
  195. fred = Distribution.from_filename("/foo_dir/fred-0.1.dist-info")
  196. ad.add(fred)
  197. res = list(ws.resolve(parse_requirements("Foo[baz,bar]"), ad))
  198. assert sorted(res) == [fred,quux,Foo]
  199. def test_marker_evaluation_with_extras_loop(self):
  200. ad = pkg_resources.Environment([])
  201. ws = WorkingSet([])
  202. # Metadata needs to be native strings due to cStringIO behaviour in
  203. # 2.6, so use str().
  204. a = Distribution.from_filename(
  205. "/foo_dir/a-0.2.dist-info",
  206. metadata=Metadata(("METADATA", str("Requires-Dist: c[a]")))
  207. )
  208. b = Distribution.from_filename(
  209. "/foo_dir/b-0.3.dist-info",
  210. metadata=Metadata(("METADATA", str("Requires-Dist: c[b]")))
  211. )
  212. c = Distribution.from_filename(
  213. "/foo_dir/c-1.0.dist-info",
  214. metadata=Metadata(("METADATA", str("Provides-Extra: a\n"
  215. "Requires-Dist: b;extra=='a'\n"
  216. "Provides-Extra: b\n"
  217. "Requires-Dist: foo;extra=='b'")))
  218. )
  219. foo = Distribution.from_filename("/foo_dir/foo-0.1.dist-info")
  220. for dist in (a, b, c, foo):
  221. ad.add(dist)
  222. res = list(ws.resolve(parse_requirements("a"), ad))
  223. assert res == [a, c, b, foo]
  224. def testDistroDependsOptions(self):
  225. d = self.distRequires("""
  226. Twisted>=1.5
  227. [docgen]
  228. ZConfig>=2.0
  229. docutils>=0.3
  230. [fastcgi]
  231. fcgiapp>=0.1""")
  232. self.checkRequires(d,"Twisted>=1.5")
  233. self.checkRequires(
  234. d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"]
  235. )
  236. self.checkRequires(
  237. d,"Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"]
  238. )
  239. self.checkRequires(
  240. d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(),
  241. ["docgen","fastcgi"]
  242. )
  243. self.checkRequires(
  244. d,"Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(),
  245. ["fastcgi", "docgen"]
  246. )
  247. with pytest.raises(pkg_resources.UnknownExtra):
  248. d.requires(["foo"])
  249. class TestWorkingSet:
  250. def test_find_conflicting(self):
  251. ws = WorkingSet([])
  252. Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg")
  253. ws.add(Foo)
  254. # create a requirement that conflicts with Foo 1.2
  255. req = next(parse_requirements("Foo<1.2"))
  256. with pytest.raises(VersionConflict) as vc:
  257. ws.find(req)
  258. msg = 'Foo 1.2 is installed but Foo<1.2 is required'
  259. assert vc.value.report() == msg
  260. def test_resolve_conflicts_with_prior(self):
  261. """
  262. A ContextualVersionConflict should be raised when a requirement
  263. conflicts with a prior requirement for a different package.
  264. """
  265. # Create installation where Foo depends on Baz 1.0 and Bar depends on
  266. # Baz 2.0.
  267. ws = WorkingSet([])
  268. md = Metadata(('depends.txt', "Baz==1.0"))
  269. Foo = Distribution.from_filename("/foo_dir/Foo-1.0.egg", metadata=md)
  270. ws.add(Foo)
  271. md = Metadata(('depends.txt', "Baz==2.0"))
  272. Bar = Distribution.from_filename("/foo_dir/Bar-1.0.egg", metadata=md)
  273. ws.add(Bar)
  274. Baz = Distribution.from_filename("/foo_dir/Baz-1.0.egg")
  275. ws.add(Baz)
  276. Baz = Distribution.from_filename("/foo_dir/Baz-2.0.egg")
  277. ws.add(Baz)
  278. with pytest.raises(VersionConflict) as vc:
  279. ws.resolve(parse_requirements("Foo\nBar\n"))
  280. msg = "Baz 1.0 is installed but Baz==2.0 is required by "
  281. msg += repr(set(['Bar']))
  282. assert vc.value.report() == msg
  283. class TestEntryPoints:
  284. def assertfields(self, ep):
  285. assert ep.name == "foo"
  286. assert ep.module_name == "pkg_resources.tests.test_resources"
  287. assert ep.attrs == ("TestEntryPoints",)
  288. assert ep.extras == ("x",)
  289. assert ep.load() is TestEntryPoints
  290. expect = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
  291. assert str(ep) == expect
  292. def setup_method(self, method):
  293. self.dist = Distribution.from_filename(
  294. "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt','[x]')))
  295. def testBasics(self):
  296. ep = EntryPoint(
  297. "foo", "pkg_resources.tests.test_resources", ["TestEntryPoints"],
  298. ["x"], self.dist
  299. )
  300. self.assertfields(ep)
  301. def testParse(self):
  302. s = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"
  303. ep = EntryPoint.parse(s, self.dist)
  304. self.assertfields(ep)
  305. ep = EntryPoint.parse("bar baz= spammity[PING]")
  306. assert ep.name == "bar baz"
  307. assert ep.module_name == "spammity"
  308. assert ep.attrs == ()
  309. assert ep.extras == ("ping",)
  310. ep = EntryPoint.parse(" fizzly = wocka:foo")
  311. assert ep.name == "fizzly"
  312. assert ep.module_name == "wocka"
  313. assert ep.attrs == ("foo",)
  314. assert ep.extras == ()
  315. # plus in the name
  316. spec = "html+mako = mako.ext.pygmentplugin:MakoHtmlLexer"
  317. ep = EntryPoint.parse(spec)
  318. assert ep.name == 'html+mako'
  319. reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2"
  320. @pytest.mark.parametrize("reject_spec", reject_specs)
  321. def test_reject_spec(self, reject_spec):
  322. with pytest.raises(ValueError):
  323. EntryPoint.parse(reject_spec)
  324. def test_printable_name(self):
  325. """
  326. Allow any printable character in the name.
  327. """
  328. # Create a name with all printable characters; strip the whitespace.
  329. name = string.printable.strip()
  330. spec = "{name} = module:attr".format(**locals())
  331. ep = EntryPoint.parse(spec)
  332. assert ep.name == name
  333. def checkSubMap(self, m):
  334. assert len(m) == len(self.submap_expect)
  335. for key, ep in self.submap_expect.items():
  336. assert m.get(key).name == ep.name
  337. assert m.get(key).module_name == ep.module_name
  338. assert sorted(m.get(key).attrs) == sorted(ep.attrs)
  339. assert sorted(m.get(key).extras) == sorted(ep.extras)
  340. submap_expect = dict(
  341. feature1=EntryPoint('feature1', 'somemodule', ['somefunction']),
  342. feature2=EntryPoint('feature2', 'another.module', ['SomeClass'], ['extra1','extra2']),
  343. feature3=EntryPoint('feature3', 'this.module', extras=['something'])
  344. )
  345. submap_str = """
  346. # define features for blah blah
  347. feature1 = somemodule:somefunction
  348. feature2 = another.module:SomeClass [extra1,extra2]
  349. feature3 = this.module [something]
  350. """
  351. def testParseList(self):
  352. self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str))
  353. with pytest.raises(ValueError):
  354. EntryPoint.parse_group("x a", "foo=bar")
  355. with pytest.raises(ValueError):
  356. EntryPoint.parse_group("x", ["foo=baz", "foo=bar"])
  357. def testParseMap(self):
  358. m = EntryPoint.parse_map({'xyz':self.submap_str})
  359. self.checkSubMap(m['xyz'])
  360. assert list(m.keys()) == ['xyz']
  361. m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
  362. self.checkSubMap(m['xyz'])
  363. assert list(m.keys()) == ['xyz']
  364. with pytest.raises(ValueError):
  365. EntryPoint.parse_map(["[xyz]", "[xyz]"])
  366. with pytest.raises(ValueError):
  367. EntryPoint.parse_map(self.submap_str)
  368. class TestRequirements:
  369. def testBasics(self):
  370. r = Requirement.parse("Twisted>=1.2")
  371. assert str(r) == "Twisted>=1.2"
  372. assert repr(r) == "Requirement.parse('Twisted>=1.2')"
  373. assert r == Requirement("Twisted>=1.2")
  374. assert r == Requirement("twisTed>=1.2")
  375. assert r != Requirement("Twisted>=2.0")
  376. assert r != Requirement("Zope>=1.2")
  377. assert r != Requirement("Zope>=3.0")
  378. assert r != Requirement("Twisted[extras]>=1.2")
  379. def testOrdering(self):
  380. r1 = Requirement("Twisted==1.2c1,>=1.2")
  381. r2 = Requirement("Twisted>=1.2,==1.2c1")
  382. assert r1 == r2
  383. assert str(r1) == str(r2)
  384. assert str(r2) == "Twisted==1.2c1,>=1.2"
  385. def testBasicContains(self):
  386. r = Requirement("Twisted>=1.2")
  387. foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg")
  388. twist11 = Distribution.from_filename("Twisted-1.1.egg")
  389. twist12 = Distribution.from_filename("Twisted-1.2.egg")
  390. assert parse_version('1.2') in r
  391. assert parse_version('1.1') not in r
  392. assert '1.2' in r
  393. assert '1.1' not in r
  394. assert foo_dist not in r
  395. assert twist11 not in r
  396. assert twist12 in r
  397. def testOptionsAndHashing(self):
  398. r1 = Requirement.parse("Twisted[foo,bar]>=1.2")
  399. r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")
  400. assert r1 == r2
  401. assert set(r1.extras) == set(("foo", "bar"))
  402. assert set(r2.extras) == set(("foo", "bar"))
  403. assert hash(r1) == hash(r2)
  404. assert (
  405. hash(r1)
  406. ==
  407. hash((
  408. "twisted",
  409. packaging.specifiers.SpecifierSet(">=1.2"),
  410. frozenset(["foo","bar"]),
  411. None
  412. ))
  413. )
  414. def testVersionEquality(self):
  415. r1 = Requirement.parse("foo==0.3a2")
  416. r2 = Requirement.parse("foo!=0.3a4")
  417. d = Distribution.from_filename
  418. assert d("foo-0.3a4.egg") not in r1
  419. assert d("foo-0.3a1.egg") not in r1
  420. assert d("foo-0.3a4.egg") not in r2
  421. assert d("foo-0.3a2.egg") in r1
  422. assert d("foo-0.3a2.egg") in r2
  423. assert d("foo-0.3a3.egg") in r2
  424. assert d("foo-0.3a5.egg") in r2
  425. def testSetuptoolsProjectName(self):
  426. """
  427. The setuptools project should implement the setuptools package.
  428. """
  429. assert (
  430. Requirement.parse('setuptools').project_name == 'setuptools')
  431. # setuptools 0.7 and higher means setuptools.
  432. assert (
  433. Requirement.parse('setuptools == 0.7').project_name == 'setuptools')
  434. assert (
  435. Requirement.parse('setuptools == 0.7a1').project_name == 'setuptools')
  436. assert (
  437. Requirement.parse('setuptools >= 0.7').project_name == 'setuptools')
  438. class TestParsing:
  439. def testEmptyParse(self):
  440. assert list(parse_requirements('')) == []
  441. def testYielding(self):
  442. for inp,out in [
  443. ([], []), ('x',['x']), ([[]],[]), (' x\n y', ['x','y']),
  444. (['x\n\n','y'], ['x','y']),
  445. ]:
  446. assert list(pkg_resources.yield_lines(inp)) == out
  447. def testSplitting(self):
  448. sample = """
  449. x
  450. [Y]
  451. z
  452. a
  453. [b ]
  454. # foo
  455. c
  456. [ d]
  457. [q]
  458. v
  459. """
  460. assert (
  461. list(pkg_resources.split_sections(sample))
  462. ==
  463. [
  464. (None, ["x"]),
  465. ("Y", ["z", "a"]),
  466. ("b", ["c"]),
  467. ("d", []),
  468. ("q", ["v"]),
  469. ]
  470. )
  471. with pytest.raises(ValueError):
  472. list(pkg_resources.split_sections("[foo"))
  473. def testSafeName(self):
  474. assert safe_name("adns-python") == "adns-python"
  475. assert safe_name("WSGI Utils") == "WSGI-Utils"
  476. assert safe_name("WSGI Utils") == "WSGI-Utils"
  477. assert safe_name("Money$$$Maker") == "Money-Maker"
  478. assert safe_name("peak.web") != "peak-web"
  479. def testSafeVersion(self):
  480. assert safe_version("1.2-1") == "1.2.post1"
  481. assert safe_version("1.2 alpha") == "1.2.alpha"
  482. assert safe_version("2.3.4 20050521") == "2.3.4.20050521"
  483. assert safe_version("Money$$$Maker") == "Money-Maker"
  484. assert safe_version("peak.web") == "peak.web"
  485. def testSimpleRequirements(self):
  486. assert (
  487. list(parse_requirements('Twis-Ted>=1.2-1'))
  488. ==
  489. [Requirement('Twis-Ted>=1.2-1')]
  490. )
  491. assert (
  492. list(parse_requirements('Twisted >=1.2, \ # more\n<2.0'))
  493. ==
  494. [Requirement('Twisted>=1.2,<2.0')]
  495. )
  496. assert (
  497. Requirement.parse("FooBar==1.99a3")
  498. ==
  499. Requirement("FooBar==1.99a3")
  500. )
  501. with pytest.raises(ValueError):
  502. Requirement.parse(">=2.3")
  503. with pytest.raises(ValueError):
  504. Requirement.parse("x\\")
  505. with pytest.raises(ValueError):
  506. Requirement.parse("x==2 q")
  507. with pytest.raises(ValueError):
  508. Requirement.parse("X==1\nY==2")
  509. with pytest.raises(ValueError):
  510. Requirement.parse("#")
  511. def test_requirements_with_markers(self):
  512. assert (
  513. Requirement.parse("foobar;os_name=='a'")
  514. ==
  515. Requirement.parse("foobar;os_name=='a'")
  516. )
  517. assert (
  518. Requirement.parse("name==1.1;python_version=='2.7'")
  519. !=
  520. Requirement.parse("name==1.1;python_version=='3.3'")
  521. )
  522. assert (
  523. Requirement.parse("name==1.0;python_version=='2.7'")
  524. !=
  525. Requirement.parse("name==1.2;python_version=='2.7'")
  526. )
  527. assert (
  528. Requirement.parse("name[foo]==1.0;python_version=='3.3'")
  529. !=
  530. Requirement.parse("name[foo,bar]==1.0;python_version=='3.3'")
  531. )
  532. def test_local_version(self):
  533. req, = parse_requirements('foo==1.0.org1')
  534. def test_spaces_between_multiple_versions(self):
  535. req, = parse_requirements('foo>=1.0, <3')
  536. req, = parse_requirements('foo >= 1.0, < 3')
  537. def testVersionEquality(self):
  538. def c(s1,s2):
  539. p1, p2 = parse_version(s1),parse_version(s2)
  540. assert p1 == p2, (s1,s2,p1,p2)
  541. c('1.2-rc1', '1.2rc1')
  542. c('0.4', '0.4.0')
  543. c('0.4.0.0', '0.4.0')
  544. c('0.4.0-0', '0.4-0')
  545. c('0post1', '0.0post1')
  546. c('0pre1', '0.0c1')
  547. c('0.0.0preview1', '0c1')
  548. c('0.0c1', '0-rc1')
  549. c('1.2a1', '1.2.a.1')
  550. c('1.2.a', '1.2a')
  551. def testVersionOrdering(self):
  552. def c(s1,s2):
  553. p1, p2 = parse_version(s1),parse_version(s2)
  554. assert p1<p2, (s1,s2,p1,p2)
  555. c('2.1','2.1.1')
  556. c('2a1','2b0')
  557. c('2a1','2.1')
  558. c('2.3a1', '2.3')
  559. c('2.1-1', '2.1-2')
  560. c('2.1-1', '2.1.1')
  561. c('2.1', '2.1post4')
  562. c('2.1a0-20040501', '2.1')
  563. c('1.1', '02.1')
  564. c('3.2', '3.2.post0')
  565. c('3.2post1', '3.2post2')
  566. c('0.4', '4.0')
  567. c('0.0.4', '0.4.0')
  568. c('0post1', '0.4post1')
  569. c('2.1.0-rc1','2.1.0')
  570. c('2.1dev','2.1a0')
  571. torture ="""
  572. 0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1
  573. 0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2
  574. 0.77.2-1 0.77.1-1 0.77.0-1
  575. """.split()
  576. for p,v1 in enumerate(torture):
  577. for v2 in torture[p+1:]:
  578. c(v2,v1)
  579. def testVersionBuildout(self):
  580. """
  581. Buildout has a function in it's bootstrap.py that inspected the return
  582. value of parse_version. The new parse_version returns a Version class
  583. which needs to support this behavior, at least for now.
  584. """
  585. def buildout(parsed_version):
  586. _final_parts = '*final-', '*final'
  587. def _final_version(parsed_version):
  588. for part in parsed_version:
  589. if (part[:1] == '*') and (part not in _final_parts):
  590. return False
  591. return True
  592. return _final_version(parsed_version)
  593. assert buildout(parse_version("1.0"))
  594. assert not buildout(parse_version("1.0a1"))
  595. def testVersionIndexable(self):
  596. """
  597. Some projects were doing things like parse_version("v")[0], so we'll
  598. support indexing the same as we support iterating.
  599. """
  600. assert parse_version("1.0")[0] == "00000001"
  601. def testVersionTupleSort(self):
  602. """
  603. Some projects expected to be able to sort tuples against the return
  604. value of parse_version. So again we'll add a warning enabled shim to
  605. make this possible.
  606. """
  607. assert parse_version("1.0") < tuple(parse_version("2.0"))
  608. assert parse_version("1.0") <= tuple(parse_version("2.0"))
  609. assert parse_version("1.0") == tuple(parse_version("1.0"))
  610. assert parse_version("3.0") > tuple(parse_version("2.0"))
  611. assert parse_version("3.0") >= tuple(parse_version("2.0"))
  612. assert parse_version("3.0") != tuple(parse_version("2.0"))
  613. assert not (parse_version("3.0") != tuple(parse_version("3.0")))
  614. def testVersionHashable(self):
  615. """
  616. Ensure that our versions stay hashable even though we've subclassed
  617. them and added some shim code to them.
  618. """
  619. assert (
  620. hash(parse_version("1.0"))
  621. ==
  622. hash(parse_version("1.0"))
  623. )
  624. class TestNamespaces:
  625. ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
  626. @pytest.yield_fixture
  627. def symlinked_tmpdir(self, tmpdir):
  628. """
  629. Where available, return the tempdir as a symlink,
  630. which as revealed in #231 is more fragile than
  631. a natural tempdir.
  632. """
  633. if not hasattr(os, 'symlink'):
  634. yield str(tmpdir)
  635. return
  636. link_name = str(tmpdir) + '-linked'
  637. os.symlink(str(tmpdir), link_name)
  638. try:
  639. yield type(tmpdir)(link_name)
  640. finally:
  641. os.unlink(link_name)
  642. @pytest.yield_fixture(autouse=True)
  643. def patched_path(self, tmpdir):
  644. """
  645. Patch sys.path to include the 'site-pkgs' dir. Also
  646. restore pkg_resources._namespace_packages to its
  647. former state.
  648. """
  649. saved_ns_pkgs = pkg_resources._namespace_packages.copy()
  650. saved_sys_path = sys.path[:]
  651. site_pkgs = tmpdir.mkdir('site-pkgs')
  652. sys.path.append(str(site_pkgs))
  653. try:
  654. yield
  655. finally:
  656. pkg_resources._namespace_packages = saved_ns_pkgs
  657. sys.path = saved_sys_path
  658. def test_two_levels_deep(self, symlinked_tmpdir):
  659. """
  660. Test nested namespace packages
  661. Create namespace packages in the following tree :
  662. site-packages-1/pkg1/pkg2
  663. site-packages-2/pkg1/pkg2
  664. Check both are in the _namespace_packages dict and that their __path__
  665. is correct
  666. """
  667. real_tmpdir = symlinked_tmpdir.realpath()
  668. tmpdir = symlinked_tmpdir
  669. sys.path.append(str(tmpdir / 'site-pkgs2'))
  670. site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2'
  671. for site in site_dirs:
  672. pkg1 = site / 'pkg1'
  673. pkg2 = pkg1 / 'pkg2'
  674. pkg2.ensure_dir()
  675. (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
  676. (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8')
  677. import pkg1
  678. assert "pkg1" in pkg_resources._namespace_packages
  679. # attempt to import pkg2 from site-pkgs2
  680. import pkg1.pkg2
  681. # check the _namespace_packages dict
  682. assert "pkg1.pkg2" in pkg_resources._namespace_packages
  683. assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]
  684. # check the __path__ attribute contains both paths
  685. expected = [
  686. str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"),
  687. str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"),
  688. ]
  689. assert pkg1.pkg2.__path__ == expected
  690. def test_path_order(self, symlinked_tmpdir):
  691. """
  692. Test that if multiple versions of the same namespace package subpackage
  693. are on different sys.path entries, that only the one earliest on
  694. sys.path is imported, and that the namespace package's __path__ is in
  695. the correct order.
  696. Regression test for https://github.com/pypa/setuptools/issues/207
  697. """
  698. tmpdir = symlinked_tmpdir
  699. site_dirs = (
  700. tmpdir / "site-pkgs",
  701. tmpdir / "site-pkgs2",
  702. tmpdir / "site-pkgs3",
  703. )
  704. vers_str = "__version__ = %r"
  705. for number, site in enumerate(site_dirs, 1):
  706. if number > 1:
  707. sys.path.append(str(site))
  708. nspkg = site / 'nspkg'
  709. subpkg = nspkg / 'subpkg'
  710. subpkg.ensure_dir()
  711. (nspkg / '__init__.py').write_text(self.ns_str, encoding='utf-8')
  712. (subpkg / '__init__.py').write_text(vers_str % number, encoding='utf-8')
  713. import nspkg.subpkg
  714. import nspkg
  715. expected = [
  716. str(site.realpath() / 'nspkg')
  717. for site in site_dirs
  718. ]
  719. assert nspkg.__path__ == expected
  720. assert nspkg.subpkg.__version__ == 1