-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
test_env.py
1410 lines (1107 loc) · 42.4 KB
/
test_env.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
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
import pytest
import tomlkit
from cleo.io.null_io import NullIO
from poetry.core.semver.version import Version
from poetry.core.toml.file import TOMLFile
from poetry.factory import Factory
from poetry.repositories.installed_repository import InstalledRepository
from poetry.utils._compat import WINDOWS
from poetry.utils.env import GET_BASE_PREFIX
from poetry.utils.env import EnvCommandError
from poetry.utils.env import EnvManager
from poetry.utils.env import GenericEnv
from poetry.utils.env import InvalidCurrentPythonVersionError
from poetry.utils.env import MockEnv
from poetry.utils.env import NoCompatiblePythonVersionFound
from poetry.utils.env import SystemEnv
from poetry.utils.env import VirtualEnv
from poetry.utils.env import build_environment
from poetry.utils.helpers import remove_directory
if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Iterator
from pytest_mock import MockerFixture
from poetry.poetry import Poetry
from tests.conftest import Config
from tests.types import ProjectFactory
MINIMAL_SCRIPT = """\
print("Minimal Output"),
"""
# Script expected to fail.
ERRORING_SCRIPT = """\
import nullpackage
print("nullpackage loaded"),
"""
class MockVirtualEnv(VirtualEnv):
def __init__(
self,
path: Path,
base: Path | None = None,
sys_path: list[str] | None = None,
) -> None:
super().__init__(path, base=base)
self._sys_path = sys_path
@property
def sys_path(self) -> list[str] | None:
if self._sys_path is not None:
return self._sys_path
return super().sys_path
@pytest.fixture()
def poetry(project_factory: ProjectFactory) -> Poetry:
fixture = Path(__file__).parent.parent / "fixtures" / "simple_project"
return project_factory("simple", source=fixture)
@pytest.fixture()
def manager(poetry: Poetry) -> EnvManager:
return EnvManager(poetry)
def test_virtualenvs_with_spaces_in_their_path_work_as_expected(
tmp_dir: str, manager: EnvManager
):
venv_path = Path(tmp_dir) / "Virtual Env"
manager.build_venv(str(venv_path))
venv = VirtualEnv(venv_path)
assert venv.run("python", "-V", shell=True).startswith("Python")
@pytest.mark.skipif(sys.platform != "darwin", reason="requires darwin")
def test_venv_backup_exclusion(tmp_dir: str, manager: EnvManager):
import xattr
venv_path = Path(tmp_dir) / "Virtual Env"
manager.build_venv(str(venv_path))
value = (
b"bplist00_\x10\x11com.apple.backupd"
b"\x08\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00"
b"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1c"
)
assert (
xattr.getxattr(
str(venv_path), "com.apple.metadata:com_apple_backup_excludeItem"
)
== value
)
def test_env_commands_with_spaces_in_their_arg_work_as_expected(
tmp_dir: str, manager: EnvManager
):
venv_path = Path(tmp_dir) / "Virtual Env"
manager.build_venv(str(venv_path))
venv = VirtualEnv(venv_path)
assert venv.run("python", venv.pip, "--version", shell=True).startswith(
f"pip {venv.pip_version} from "
)
def test_env_shell_commands_with_stdinput_in_their_arg_work_as_expected(
tmp_dir: str, manager: EnvManager
):
venv_path = Path(tmp_dir) / "Virtual Env"
manager.build_venv(str(venv_path))
venv = VirtualEnv(venv_path)
run_output_path = Path(
venv.run("python", "-", input_=GET_BASE_PREFIX, shell=True).strip()
)
venv_base_prefix_path = Path(str(venv.get_base_prefix()))
assert run_output_path.resolve() == venv_base_prefix_path.resolve()
def test_env_get_supported_tags_matches_inside_virtualenv(
tmp_dir: str, manager: EnvManager
):
venv_path = Path(tmp_dir) / "Virtual Env"
manager.build_venv(str(venv_path))
venv = VirtualEnv(venv_path)
import packaging.tags
assert venv.get_supported_tags() == list(packaging.tags.sys_tags())
@pytest.fixture
def in_project_venv_dir(poetry: Poetry) -> Iterator[Path]:
os.environ.pop("VIRTUAL_ENV", None)
venv_dir = poetry.file.parent.joinpath(".venv")
venv_dir.mkdir()
try:
yield venv_dir
finally:
venv_dir.rmdir()
@pytest.mark.parametrize("in_project", [True, False, None])
def test_env_get_venv_with_venv_folder_present(
manager: EnvManager,
poetry: Poetry,
in_project_venv_dir: Path,
in_project: bool | None,
):
poetry.config.config["virtualenvs"]["in-project"] = in_project
venv = manager.get()
if in_project is False:
assert venv.path != in_project_venv_dir
else:
assert venv.path == in_project_venv_dir
def build_venv(path: Path | str, **__: Any) -> None:
os.mkdir(str(path))
VERSION_3_7_1 = Version.parse("3.7.1")
def check_output_wrapper(
version: Version = VERSION_3_7_1,
) -> Callable[[str, Any, Any], str]:
def check_output(cmd: str, *args: Any, **kwargs: Any) -> str:
if "sys.version_info[:3]" in cmd:
return version.text
elif "sys.version_info[:2]" in cmd:
return f"{version.major}.{version.minor}"
elif '-c "import sys; print(sys.executable)"' in cmd:
return f"/usr/bin/{cmd.split()[0]}"
else:
return str(Path("/prefix"))
return check_output
def test_activate_activates_non_existing_virtualenv_no_envs_file(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None), ("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.build_venv", side_effect=build_venv)
env = manager.activate("python3.7", NullIO())
venv_name = EnvManager.generate_env_name("simple-project", str(poetry.file.parent))
m.assert_called_with(
Path(tmp_dir) / f"{venv_name}-py3.7",
executable="/usr/bin/python3.7",
flags={
"always-copy": False,
"system-site-packages": False,
"no-pip": False,
"no-setuptools": False,
},
prompt="simple-project-py3.7",
)
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix")
def test_activate_activates_existing_virtualenv_no_envs_file(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.build_venv", side_effect=build_venv)
env = manager.activate("python3.7", NullIO())
m.assert_not_called()
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix")
def test_activate_activates_same_virtualenv_with_envs_file(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.create_venv")
env = manager.activate("python3.7", NullIO())
m.assert_not_called()
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix")
def test_activate_activates_different_virtualenv_with_envs_file(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None), ("/prefix", None), ("/prefix", None)],
)
m = mocker.patch("poetry.utils.env.EnvManager.build_venv", side_effect=build_venv)
env = manager.activate("python3.6", NullIO())
m.assert_called_with(
Path(tmp_dir) / f"{venv_name}-py3.6",
executable="/usr/bin/python3.6",
flags={
"always-copy": False,
"system-site-packages": False,
"no-pip": False,
"no-setuptools": False,
},
prompt="simple-project-py3.6",
)
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.6"
assert envs[venv_name]["patch"] == "3.6.6"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6"
assert env.base == Path("/prefix")
def test_activate_activates_recreates_for_different_patch(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[
("/prefix", None),
('{"version_info": [3, 7, 0]}', None),
("/prefix", None),
("/prefix", None),
("/prefix", None),
],
)
build_venv_m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=build_venv
)
remove_venv_m = mocker.patch(
"poetry.utils.env.EnvManager.remove_venv", side_effect=EnvManager.remove_venv
)
env = manager.activate("python3.7", NullIO())
build_venv_m.assert_called_with(
Path(tmp_dir) / f"{venv_name}-py3.7",
executable="/usr/bin/python3.7",
flags={
"always-copy": False,
"system-site-packages": False,
"no-pip": False,
"no-setuptools": False,
},
prompt="simple-project-py3.7",
)
remove_venv_m.assert_called_with(Path(tmp_dir) / f"{venv_name}-py3.7")
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.7"
assert envs[venv_name]["patch"] == "3.7.1"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix")
assert (Path(tmp_dir) / f"{venv_name}-py3.7").exists()
def test_activate_does_not_recreate_when_switching_minor(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc)
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7"))
os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.6"))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None), ("/prefix", None), ("/prefix", None)],
)
build_venv_m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=build_venv
)
remove_venv_m = mocker.patch(
"poetry.utils.env.EnvManager.remove_venv", side_effect=EnvManager.remove_venv
)
env = manager.activate("python3.6", NullIO())
build_venv_m.assert_not_called()
remove_venv_m.assert_not_called()
assert envs_file.exists()
envs = envs_file.read()
assert envs[venv_name]["minor"] == "3.6"
assert envs[venv_name]["patch"] == "3.6.6"
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6"
assert env.base == Path("/prefix")
assert (Path(tmp_dir) / f"{venv_name}-py3.6").exists()
def test_deactivate_non_activated_but_existing(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
python = ".".join(str(c) for c in sys.version_info[:2])
(Path(tmp_dir) / f"{venv_name}-py{python}").mkdir()
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
manager.deactivate(NullIO())
env = manager.get()
assert env.path == Path(tmp_dir) / f"{venv_name}-py{python}"
assert Path("/prefix")
def test_deactivate_activated(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
version = Version.from_parts(*sys.version_info[:3])
other_version = Version.parse("3.4") if version.major == 2 else version.next_minor()
(Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}").mkdir()
(
Path(tmp_dir) / f"{venv_name}-py{other_version.major}.{other_version.minor}"
).mkdir()
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {
"minor": f"{other_version.major}.{other_version.minor}",
"patch": other_version.text,
}
envs_file.write(doc)
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
manager.deactivate(NullIO())
env = manager.get()
assert env.path == Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}"
assert Path("/prefix")
envs = envs_file.read()
assert len(envs) == 0
def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
os.environ["VIRTUAL_ENV"] = "/environment/prefix"
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
(Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"}
envs_file.write(doc)
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(),
)
mocker.patch(
"subprocess.Popen.communicate",
side_effect=[("/prefix", None)],
)
env = manager.get()
assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7"
assert env.base == Path("/prefix")
def test_list(tmp_dir: str, manager: EnvManager, poetry: Poetry, config: Config):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
venvs = manager.list()
assert len(venvs) == 2
assert venvs[0].path == (Path(tmp_dir) / f"{venv_name}-py3.6")
assert venvs[1].path == (Path(tmp_dir) / f"{venv_name}-py3.7")
def test_remove_by_python_version(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
venv = manager.remove("3.6")
expected_venv_path = Path(tmp_dir) / f"{venv_name}-py3.6"
assert venv.path == expected_venv_path
assert not expected_venv_path.exists()
def test_remove_by_name(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
venv = manager.remove(f"{venv_name}-py3.6")
expected_venv_path = Path(tmp_dir) / f"{venv_name}-py3.6"
assert venv.path == expected_venv_path
assert not expected_venv_path.exists()
def test_remove_also_deactivates(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
(Path(tmp_dir) / f"{venv_name}-py3.7").mkdir()
(Path(tmp_dir) / f"{venv_name}-py3.6").mkdir()
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
envs_file = TOMLFile(Path(tmp_dir) / "envs.toml")
doc = tomlkit.document()
doc[venv_name] = {"minor": "3.6", "patch": "3.6.6"}
envs_file.write(doc)
venv = manager.remove("python3.6")
expected_venv_path = Path(tmp_dir) / f"{venv_name}-py3.6"
assert venv.path == expected_venv_path
assert not expected_venv_path.exists()
envs = envs_file.read()
assert venv_name not in envs
def test_remove_keeps_dir_if_not_deleteable(
tmp_dir: str,
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
):
# Ensure we empty rather than delete folder if its is an active mount point.
# See https://github.com/python-poetry/poetry/pull/2064
config.merge({"virtualenvs": {"path": str(tmp_dir)}})
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
venv_path = Path(tmp_dir) / f"{venv_name}-py3.6"
venv_path.mkdir()
folder1_path = venv_path / "folder1"
folder1_path.mkdir()
file1_path = folder1_path / "file1"
file1_path.touch(exist_ok=False)
file2_path = venv_path / "file2"
file2_path.touch(exist_ok=False)
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.6")),
)
def err_on_rm_venv_only(path: Path | str, *args: Any, **kwargs: Any) -> None:
if str(path) == str(venv_path):
raise OSError(16, "Test error") # ERRNO 16: Device or resource busy
else:
remove_directory(path)
m = mocker.patch(
"poetry.utils.env.remove_directory", side_effect=err_on_rm_venv_only
)
venv = manager.remove(f"{venv_name}-py3.6")
m.assert_any_call(venv_path)
assert venv_path == venv.path
assert venv_path.exists()
assert not folder1_path.exists()
assert not file1_path.exists()
assert not file2_path.exists()
m.side_effect = remove_directory # Avoid teardown using `err_on_rm_venv_only`
@pytest.mark.skipif(os.name == "nt", reason="Symlinks are not support for Windows")
def test_env_has_symlinks_on_nix(tmp_dir: str, tmp_venv: VirtualEnv):
assert os.path.islink(tmp_venv.python)
def test_run_with_input(tmp_dir: str, tmp_venv: VirtualEnv):
result = tmp_venv.run("python", "-", input_=MINIMAL_SCRIPT)
assert result == "Minimal Output" + os.linesep
def test_run_with_input_non_zero_return(tmp_dir: str, tmp_venv: VirtualEnv):
with pytest.raises(EnvCommandError) as process_error:
# Test command that will return non-zero returncode.
tmp_venv.run("python", "-", input_=ERRORING_SCRIPT)
assert process_error.value.e.returncode == 1
def test_run_with_keyboard_interrupt(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.run", side_effect=KeyboardInterrupt())
with pytest.raises(KeyboardInterrupt):
tmp_venv.run("python", "-", input_=MINIMAL_SCRIPT)
subprocess.run.assert_called_once()
def test_call_with_input_and_keyboard_interrupt(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.run", side_effect=KeyboardInterrupt())
kwargs = {"call": True}
with pytest.raises(KeyboardInterrupt):
tmp_venv.run("python", "-", input_=MINIMAL_SCRIPT, **kwargs)
subprocess.run.assert_called_once()
def test_call_no_input_with_keyboard_interrupt(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch("subprocess.call", side_effect=KeyboardInterrupt())
kwargs = {"call": True}
with pytest.raises(KeyboardInterrupt):
tmp_venv.run("python", "-", **kwargs)
subprocess.call.assert_called_once()
def test_run_with_called_process_error(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.run", side_effect=subprocess.CalledProcessError(42, "some_command")
)
with pytest.raises(EnvCommandError):
tmp_venv.run("python", "-", input_=MINIMAL_SCRIPT)
subprocess.run.assert_called_once()
def test_call_with_input_and_called_process_error(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.run", side_effect=subprocess.CalledProcessError(42, "some_command")
)
kwargs = {"call": True}
with pytest.raises(EnvCommandError):
tmp_venv.run("python", "-", input_=MINIMAL_SCRIPT, **kwargs)
subprocess.run.assert_called_once()
def test_call_no_input_with_called_process_error(
tmp_dir: str, tmp_venv: VirtualEnv, mocker: MockerFixture
):
mocker.patch(
"subprocess.call", side_effect=subprocess.CalledProcessError(42, "some_command")
)
kwargs = {"call": True}
with pytest.raises(EnvCommandError):
tmp_venv.run("python", "-", **kwargs)
subprocess.call.assert_called_once()
def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_ones_first( # noqa: E501
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
poetry.package.python_versions = "^3.6"
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
mocker.patch("sys.version_info", (2, 7, 16))
mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.7.5")),
)
m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
)
manager.create_venv(NullIO())
m.assert_called_with(
config_virtualenvs_path / f"{venv_name}-py3.7",
executable="python3",
flags={
"always-copy": False,
"system-site-packages": False,
"no-pip": False,
"no-setuptools": False,
},
prompt="simple-project-py3.7",
)
def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific_ones(
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
poetry.package.python_versions = "^3.6"
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
mocker.patch("sys.version_info", (2, 7, 16))
mocker.patch("subprocess.check_output", side_effect=["3.5.3", "3.9.0"])
m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
)
manager.create_venv(NullIO())
m.assert_called_with(
config_virtualenvs_path / f"{venv_name}-py3.9",
executable="python3.9",
flags={
"always-copy": False,
"system-site-packages": False,
"no-pip": False,
"no-setuptools": False,
},
prompt="simple-project-py3.9",
)
def test_create_venv_fails_if_no_compatible_python_version_could_be_found(
manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
poetry.package.python_versions = "^4.8"
mocker.patch("subprocess.check_output", side_effect=["", "", "", ""])
m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
)
with pytest.raises(NoCompatiblePythonVersionFound) as e:
manager.create_venv(NullIO())
expected_message = (
"Poetry was unable to find a compatible version. "
"If you have one, you can explicitly use it "
'via the "env use" command.'
)
assert str(e.value) == expected_message
assert m.call_count == 0
def test_create_venv_does_not_try_to_find_compatible_versions_with_executable(
manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
poetry.package.python_versions = "^4.8"
mocker.patch("subprocess.check_output", side_effect=["3.8.0"])
m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
)
with pytest.raises(NoCompatiblePythonVersionFound) as e:
manager.create_venv(NullIO(), executable="3.8")
expected_message = (
"The specified Python version (3.8.0) is not supported by the project (^4.8).\n"
"Please choose a compatible version or loosen the python constraint "
"specified in the pyproject.toml file."
)
assert str(e.value) == expected_message
assert m.call_count == 0
def test_create_venv_uses_patch_version_to_detect_compatibility(
manager: EnvManager,
poetry: Poetry,
config: Config,
mocker: MockerFixture,
config_virtualenvs_path: Path,
):
if "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
version = Version.from_parts(*sys.version_info[:3])
poetry.package.python_versions = "^" + ".".join(
str(c) for c in sys.version_info[:3]
)
venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent))
mocker.patch("sys.version_info", (version.major, version.minor, version.patch + 1))
check_output = mocker.patch(
"subprocess.check_output",
side_effect=check_output_wrapper(Version.parse("3.6.9")),
)
m = mocker.patch(
"poetry.utils.env.EnvManager.build_venv", side_effect=lambda *args, **kwargs: ""
)
manager.create_venv(NullIO())
assert not check_output.called
m.assert_called_with(
config_virtualenvs_path / f"{venv_name}-py{version.major}.{version.minor}",
executable=None,
flags={
"always-copy": False,