File: test_deployment.py

package info (click to toggle)
dh-virtualenv 1.2.2-1.7
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 464 kB
  • sloc: python: 1,237; perl: 157; makefile: 135; sh: 22
file content (562 lines) | stat: -rw-r--r-- 17,859 bytes parent folder | download
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
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Spotify AB

# This file is part of dh-virtualenv.

# dh-virtualenv is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.

# dh-virtualenv is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with dh-virtualenv. If not, see
# <http://www.gnu.org/licenses/>.

import functools
import os
import shutil
import tempfile
import textwrap
import contextlib

from mock import patch, call, ANY

from nose.tools import eq_
from dh_virtualenv import Deployment
from dh_virtualenv.cmdline import get_default_parser


PY_CMD = os.path.abspath('debian/test/opt/venvs/test/bin/python')
PIP_CMD = os.path.abspath('debian/test/opt/venvs/test/bin/pip')
TEST_VENV_PATH = 'debian/test/opt/venvs/test'


class FakeTemporaryFile(object):
    name = 'foo'


def _test_bin(name):
    return os.path.abspath(os.path.join(
        'debian/test/opt/venvs/test/bin', name,
    ))


PY_CMD = _test_bin('python')
PIP_CMD = _test_bin('pip')
CUSTOM_PIP_CMD = _test_bin('pip-custom-platform')
LOG_ARG = '--log=' + os.path.abspath(FakeTemporaryFile.name)


def temporary_dir(fn):
    """Pass a temporary directory to the fn.

    This method makes sure it is destroyed at the end
    """
    @functools.wraps(fn)
    def _inner(*args, **kwargs):
        try:
            tempdir = tempfile.mkdtemp()
            return fn(tempdir, *args, **kwargs)
        finally:
            shutil.rmtree(tempdir)
    return _inner


def create_new_style_shebang(executable):
    shebang = '#!/bin/sh\n'
    shebang += "'''exec' " + executable + ' "$0" "$@"' + '\n'
    shebang += "' '''\n"
    return shebang


def test_shebangs_fix():
    """Generate a test for each possible interpreter"""
    for interpreter in ('python', 'pypy', 'ipy', 'jython'):
        yield check_shebangs_fix, interpreter, '/opt/venvs/test'


def test_shebangs_fix_overridden_root():
    """Generate a test for each possible interpreter while overriding root"""
    with patch.dict(os.environ, {'DH_VIRTUALENV_INSTALL_ROOT': 'foo'}):
        for interpreter in ('python', 'pypy', 'ipy', 'jython'):
            yield check_shebangs_fix, interpreter, 'foo/test'


def test_shebangs_fix_special_chars_in_path():
    """Shebang fix: Don't trip on special characters in path"""
    with patch.dict(
        os.environ,
        {'DH_VIRTUALENV_INSTALL_ROOT': 'some-directory:with/special_chars'}):
        for interpreter in ('python', 'pypy', 'ipy', 'jython'):
            yield (check_shebangs_fix, interpreter,
                   'some-directory:with/special_chars/test')


def test_shebangs_fix_new_pip_with_over_127_chars():
    """Shebang fix: Handle new pip with long shebangs"""
    with patch.dict(
        os.environ,
        {'DH_VIRTUALENV_INSTALL_ROOT': 127 * 'p'}):
        check_shebangs_fix_on_new_pip(127 * 'p' + '/test')


def check_shebangs_fix(interpreter, path):
    """Checks shebang substitution for the given interpreter"""
    deployment = Deployment('test')
    temp = tempfile.NamedTemporaryFile()
    # We cheat here a little. The fix_shebangs walks through the
    # project directory, however we can just point to a single
    # file, as the underlying mechanism is just grep -r.
    deployment.bin_dir = temp.name
    expected_shebang = '#!' + os.path.join(path, 'bin/python') + '\n'

    with open(temp.name, 'w') as f:
        f.write('#!/usr/bin/{0}\n'.format(interpreter))

    deployment.fix_shebangs()

    with open(temp.name) as f:
        eq_(f.read(), expected_shebang)

    with open(temp.name, 'w') as f:
        f.write('#!/usr/bin/env {0}\n'.format(interpreter))

    deployment.fix_shebangs()

    with open(temp.name) as f:
        eq_(f.readline(), expected_shebang)

    # Additional test to check for paths wrapped in quotes because they contained space
    # Example:
    #           #!"/some/local/path/dest/path/bin/python"
    # was changed to:
    #           #!/dest/path/bin/python"
    # which caused interpreter not found error

    with open(temp.name, 'w') as f:
        f.write('#!"/usr/bin/{0}"\n'.format(interpreter))

    deployment.fix_shebangs()

    with open(temp.name) as f:
        eq_(f.readline(), expected_shebang)


def check_shebangs_fix_on_new_pip(path):
    """Test new pip style shebangs get replaced properly"""
    deployment = Deployment('test')
    temp = tempfile.NamedTemporaryFile()

    # We cheat here a little. The fix_shebangs walks through the
    # project directory, however we can just point to a single
    # file, as the underlying mechanism is just grep -r.
    deployment.bin_dir = temp.name
    build_time_shebang = create_new_style_shebang(os.path.join(
        deployment.virtualenv_install_dir, 'bin', 'python'))
    expected_shebang = create_new_style_shebang(os.path.join(
        path, 'bin/python'))

    with open(temp.name, 'w') as f:
        f.write(build_time_shebang)

    deployment.fix_shebangs()

    with open(temp.name) as f:
        eq_(f.read(), expected_shebang)


@patch('os.path.exists', lambda x: False)
@patch('subprocess.check_call')
def test_install_dependencies_with_no_requirements(callmock):
    d = Deployment('test')
    d.pip_prefix = ['pip']
    d.install_dependencies()
    callmock.assert_has_calls([])


@patch('os.path.exists', lambda x: True)
@patch('subprocess.check_call')
def test_install_dependencies_with_requirements(callmock):
    d = Deployment('test')
    d.pip_prefix = ['pip']
    d.pip_args = ['install']
    d.install_dependencies()
    callmock.assert_called_with(
        ['pip', 'install', '-r', './requirements.txt'])


@patch('subprocess.check_call')
def test_install_dependencies_with_preinstall(callmock):
    d = Deployment('test', preinstall=['foobar'])
    d.pip_prefix = d.pip_preinstall_prefix = ['pip']
    d.pip_args = ['install']
    d.install_dependencies()
    callmock.assert_called_with(
        ['pip', 'install', 'foobar'])


@patch('subprocess.check_call')
def test_upgrade_pip(callmock):
    d = Deployment('test', upgrade_pip=True)
    d.pip_prefix = d.pip_preinstall_prefix = ['pip']
    d.pip_args = ['install']
    d.install_dependencies()
    callmock.assert_called_with(
        ['pip', 'install', ANY, '-U', 'pip'])


@patch('subprocess.check_call')
def test_upgrade_pip_with_preinstall(callmock):
    d = Deployment('test', upgrade_pip=True, preinstall=['foobar'])
    d.pip_prefix = d.pip_preinstall_prefix = ['pip']
    d.pip_args = ['install']
    d.install_dependencies()
    callmock.assert_has_calls([
        call(['pip', 'install', ANY, '-U', 'pip']),
        call(['pip', 'install', 'foobar'])])


@patch('os.path.exists', lambda x: True)
@patch('subprocess.check_call')
def test_install_dependencies_with_preinstall_with_requirements(callmock):
    d = Deployment('test', preinstall=['foobar'])
    d.pip_prefix = d.pip_preinstall_prefix = ['pip']
    d.pip_args = ['install']
    d.install_dependencies()
    callmock.assert_has_calls([
        call(['pip', 'install', 'foobar']),
        call(['pip', 'install', '-r', './requirements.txt'])
    ])


@patch('os.path.exists', return_value=True)
@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_custom_pip_tool_used_for_installation(callmock, _):
    d = Deployment(
        'test', preinstall=['pip-custom-platform'],
        pip_tool='pip-custom-platform',
    )
    d.install_dependencies()
    d.install_package()
    callmock.assert_has_calls([
        call([PY_CMD, PIP_CMD, 'install', LOG_ARG, 'pip-custom-platform']),
        call([PY_CMD, CUSTOM_PIP_CMD, 'install', LOG_ARG, '-r', './requirements.txt']),
        call([PY_CMD, CUSTOM_PIP_CMD, 'install', LOG_ARG, '.'], cwd=os.path.abspath('.')),
    ])


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv(callmock):
    d = Deployment('test')
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_verbose(callmock):
    d = Deployment('test', verbose=True)
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', '--verbose', TEST_VENV_PATH])


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_extra_urls(callmock):
    d = Deployment('test', extra_urls=['foo', 'bar'])
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install', '--extra-index-url=foo',
         '--extra-index-url=bar',
         LOG_ARG], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_extra_virtualenv(callmock):
    d = Deployment('test', extra_virtualenv_arg=["--never-download"])
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', '--never-download', TEST_VENV_PATH])


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_custom_index_url(callmock):
    d = Deployment('test', extra_urls=['foo', 'bar'],
                   index_url='http://example.com/simple')
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install',
         '--index-url=http://example.com/simple',
         '--extra-index-url=foo',
         '--extra-index-url=bar',
         LOG_ARG], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_extra_pip_arg(callmock):
    d = Deployment('test', extra_pip_arg=['--no-compile'])
    d.create_virtualenv()
    d.install_dependencies()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install', LOG_ARG, '--no-compile'], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_setuptools(callmock):
    d = Deployment('test', setuptools=True)
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', '--setuptools', TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install', LOG_ARG], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_venv_with_system_packages(callmock):
    d = Deployment('test', use_system_packages=True)
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', '--system-site-packages',
                                 TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install', LOG_ARG], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_venv_with_custom_python(callmock):
    d = Deployment('test', python='/tmp/python')
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(['virtualenv', '--python', '/tmp/python', TEST_VENV_PATH])
    eq_([PY_CMD, PIP_CMD], d.pip_prefix)
    eq_(['install', LOG_ARG], d.pip_args)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_create_builtin_venv_with_unsupported_options(callmock):
    d = Deployment(
        'test', python='python_interpreter',
        builtin_venv=True, setuptools=True, verbose=True
    )
    d.create_virtualenv()
    eq_(TEST_VENV_PATH, d.package_dir)
    callmock.assert_called_with(
        ['python_interpreter', '-m', 'venv', TEST_VENV_PATH]
    )


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_install_package(callmock):
    d = Deployment('test')
    d.bin_dir = 'derp'
    d.pip_prefix = ['derp/python', 'derp/pip']
    d.pip_args = ['install']
    d.install_package()
    callmock.assert_called_with([
        'derp/python', 'derp/pip', 'install', '.',
    ], cwd=os.getcwd())


def test_fix_activate_path():
    deployment = Deployment('test')
    temp = tempfile.NamedTemporaryFile()

    with open(temp.name, 'w') as fh:
        fh.write(textwrap.dedent("""
            other things

            VIRTUAL_ENV="/this/path/is/wrong/and/longer/than/new/path"

            more other things
        """))

    expected = textwrap.dedent("""
        other things

        VIRTUAL_ENV="/opt/venvs/test"

        more other things
    """)

    with patch('dh_virtualenv.deployment.os.path.join',
               return_value=temp.name):
        deployment.fix_activate_path()

    with open(temp.name) as fh:
        eq_(expected, fh.read())


@patch('os.path.exists', lambda x: True)
@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
@patch('subprocess.check_call')
def test_custom_src_dir(callmock):
    d = Deployment('test')
    d.sourcedirectory = 'root/srv/application'
    d.create_virtualenv()
    d.install_dependencies()
    callmock.assert_called_with([
        PY_CMD,
        PIP_CMD,
        'install',
        LOG_ARG,
        '-r',
        'root/srv/application/requirements.txt'],
    )
    d.install_package()
    callmock.assert_called_with([
        PY_CMD,
        PIP_CMD,
        'install',
        LOG_ARG,
        '.',
    ], cwd=os.path.abspath('root/srv/application'))


@patch('os.path.exists', lambda *a: True)
@patch('subprocess.check_call')
def test_testrunner(callmock):
    d = Deployment('test')
    d.run_tests()
    callmock.assert_called_once_with([
        PY_CMD,
        'setup.py',
        'test',
    ], cwd='.')


@patch('os.path.exists', lambda *a: False)
@patch('subprocess.check_call')
def test_testrunner_setuppy_not_found(callmock):
    d = Deployment('test')
    d.run_tests()
    eq_(callmock.call_count, 0)


@patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
def test_deployment_from_options():
        options, _ = get_default_parser().parse_args([
            '--extra-index-url', 'http://example.com',
            '-O--pypi-url', 'http://example.org'
        ])
        d = Deployment.from_options('foo', options)
        eq_(d.package, 'foo')
        eq_(d.pip_args,
            ['install', '--index-url=http://example.org',
             '--extra-index-url=http://example.com', LOG_ARG])


def test_deployment_from_options_with_verbose():
        options, _ = get_default_parser().parse_args([
            '--verbose'
        ])
        d = Deployment.from_options('foo', options)
        eq_(d.package, 'foo')
        eq_(d.verbose, True)


@patch('os.environ.get')
def test_deployment_from_options_with_verbose_from_env(env_mock):
        env_mock.return_value = '1'
        options, _ = get_default_parser().parse_args([])
        d = Deployment.from_options('foo', options)
        eq_(d.package, 'foo')
        eq_(d.verbose, True)


@temporary_dir
def test_fix_local_symlinks(deployment_dir):
        d = Deployment('testing')
        d.package_dir = deployment_dir

        local = os.path.join(deployment_dir, 'local')
        os.makedirs(local)
        target = os.path.join(deployment_dir, 'sometarget')
        symlink = os.path.join(local, 'symlink')
        os.symlink(target, symlink)

        d.fix_local_symlinks()
        eq_(os.readlink(symlink), '../sometarget')


@temporary_dir
def test_fix_local_symlinks_with_relative_links(deployment_dir):
        # Runs shouldn't ruin the already relative symlinks.
        d = Deployment('testing')
        d.package_dir = deployment_dir

        local = os.path.join(deployment_dir, 'local')
        os.makedirs(local)
        symlink = os.path.join(local, 'symlink')
        os.symlink('../target', symlink)

        d.fix_local_symlinks()
        eq_(os.readlink(symlink), '../target')


@temporary_dir
def test_fix_local_symlinks_does_not_blow_up_on_missing_local(deployment_dir):
        d = Deployment('testing')
        d.package_dir = deployment_dir
        d.fix_local_symlinks()


@temporary_dir
def test_find_script_files_normal_shebang(bin_dir):
    d = Deployment('testing')
    d.bin_dir = bin_dir

    script_files = [os.path.join(bin_dir, s) for s in
                    ('s1', 's2', 's3')]
    for script in script_files:
        with open(os.path.join(bin_dir, script), 'w') as f:
            f.write('#!/usr/bin/python\n')

    with open(os.path.join(bin_dir, 'n1'), 'w') as f:
        f.write('#!/bin/bash')

    found_files = sorted(d.find_script_files())
    eq_(found_files, script_files)


@temporary_dir
def test_find_script_files_long_shebang(bin_dir):
    d = Deployment('testing')
    d.bin_dir = bin_dir

    script_files = [os.path.join(bin_dir, s) for s in
                    ('s1', 's2', 's3')]
    for script in script_files:
        with open(os.path.join(bin_dir, script), 'w') as f:
            # It does not really matter what we write into the
            # exec statement as executable here
            f.write(
                create_new_style_shebang('/usr/bin/python'))

    with open(os.path.join(bin_dir, 'n1'), 'w') as f:
        f.write('#!/bin/bash')

    found_files = sorted(d.find_script_files())
    eq_(found_files, script_files)