Statistics
| Branch: | Revision:

root / env / lib / python2.7 / site-packages / distribute-0.6.19-py2.7.egg / setuptools / tests / test_resources.py @ 1a305335

History | View | Annotate | Download (23.1 KB)

1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
# NOTE: the shebang and encoding lines are for ScriptHeaderTests; do not remove
4
from unittest import TestCase, makeSuite; from pkg_resources import *
5
from setuptools.command.easy_install import get_script_header, is_sh
6
import os, pkg_resources, sys, StringIO, tempfile, shutil
7
try: frozenset
8
except NameError:
9
    from sets import ImmutableSet as frozenset
10

    
11
class Metadata(EmptyProvider):
12
    """Mock object to return metadata as if from an on-disk distribution"""
13

    
14
    def __init__(self,*pairs):
15
        self.metadata = dict(pairs)
16

    
17
    def has_metadata(self,name):
18
        return name in self.metadata
19

    
20
    def get_metadata(self,name):
21
        return self.metadata[name]
22

    
23
    def get_metadata_lines(self,name):
24
        return yield_lines(self.get_metadata(name))
25

    
26
class DistroTests(TestCase):
27

    
28
    def testCollection(self):
29
        # empty path should produce no distributions
30
        ad = Environment([], platform=None, python=None)
31
        self.assertEqual(list(ad), [])
32
        self.assertEqual(ad['FooPkg'],[])
33
        ad.add(Distribution.from_filename("FooPkg-1.3_1.egg"))
34
        ad.add(Distribution.from_filename("FooPkg-1.4-py2.4-win32.egg"))
35
        ad.add(Distribution.from_filename("FooPkg-1.2-py2.4.egg"))
36

    
37
        # Name is in there now
38
        self.assert_(ad['FooPkg'])
39
        # But only 1 package
40
        self.assertEqual(list(ad), ['foopkg'])
41

    
42
        # Distributions sort by version
43
        self.assertEqual(
44
            [dist.version for dist in ad['FooPkg']], ['1.4','1.3-1','1.2']
45
        )
46
        # Removing a distribution leaves sequence alone
47
        ad.remove(ad['FooPkg'][1])
48
        self.assertEqual(
49
            [dist.version for dist in ad['FooPkg']], ['1.4','1.2']
50
        )
51
        # And inserting adds them in order
52
        ad.add(Distribution.from_filename("FooPkg-1.9.egg"))
53
        self.assertEqual(
54
            [dist.version for dist in ad['FooPkg']], ['1.9','1.4','1.2']
55
        )
56

    
57
        ws = WorkingSet([])
58
        foo12 = Distribution.from_filename("FooPkg-1.2-py2.4.egg")
59
        foo14 = Distribution.from_filename("FooPkg-1.4-py2.4-win32.egg")
60
        req, = parse_requirements("FooPkg>=1.3")
61

    
62
        # Nominal case: no distros on path, should yield all applicable
63
        self.assertEqual(ad.best_match(req,ws).version, '1.9')
64
        # If a matching distro is already installed, should return only that
65
        ws.add(foo14); self.assertEqual(ad.best_match(req,ws).version, '1.4')
66

    
67
        # If the first matching distro is unsuitable, it's a version conflict
68
        ws = WorkingSet([]); ws.add(foo12); ws.add(foo14)
69
        self.assertRaises(VersionConflict, ad.best_match, req, ws)
70

    
71
        # If more than one match on the path, the first one takes precedence
72
        ws = WorkingSet([]); ws.add(foo14); ws.add(foo12); ws.add(foo14);
73
        self.assertEqual(ad.best_match(req,ws).version, '1.4')
74

    
75
    def checkFooPkg(self,d):
76
        self.assertEqual(d.project_name, "FooPkg")
77
        self.assertEqual(d.key, "foopkg")
78
        self.assertEqual(d.version, "1.3-1")
79
        self.assertEqual(d.py_version, "2.4")
80
        self.assertEqual(d.platform, "win32")
81
        self.assertEqual(d.parsed_version, parse_version("1.3-1"))
82

    
83
    def testDistroBasics(self):
84
        d = Distribution(
85
            "/some/path",
86
            project_name="FooPkg",version="1.3-1",py_version="2.4",platform="win32"
87
        )
88
        self.checkFooPkg(d)
89

    
90
        d = Distribution("/some/path")
91
        self.assertEqual(d.py_version, sys.version[:3])
92
        self.assertEqual(d.platform, None)
93

    
94
    def testDistroParse(self):
95
        d = Distribution.from_filename("FooPkg-1.3_1-py2.4-win32.egg")
96
        self.checkFooPkg(d)
97
        d = Distribution.from_filename("FooPkg-1.3_1-py2.4-win32.egg-info")
98
        self.checkFooPkg(d)
99

    
100
    def testDistroMetadata(self):
101
        d = Distribution(
102
            "/some/path", project_name="FooPkg", py_version="2.4", platform="win32",
103
            metadata = Metadata(
104
                ('PKG-INFO',"Metadata-Version: 1.0\nVersion: 1.3-1\n")
105
            )
106
        )
107
        self.checkFooPkg(d)
108

    
109

    
110
    def distRequires(self, txt):
111
        return Distribution("/foo", metadata=Metadata(('depends.txt', txt)))
112

    
113
    def checkRequires(self, dist, txt, extras=()):
114
        self.assertEqual(
115
            list(dist.requires(extras)),
116
            list(parse_requirements(txt))
117
        )
118

    
119
    def testDistroDependsSimple(self):
120
        for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0":
121
            self.checkRequires(self.distRequires(v), v)
122

    
123

    
124
    def testResolve(self):
125
        ad = Environment([]); ws = WorkingSet([])
126
        # Resolving no requirements -> nothing to install
127
        self.assertEqual( list(ws.resolve([],ad)), [] )
128
        # Request something not in the collection -> DistributionNotFound
129
        self.assertRaises(
130
            DistributionNotFound, ws.resolve, parse_requirements("Foo"), ad
131
        )
132
        Foo = Distribution.from_filename(
133
            "/foo_dir/Foo-1.2.egg",
134
            metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0"))
135
        )
136
        ad.add(Foo); ad.add(Distribution.from_filename("Foo-0.9.egg"))
137

    
138
        # Request thing(s) that are available -> list to activate
139
        for i in range(3):
140
            targets = list(ws.resolve(parse_requirements("Foo"), ad))
141
            self.assertEqual(targets, [Foo])
142
            map(ws.add,targets)
143
        self.assertRaises(VersionConflict, ws.resolve,
144
            parse_requirements("Foo==0.9"), ad)
145
        ws = WorkingSet([]) # reset
146

    
147
        # Request an extra that causes an unresolved dependency for "Baz"
148
        self.assertRaises(
149
            DistributionNotFound, ws.resolve,parse_requirements("Foo[bar]"), ad
150
        )
151
        Baz = Distribution.from_filename(
152
            "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))
153
        )
154
        ad.add(Baz)
155

    
156
        # Activation list now includes resolved dependency
157
        self.assertEqual(
158
            list(ws.resolve(parse_requirements("Foo[bar]"), ad)), [Foo,Baz]
159
        )
160
        # Requests for conflicting versions produce VersionConflict
161
        self.assertRaises( VersionConflict,
162
            ws.resolve, parse_requirements("Foo==1.2\nFoo!=1.2"), ad
163
        )
164

    
165
    def testDistroDependsOptions(self):
166
        d = self.distRequires("""
167
            Twisted>=1.5
168
            [docgen]
169
            ZConfig>=2.0
170
            docutils>=0.3
171
            [fastcgi]
172
            fcgiapp>=0.1""")
173
        self.checkRequires(d,"Twisted>=1.5")
174
        self.checkRequires(
175
            d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"]
176
        )
177
        self.checkRequires(
178
            d,"Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"]
179
        )
180
        self.checkRequires(
181
            d,"Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(),
182
            ["docgen","fastcgi"]
183
        )
184
        self.checkRequires(
185
            d,"Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(),
186
            ["fastcgi", "docgen"]
187
        )
188
        self.assertRaises(UnknownExtra, d.requires, ["foo"])
189

    
190
    def testSetuptoolsDistributeCombination(self):
191
        # Ensure that installing a 0.7-series setuptools fails.  PJE says that
192
        # it will not co-exist.
193
        ws = WorkingSet([])
194
        d = Distribution(
195
            "/some/path",
196
            project_name="setuptools",
197
            version="0.7a1")
198
        self.assertRaises(ValueError, ws.add, d)
199
        # A 0.6-series is no problem
200
        d2 = Distribution(
201
            "/some/path",
202
            project_name="setuptools",
203
            version="0.6c9")
204
        ws.add(d2)
205

    
206
        # a unexisting version needs to work
207
        ws = WorkingSet([])
208
        d3 = Distribution(
209
            "/some/path",
210
            project_name="setuptools")
211
        ws.add(d3)
212

    
213

    
214
class EntryPointTests(TestCase):
215

    
216
    def assertfields(self, ep):
217
        self.assertEqual(ep.name,"foo")
218
        self.assertEqual(ep.module_name,"setuptools.tests.test_resources")
219
        self.assertEqual(ep.attrs, ("EntryPointTests",))
220
        self.assertEqual(ep.extras, ("x",))
221
        self.assert_(ep.load() is EntryPointTests)
222
        self.assertEqual(
223
            str(ep),
224
            "foo = setuptools.tests.test_resources:EntryPointTests [x]"
225
        )
226

    
227
    def setUp(self):
228
        self.dist = Distribution.from_filename(
229
            "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt','[x]')))
230

    
231
    def testBasics(self):
232
        ep = EntryPoint(
233
            "foo", "setuptools.tests.test_resources", ["EntryPointTests"],
234
            ["x"], self.dist
235
        )
236
        self.assertfields(ep)
237

    
238
    def testParse(self):
239
        s = "foo = setuptools.tests.test_resources:EntryPointTests [x]"
240
        ep = EntryPoint.parse(s, self.dist)
241
        self.assertfields(ep)
242

    
243
        ep = EntryPoint.parse("bar baz=  spammity[PING]")
244
        self.assertEqual(ep.name,"bar baz")
245
        self.assertEqual(ep.module_name,"spammity")
246
        self.assertEqual(ep.attrs, ())
247
        self.assertEqual(ep.extras, ("ping",))
248

    
249
        ep = EntryPoint.parse(" fizzly =  wocka:foo")
250
        self.assertEqual(ep.name,"fizzly")
251
        self.assertEqual(ep.module_name,"wocka")
252
        self.assertEqual(ep.attrs, ("foo",))
253
        self.assertEqual(ep.extras, ())
254

    
255
    def testRejects(self):
256
        for ep in [
257
            "foo", "x=1=2", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2",
258
        ]:
259
            try: EntryPoint.parse(ep)
260
            except ValueError: pass
261
            else: raise AssertionError("Should've been bad", ep)
262

    
263
    def checkSubMap(self, m):
264
        self.assertEqual(len(m), len(self.submap_expect))
265
        for key, ep in self.submap_expect.iteritems():
266
            self.assertEqual(repr(m.get(key)), repr(ep))
267

    
268
    submap_expect = dict(
269
        feature1=EntryPoint('feature1', 'somemodule', ['somefunction']),
270
        feature2=EntryPoint('feature2', 'another.module', ['SomeClass'], ['extra1','extra2']),
271
        feature3=EntryPoint('feature3', 'this.module', extras=['something'])
272
    )
273
    submap_str = """
274
            # define features for blah blah
275
            feature1 = somemodule:somefunction
276
            feature2 = another.module:SomeClass [extra1,extra2]
277
            feature3 = this.module [something]
278
    """
279

    
280
    def testParseList(self):
281
        self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str))
282
        self.assertRaises(ValueError, EntryPoint.parse_group, "x a", "foo=bar")
283
        self.assertRaises(ValueError, EntryPoint.parse_group, "x",
284
            ["foo=baz", "foo=bar"])
285

    
286
    def testParseMap(self):
287
        m = EntryPoint.parse_map({'xyz':self.submap_str})
288
        self.checkSubMap(m['xyz'])
289
        self.assertEqual(m.keys(),['xyz'])
290
        m = EntryPoint.parse_map("[xyz]\n"+self.submap_str)
291
        self.checkSubMap(m['xyz'])
292
        self.assertEqual(m.keys(),['xyz'])
293
        self.assertRaises(ValueError, EntryPoint.parse_map, ["[xyz]", "[xyz]"])
294
        self.assertRaises(ValueError, EntryPoint.parse_map, self.submap_str)
295

    
296
class RequirementsTests(TestCase):
297

    
298
    def testBasics(self):
299
        r = Requirement.parse("Twisted>=1.2")
300
        self.assertEqual(str(r),"Twisted>=1.2")
301
        self.assertEqual(repr(r),"Requirement.parse('Twisted>=1.2')")
302
        self.assertEqual(r, Requirement("Twisted", [('>=','1.2')], ()))
303
        self.assertEqual(r, Requirement("twisTed", [('>=','1.2')], ()))
304
        self.assertNotEqual(r, Requirement("Twisted", [('>=','2.0')], ()))
305
        self.assertNotEqual(r, Requirement("Zope", [('>=','1.2')], ()))
306
        self.assertNotEqual(r, Requirement("Zope", [('>=','3.0')], ()))
307
        self.assertNotEqual(r, Requirement.parse("Twisted[extras]>=1.2"))
308

    
309
    def testOrdering(self):
310
        r1 = Requirement("Twisted", [('==','1.2c1'),('>=','1.2')], ())
311
        r2 = Requirement("Twisted", [('>=','1.2'),('==','1.2c1')], ())
312
        self.assertEqual(r1,r2)
313
        self.assertEqual(str(r1),str(r2))
314
        self.assertEqual(str(r2),"Twisted==1.2c1,>=1.2")
315

    
316
    def testBasicContains(self):
317
        r = Requirement("Twisted", [('>=','1.2')], ())
318
        foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg")
319
        twist11  = Distribution.from_filename("Twisted-1.1.egg")
320
        twist12  = Distribution.from_filename("Twisted-1.2.egg")
321
        self.assert_(parse_version('1.2') in r)
322
        self.assert_(parse_version('1.1') not in r)
323
        self.assert_('1.2' in r)
324
        self.assert_('1.1' not in r)
325
        self.assert_(foo_dist not in r)
326
        self.assert_(twist11 not in r)
327
        self.assert_(twist12 in r)
328

    
329
    def testAdvancedContains(self):
330
        r, = parse_requirements("Foo>=1.2,<=1.3,==1.9,>2.0,!=2.5,<3.0,==4.5")
331
        for v in ('1.2','1.2.2','1.3','1.9','2.0.1','2.3','2.6','3.0c1','4.5'):
332
            self.assert_(v in r, (v,r))
333
        for v in ('1.2c1','1.3.1','1.5','1.9.1','2.0','2.5','3.0','4.0'):
334
            self.assert_(v not in r, (v,r))
335

    
336

    
337
    def testOptionsAndHashing(self):
338
        r1 = Requirement.parse("Twisted[foo,bar]>=1.2")
339
        r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")
340
        r3 = Requirement.parse("Twisted[BAR,FOO]>=1.2.0")
341
        self.assertEqual(r1,r2)
342
        self.assertEqual(r1,r3)
343
        self.assertEqual(r1.extras, ("foo","bar"))
344
        self.assertEqual(r2.extras, ("bar","foo"))  # extras are normalized
345
        self.assertEqual(hash(r1), hash(r2))
346
        self.assertEqual(
347
            hash(r1), hash(("twisted", ((">=",parse_version("1.2")),),
348
                            frozenset(["foo","bar"])))
349
        )
350

    
351
    def testVersionEquality(self):
352
        r1 = Requirement.parse("foo==0.3a2")
353
        r2 = Requirement.parse("foo!=0.3a4")
354
        d = Distribution.from_filename
355

    
356
        self.assert_(d("foo-0.3a4.egg") not in r1)
357
        self.assert_(d("foo-0.3a1.egg") not in r1)
358
        self.assert_(d("foo-0.3a4.egg") not in r2)
359

    
360
        self.assert_(d("foo-0.3a2.egg") in r1)
361
        self.assert_(d("foo-0.3a2.egg") in r2)
362
        self.assert_(d("foo-0.3a3.egg") in r2)
363
        self.assert_(d("foo-0.3a5.egg") in r2)
364

    
365
    def testDistributeSetuptoolsOverride(self):
366
        # Plain setuptools or distribute mean we return distribute.
367
        self.assertEqual(
368
            Requirement.parse('setuptools').project_name, 'distribute')
369
        self.assertEqual(
370
            Requirement.parse('distribute').project_name, 'distribute')
371
        # setuptools lower than 0.7 means distribute
372
        self.assertEqual(
373
            Requirement.parse('setuptools==0.6c9').project_name, 'distribute')
374
        self.assertEqual(
375
            Requirement.parse('setuptools==0.6c10').project_name, 'distribute')
376
        self.assertEqual(
377
            Requirement.parse('setuptools>=0.6').project_name, 'distribute')
378
        self.assertEqual(
379
            Requirement.parse('setuptools < 0.7').project_name, 'distribute')
380
        # setuptools 0.7 and higher means setuptools.
381
        self.assertEqual(
382
            Requirement.parse('setuptools == 0.7').project_name, 'setuptools')
383
        self.assertEqual(
384
            Requirement.parse('setuptools == 0.7a1').project_name, 'setuptools')
385
        self.assertEqual(
386
            Requirement.parse('setuptools >= 0.7').project_name, 'setuptools')
387

    
388

    
389

    
390

    
391

    
392

    
393

    
394

    
395

    
396

    
397

    
398
class ParseTests(TestCase):
399

    
400
    def testEmptyParse(self):
401
        self.assertEqual(list(parse_requirements('')), [])
402

    
403
    def testYielding(self):
404
        for inp,out in [
405
            ([], []), ('x',['x']), ([[]],[]), (' x\n y', ['x','y']),
406
            (['x\n\n','y'], ['x','y']),
407
        ]:
408
            self.assertEqual(list(pkg_resources.yield_lines(inp)),out)
409

    
410
    def testSplitting(self):
411
        self.assertEqual(
412
            list(
413
                pkg_resources.split_sections("""
414
                    x
415
                    [Y]
416
                    z
417

418
                    a
419
                    [b ]
420
                    # foo
421
                    c
422
                    [ d]
423
                    [q]
424
                    v
425
                    """
426
                )
427
            ),
428
            [(None,["x"]), ("Y",["z","a"]), ("b",["c"]), ("d",[]), ("q",["v"])]
429
        )
430
        self.assertRaises(ValueError,list,pkg_resources.split_sections("[foo"))
431

    
432
    def testSafeName(self):
433
        self.assertEqual(safe_name("adns-python"), "adns-python")
434
        self.assertEqual(safe_name("WSGI Utils"),  "WSGI-Utils")
435
        self.assertEqual(safe_name("WSGI  Utils"), "WSGI-Utils")
436
        self.assertEqual(safe_name("Money$$$Maker"), "Money-Maker")
437
        self.assertNotEqual(safe_name("peak.web"), "peak-web")
438

    
439
    def testSafeVersion(self):
440
        self.assertEqual(safe_version("1.2-1"), "1.2-1")
441
        self.assertEqual(safe_version("1.2 alpha"),  "1.2.alpha")
442
        self.assertEqual(safe_version("2.3.4 20050521"), "2.3.4.20050521")
443
        self.assertEqual(safe_version("Money$$$Maker"), "Money-Maker")
444
        self.assertEqual(safe_version("peak.web"), "peak.web")
445

    
446
    def testSimpleRequirements(self):
447
        self.assertEqual(
448
            list(parse_requirements('Twis-Ted>=1.2-1')),
449
            [Requirement('Twis-Ted',[('>=','1.2-1')], ())]
450
        )
451
        self.assertEqual(
452
            list(parse_requirements('Twisted >=1.2, \ # more\n<2.0')),
453
            [Requirement('Twisted',[('>=','1.2'),('<','2.0')], ())]
454
        )
455
        self.assertEqual(
456
            Requirement.parse("FooBar==1.99a3"),
457
            Requirement("FooBar", [('==','1.99a3')], ())
458
        )
459
        self.assertRaises(ValueError,Requirement.parse,">=2.3")
460
        self.assertRaises(ValueError,Requirement.parse,"x\\")
461
        self.assertRaises(ValueError,Requirement.parse,"x==2 q")
462
        self.assertRaises(ValueError,Requirement.parse,"X==1\nY==2")
463
        self.assertRaises(ValueError,Requirement.parse,"#")
464

    
465
    def testVersionEquality(self):
466
        def c(s1,s2):
467
            p1, p2 = parse_version(s1),parse_version(s2)
468
            self.assertEqual(p1,p2, (s1,s2,p1,p2))
469

    
470
        c('1.2-rc1', '1.2rc1')
471
        c('0.4', '0.4.0')
472
        c('0.4.0.0', '0.4.0')
473
        c('0.4.0-0', '0.4-0')
474
        c('0pl1', '0.0pl1')
475
        c('0pre1', '0.0c1')
476
        c('0.0.0preview1', '0c1')
477
        c('0.0c1', '0-rc1')
478
        c('1.2a1', '1.2.a.1'); c('1.2...a', '1.2a')
479

    
480
    def testVersionOrdering(self):
481
        def c(s1,s2):
482
            p1, p2 = parse_version(s1),parse_version(s2)
483
            self.assert_(p1<p2, (s1,s2,p1,p2))
484

    
485
        c('2.1','2.1.1')
486
        c('2a1','2b0')
487
        c('2a1','2.1')
488
        c('2.3a1', '2.3')
489
        c('2.1-1', '2.1-2')
490
        c('2.1-1', '2.1.1')
491
        c('2.1', '2.1pl4')
492
        c('2.1a0-20040501', '2.1')
493
        c('1.1', '02.1')
494
        c('A56','B27')
495
        c('3.2', '3.2.pl0')
496
        c('3.2-1', '3.2pl1')
497
        c('3.2pl1', '3.2pl1-1')
498
        c('0.4', '4.0')
499
        c('0.0.4', '0.4.0')
500
        c('0pl1', '0.4pl1')
501
        c('2.1.0-rc1','2.1.0')
502
        c('2.1dev','2.1a0')
503

    
504
        torture ="""
505
        0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1
506
        0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2
507
        0.77.2-1 0.77.1-1 0.77.0-1
508
        """.split()
509

    
510
        for p,v1 in enumerate(torture):
511
            for v2 in torture[p+1:]:
512
                c(v2,v1)
513

    
514

    
515

    
516

    
517

    
518

    
519

    
520

    
521
class ScriptHeaderTests(TestCase):
522
    non_ascii_exe = '/Users/José/bin/python'
523

    
524
    def test_get_script_header(self):
525
        if not sys.platform.startswith('java') or not is_sh(sys.executable):
526
            # This test is for non-Jython platforms
527
            self.assertEqual(get_script_header('#!/usr/local/bin/python'),
528
                             '#!%s\n' % os.path.normpath(sys.executable))
529
            self.assertEqual(get_script_header('#!/usr/bin/python -x'),
530
                             '#!%s  -x\n' % os.path.normpath(sys.executable))
531
            self.assertEqual(get_script_header('#!/usr/bin/python',
532
                                               executable=self.non_ascii_exe),
533
                             '#!%s -x\n' % self.non_ascii_exe)
534

    
535
    def test_get_script_header_jython_workaround(self):
536
        # This test doesn't work with Python 3 in some locales
537
        if (sys.version_info >= (3,) and os.environ.get("LC_CTYPE")
538
            in (None, "C", "POSIX")):
539
            return
540
        platform = sys.platform
541
        sys.platform = 'java1.5.0_13'
542
        stdout = sys.stdout
543
        try:
544
            # A mock sys.executable that uses a shebang line (this file)
545
            exe = os.path.normpath(os.path.splitext(__file__)[0] + '.py')
546
            self.assertEqual(
547
                get_script_header('#!/usr/local/bin/python', executable=exe),
548
                '#!/usr/bin/env %s\n' % exe)
549

    
550
            # Ensure we generate what is basically a broken shebang line
551
            # when there's options, with a warning emitted
552
            sys.stdout = sys.stderr = StringIO.StringIO()
553
            self.assertEqual(get_script_header('#!/usr/bin/python -x',
554
                                               executable=exe),
555
                             '#!%s  -x\n' % exe)
556
            self.assert_('Unable to adapt shebang line' in sys.stdout.getvalue())
557
            sys.stdout = sys.stderr = StringIO.StringIO()
558
            self.assertEqual(get_script_header('#!/usr/bin/python',
559
                                               executable=self.non_ascii_exe),
560
                             '#!%s -x\n' % self.non_ascii_exe)
561
            self.assert_('Unable to adapt shebang line' in sys.stdout.getvalue())
562
        finally:
563
            sys.platform = platform
564
            sys.stdout = stdout
565

    
566

    
567

    
568

    
569
class NamespaceTests(TestCase):
570

    
571
    def setUp(self):
572
        self._ns_pkgs = pkg_resources._namespace_packages.copy()
573
        self._tmpdir = tempfile.mkdtemp(prefix="tests-distribute-")
574
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs"))
575
        self._prev_sys_path = sys.path[:]
576
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs"))
577

    
578
    def tearDown(self):
579
        shutil.rmtree(self._tmpdir)
580
        pkg_resources._namespace_packages = self._ns_pkgs.copy()
581
        sys.path = self._prev_sys_path[:]
582

    
583
    def test_two_levels_deep(self):
584
        """
585
        Test nested namespace packages
586
        Create namespace packages in the following tree :
587
            site-packages-1/pkg1/pkg2
588
            site-packages-2/pkg1/pkg2
589
        Check both are in the _namespace_packages dict and that their __path__
590
        is correct
591
        """
592
        sys.path.append(os.path.join(self._tmpdir, "site-pkgs2"))
593
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"))
594
        os.makedirs(os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2"))
595
        ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"
596
        for site in ["site-pkgs", "site-pkgs2"]:
597
            pkg1_init = open(os.path.join(self._tmpdir, site,
598
                             "pkg1", "__init__.py"), "w")
599
            pkg1_init.write(ns_str)
600
            pkg1_init.close()
601
            pkg2_init = open(os.path.join(self._tmpdir, site,
602
                             "pkg1", "pkg2", "__init__.py"), "w")
603
            pkg2_init.write(ns_str)
604
            pkg2_init.close()
605
        import pkg1
606
        self.assertTrue("pkg1" in pkg_resources._namespace_packages.keys())
607
        try:
608
            import pkg1.pkg2
609
        except ImportError, e:
610
            self.fail("Distribute tried to import the parent namespace package")
611
        # check the _namespace_packages dict
612
        self.assertTrue("pkg1.pkg2" in pkg_resources._namespace_packages.keys())
613
        self.assertEqual(pkg_resources._namespace_packages["pkg1"], ["pkg1.pkg2"])
614
        # check the __path__ attribute contains both paths
615
        self.assertEqual(pkg1.pkg2.__path__, [
616
                os.path.join(self._tmpdir, "site-pkgs", "pkg1", "pkg2"),
617
                os.path.join(self._tmpdir, "site-pkgs2", "pkg1", "pkg2") ])
618