-
-
Notifications
You must be signed in to change notification settings - Fork 258
/
test_integration.py
1661 lines (1344 loc) · 59.8 KB
/
test_integration.py
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import filecmp
import functools
import json
import os
import platform
import subprocess
import sys
from contextlib import contextmanager
from textwrap import dedent
from zipfile import ZipFile
import pytest
from pex.common import safe_copy, safe_open, safe_sleep
from pex.compatibility import WINDOWS, nested, to_bytes
from pex.installer import EggInstaller
from pex.pex_info import PexInfo
from pex.resolver import resolve
from pex.testing import (
IS_PYPY,
NOT_CPYTHON27,
NOT_CPYTHON27_OR_LINUX,
NOT_CPYTHON27_OR_OSX,
NOT_CPYTHON36,
NOT_CPYTHON36_OR_LINUX,
PY27,
PY35,
PY36,
ensure_python_distribution,
ensure_python_interpreter,
get_dep_dist_names_from_pex,
make_sdist,
make_source_dir,
run_pex_command,
run_simple_pex,
run_simple_pex_test,
temporary_content,
temporary_dir
)
from pex.util import DistributionHelper, named_temporary_file
def make_env(**kwargs):
env = os.environ.copy()
env.update((k, str(v)) for k, v in kwargs.items() if v is not None)
for k, v in kwargs.items():
if v is None:
env.pop(k, None)
return env
def test_pex_execute():
body = "print('Hello')"
_, rc = run_simple_pex_test(body, coverage=True)
assert rc == 0
def test_pex_raise():
body = "raise Exception('This will improve coverage.')"
run_simple_pex_test(body, coverage=True)
def test_pex_root():
with nested(temporary_dir(), temporary_dir(), temporary_dir()) as (td, output_dir, tmp_home):
output_path = os.path.join(output_dir, 'pex.pex')
args = ['pex', '-o', output_path, '--not-zip-safe', '--pex-root={0}'.format(td)]
results = run_pex_command(args=args, env=make_env(HOME=tmp_home, PEX_INTERPRETER='1'))
results.assert_success()
assert ['pex.pex'] == os.listdir(output_dir), 'Expected built pex file.'
assert [] == os.listdir(tmp_home), 'Expected empty temp home dir.'
assert 'build' in os.listdir(td), 'Expected build directory in tmp pex root.'
def test_cache_disable():
with nested(temporary_dir(), temporary_dir(), temporary_dir()) as (td, output_dir, tmp_home):
output_path = os.path.join(output_dir, 'pex.pex')
args = [
'pex',
'-o', output_path,
'--not-zip-safe',
'--disable-cache',
'--pex-root={0}'.format(td),
]
results = run_pex_command(args=args, env=make_env(HOME=tmp_home, PEX_INTERPRETER='1'))
results.assert_success()
assert ['pex.pex'] == os.listdir(output_dir), 'Expected built pex file.'
assert [] == os.listdir(tmp_home), 'Expected empty temp home dir.'
def test_pex_interpreter():
with named_temporary_file() as fp:
fp.write(b"print('Hello world')")
fp.flush()
env = make_env(PEX_INTERPRETER=1)
so, rc = run_simple_pex_test("", args=(fp.name,), coverage=True, env=env)
assert so == b'Hello world\n'
assert rc == 0
def test_pex_repl_cli():
"""Tests the REPL in the context of the pex cli itself."""
stdin_payload = b'import sys; sys.exit(3)'
with temporary_dir() as output_dir:
# Create a temporary pex containing just `requests` with no entrypoint.
pex_path = os.path.join(output_dir, 'pex.pex')
results = run_pex_command(['--disable-cache',
'requests',
'./',
'-e', 'pex.bin.pex:main',
'-o', pex_path])
results.assert_success()
# Test that the REPL is functional.
stdout, rc = run_simple_pex(pex_path, stdin=stdin_payload)
assert rc == 3
assert b'>>>' in stdout
def test_pex_repl_built():
"""Tests the REPL in the context of a built pex."""
stdin_payload = b'import requests; import sys; sys.exit(3)'
with temporary_dir() as output_dir:
# Create a temporary pex containing just `requests` with no entrypoint.
pex_path = os.path.join(output_dir, 'requests.pex')
results = run_pex_command(['--disable-cache', 'requests', '-o', pex_path])
results.assert_success()
# Test that the REPL is functional.
stdout, rc = run_simple_pex(pex_path, stdin=stdin_payload)
assert rc == 3
assert b'>>>' in stdout
@pytest.mark.skipif(WINDOWS, reason='No symlinks on windows')
def test_pex_python_symlink():
with temporary_dir() as td:
symlink_path = os.path.join(td, 'python-symlink')
os.symlink(sys.executable, symlink_path)
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
pexrc.write("PEX_PYTHON=%s" % symlink_path)
body = "print('Hello')"
_, rc = run_simple_pex_test(body, coverage=True, env=make_env(HOME=td))
assert rc == 0
def test_entry_point_exit_code():
setup_py = dedent("""
from setuptools import setup
setup(
name='my_app',
version='0.0.0',
zip_safe=True,
packages=[''],
entry_points={'console_scripts': ['my_app = my_app:do_something']},
)
""")
error_msg = 'setuptools expects this to exit non-zero'
my_app = dedent("""
def do_something():
return '%s'
""" % error_msg)
with temporary_content({'setup.py': setup_py, 'my_app.py': my_app}) as project_dir:
installer = EggInstaller(project_dir)
dist = DistributionHelper.distribution_from_path(installer.bdist())
so, rc = run_simple_pex_test('', env=make_env(PEX_SCRIPT='my_app'), dists=[dist])
assert so.decode('utf-8').strip() == error_msg
assert rc == 1
# TODO: https://github.com/pantsbuild/pex/issues/479
@pytest.mark.skipif(NOT_CPYTHON36_OR_LINUX,
reason='inherits linux abi on linux w/ no backing packages')
def test_pex_multi_resolve():
"""Tests multi-interpreter + multi-platform resolution."""
with temporary_dir() as output_dir:
pex_path = os.path.join(output_dir, 'pex.pex')
results = run_pex_command(['--disable-cache',
'lxml==3.8.0',
'--no-build',
'--platform=linux-x86_64',
'--platform=macosx-10.6-x86_64',
'--python=python2.7',
'--python=python3.6',
'-o', pex_path])
results.assert_success()
included_dists = get_dep_dist_names_from_pex(pex_path, 'lxml')
assert len(included_dists) == 4
for dist_substr in ('-cp27-', '-cp36-', '-manylinux1_x86_64', '-macosx_'):
assert any(dist_substr in f for f in included_dists)
@pytest.mark.xfail(reason='See https://github.com/pantsbuild/pants/issues/4682')
def test_pex_re_exec_failure():
with temporary_dir() as output_dir:
# create 2 pex files for PEX_PATH
pex1_path = os.path.join(output_dir, 'pex1.pex')
res1 = run_pex_command(['--disable-cache', 'requests', '-o', pex1_path])
res1.assert_success()
pex2_path = os.path.join(output_dir, 'pex2.pex')
res2 = run_pex_command(['--disable-cache', 'flask', '-o', pex2_path])
res2.assert_success()
pex_path = ':'.join(os.path.join(output_dir, name) for name in ('pex1.pex', 'pex2.pex'))
# create test file test.py that attmepts to import modules from pex1/pex2
test_file_path = os.path.join(output_dir, 'test.py')
with open(test_file_path, 'w') as fh:
fh.write(dedent('''
import requests
import flask
import sys
import os
import subprocess
if 'RAN_ONCE' in os.environ::
print('Hello world')
else:
env = os.environ.copy()
env['RAN_ONCE'] = '1'
subprocess.call([sys.executable] + sys.argv, env=env)
sys.exit()
'''))
# set up env for pex build with PEX_PATH in the environment
env = make_env(PEX_PATH=pex_path)
# build composite pex of pex1/pex1
pex_out_path = os.path.join(output_dir, 'out.pex')
run_pex_command(['--disable-cache',
'wheel',
'-o', pex_out_path])
# run test.py with composite env
stdout, rc = run_simple_pex(pex_out_path, [test_file_path], env=env)
assert rc == 0
assert stdout == b'Hello world\n'
def test_pex_path_arg():
with temporary_dir() as output_dir:
# create 2 pex files for PEX_PATH
pex1_path = os.path.join(output_dir, 'pex1.pex')
res1 = run_pex_command(['--disable-cache', 'requests', '-o', pex1_path])
res1.assert_success()
pex2_path = os.path.join(output_dir, 'pex2.pex')
res2 = run_pex_command(['--disable-cache', 'flask', '-o', pex2_path])
res2.assert_success()
pex_path = ':'.join(os.path.join(output_dir, name) for name in ('pex1.pex', 'pex2.pex'))
# parameterize the pex arg for test.py
pex_out_path = os.path.join(output_dir, 'out.pex')
# create test file test.py that attempts to import modules from pex1/pex2
test_file_path = os.path.join(output_dir, 'test.py')
with open(test_file_path, 'w') as fh:
fh.write(dedent('''
import requests
import flask
import sys
import os
import subprocess
if 'RAN_ONCE' in os.environ:
print('Success!')
else:
env = os.environ.copy()
env['RAN_ONCE'] = '1'
subprocess.call([sys.executable] + ['%s'] + sys.argv, env=env)
sys.exit()
''' % pex_out_path))
# build out.pex composed from pex1/pex1
run_pex_command(['--disable-cache',
'--pex-path={}'.format(pex_path),
'wheel',
'-o', pex_out_path])
# run test.py with composite env
stdout, rc = run_simple_pex(pex_out_path, [test_file_path])
assert rc == 0
assert stdout == b'Success!\n'
def test_pex_path_in_pex_info_and_env():
with temporary_dir() as output_dir:
# create 2 pex files for PEX-INFO pex_path
pex1_path = os.path.join(output_dir, 'pex1.pex')
res1 = run_pex_command(['--disable-cache', 'requests', '-o', pex1_path])
res1.assert_success()
pex2_path = os.path.join(output_dir, 'pex2.pex')
res2 = run_pex_command(['--disable-cache', 'flask', '-o', pex2_path])
res2.assert_success()
pex_path = ':'.join(os.path.join(output_dir, name) for name in ('pex1.pex', 'pex2.pex'))
# create a pex for environment PEX_PATH
pex3_path = os.path.join(output_dir, 'pex3.pex')
res3 = run_pex_command(['--disable-cache', 'wheel', '-o', pex3_path])
res3.assert_success()
env_pex_path = os.path.join(output_dir, 'pex3.pex')
# parameterize the pex arg for test.py
pex_out_path = os.path.join(output_dir, 'out.pex')
# create test file test.py that attempts to import modules from pex1/pex2
test_file_path = os.path.join(output_dir, 'test.py')
with open(test_file_path, 'w') as fh:
fh.write(dedent('''
import requests
import flask
import wheel
import sys
import os
import subprocess
print('Success!')
'''))
# build out.pex composed from pex1/pex1
run_pex_command(['--disable-cache',
'--pex-path={}'.format(pex_path),
'-o', pex_out_path])
# load secondary PEX_PATH
env = make_env(PEX_PATH=env_pex_path)
# run test.py with composite env
stdout, rc = run_simple_pex(pex_out_path, [test_file_path], env=env)
assert rc == 0
assert stdout == b'Success!\n'
def test_interpreter_constraints_to_pex_info_py2():
with temporary_dir() as output_dir:
# target python 2
pex_out_path = os.path.join(output_dir, 'pex_py2.pex')
res = run_pex_command(['--disable-cache',
'--interpreter-constraint=>=2.7,<3',
'--interpreter-constraint=>=3.5',
'-o', pex_out_path])
res.assert_success()
pex_info = PexInfo.from_pex(pex_out_path)
assert {'>=2.7,<3', '>=3.5'} == set(pex_info.interpreter_constraints)
@pytest.mark.skipif(IS_PYPY)
def test_interpreter_constraints_to_pex_info_py3():
py3_interpreter = ensure_python_interpreter(PY36)
with temporary_dir() as output_dir:
# target python 3
pex_out_path = os.path.join(output_dir, 'pex_py3.pex')
res = run_pex_command(['--disable-cache', '--interpreter-constraint=>3', '-o', pex_out_path],
env=make_env(PATH=os.path.dirname(py3_interpreter)))
res.assert_success()
pex_info = PexInfo.from_pex(pex_out_path)
assert ['>3'] == pex_info.interpreter_constraints
def test_interpreter_resolution_with_constraint_option():
with temporary_dir() as output_dir:
pex_out_path = os.path.join(output_dir, 'pex1.pex')
res = run_pex_command(['--disable-cache',
'--interpreter-constraint=>=2.7,<3',
'-o', pex_out_path])
res.assert_success()
pex_info = PexInfo.from_pex(pex_out_path)
assert ['>=2.7,<3'] == pex_info.interpreter_constraints
assert pex_info.build_properties['version'][0] < 3
def test_interpreter_resolution_with_multiple_constraint_options():
with temporary_dir() as output_dir:
pex_out_path = os.path.join(output_dir, 'pex1.pex')
res = run_pex_command(['--disable-cache',
'--interpreter-constraint=>=2.7,<3',
# Add a constraint that's impossible to satisfy. Because multiple
# constraints OR, the interpeter should still resolve to Python 2.7.
'--interpreter-constraint=>=500',
'-o', pex_out_path])
res.assert_success()
pex_info = PexInfo.from_pex(pex_out_path)
assert {'>=2.7,<3', '>=500'} == set(pex_info.interpreter_constraints)
assert pex_info.build_properties['version'][0] < 3
@pytest.mark.skipif(IS_PYPY)
def test_interpreter_resolution_with_pex_python_path():
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
# set pex python path
pex_python_path = ':'.join([
ensure_python_interpreter(PY27),
ensure_python_interpreter(PY36)
])
pexrc.write("PEX_PYTHON_PATH=%s" % pex_python_path)
# constraints to build pex cleanly; PPP + pex_bootstrapper.py
# will use these constraints to override sys.executable on pex re-exec
interpreter_constraint1 = '>3' if sys.version_info[0] == 3 else '<3'
interpreter_constraint2 = '<3.8' if sys.version_info[0] == 3 else '>=2.7'
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'--interpreter-constraint=%s,%s' % (interpreter_constraint1, interpreter_constraint2),
'-o', pex_out_path])
res.assert_success()
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload)
assert rc == 0
if sys.version_info[0] == 3:
assert str(pex_python_path.split(':')[1]).encode() in stdout
else:
assert str(pex_python_path.split(':')[0]).encode() in stdout
@pytest.mark.skipif(IS_PYPY)
def test_interpreter_constraints_honored_without_ppp_or_pp():
# Create a pex with interpreter constraints, but for not the default interpreter in the path.
with temporary_dir() as td:
py36_path = ensure_python_interpreter(PY36)
py35_path = ensure_python_interpreter(PY35)
pex_out_path = os.path.join(td, 'pex.pex')
env = make_env(
PEX_IGNORE_RCFILES="1",
PATH=os.pathsep.join([
os.path.dirname(py35_path),
os.path.dirname(py36_path),
])
)
res = run_pex_command(['--disable-cache',
'--interpreter-constraint===%s' % PY36,
'-o', pex_out_path],
env=env
)
res.assert_success()
# We want to try to run that pex with no environment variables set
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload, env=env)
assert rc == 0
# If the constraints are honored, it will have run python3.6 and not python3.5
# Without constraints, we would expect it to use python3.5 as it is the minimum interpreter
# in the PATH.
assert str(py36_path).encode() in stdout
@pytest.mark.skipif(NOT_CPYTHON36)
def test_interpreter_resolution_pex_python_path_precedence_over_pex_python():
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
# set both PPP and PP
pex_python_path = ':'.join([
ensure_python_interpreter(PY27),
ensure_python_interpreter(PY36)
])
pexrc.write("PEX_PYTHON_PATH=%s\n" % pex_python_path)
pex_python = '/path/to/some/python'
pexrc.write("PEX_PYTHON=%s" % pex_python)
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'--interpreter-constraint=>3,<3.8',
'-o', pex_out_path])
res.assert_success()
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload)
assert rc == 0
correct_interpreter_path = pex_python_path.split(':')[1].encode()
assert correct_interpreter_path in stdout
def test_plain_pex_exec_no_ppp_no_pp_no_constraints():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
env = make_env(
PEX_IGNORE_RCFILES="1",
PATH=os.path.dirname(os.path.realpath(sys.executable))
)
res = run_pex_command([
'--disable-cache',
'-o', pex_out_path],
env=env
)
res.assert_success()
stdin_payload = b'import os, sys; print(os.path.realpath(sys.executable)); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload, env=env)
assert rc == 0
assert os.path.realpath(sys.executable).encode() in stdout
@pytest.mark.skipif(IS_PYPY)
def test_pex_exec_with_pex_python_path_only():
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
# set pex python path
pex_python_path = ':'.join([
ensure_python_interpreter(PY27),
ensure_python_interpreter(PY36)
])
pexrc.write("PEX_PYTHON_PATH=%s" % pex_python_path)
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'-o', pex_out_path])
res.assert_success()
# test that pex bootstrapper selects lowest version interpreter
# in pex python path (python2.7)
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload)
assert rc == 0
assert str(pex_python_path.split(':')[0]).encode() in stdout
@pytest.mark.skipif(IS_PYPY)
def test_pex_exec_with_pex_python_path_and_pex_python_but_no_constraints():
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
# set both PPP and PP
pex_python_path = ':'.join([
ensure_python_interpreter(PY27),
ensure_python_interpreter(PY36)
])
pexrc.write("PEX_PYTHON_PATH=%s\n" % pex_python_path)
pex_python = '/path/to/some/python'
pexrc.write("PEX_PYTHON=%s" % pex_python)
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'-o', pex_out_path])
res.assert_success()
# test that pex bootstrapper selects lowest version interpreter
# in pex python path (python2.7)
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload)
assert rc == 0
assert str(pex_python_path.split(':')[0]).encode() in stdout
@pytest.mark.skipif(IS_PYPY)
def test_pex_python():
py2_path_interpreter = ensure_python_interpreter(PY27)
py3_path_interpreter = ensure_python_interpreter(PY36)
path = ':'.join([os.path.dirname(py2_path_interpreter), os.path.dirname(py3_path_interpreter)])
env = make_env(PATH=path)
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
pex_python = ensure_python_interpreter(PY36)
pexrc.write("PEX_PYTHON=%s" % pex_python)
# test PEX_PYTHON with valid constraints
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'--interpreter-constraint=>3,<3.8',
'-o', pex_out_path],
env=env)
res.assert_success()
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload, env=env)
assert rc == 0
correct_interpreter_path = pex_python.encode()
assert correct_interpreter_path in stdout
# test PEX_PYTHON with incompatible constraints
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
pex_python = ensure_python_interpreter(PY27)
pexrc.write("PEX_PYTHON=%s" % pex_python)
pex_out_path = os.path.join(td, 'pex2.pex')
res = run_pex_command(['--disable-cache',
'--rcfile=%s' % pexrc_path,
'--interpreter-constraint=>3,<3.8',
'-o', pex_out_path],
env=env)
res.assert_success()
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload, env=env)
assert rc == 1
fail_str = ('Failed to find a compatible PEX_PYTHON={} for constraints'
.format(pex_python)).encode()
assert fail_str in stdout
# test PEX_PYTHON with no constraints
pex_out_path = os.path.join(td, 'pex3.pex')
res = run_pex_command(['--disable-cache', '--rcfile=%s' % pexrc_path, '-o', pex_out_path],
env=env)
res.assert_success()
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload, env=env)
assert rc == 0
correct_interpreter_path = pex_python.encode()
assert correct_interpreter_path in stdout
@pytest.mark.skipif(IS_PYPY)
def test_entry_point_targeting():
"""Test bugfix for https://github.com/pantsbuild/pex/issues/434"""
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
pex_python = ensure_python_interpreter(PY36)
pexrc.write("PEX_PYTHON=%s" % pex_python)
# test pex with entry point
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'autopep8',
'-e', 'autopep8',
'-o', pex_out_path])
res.assert_success()
stdout, rc = run_simple_pex(pex_out_path)
assert 'usage: autopep8'.encode() in stdout
@pytest.mark.skipif(IS_PYPY)
def test_interpreter_selection_using_os_environ_for_bootstrap_reexec():
"""
This is a test for verifying the proper function of the
pex bootstrapper's interpreter selection logic and validate a corresponding
bugfix. More details on the nature of the bug can be found at:
https://github.com/pantsbuild/pex/pull/441
"""
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
# Select pexrc interpreter versions based on test environment.
# The parent interpreter is the interpreter we expect the parent pex to
# execute with. The child interpreter is the interpreter we expect the
# child pex to execute with.
if (sys.version_info[0], sys.version_info[1]) == (3, 6):
child_pex_interpreter_version = PY36
else:
child_pex_interpreter_version = PY27
# Write parent pex's pexrc.
with open(pexrc_path, 'w') as pexrc:
pexrc.write("PEX_PYTHON=%s" % sys.executable)
test_setup_path = os.path.join(td, 'setup.py')
with open(test_setup_path, 'w') as fh:
fh.write(dedent('''
from setuptools import setup
setup(
name='tester',
version='1.0',
description='tests',
author='tester',
author_email='test@test.com',
packages=['testing']
)
'''))
os.mkdir(os.path.join(td, 'testing'))
test_init_path = os.path.join(td, 'testing/__init__.py')
with open(test_init_path, 'w') as fh:
fh.write(dedent('''
def tester():
from pex.testing import (
run_pex_command,
run_simple_pex,
temporary_dir
)
import os
from textwrap import dedent
with temporary_dir() as td:
pexrc_path = os.path.join(td, '.pexrc')
with open(pexrc_path, 'w') as pexrc:
pexrc.write("PEX_PYTHON={}")
test_file_path = os.path.join(td, 'build_and_run_child_pex.py')
with open(test_file_path, 'w') as fh:
fh.write(dedent("""
import sys
print(sys.executable)
"""))
pex_out_path = os.path.join(td, 'child.pex')
res = run_pex_command(['--disable-cache',
'-o', pex_out_path])
stdin_payload = b'import sys; print(sys.executable); sys.exit(0)'
stdout, rc = run_simple_pex(pex_out_path, stdin=stdin_payload)
print(stdout)
'''.format(ensure_python_interpreter(child_pex_interpreter_version))))
pex_out_path = os.path.join(td, 'parent.pex')
res = run_pex_command(['--disable-cache',
'pex',
'{}'.format(td),
'-e', 'testing:tester',
'-o', pex_out_path])
res.assert_success()
stdout, rc = run_simple_pex(pex_out_path)
assert rc == 0
# Ensure that child pex used the proper interpreter as specified by its pexrc.
correct_interpreter_path = ensure_python_interpreter(child_pex_interpreter_version)
correct_interpreter_path = correct_interpreter_path.encode() # Py 2/3 compatibility
assert correct_interpreter_path in stdout
def test_inherit_path_fallback():
inherit_path("=fallback")
def test_inherit_path_backwards_compatibility():
inherit_path("")
def test_inherit_path_prefer():
inherit_path("=prefer")
def inherit_path(inherit_path):
with temporary_dir() as output_dir:
exe = os.path.join(output_dir, 'exe.py')
body = "import sys ; print('\\n'.join(sys.path))"
with open(exe, 'w') as f:
f.write(body)
pex_path = os.path.join(output_dir, 'pex.pex')
results = run_pex_command([
'--disable-cache',
'msgpack_python',
'--inherit-path{}'.format(inherit_path),
'-o',
pex_path,
])
results.assert_success()
env = make_env(PYTHONPATH='/doesnotexist')
stdout, rc = run_simple_pex(
pex_path,
args=(exe,),
env=env,
)
assert rc == 0
stdout_lines = stdout.decode().split('\n')
requests_paths = tuple(i for i, l in enumerate(stdout_lines) if 'msgpack_python' in l)
sys_paths = tuple(i for i, l in enumerate(stdout_lines) if 'doesnotexist' in l)
assert len(requests_paths) == 1
assert len(sys_paths) == 1
if inherit_path == "=fallback":
assert requests_paths[0] < sys_paths[0]
else:
assert requests_paths[0] > sys_paths[0]
def test_pex_multi_resolve_2():
"""Tests multi-interpreter + multi-platform resolution using extended platform notation."""
with temporary_dir() as output_dir:
pex_path = os.path.join(output_dir, 'pex.pex')
results = run_pex_command(['--disable-cache',
'lxml==3.8.0',
'--no-build',
'--platform=linux-x86_64-cp-36-m',
'--platform=linux-x86_64-cp-27-m',
'--platform=macosx-10.6-x86_64-cp-36-m',
'--platform=macosx-10.6-x86_64-cp-27-m',
'-o', pex_path])
results.assert_success()
included_dists = get_dep_dist_names_from_pex(pex_path, 'lxml')
assert len(included_dists) == 4
for dist_substr in ('-cp27-', '-cp36-', '-manylinux1_x86_64', '-macosx_'):
assert any(dist_substr in f for f in included_dists), (
'{} was not found in wheel'.format(dist_substr)
)
@contextmanager
def pex_manylinux_and_tag_selection_context():
with temporary_dir() as output_dir:
def do_resolve(req_name, req_version, platform, extra_flags=None):
extra_flags = extra_flags or ''
pex_path = os.path.join(output_dir, 'test.pex')
results = run_pex_command(['--disable-cache',
'--no-build',
'%s==%s' % (req_name, req_version),
'--platform=%s' % (platform),
'-o', pex_path] + extra_flags.split())
return pex_path, results
def test_resolve(req_name, req_version, platform, substr, extra_flags=None):
pex_path, results = do_resolve(req_name, req_version, platform, extra_flags)
results.assert_success()
included_dists = get_dep_dist_names_from_pex(pex_path, req_name.replace('-', '_'))
assert any(
substr in d for d in included_dists
), 'couldnt find {} in {}'.format(substr, included_dists)
def ensure_failure(req_name, req_version, platform, extra_flags):
pex_path, results = do_resolve(req_name, req_version, platform, extra_flags)
results.assert_failure()
yield test_resolve, ensure_failure
@pytest.mark.skipif(IS_PYPY)
def test_pex_manylinux_and_tag_selection_linux_msgpack():
"""Tests resolver manylinux support and tag targeting."""
with pex_manylinux_and_tag_selection_context() as (test_resolve, ensure_failure):
msgpack, msgpack_ver = 'msgpack-python', '0.4.7'
test_msgpack = functools.partial(test_resolve, msgpack, msgpack_ver)
# Exclude 3.3, >=3.6 because no wheels exist for these versions on pypi.
current_version = sys.version_info[:2]
if current_version != (3, 3) and current_version < (3, 6):
test_msgpack('linux-x86_64', 'manylinux1_x86_64.whl')
test_msgpack('linux-x86_64-cp-27-m', 'msgpack_python-0.4.7-cp27-cp27m-manylinux1_x86_64.whl')
test_msgpack('linux-x86_64-cp-27-mu', 'msgpack_python-0.4.7-cp27-cp27mu-manylinux1_x86_64.whl')
test_msgpack('linux-i686-cp-27-m', 'msgpack_python-0.4.7-cp27-cp27m-manylinux1_i686.whl')
test_msgpack('linux-i686-cp-27-mu', 'msgpack_python-0.4.7-cp27-cp27mu-manylinux1_i686.whl')
test_msgpack('linux-x86_64-cp-27-mu', 'msgpack_python-0.4.7-cp27-cp27mu-manylinux1_x86_64.whl')
test_msgpack('linux-x86_64-cp-34-m', 'msgpack_python-0.4.7-cp34-cp34m-manylinux1_x86_64.whl')
test_msgpack('linux-x86_64-cp-35-m', 'msgpack_python-0.4.7-cp35-cp35m-manylinux1_x86_64.whl')
ensure_failure(msgpack, msgpack_ver, 'linux-x86_64', '--no-manylinux')
def test_pex_manylinux_and_tag_selection_lxml_osx():
with pex_manylinux_and_tag_selection_context() as (test_resolve, ensure_failure):
test_resolve('lxml', '3.8.0', 'macosx-10.6-x86_64-cp-27-m', 'lxml-3.8.0-cp27-cp27m-macosx')
test_resolve('lxml', '3.8.0', 'macosx-10.6-x86_64-cp-36-m', 'lxml-3.8.0-cp36-cp36m-macosx')
@pytest.mark.skipif(NOT_CPYTHON27_OR_OSX)
def test_pex_manylinux_runtime():
"""Tests resolver manylinux support and runtime resolution (and --platform=current)."""
test_stub = dedent(
"""
import msgpack
print(msgpack.unpackb(msgpack.packb([1, 2, 3])))
"""
)
with temporary_content({'tester.py': test_stub}) as output_dir:
pex_path = os.path.join(output_dir, 'test.pex')
tester_path = os.path.join(output_dir, 'tester.py')
results = run_pex_command(['--disable-cache',
'--no-build',
'msgpack-python==0.4.7',
'--platform=current'.format(platform),
'-o', pex_path])
results.assert_success()
out = subprocess.check_output([pex_path, tester_path])
assert out.strip() == '[1, 2, 3]'
def test_pex_exit_code_propagation():
"""Tests exit code propagation."""
test_stub = dedent(
"""
def test_fail():
assert False
"""
)
with temporary_content({'tester.py': test_stub}) as output_dir:
pex_path = os.path.join(output_dir, 'test.pex')
tester_path = os.path.join(output_dir, 'tester.py')
results = run_pex_command(['pytest==3.9.1',
'-e', 'pytest:main',
'-o', pex_path])
results.assert_success()
assert subprocess.call([pex_path, os.path.realpath(tester_path)]) == 1
@pytest.mark.skipif(NOT_CPYTHON27)
def test_platform_specific_inline_egg_resolution():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--no-wheel',
'MarkupSafe==1.0',
'-o', pex_out_path])
res.assert_success()
@pytest.mark.skipif(NOT_CPYTHON27)
def test_platform_specific_egg_resolution():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--no-wheel',
'--no-build',
'--no-pypi',
'--platform=linux-x86_64',
'--find-links=tests/example_packages/',
'M2Crypto==0.22.3',
'-o', pex_out_path])
res.assert_success()
@pytest.mark.skipif(NOT_CPYTHON27)
def test_platform_specific_egg_resolution_matching():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--no-wheel',
'--no-build',
'netifaces==0.10.6', # Only provides win32 eggs.
'-o', pex_out_path])
res.assert_failure()
@pytest.mark.skipif(NOT_CPYTHON27)
def test_ipython_appnope_env_markers():
res = run_pex_command(['--disable-cache',
'ipython==5.8.0',
'-c', 'ipython',
'--',
'--version'])
res.assert_success()
# TODO: https://github.com/pantsbuild/pex/issues/479
@pytest.mark.skipif(NOT_CPYTHON27_OR_LINUX,
reason='this needs to run on an interpreter with ABI type m (OSX) vs mu (linux)')
def test_cross_platform_abi_targeting_behavior():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--no-pypi',
'--platform=linux-x86_64',
'--find-links=tests/example_packages/',
'MarkupSafe==1.0',
'-o', pex_out_path])
res.assert_success()
@pytest.mark.skipif(NOT_CPYTHON27)
def test_cross_platform_abi_targeting_behavior_exact():
with temporary_dir() as td:
pex_out_path = os.path.join(td, 'pex.pex')
res = run_pex_command(['--disable-cache',
'--no-pypi',
'--platform=linux-x86_64-cp-27-mu',
'--find-links=tests/example_packages/',
'MarkupSafe==1.0',
'-o', pex_out_path])
res.assert_success()
def test_pex_source_bundling():
with temporary_dir() as output_dir:
with temporary_dir() as input_dir:
with open(os.path.join(input_dir, 'exe.py'), 'w') as fh:
fh.write(dedent('''
print('hello')
'''
))
pex_path = os.path.join(output_dir, 'pex1.pex')
res = run_pex_command([
'-o', pex_path,
'-D', input_dir,
'-e', 'exe',
])
res.assert_success()
stdout, rc = run_simple_pex(pex_path)