Source

eco / tests.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580

import sys
import os
import eco
import unittest
import optparse
import subprocess
import nose
import fudge
from textwrap import dedent
from nose.tools import eq_, raises
from fixture import TempIO

eco_module_path = None

def setup():
    global eco_module_path
    c = os.path.abspath(os.path.join(os.path.dirname(__file__), 'eco.py'))
    if not os.path.exists(c):
        raise RuntimeError("Could not locate development path to eco module (tried %r)" % c)
    eco_module_path = os.path.dirname(c)
    
    # clean up after last failure, if necessary:
    piplog = os.path.join(os.getcwd(), 'pip-log.txt')
    if os.path.exists(piplog):
        os.remove(piplog)

def teardown():
    fudge.clear_expectations()

class EcoTester(unittest.TestCase):
    
    def setUp(self):
        self.tmp = TempIO()
        self.patches = []
        
        # since the parser is global, we need to reset some "sticky" values.
        # there doesn't seem to be an easy programmatic way to reset 
        # everything at once.
        eco.eco_command.parser.defaults['requirements'] = []
    
    def tearDown(self):
        del self.tmp
        for p in self.patches:
            p.restore()
    
    def eco(self, args):
        """run eco in a TempIO with a list of command line args.
        
        you do not need to specify arg[0], the program.
        """
        cwd = os.getcwd()
        os.chdir(self.tmp)
        _saved_stderr = sys.stderr
        sys.stderr = sys.stdout
        try:
            # note: eco_root is global and has cached os.getcwd()
            # so that's why --eco-root is needed
            exit = eco.main(['<prog>', '--eco-root', str(self.tmp.join('eco'))] + args)
        finally:
            os.chdir(cwd)
            sys.stderr = _saved_stderr
        if exit is None:
            exit = 0
        eq_(exit, 0)

class TestInstall(EcoTester):
    
    def setUp(self):
        super(TestInstall, self).setUp()
        
        PackageFinder = fudge.Fake('PackageFinder').expects('__init__')
        
        def inspect_req(install_req):
            eq_(install_req.req.project_name, 'belzebub')
        
        RequirementSet = fudge.Fake('RequirementSet')\
                            .expects('__init__')\
                            .expects('add_requirement')\
                            .calls(inspect_req)\
                            .expects('install_files')\
                            .expects('install')\
                            .has_attr(requirements={})
                            
        self.patches.extend([
            fudge.patch_object(eco.pip, "PackageFinder", PackageFinder),
            fudge.patch_object(eco.pip, "RequirementSet", RequirementSet)
        ])
        fudge.start()
    
    def tearDown(self):
        super(TestInstall, self).tearDown()
        fudge.clear_expectations()
    
    def test_install_from_args(self):
        self.eco(['belzebub'])
        fudge.stop()
    
    def test_install_from_file(self):
        self.tmp.putfile('requirements.txt', '''
            belzebub
        ''')
        self.eco(['-r', self.tmp.join('requirements.txt')])
        fudge.stop()
    
    def test_install_from_setup(self):
        self.tmp.putfile('setup.py', dedent('''
            from setuptools import setup
            setup(
                name='foobar',
                install_requires=['belzebub']
            )
        '''))
        self.eco([])
        fudge.stop()

class TestRealInstall(EcoTester):
    
    def setUp(self):
        super(TestRealInstall, self).setUp()
        self.tmp.mkdir("foobar")
        self.tmp.putfile("foobar/__init__.py", dedent('''
        def i_am_foobar(): 
            print "foobar"
        '''))
    
    def test_install_for_real(self):
        # check a real installation with no requirements
        # to see if we successfully created a setuptools script in develop mode:
        self.tmp.putfile('setup.py', dedent('''
            from setuptools import setup, find_packages
            setup(
                name='foobar',
                packages=find_packages(),
                entry_points="""
                [console_scripts]
                foob = foobar:i_am_foobar
                """
            )
        '''))
        self.eco([])
        
        self.tmp.putfile('eco/lib/eco.pth', "import os, site; site.addsitedir(%r)" % self.tmp.join('eco/lib'))
        
        cmd = self.tmp.join('eco/bin/foob')
        p = subprocess.Popen([cmd], 
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
                # module path for the version of eco we are testing against:
                env={'PYTHONPATH': os.pathsep.join([eco_module_path])}
                )
        p.wait()
        stdout = p.stdout.read().strip()
        
        
        print "*"*60
        print "contents:", cmd.replace(str(self.tmp), ".")
        print "*"*60
        print open(cmd).read()
        print "*"*60
        print "output:", cmd.replace(str(self.tmp), ".")
        print "*"*60
        print stdout
        print "*"*60
        
        eq_(stdout, "foobar")

class TestClean(EcoTester):
    
    def setUp(self):
        super(TestClean, self).setUp()
        
        self.tmp.mkdir('eco/bin')
        self.tmp.putfile('eco/bin/somescript', "<code>")
        
        self.tmp.mkdir('eco/lib/othermodule/')
        self.tmp.mkdir('eco/lib/othermodule.egg-info')
        self.tmp.putfile('eco/lib/othermodule/__init__.py', "<code>")
        self.tmp.putfile('eco/lib/mymodule.py', "<code>")
        
        self.tmp.mkdir('eco/data/man')
        self.tmp.putfile('eco/data/man/manpage.1', '<docs>')
    
    def test_clean(self):
        self.eco(['--clean'])
        eq_(os.listdir(self.tmp.join('eco/bin')), [])
        eq_(os.listdir(self.tmp.join('eco/lib')), [])
        eq_(os.listdir(self.tmp.join('eco/data')), [])

class TestInstallWhenExisting(EcoTester):
    
    def setUp(self):
        super(TestInstallWhenExisting, self).setUp()
        
        self.tmp.mkdir('eco/lib/belzebubnoitisnt')
        self.tmp.mkdir('eco/lib/belzebubnoitisnt/__init__.py')
        self.tmp.mkdir('eco/lib/belzebubnoitisnt.egg-info/')
        self.tmp.putfile('eco/lib/belzebubnoitisnt.egg-info/PKG-INFO', 
            dedent("""
            Name: belzebubnoitisnt
            Version: 1.0
            """))
        
    def test_install_when_existing(self):
        self.eco(['belzebubnoitisnt'])
        # this would otherwise fail by looking up the package on pypi

class TestPatchSetuptoolsScript(EcoTester):
    
    def setUp(self):
        super(TestPatchSetuptoolsScript, self).setUp()
        
        self.tmp.mkdir('eco/bin')
        
        self.some_st_script = dedent("""\
        #!/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python
        # EASY-INSTALL-ENTRY-SCRIPT: 'nose==0.10.3','console_scripts','nosetests'
        __requires__ = 'nose==0.10.3'
        import sys
        from pkg_resources import load_entry_point

        sys.exit(
           load_entry_point('nose==0.10.3', 'console_scripts', 'nosetests')()
        )
        """)
        self.tmp.putfile('eco/bin/some_st_script', self.some_st_script)
        
        self.non_st_script = "import sys; print sys.path"
        self.tmp.putfile('eco/bin/non_st_script', self.non_st_script)
    
    def test_setuptools_script_gets_patched(self):
        self.eco(['-vv'])
        # not a very good test, just for sanity make sure something changed
        
        f = open(self.tmp.join('eco/bin/some_st_script'))
        new_st_script = f.read()
        f.close()
        assert new_st_script != self.some_st_script, (
            "Expected %s to be patched" % self.tmp.join('eco/bin/some_st_script')
        )
        
        f = open(self.tmp.join('eco/bin/non_st_script'))
        new_non_st_script = f.read()
        f.close()
        assert new_non_st_script == self.non_st_script, (
            "Expected %s to be left untouched" % self.tmp.join('eco/bin/non_st_script')
        )

class TestEcoScript(EcoTester):
    
    def setUp(self):
        super(TestEcoScript, self).setUp()
        
        self.tmp.mkdir("eco/bin")
        self.tmp.mkdir("eco/lib")
        
        self.tmp.putfile('setup.cfg', dedent("""
        [eco.scripts]
        foo = foobar:main
        """))
        self.tmp.putfile('eco.cfg', dedent("""
        [eco.scripts]
        bar = barbar.bar:main
        """))
    
    def test_eco_script(self):
        
        cwd = os.getcwd()
        os.chdir(self.tmp)
        try:
            eco.eco_command.make_scripts_from_configs(
                self.tmp.join("eco/bin"),
                self.tmp.join("eco/lib")
            )
        finally:
            os.chdir(cwd)
        
        f = open(self.tmp.join('eco/bin/foo'))
        new_script = f.read()
        print new_script
        
        lines = new_script.split("\n")
        eq_(lines.pop(0), "")
        eq_(lines.pop(0), "#!%s" % sys.executable)
        eq_(lines.pop(0), "import sys")
        eq_(lines.pop(0), "sys.path.insert(0, %r)" % self.tmp.join("eco/lib"))
        eq_(lines.pop(0), "from foobar import main")
        eq_(lines.pop(0), "if __name__ == '__main__':")
        eq_(lines.pop(0), "    main()")
        eq_(lines.pop(0), "")
        
        eq_(len(lines), 0, "script contained unexpected additional lines")
        
        
        f = open(self.tmp.join('eco/bin/bar'))
        new_script = f.read()
        print new_script
        
        lines = new_script.split("\n")
        eq_(lines.pop(0), "")
        eq_(lines.pop(0), "#!%s" % sys.executable)
        eq_(lines.pop(0), "import sys")
        eq_(lines.pop(0), "sys.path.insert(0, %r)" % self.tmp.join("eco/lib"))
        eq_(lines.pop(0), "from barbar.bar import main")
        eq_(lines.pop(0), "if __name__ == '__main__':")
        eq_(lines.pop(0), "    main()")
        eq_(lines.pop(0), "")
        
        eq_(len(lines), 0, "script contained unexpected additional lines")
        

class TestEcoWSGIScript(EcoTester):
    
    def setUp(self):
        super(TestEcoWSGIScript, self).setUp()
        
        self.tmp.mkdir("eco/bin")
        self.tmp.mkdir("eco/lib")
        
        self.tmp.putfile('setup.cfg', dedent("""
        [eco.wsgi_scripts]
        app.wsgi = foobar:application
        """))
    
    def test_eco_wsgi_script(self):
        
        cwd = os.getcwd()
        os.chdir(self.tmp)
        try:
            eco.eco_command.make_scripts_from_configs(
                self.tmp.join("eco/bin"),
                self.tmp.join("eco/lib")
            )
        finally:
            os.chdir(cwd)
        
        f = open(self.tmp.join('eco/bin/app.wsgi'))
        new_script = f.read()
        print new_script
        
        lines = new_script.split("\n")
        eq_(lines.pop(0), "")
        eq_(lines.pop(0), "#!%s" % sys.executable)
        eq_(lines.pop(0), "import sys")
        eq_(lines.pop(0), "sys.path.insert(0, %r)" % self.tmp.join("eco/lib"))
        eq_(lines.pop(0), "from foobar import application")
        eq_(lines.pop(0), "")
        
        eq_(len(lines), 0, "script contained unexpected additional lines")
    
    def test_misnamed_wsgi_script_is_corrected(self):
        w = eco.WSGIScriptWriter(
                    self.tmp.join("eco/bin"),
                    self.tmp.join("eco/lib"))
        w.write("app.wsgi", "foobar", "not_named_application")
        
        f = open(self.tmp.join('eco/bin/app.wsgi'))
        new_script = f.read()
        print new_script
        
        lines = new_script.split("\n")
        eq_(lines.pop(0), "")
        eq_(lines.pop(0), "#!%s" % sys.executable)
        eq_(lines.pop(0), "import sys")
        eq_(lines.pop(0), "sys.path.insert(0, %r)" % self.tmp.join("eco/lib"))
        eq_(lines.pop(0), "from foobar import not_named_application as application")
        eq_(lines.pop(0), "")
        
        eq_(len(lines), 0, "script contained unexpected additional lines")

class TestOptionConfigFile(EcoTester):
    
    def setUp(self):
        super(TestOptionConfigFile, self).setUp()
        self.tmp.putfile('setup.cfg', dedent("""
        [eco]
        index-url = http://custom-pypi/
        """))
        self.tmp.putfile('eco.cfg', dedent("""
        [eco]
        eco-root = /somwhere/else
        """))
    
    def test_config_merges_with_options(self):
        cwd = os.getcwd()
        os.chdir(self.tmp)
        try:
            eco.eco_command.apply_config_files_to_parser()
            options, args = eco.eco_command.parser.parse_args([])
            eq_(options.index_url, 'http://custom-pypi/')
            eq_(options.eco_root, '/somwhere/else')
        finally:
            os.chdir(cwd)

class InterceptedConfigError(Exception):
    pass

class TestConfiguredParser(unittest.TestCase):
    
    def setUp(self):
        self.parser = optparse.OptionParser()
        self.parser.add_option(
            "-v", "--verbose",
            action="count", dest="verbosity", default=1)
        self.parser.add_option(
            "--verbosity", action="store", dest="verbosity",
            type="int")
        self.parser.add_option(
            "--many-values", action="append")
        
        def raise_error(msg):
            raise InterceptedConfigError(msg)
            
        self.config = eco.ConfiguredParser(self.parser, 'eco', error=raise_error)
        self.tmp = TempIO()
    
    def tearDown(self):
        del self.tmp
    
    def test_override(self):
        options, args = self.config.parse_args_and_configs([], [])
        eq_(options.verbosity, 1)
        
        self.tmp.putfile("eco.cfg", dedent("""
        [eco]
        verbosity = 3
        """))
        options, args = self.config.parse_args_and_configs([], [self.tmp.join("eco.cfg")])
        eq_(options.verbosity, 3)
    
    def test_merge(self):
        options, args = self.config.parse_args_and_configs([], [])
        eq_(options.verbosity, 1)
        
        self.tmp.putfile("eco.cfg", dedent("""
        [eco]
        verbosity = 3
        """))
        # add an extra arg:
        options, args = self.config.parse_args_and_configs(['-v'], [self.tmp.join("eco.cfg")])
        eq_(options.verbosity, 4)
    
    def test_args_take_precedence(self):        
        self.tmp.putfile("eco.cfg", dedent("""
        [eco]
        verbosity = 3
        """))
        options, args = self.config.parse_args_and_configs(
            ['--verbosity=7'], [self.tmp.join("eco.cfg")])
        eq_(options.verbosity, 7)
    
    def test_last_config_var_wins(self):        
        
        self.tmp.putfile("eco1.cfg", dedent("""
        [eco]
        verbosity = 7
        """))
        
        self.tmp.putfile("eco2.cfg", dedent("""
        [eco]
        verbosity = 1
        """))
        
        options, args = self.config.parse_args_and_configs(
            [], [ self.tmp.join("eco1.cfg"), self.tmp.join("eco2.cfg") ])
            
        eq_(options.verbosity, 1)
    
    def test_multiple_values(self):
        
        self.tmp.putfile("eco.cfg", dedent("""
        [eco]
        many-values = 1 
                      2 
                      3 
        """))
        
        options, args = self.config.parse_args_and_configs([], [self.tmp.join("eco.cfg")])
        eq_(options.many_values, ['1','2','3'])
    
    @raises(InterceptedConfigError)
    def test_unkown_option(self):
        self.tmp.putfile("eco.cfg", dedent("""
        [eco]
        not-a-real-option = None
        """))
        
        options, args = self.config.parse_args_and_configs([], [self.tmp.join("eco.cfg")])
        

class TestParseSetup(unittest.TestCase):
    
    def test_setuptools(self):
        setup = eco.parse_setup(dedent('''
            from setuptools import setup, find_packages
            setup(
                name='foo',
                packages=find_packages(),
                install_requires=['foo','bar'],
                tests_require=['baz'],
                setup_requires=['ver']
            )
            '''))
        eq_(setup.name, 'foo')
        eq_(setup.setup_requires, ['ver'])
        eq_(setup.install_requires, ['foo','bar'])
        eq_(setup.tests_require, ['baz'])
        
    def test_ez_setup(self):
        setup = eco.parse_setup(dedent('''
            import ez_setup
            ez_setup.use_setuptools()
            from setuptools import setup, find_packages
            setup(
                name='foo',
                packages=find_packages(),
                install_requires=['foo','bar']
            )
            '''))
        eq_(setup.name, 'foo')
        eq_(setup.setup_requires, [])
        eq_(setup.install_requires, ['foo','bar'])
        eq_(setup.tests_require, [])
        
    def test_setup_with_magic_main(self):
        setup = eco.parse_setup(dedent('''
            from setuptools import setup, find_packages
            if __name__ == '__main__':
                setup(
                    name='foo',
                    packages=find_packages(),
                    install_requires=['foo','bar']
                )
            '''))
        eq_(setup.name, 'foo')
        eq_(setup.setup_requires, [])
        eq_(setup.install_requires, ['foo','bar'])
        eq_(setup.tests_require, [])
    
    def test_dynamic_setup(self):
        setup = eco.parse_setup(dedent('''
            from setuptools import setup, find_packages
            import compiler
            def get_meta():
                return compiler # etc
            get_meta()
            def mk_req():
                return ['foo','bar']
            def mk_test_req():
                return ['baz']
            setup(
                name='foo',
                packages=find_packages(),
                install_requires=mk_req(),
                tests_require=mk_test_req()
            )
            '''))
        eq_(setup.name, 'foo')
        eq_(setup.install_requires, ['foo','bar'])
        eq_(setup.tests_require, ['baz'])
        
    def test_vanilla(self):
        setup = eco.parse_setup(dedent('''
            from distutils.core import setup
            setup(name='foo')
            '''))
        eq_(setup.name, 'foo')
        eq_(setup.setup_requires, [])
        eq_(setup.install_requires, [])
        eq_(setup.tests_require, [])

def test_remove_dupes():
    eq_(eco.remove_dupes(
        ['one', 'three', 'three', 'four', 'four', 'four']),
        ['one','three','four'])
    eq_(eco.remove_dupes(
        ['one', 'two', 'three']),
        ['one', 'two', 'three'])

if __name__ == '__main__':
    nose.main()