Debian Codegraph @

test/test_deployment.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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_install_package(callmock):
359 d = Deployment('test')
360 d.bin_dir = 'derp'
361 d.pip_prefix = ['derp/python', 'derp/pip']
362 d.pip_args = ['install']
363 d.install_package()
364 callmock.assert_called_with([
365 'derp/python', 'derp/pip', 'install', '.',
366 ], cwd=os.getcwd())
367
368
369 def test_fix_activate_path():
370 deployment = Deployment('test')
371 temp = tempfile.NamedTemporaryFile()
372
373 with open(temp.name, 'w') as fh:
374 fh.write(textwrap.dedent("""
375 other things
376
377 VIRTUAL_ENV="/this/path/is/wrong/and/longer/than/new/path"
378
379 more other things
380 """))
381
382 expected = textwrap.dedent("""
383 other things
384
385 VIRTUAL_ENV="/opt/venvs/test"
386
387 more other things
388 """)
389
390 with patch('dh_virtualenv.deployment.os.path.join',
391 return_value=temp.name):
392 deployment.fix_activate_path()
393
394 with open(temp.name) as fh:
395 eq_(expected, fh.read())
396
397
398 @patch('os.path.exists', lambda x: True)
399 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
400 @patch('subprocess.check_call')
401 def test_custom_src_dir(callmock):
402 d = Deployment('test')
403 d.sourcedirectory = 'root/srv/application'
404 d.create_virtualenv()
405 d.install_dependencies()
406 callmock.assert_called_with([
407 PY_CMD,
408 PIP_CMD,
409 'install',
410 LOG_ARG,
411 '-r',
412 'root/srv/application/requirements.txt'],
413 )
414 d.install_package()
415 callmock.assert_called_with([
416 PY_CMD,
417 PIP_CMD,
418 'install',
419 LOG_ARG,
420 '.',
421 ], cwd=os.path.abspath('root/srv/application'))
422
423
424 @patch('os.path.exists', lambda *a: True)
425 @patch('subprocess.check_call')
426 def test_testrunner(callmock):
427 d = Deployment('test')
428 d.run_tests()
429 callmock.assert_called_once_with([
430 PY_CMD,
431 'setup.py',
432 'test',
433 ], cwd='.')
434
435
436 @patch('os.path.exists', lambda *a: False)
437 @patch('subprocess.check_call')
438 def test_testrunner_setuppy_not_found(callmock):
439 d = Deployment('test')
440 d.run_tests()
441 eq_(callmock.call_count, 0)
442
443
444 @patch('tempfile.NamedTemporaryFile', FakeTemporaryFile)
445 def test_deployment_from_options():
446 options, _ = get_default_parser().parse_args([
447 '--extra-index-url', 'http://example.com',
448 '-O--pypi-url', 'http://example.org'
449 ])
450 d = Deployment.from_options('foo', options)
451 eq_(d.package, 'foo')
452 eq_(d.pip_args,
453 ['install', '--index-url=http://example.org',
454 '--extra-index-url=http://example.com', LOG_ARG])
455
456
457 def test_deployment_from_options_with_verbose():
458 options, _ = get_default_parser().parse_args([
459 '--verbose'
460 ])
461 d = Deployment.from_options('foo', options)
462 eq_(d.package, 'foo')
463 eq_(d.verbose, True)
464
465
466 @patch('os.environ.get')
467 def test_deployment_from_options_with_verbose_from_env(env_mock):
468 env_mock.return_value = '1'
469 options, _ = get_default_parser().parse_args([])
470 d = Deployment.from_options('foo', options)
471 eq_(d.package, 'foo')
472 eq_(d.verbose, True)
473
474
475 @temporary_dir
476 def test_fix_local_symlinks(deployment_dir):
477 d = Deployment('testing')
478 d.package_dir = deployment_dir
479
480 local = os.path.join(deployment_dir, 'local')
481 os.makedirs(local)
482 target = os.path.join(deployment_dir, 'sometarget')
483 symlink = os.path.join(local, 'symlink')
484 os.symlink(target, symlink)
485
486 d.fix_local_symlinks()
487 eq_(os.readlink(symlink), '../sometarget')
488
489
490 @temporary_dir
491 def test_fix_local_symlinks_with_relative_links(deployment_dir):
492 # Runs shouldn't ruin the already relative symlinks.
493 d = Deployment('testing')
494 d.package_dir = deployment_dir
495
496 local = os.path.join(deployment_dir, 'local')
497 os.makedirs(local)
498 symlink = os.path.join(local, 'symlink')
499 os.symlink('../target', symlink)
500
501 d.fix_local_symlinks()
502 eq_(os.readlink(symlink), '../target')
503
504
505 @temporary_dir
506 def test_fix_local_symlinks_does_not_blow_up_on_missing_local(deployment_dir):
507 d = Deployment('testing')
508 d.package_dir = deployment_dir
509 d.fix_local_symlinks()
510
511
512 @temporary_dir
513 def test_find_script_files_normal_shebang(bin_dir):
514 d = Deployment('testing')
515 d.bin_dir = bin_dir
516
517 script_files = [os.path.join(bin_dir, s) for s in
518 ('s1', 's2', 's3')]
519 for script in script_files:
520 with open(os.path.join(bin_dir, script), 'w') as f:
521 f.write('#!/usr/bin/python\n')
522
523 with open(os.path.join(bin_dir, 'n1'), 'w') as f:
524 f.write('#!/bin/bash')
525
526 found_files = sorted(d.find_script_files())
527 eq_(found_files, script_files)
528
529
530 @temporary_dir
531 def test_find_script_files_long_shebang(bin_dir):
532 d = Deployment('testing')
533 d.bin_dir = bin_dir
534
535 script_files = [os.path.join(bin_dir, s) for s in
536 ('s1', 's2', 's3')]
537 for script in script_files:
538 with open(os.path.join(bin_dir, script), 'w') as f:
539 # It does not really matter what we write into the
540 # exec statement as executable here
541 f.write(
542 create_new_style_shebang('/usr/bin/python'))
543
544 with open(os.path.join(bin_dir, 'n1'), 'w') as f:
545 f.write('#!/bin/bash')
546
547 found_files = sorted(d.find_script_files())
548 eq_(found_files, script_files)