Debian Codegraph @

test/test_deployment.py

raw ◀ ▶
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013-2014 Spotify AB
3
4 # This file is part of dh-virtualenv.
5
6 # dh-virtualenv is free software: you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation, either version 2 of the
9 # License, or (at your option) any later version.
10
11 # dh-virtualenv is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with dh-virtualenv. If not, see
18 # <http://www.gnu.org/licenses/>.
19
20 import functools
21 import os
22 import shutil
23 import tempfile
24 import textwrap
25 import contextlib
26
27 from mock import patch, call, ANY
28
29 from nose.tools import eq_
30 from dh_virtualenv import Deployment
31 from dh_virtualenv.cmdline import get_default_parser
32
33
34 PY_CMD = os.path.abspath('debian/test/opt/venvs/test/bin/python')
35 PIP_CMD = os.path.abspath('debian/test/opt/venvs/test/bin/pip')
36 TEST_VENV_PATH = 'debian/test/opt/venvs/test'
37
38
39 class FakeTemporaryFile(object):
40 name = 'foo'
41
42
43 def _test_bin(name):
44 return os.path.abspath(os.path.join(
45 'debian/test/opt/venvs/test/bin', name,
46 ))
47
48
49 PY_CMD = _test_bin('python')
50 PIP_CMD = _test_bin('pip')
51 CUSTOM_PIP_CMD = _test_bin('pip-custom-platform')
52 LOG_ARG = '--log=' + os.path.abspath(FakeTemporaryFile.name)
53
54
55 def temporary_dir(fn):
56 """Pass a temporary directory to the fn.
57
58 This method makes sure it is destroyed at the end
59 """
60 @functools.wraps(fn)
61 def _inner(*args, **kwargs):
62 try:
63 tempdir = tempfile.mkdtemp()
64 return fn(tempdir, *args, **kwargs)
65 finally:
66 shutil.rmtree(tempdir)
67 return _inner
68
69
70 def create_new_style_shebang(executable):
71 shebang = '#!/bin/sh\n'
72 shebang += "'''exec' " + executable + ' "$0" "$@"' + '\n'
73 shebang += "' '''\n"
74 return shebang
75
76
77 def test_shebangs_fix():
78 """Generate a test for each possible interpreter"""
79 for interpreter in ('python', 'pypy', 'ipy', 'jython'):
80 yield check_shebangs_fix, interpreter, '/opt/venvs/test'
81
82
83 def test_shebangs_fix_overridden_root():
84 """Generate a test for each possible interpreter while overriding root"""
85 with patch.dict(os.environ, {'DH_VIRTUALENV_INSTALL_ROOT': 'foo'}):
86 for interpreter in ('python', 'pypy', 'ipy', 'jython'):
87 yield check_shebangs_fix, interpreter, 'foo/test'
88
89
90 def test_shebangs_fix_special_chars_in_path():
91 """Shebang fix: Don't trip on special characters in path"""
92 with patch.dict(
93 os.environ,
94 {'DH_VIRTUALENV_INSTALL_ROOT': 'some-directory:with/special_chars'}):
95 for interpreter in ('python', 'pypy', 'ipy', 'jython'):
96 yield (check_shebangs_fix, interpreter,
97 'some-directory:with/special_chars/test')
98
99
100 def test_shebangs_fix_new_pip_with_over_127_chars():
101 """Shebang fix: Handle new pip with long shebangs"""
102 with patch.dict(
103 os.environ,
104 {'DH_VIRTUALENV_INSTALL_ROOT': 127 * 'p'}):
105 check_shebangs_fix_on_new_pip(127 * 'p' + '/test')
106
107
108 def check_shebangs_fix(interpreter, path):
109 """Checks shebang substitution for the given interpreter"""
110 deployment = Deployment('test')
111 temp = tempfile.NamedTemporaryFile()
112 # We cheat here a little. The fix_shebangs walks through the
113 # project directory, however we can just point to a single
114 # file, as the underlying mechanism is just grep -r.
115 deployment.bin_dir = temp.name
116 expected_shebang = '#!' + os.path.join(path, 'bin/python') + '\n'
117
118 with open(temp.name, 'w') as f:
119 f.write('#!/usr/bin/{0}\n'.format(interpreter))
120
121 deployment.fix_shebangs()
122
123 with open(temp.name) as f:
124 eq_(f.read(), expected_shebang)
125
126 with open(temp.name, 'w') as f:
127 f.write('#!/usr/bin/env {0}\n'.format(interpreter))
128
129 deployment.fix_shebangs()
130
131 with open(temp.name) as f:
132 eq_(f.readline(), expected_shebang)
133
134 # Additional test to check for paths wrapped in quotes because they contained space
135 # Example:
136 # #!"/some/local/path/dest/path/bin/python"
137 # was changed to:
138 # #!/dest/path/bin/python"
139 # which caused interpreter not found error
140
141 with open(temp.name, 'w') as f:
142 f.write('#!"/usr/bin/{0}"\n'.format(interpreter))
143
144 deployment.fix_shebangs()
145
146 with open(temp.name) as f:
147 eq_(f.readline(), expected_shebang)
148
149
150 def check_shebangs_fix_on_new_pip(path):
151 """Test new pip style shebangs get replaced properly"""
152 deployment = Deployment('test')
153 temp = tempfile.NamedTemporaryFile()
154
155 # We cheat here a little. The fix_shebangs walks through the
156 # project directory, however we can just point to a single
157 # file, as the underlying mechanism is just grep -r.
158 deployment.bin_dir = temp.name
159 build_time_shebang = create_new_style_shebang(os.path.join(
160 deployment.virtualenv_install_dir, 'bin', 'python'))
161 expected_shebang = create_new_style_shebang(os.path.join(
162 path, 'bin/python'))
163
164 with open(temp.name, 'w') as f:
165 f.write(build_time_shebang)
166
167 deployment.fix_shebangs()
168
169 with open(temp.name) as f:
170 eq_(f.read(), expected_shebang)
171
172
173 @patch('os.path.exists', lambda x: False)
174 @patch('subprocess.check_call')
175 def test_install_dependencies_with_no_requirements(callmock):
176 d = Deployment('test')
177 d.pip_prefix = ['pip']
178 d.install_dependencies()
179 callmock.assert_has_calls([])
180
181
182 @patch('os.path.exists', lambda x: True)
183 @patch('subprocess.check_call')
184 def test_install_dependencies_with_requirements(callmock):
185 d = Deployment('test')
186 d.pip_prefix = ['pip']
187 d.pip_args = ['install']
188 d.install_dependencies()
189 callmock.assert_called_with(
190 ['pip', 'install', '-r', './requirements.txt'])
191
192
193 @patch('subprocess.check_call')
194 def test_install_dependencies_with_preinstall(callmock):
195 d = Deployment('test', preinstall=['foobar'])
196 d.pip_prefix = d.pip_preinstall_prefix = ['pip']
197 d.pip_args = ['install']
198 d.install_dependencies()
199 callmock.assert_called_with(
200 ['pip', 'install', 'foobar'])
201
202
203 @patch('subprocess.check_call')
204 def test_upgrade_pip(callmock):
205 d = Deployment('test', upgrade_pip=True)
206 d.pip_prefix = d.pip_preinstall_prefix = ['pip']
207 d.pip_args = ['install']
208 d.install_dependencies()
209 callmock.assert_called_with(
210 ['pip', 'install', ANY, '-U', 'pip'])
211
212
213 @patch('subprocess.check_call')
214 def test_upgrade_pip_with_preinstall(callmock):
215 d = Deployment('test', upgrade_pip=True, preinstall=['foobar'])
216 d.pip_prefix = d.pip_preinstall_prefix = ['pip']
217 d.pip_args = ['install']
218 d.install_dependencies()
219 callmock.assert_has_calls([
220 call(['pip', 'install', ANY, '-U', 'pip']),
221 call(['pip', 'install', 'foobar'])])
222
223
224 @patch('os.path.exists', lambda x: True)
225 @patch('subprocess.check_call')
226 def test_install_dependencies_with_preinstall_with_requirements(callmock):
227 d = Deployment('test', preinstall=['foobar'])
228 d.pip_prefix = d.pip_preinstall_prefix = ['pip']
229 d.pip_args = ['install']
230 d.install_dependencies()
231 callmock.assert_has_calls([
232 call(['pip', 'install', 'foobar']),
233 call(['pip', 'install', '-r', './requirements.txt'])
234 ])
235
236
237 @patch('os.path.exists', return_value=True)
238 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
239 @patch('subprocess.check_call')
240 def test_custom_pip_tool_used_for_installation(callmock, _):
241 d = Deployment(
242 'test', preinstall=['pip-custom-platform'],
243 pip_tool='pip-custom-platform',
244 )
245 d.install_dependencies()
246 d.install_package()
247 callmock.assert_has_calls([
248 call([PY_CMD, PIP_CMD, 'install', LOG_ARG, 'pip-custom-platform']),
249 call([PY_CMD, CUSTOM_PIP_CMD, 'install', LOG_ARG, '-r', './requirements.txt']),
250 call([PY_CMD, CUSTOM_PIP_CMD, 'install', LOG_ARG, '.'], cwd=os.path.abspath('.')),
251 ])
252
253
254 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
255 @patch('subprocess.check_call')
256 def test_create_venv(callmock):
257 d = Deployment('test')
258 d.create_virtualenv()
259 eq_(TEST_VENV_PATH, d.package_dir)
260 callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
261
262
263 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
264 @patch('subprocess.check_call')
265 def test_create_venv_with_verbose(callmock):
266 d = Deployment('test', verbose=True)
267 d.create_virtualenv()
268 eq_(TEST_VENV_PATH, d.package_dir)
269 callmock.assert_called_with(['virtualenv', '--verbose', TEST_VENV_PATH])
270
271
272 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
273 @patch('subprocess.check_call')
274 def test_create_venv_with_extra_urls(callmock):
275 d = Deployment('test', extra_urls=['foo', 'bar'])
276 d.create_virtualenv()
277 eq_(TEST_VENV_PATH, d.package_dir)
278 callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
279 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
280 eq_(['install', '--extra-index-url=foo',
281 '--extra-index-url=bar',
282 LOG_ARG], d.pip_args)
283
284
285 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
286 @patch('subprocess.check_call')
287 def test_create_venv_with_extra_virtualenv(callmock):
288 d = Deployment('test', extra_virtualenv_arg=["--never-download"])
289 d.create_virtualenv()
290 eq_(TEST_VENV_PATH, d.package_dir)
291 callmock.assert_called_with(['virtualenv', '--never-download', TEST_VENV_PATH])
292
293
294 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
295 @patch('subprocess.check_call')
296 def test_create_venv_with_custom_index_url(callmock):
297 d = Deployment('test', extra_urls=['foo', 'bar'],
298 index_url='http://example.com/simple')
299 d.create_virtualenv()
300 eq_(TEST_VENV_PATH, d.package_dir)
301 callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
302 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
303 eq_(['install',
304 '--index-url=http://example.com/simple',
305 '--extra-index-url=foo',
306 '--extra-index-url=bar',
307 LOG_ARG], d.pip_args)
308
309
310 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
311 @patch('subprocess.check_call')
312 def test_create_venv_with_extra_pip_arg(callmock):
313 d = Deployment('test', extra_pip_arg=['--no-compile'])
314 d.create_virtualenv()
315 d.install_dependencies()
316 eq_(TEST_VENV_PATH, d.package_dir)
317 callmock.assert_called_with(['virtualenv', TEST_VENV_PATH])
318 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
319 eq_(['install', LOG_ARG, '--no-compile'], d.pip_args)
320
321
322 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
323 @patch('subprocess.check_call')
324 def test_create_venv_with_setuptools(callmock):
325 d = Deployment('test', setuptools=True)
326 d.create_virtualenv()
327 eq_(TEST_VENV_PATH, d.package_dir)
328 callmock.assert_called_with(['virtualenv', '--setuptools', TEST_VENV_PATH])
329 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
330 eq_(['install', LOG_ARG], d.pip_args)
331
332
333 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
334 @patch('subprocess.check_call')
335 def test_create_venv_with_system_packages(callmock):
336 d = Deployment('test', use_system_packages=True)
337 d.create_virtualenv()
338 eq_(TEST_VENV_PATH, d.package_dir)
339 callmock.assert_called_with(['virtualenv', '--system-site-packages',
340 TEST_VENV_PATH])
341 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
342 eq_(['install', LOG_ARG], d.pip_args)
343
344
345 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
346 @patch('subprocess.check_call')
347 def test_venv_with_custom_python(callmock):
348 d = Deployment('test', python='/tmp/python')
349 d.create_virtualenv()
350 eq_(TEST_VENV_PATH, d.package_dir)
351 callmock.assert_called_with(['virtualenv', '--python', '/tmp/python', TEST_VENV_PATH])
352 eq_([PY_CMD, PIP_CMD], d.pip_prefix)
353 eq_(['install', LOG_ARG], d.pip_args)
354
355
356 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
357 @patch('subprocess.check_call')
•358 def test_create_builtin_venv_with_unsupported_options(callmock):
359 d = Deployment(
360 'test', python='python_interpreter',
361 builtin_venv=True, setuptools=True, verbose=True
362 )
363 d.create_virtualenv()
364 eq_(TEST_VENV_PATH, d.package_dir)
365 callmock.assert_called_with(
366 ['python_interpreter', '-m', 'venv', TEST_VENV_PATH]
367 )
368
369
370 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
371 @patch('subprocess.check_call')
372 def test_install_package(callmock):
373 d = Deployment('test')
374 d.bin_dir = 'derp'
375 d.pip_prefix = ['derp/python', 'derp/pip']
376 d.pip_args = ['install']
377 d.install_package()
378 callmock.assert_called_with([
379 'derp/python', 'derp/pip', 'install', '.',
380 ], cwd=os.getcwd())
381
382
383 def test_fix_activate_path():
384 deployment = Deployment('test')
385 temp = tempfile.NamedTemporaryFile()
386
387 with open(temp.name, 'w') as fh:
388 fh.write(textwrap.dedent("""
389 other things
390
391 VIRTUAL_ENV="/this/path/is/wrong/and/longer/than/new/path"
392
393 more other things
394 """))
395
396 expected = textwrap.dedent("""
397 other things
398
399 VIRTUAL_ENV="/opt/venvs/test"
400
401 more other things
402 """)
403
404 with patch('dh_virtualenv.deployment.os.path.join',
405 return_value=temp.name):
406 deployment.fix_activate_path()
407
408 with open(temp.name) as fh:
409 eq_(expected, fh.read())
410
411
412 @patch('os.path.exists', lambda x: True)
413 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
414 @patch('subprocess.check_call')
415 def test_custom_src_dir(callmock):
416 d = Deployment('test')
417 d.sourcedirectory = 'root/srv/application'
418 d.create_virtualenv()
419 d.install_dependencies()
420 callmock.assert_called_with([
421 PY_CMD,
422 PIP_CMD,
423 'install',
424 LOG_ARG,
425 '-r',
426 'root/srv/application/requirements.txt'],
427 )
428 d.install_package()
429 callmock.assert_called_with([
430 PY_CMD,
431 PIP_CMD,
432 'install',
433 LOG_ARG,
434 '.',
435 ], cwd=os.path.abspath('root/srv/application'))
436
437
438 @patch('os.path.exists', lambda *a: True)
439 @patch('subprocess.check_call')
440 def test_testrunner(callmock):
441 d = Deployment('test')
442 d.run_tests()
443 callmock.assert_called_once_with([
444 PY_CMD,
445 'setup.py',
446 'test',
447 ], cwd='.')
448
449
450 @patch('os.path.exists', lambda *a: False)
451 @patch('subprocess.check_call')
452 def test_testrunner_setuppy_not_found(callmock):
453 d = Deployment('test')
454 d.run_tests()
455 eq_(callmock.call_count, 0)
456
457
458 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
459 def test_deployment_from_options():
460 options, _ = get_default_parser().parse_args([
461 '--extra-index-url', 'http://example.com',
462 '-O--pypi-url', 'http://example.org'
463 ])
464 d = Deployment.from_options('foo', options)
465 eq_(d.package, 'foo')
466 eq_(d.pip_args,
467 ['install', '--index-url=http://example.org',
468 '--extra-index-url=http://example.com', LOG_ARG])
469
470
471 def test_deployment_from_options_with_verbose():
472 options, _ = get_default_parser().parse_args([
473 '--verbose'
474 ])
475 d = Deployment.from_options('foo', options)
476 eq_(d.package, 'foo')
477 eq_(d.verbose, True)
478
479
480 @patch('os.environ.get')
481 def test_deployment_from_options_with_verbose_from_env(env_mock):
482 env_mock.return_value = '1'
483 options, _ = get_default_parser().parse_args([])
484 d = Deployment.from_options('foo', options)
485 eq_(d.package, 'foo')
486 eq_(d.verbose, True)
487
488
489 @temporary_dir
490 def test_fix_local_symlinks(deployment_dir):
491 d = Deployment('testing')
492 d.package_dir = deployment_dir
493
494 local = os.path.join(deployment_dir, 'local')
495 os.makedirs(local)
496 target = os.path.join(deployment_dir, 'sometarget')
497 symlink = os.path.join(local, 'symlink')
498 os.symlink(target, symlink)
499
500 d.fix_local_symlinks()
501 eq_(os.readlink(symlink), '../sometarget')
502
503
504 @temporary_dir
505 def test_fix_local_symlinks_with_relative_links(deployment_dir):
506 # Runs shouldn't ruin the already relative symlinks.
507 d = Deployment('testing')
508 d.package_dir = deployment_dir
509
510 local = os.path.join(deployment_dir, 'local')
511 os.makedirs(local)
512 symlink = os.path.join(local, 'symlink')
513 os.symlink('../target', symlink)
514
515 d.fix_local_symlinks()
516 eq_(os.readlink(symlink), '../target')
517
518
519 @temporary_dir
520 def test_fix_local_symlinks_does_not_blow_up_on_missing_local(deployment_dir):
521 d = Deployment('testing')
522 d.package_dir = deployment_dir
523 d.fix_local_symlinks()
524
525
526 @temporary_dir
527 def test_find_script_files_normal_shebang(bin_dir):
528 d = Deployment('testing')
529 d.bin_dir = bin_dir
530
531 script_files = [os.path.join(bin_dir, s) for s in
532 ('s1', 's2', 's3')]
533 for script in script_files:
534 with open(os.path.join(bin_dir, script), 'w') as f:
535 f.write('#!/usr/bin/python\n')
536
537 with open(os.path.join(bin_dir, 'n1'), 'w') as f:
538 f.write('#!/bin/bash')
539
540 found_files = sorted(d.find_script_files())
541 eq_(found_files, script_files)
542
543
544 @temporary_dir
545 def test_find_script_files_long_shebang(bin_dir):
546 d = Deployment('testing')
547 d.bin_dir = bin_dir
548
549 script_files = [os.path.join(bin_dir, s) for s in
550 ('s1', 's2', 's3')]
551 for script in script_files:
552 with open(os.path.join(bin_dir, script), 'w') as f:
553 # It does not really matter what we write into the
554 # exec statement as executable here
555 f.write(
556 create_new_style_shebang('/usr/bin/python'))
557
558 with open(os.path.join(bin_dir, 'n1'), 'w') as f:
559 f.write('#!/bin/bash')
560
561 found_files = sorted(d.find_script_files())
562 eq_(found_files, script_files)