forked from conda/conda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_create.py
2994 lines (2557 loc) · 116 KB
/
test_create.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 (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
import json
import os
import re
import sys
from glob import glob
from itertools import chain
from json import loads as json_loads
from logging import getLogger
from os.path import (
abspath,
basename,
dirname,
exists,
isdir,
isfile,
islink,
join,
lexists,
relpath,
)
from pathlib import Path
from shutil import copyfile, rmtree
from subprocess import PIPE, Popen, check_call, check_output
from textwrap import dedent
from unittest.mock import patch
from uuid import uuid4
import pytest
import requests
from pytest import CaptureFixture, MonkeyPatch
from conda import CondaError, CondaMultiError
from conda.auxlib.compat import Utf8NamedTemporaryFile
from conda.auxlib.ish import dals
from conda.base.constants import (
CONDA_PACKAGE_EXTENSIONS,
PREFIX_MAGIC_FILE,
SafetyChecks,
)
from conda.base.context import conda_tests_ctxt_mgmt_def_pol, context, reset_context
from conda.common.compat import ensure_text_type, on_mac, on_win
from conda.common.io import env_var, env_vars, stderr_log_level
from conda.common.iterators import groupby_to_dict as groupby
from conda.common.path import (
get_bin_directory_short_path,
get_python_site_packages_short_path,
pyc_path,
)
from conda.common.serialize import json_dump, yaml_round_trip_load
from conda.core.index import get_reduced_index
from conda.core.package_cache_data import PackageCacheData
from conda.core.prefix_data import PrefixData, get_python_version_for_prefix
from conda.core.subdir_data import create_cache_dir
from conda.exceptions import (
ArgumentError,
CondaValueError,
DirectoryNotACondaEnvironmentError,
DisallowedPackageError,
DryRunExit,
EnvironmentLocationNotFound,
OperationNotAllowed,
PackageNotInstalledError,
PackagesNotFoundError,
RemoveError,
)
from conda.gateways.anaconda_client import read_binstar_tokens
from conda.gateways.disk.create import compile_multiple_pyc
from conda.gateways.disk.delete import path_is_clean, rm_rf
from conda.gateways.disk.permissions import make_read_only
from conda.gateways.disk.update import touch
from conda.gateways.subprocess import (
Response,
subprocess_call,
subprocess_call_with_clean_env,
)
from conda.models.channel import Channel
from conda.models.match_spec import MatchSpec
from conda.models.version import VersionOrder
from conda.resolve import Resolve
from conda.testing import CondaCLIFixture
from conda.testing.integration import (
BIN_DIRECTORY,
PYTHON_BINARY,
TEST_LOG_LEVEL,
Commands,
cp_or_copy,
env_or_set,
get_shortcut_dir,
make_temp_channel,
make_temp_env,
make_temp_package_cache,
make_temp_prefix,
package_is_installed,
reload_config,
run_command,
tempdir,
which_or_where,
)
log = getLogger(__name__)
stderr_log_level(TEST_LOG_LEVEL, "conda")
stderr_log_level(TEST_LOG_LEVEL, "requests")
# all tests in this file are integration tests
pytestmark = pytest.mark.integration
@pytest.fixture
def clear_package_cache() -> None:
PackageCacheData.clear()
@pytest.mark.skipif(
context.subdir not in ("linux-64", "osx-64", "win-32", "win-64", "linux-32"),
reason="Skip unsupported platforms",
)
def test_install_python2_and_search(clear_package_cache: None):
with Utf8NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as env_txt:
log.warning(f"Creating empty temporary environment txt file {env_txt}")
environment_txt = env_txt.name
with patch(
"conda.core.envs_manager.get_user_environments_txt_file",
return_value=environment_txt,
) as _:
with env_vars(
{
"CONDA_ALLOW_NON_CHANNEL_URLS": "true",
"CONDA_REGISTER_ENVS": "true",
},
stack_callback=conda_tests_ctxt_mgmt_def_pol,
):
with make_temp_env("python=2", use_restricted_unicode=on_win) as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, "python=2")
run_command(
Commands.CONFIG,
prefix,
"--add",
"channels",
"https://repo.continuum.io/pkgs/not-a-channel",
)
# regression test for #4513
run_command(
Commands.CONFIG,
prefix,
"--add",
"channels",
"https://repo.continuum.io/pkgs/not-a-channel",
)
stdout, stderr, _ = run_command(
Commands.SEARCH, prefix, "python", "--json"
)
packages = json.loads(stdout)
assert len(packages) == 1
stdout, stderr, _ = run_command(
Commands.SEARCH, prefix, "python", "--json", "--envs"
)
envs_result = json.loads(stdout)
assert any(match["location"] == prefix for match in envs_result)
stdout, stderr, _ = run_command(
Commands.SEARCH, prefix, "python", "--envs"
)
assert prefix in stdout
os.unlink(environment_txt)
def test_run_preserves_arguments(clear_package_cache: None):
with make_temp_env("python=3") as prefix:
echo_args_py = os.path.join(prefix, "echo-args.py")
with open(echo_args_py, "w") as echo_args:
echo_args.write("import sys\n")
echo_args.write("for arg in sys.argv[1:]: print(arg)\n")
# If 'two two' were 'two' this test would pass.
args = ("one", "two two", "three")
output, _, _ = run_command(Commands.RUN, prefix, "python", echo_args_py, *args)
os.unlink(echo_args_py)
lines = output.split("\n")
for i, line in enumerate(lines):
if i < len(args):
assert args[i] == line.replace("\r", "")
def test_create_install_update_remove_smoketest(clear_package_cache: None):
with make_temp_env("python=3.9") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, "python=3")
run_command(Commands.INSTALL, prefix, "flask=2.0.1")
assert package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "python=3")
run_command(Commands.INSTALL, prefix, "--force-reinstall", "flask=2.0.1")
assert package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "python=3")
run_command(Commands.UPDATE, prefix, "flask")
assert not package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "flask")
assert package_is_installed(prefix, "python=3")
run_command(Commands.REMOVE, prefix, "flask")
assert not package_is_installed(prefix, "flask=0.*")
assert package_is_installed(prefix, "python=3")
stdout, stderr, _ = run_command(Commands.LIST, prefix, "--revisions")
assert not stderr
assert " (rev 4)\n" in stdout
assert " (rev 5)\n" not in stdout
run_command(Commands.INSTALL, prefix, "--revision", "0")
assert not package_is_installed(prefix, "flask")
assert package_is_installed(prefix, "python=3")
def test_install_broken_post_install_keeps_existing_folders(clear_package_cache: None):
# regression test for https://github.com/conda/conda/issues/8258
with make_temp_env("python=3.5") as prefix:
assert exists(join(prefix, BIN_DIRECTORY))
assert package_is_installed(prefix, "python=3")
run_command(
Commands.INSTALL,
prefix,
"-c",
"conda-test",
"failing_post_link",
use_exception_handler=True,
)
assert exists(join(prefix, BIN_DIRECTORY))
def test_safety_checks(clear_package_cache: None):
# This test uses https://anaconda.org/conda-test/spiffy-test-app/0.5/download/noarch/spiffy-test-app-0.5-pyh6afbcc8_0.tar.bz2
# which is a modification of https://anaconda.org/conda-test/spiffy-test-app/1.0/download/noarch/spiffy-test-app-1.0-pyh6afabb7_0.tar.bz2
# as documented in info/README within that package.
# I also had to fix the post-link script in the package by adding quotation marks to handle
# spaces in path names.
with make_temp_env() as prefix:
with open(join(prefix, "condarc"), "a") as fh:
fh.write("safety_checks: enabled\n")
fh.write("extra_safety_checks: true\n")
reload_config(prefix)
assert context.safety_checks is SafetyChecks.enabled
with pytest.raises(CondaMultiError) as exc:
run_command(
Commands.INSTALL, prefix, "-c", "conda-test", "spiffy-test-app=0.5"
)
error_message = str(exc.value)
message1 = dals(
"""
The path 'site-packages/spiffy_test_app-1.0-py2.7.egg-info/top_level.txt'
has an incorrect size.
reported size: 32 bytes
actual size: 16 bytes
"""
)
message2 = "has a sha256 mismatch."
assert message1 in error_message
assert message2 in error_message
with open(join(prefix, "condarc"), "w") as fh:
fh.write("safety_checks: warn\n")
fh.write("extra_safety_checks: true\n")
reload_config(prefix)
assert context.safety_checks is SafetyChecks.warn
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "-c", "conda-test", "spiffy-test-app=0.5"
)
assert message1 in stderr
assert message2 in stderr
assert package_is_installed(prefix, "spiffy-test-app=0.5")
with make_temp_env() as prefix:
with open(join(prefix, "condarc"), "a") as fh:
fh.write("safety_checks: disabled\n")
reload_config(prefix)
assert context.safety_checks is SafetyChecks.disabled
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "-c", "conda-test", "spiffy-test-app=0.5"
)
assert message1 not in stderr
assert message2 not in stderr
assert package_is_installed(prefix, "spiffy-test-app=0.5")
def test_json_create_install_update_remove(clear_package_cache: None):
# regression test for #5384
def assert_json_parsable(content):
string = None
try:
for string in content and content.split("\0") or ():
json.loads(string)
except Exception as e:
log.warn(
"Problem parsing json output.\n"
" content: %s\n"
" string: %s\n"
" error: %r",
content,
string,
e,
)
raise
try:
prefix = make_temp_prefix(str(uuid4())[:7])
stdout, stderr, _ = run_command(
Commands.CREATE,
prefix,
"python=3.8",
"--json",
"--dry-run",
use_exception_handler=True,
)
assert_json_parsable(stdout)
# regression test for #5825
# contents of LINK and UNLINK is expected to have Dist format
json_obj = json.loads(stdout)
dist_dump = json_obj["actions"]["LINK"][0]
assert "dist_name" in dist_dump
stdout, stderr, _ = run_command(Commands.CREATE, prefix, "python=3.8", "--json")
assert_json_parsable(stdout)
assert not stderr
json_obj = json.loads(stdout)
dist_dump = json_obj["actions"]["LINK"][0]
assert "dist_name" in dist_dump
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "flask=2.0.1", "--json"
)
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "python=3")
# Test force reinstall
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "--force-reinstall", "flask=2.0.1", "--json"
)
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "python=3")
stdout, stderr, _ = run_command(Commands.UPDATE, prefix, "flask", "--json")
assert_json_parsable(stdout)
assert not stderr
assert not package_is_installed(prefix, "flask=2.0.1")
assert package_is_installed(prefix, "flask")
assert package_is_installed(prefix, "python=3")
stdout, stderr, _ = run_command(Commands.REMOVE, prefix, "flask", "--json")
assert_json_parsable(stdout)
assert not stderr
assert not package_is_installed(prefix, "flask=2.*")
assert package_is_installed(prefix, "python=3")
# regression test for #5825
# contents of LINK and UNLINK is expected to have Dist format
json_obj = json.loads(stdout)
dist_dump = json_obj["actions"]["UNLINK"][0]
assert "dist_name" in dist_dump
stdout, stderr, _ = run_command(Commands.LIST, prefix, "--revisions", "--json")
assert not stderr
json_obj = json.loads(stdout)
assert len(json_obj) == 5
assert json_obj[4]["rev"] == 4
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "--revision", "0", "--json"
)
assert_json_parsable(stdout)
assert not stderr
assert not package_is_installed(prefix, "flask")
assert package_is_installed(prefix, "python=3")
finally:
rmtree(prefix, ignore_errors=True)
def test_not_writable_env_raises_EnvironmentNotWritableError(clear_package_cache: None):
with make_temp_env() as prefix:
make_read_only(join(prefix, PREFIX_MAGIC_FILE))
stdout, stderr, _ = run_command(
Commands.INSTALL, prefix, "openssl", use_exception_handler=True
)
assert "EnvironmentNotWritableError" in stderr
assert prefix in stderr
def test_conda_update_package_not_installed(clear_package_cache: None):
with make_temp_env() as prefix:
with pytest.raises(PackageNotInstalledError):
run_command(Commands.UPDATE, prefix, "sqlite", "openssl")
with pytest.raises(CondaError) as conda_error:
run_command(Commands.UPDATE, prefix, "conda-forge::*")
assert conda_error.value.message.startswith("Invalid spec for 'conda update'")
def test_noarch_python_package_with_entry_points(clear_package_cache: None):
# this channel has an ancient flask that is incompatible with jinja2>=3.1.0
with make_temp_env("-c", "conda-test", "flask", "jinja2<3.1") as prefix:
py_ver = get_python_version_for_prefix(prefix)
sp_dir = get_python_site_packages_short_path(py_ver)
py_file = sp_dir + "/flask/__init__.py"
pyc_file = pyc_path(py_file, py_ver).replace("/", os.sep)
assert isfile(join(prefix, py_file))
assert isfile(join(prefix, pyc_file))
exe_path = join(prefix, get_bin_directory_short_path(), "flask")
if on_win:
exe_path += ".exe"
assert isfile(exe_path)
output = check_output([exe_path, "--help"], text=True)
assert "Usage: flask" in output
run_command(Commands.REMOVE, prefix, "flask")
assert not isfile(join(prefix, py_file))
assert not isfile(join(prefix, pyc_file))
assert not isfile(exe_path)
def test_noarch_python_package_without_entry_points(clear_package_cache: None):
# regression test for #4546
with make_temp_env("-c", "conda-test", "itsdangerous") as prefix:
py_ver = get_python_version_for_prefix(prefix)
sp_dir = get_python_site_packages_short_path(py_ver)
py_file = sp_dir + "/itsdangerous.py"
pyc_file = pyc_path(py_file, py_ver).replace("/", os.sep)
assert isfile(join(prefix, py_file))
assert isfile(join(prefix, pyc_file))
run_command(Commands.REMOVE, prefix, "itsdangerous")
assert not isfile(join(prefix, py_file))
assert not isfile(join(prefix, pyc_file))
def test_noarch_python_package_reinstall_on_pyver_change(clear_package_cache: None):
with make_temp_env(
"-c",
"conda-test",
"itsdangerous=0.24",
"python=3",
use_restricted_unicode=on_win,
) as prefix:
py_ver = get_python_version_for_prefix(prefix)
assert py_ver.startswith("3")
sp_dir = get_python_site_packages_short_path(py_ver)
py_file = sp_dir + "/itsdangerous.py"
pyc_file_py3 = pyc_path(py_file, py_ver).replace("/", os.sep)
assert isfile(join(prefix, py_file))
assert isfile(join(prefix, pyc_file_py3))
run_command(Commands.INSTALL, prefix, "python=2")
assert not isfile(join(prefix, pyc_file_py3)) # python3 pyc file should be gone
py_ver = get_python_version_for_prefix(prefix)
assert py_ver.startswith("2")
sp_dir = get_python_site_packages_short_path(py_ver)
py_file = sp_dir + "/itsdangerous.py"
pyc_file_py2 = pyc_path(py_file, py_ver).replace("/", os.sep)
assert isfile(join(prefix, py_file))
assert isfile(join(prefix, pyc_file_py2))
def test_noarch_generic_package(clear_package_cache: None):
with make_temp_env("-c", "conda-test", "font-ttf-inconsolata") as prefix:
assert isfile(join(prefix, "fonts", "Inconsolata-Regular.ttf"))
def test_override_channels(clear_package_cache: None):
with pytest.raises(OperationNotAllowed):
with env_var(
"CONDA_OVERRIDE_CHANNELS_ENABLED",
"no",
stack_callback=conda_tests_ctxt_mgmt_def_pol,
):
with make_temp_env("--override-channels", "python") as prefix:
assert prefix
with pytest.raises(ArgumentError):
with make_temp_env("--override-channels", "python") as prefix:
assert prefix
stdout, stderr, _ = run_command(
Commands.SEARCH,
None,
"--override-channels",
"-c",
"conda-test",
"flask",
"--json",
)
assert not stderr
assert len(json.loads(stdout)["flask"]) < 3
assert json.loads(stdout)["flask"][0]["noarch"] == "python"
def test_create_empty_env(clear_package_cache: None):
with make_temp_env() as prefix:
assert exists(join(prefix, "conda-meta/history"))
list_output = run_command(Commands.LIST, prefix)
stdout = list_output[0]
stderr = list_output[1]
assert stdout == dals(
f"""
# packages in environment at {prefix}:
#
# Name Version Build Channel
"""
)
assert not stderr
revision_output = run_command(Commands.LIST, prefix, "--revisions")
stdout = revision_output[0]
stderr = revision_output[1]
assert not stderr
assert isinstance(stdout, str)
@pytest.mark.skipif(reason="conda-forge doesn't have a full set of packages")
def test_strict_channel_priority(clear_package_cache: None):
with make_temp_env() as prefix:
stdout, stderr, rc = run_command(
Commands.CREATE,
prefix,
"-c",
"conda-forge",
"-c",
"defaults",
"python=3.6",
"quaternion",
"--strict-channel-priority",
"--dry-run",
"--json",
use_exception_handler=True,
)
assert not rc
json_obj = json_loads(stdout)
# We see:
# libcxx pkgs/main/osx-64::libcxx-4.0.1-h579ed51_0
# Rather than spending more time looking for another package, just filter it out.
# Same thing for Windows, this is because we use MKL always. Perhaps there's a
# way to exclude it, I tried the "nomkl" package but that did not work.
json_obj["actions"]["LINK"] = [
link
for link in json_obj["actions"]["LINK"]
if link["name"] not in ("libcxx", "libcxxabi", "mkl", "intel-openmp")
]
channel_groups = groupby(lambda x: x["channel"], json_obj["actions"]["LINK"])
channel_groups = sorted(list(channel_groups))
assert channel_groups == [
"conda-forge",
]
def test_strict_resolve_get_reduced_index(clear_package_cache: None):
channels = (Channel("defaults"),)
specs = (MatchSpec("anaconda"),)
index = get_reduced_index(None, channels, context.subdirs, specs, "repodata.json")
r = Resolve(index, channels=channels)
with env_var(
"CONDA_CHANNEL_PRIORITY",
"strict",
stack_callback=conda_tests_ctxt_mgmt_def_pol,
):
reduced_index = r.get_reduced_index(specs)
channel_name_groups = {
name: {prec.channel.name for prec in group}
for name, group in groupby(lambda x: x["name"], reduced_index).items()
}
channel_name_groups = {
name: channel_names
for name, channel_names in channel_name_groups.items()
if len(channel_names) > 1
}
assert {} == channel_name_groups
def test_list_with_pip_no_binary(clear_package_cache: None):
from conda.exports import rm_rf as _rm_rf
# For this test to work on Windows, you can either pass use_restricted_unicode=on_win
# to make_temp_env(), or you can set PYTHONUTF8 to 1 (and use Python 3.7 or above).
# We elect to test the more complex of the two options.
py_ver = "3.10"
with make_temp_env("python=" + py_ver, "pip") as prefix:
evs = {"PYTHONUTF8": "1"}
# This test does not activate the env.
if on_win:
evs["CONDA_DLL_SEARCH_MODIFICATION_ENABLE"] = "1"
with env_vars(evs, stack_callback=conda_tests_ctxt_mgmt_def_pol):
check_call(
PYTHON_BINARY + " -m pip install --no-binary flask flask==1.0.2",
cwd=prefix,
shell=True,
)
PrefixData._cache_.clear()
stdout, stderr, _ = run_command(Commands.LIST, prefix)
stdout_lines = stdout.split("\n")
assert any(
line.endswith("pypi")
for line in stdout_lines
if line.lower().startswith("flask")
)
# regression test for #5847
# when using rm_rf on a directory
assert prefix in PrefixData._cache_
_rm_rf(join(prefix, get_python_site_packages_short_path(py_ver)))
assert prefix not in PrefixData._cache_
def test_list_with_pip_wheel(clear_package_cache: None):
from conda.exports import rm_rf as _rm_rf
py_ver = "3.10"
with make_temp_env("python=" + py_ver, "pip") as prefix:
evs = {"PYTHONUTF8": "1"}
# This test does not activate the env.
if on_win:
evs["CONDA_DLL_SEARCH_MODIFICATION_ENABLE"] = "1"
with env_vars(evs, stack_callback=conda_tests_ctxt_mgmt_def_pol):
check_call(
PYTHON_BINARY + " -m pip install flask==1.0.2",
cwd=prefix,
shell=True,
)
PrefixData._cache_.clear()
stdout, stderr, _ = run_command(Commands.LIST, prefix)
stdout_lines = stdout.split("\n")
assert any(
line.endswith("pypi")
for line in stdout_lines
if line.lower().startswith("flask")
)
# regression test for #3433
run_command(Commands.INSTALL, prefix, "python=3.9", no_capture=True)
assert package_is_installed(prefix, "python=3.9")
# regression test for #5847
# when using rm_rf on a file
assert prefix in PrefixData._cache_
_rm_rf(join(prefix, get_python_site_packages_short_path("3.9")), "os.py")
assert prefix not in PrefixData._cache_
# regression test for #5980, related to #5847
with make_temp_env() as prefix:
assert isdir(prefix)
assert prefix in PrefixData._cache_
rmtree(prefix)
assert not isdir(prefix)
assert prefix in PrefixData._cache_
_rm_rf(prefix)
assert not isdir(prefix)
assert prefix not in PrefixData._cache_
def test_compare_success(clear_package_cache: None):
with make_temp_env("python=3.6", "flask=1.0.2", "bzip2=1.0.8") as prefix:
env_file = join(prefix, "env.yml")
touch(env_file)
with open(env_file, "w") as f:
f.write(
dals(
"""
name: dummy
channels:
- defaults
dependencies:
- bzip2=1.0.8
- flask>=1.0.1,<=1.0.4
"""
)
)
output, _, _ = run_command(Commands.COMPARE, prefix, env_file, "--json")
assert "Success" in output
rmtree(prefix, ignore_errors=True)
def test_compare_fail(clear_package_cache: None):
with make_temp_env("python=3.6", "flask=1.0.2", "bzip2=1.0.8") as prefix:
env_file = join(prefix, "env.yml")
touch(env_file)
with open(env_file, "w") as f:
f.write(
dals(
"""
name: dummy
channels:
- defaults
dependencies:
- yaml
- flask=1.0.3
"""
)
)
output, _, _ = run_command(Commands.COMPARE, prefix, env_file, "--json")
assert "yaml not found" in output
assert (
"flask found but mismatch. Specification pkg: flask=1.0.3, Running pkg: flask==1.0.2=py36_1"
in output
)
rmtree(prefix, ignore_errors=True)
def test_install_tarball_from_local_channel(
clear_package_cache: None, tmp_path: Path, monkeypatch: MonkeyPatch
):
# Regression test for #2812
# install from local channel
"""
path = u'/private/var/folders/y1/ljv50nrs49gdqkrp01wy3_qm0000gn/T/pytest-of-rdonnelly/pytest-16/test_install_tarball_from_loca0/c352_çñßôêá'
if on_win:
path = u'C:\\çñ'
percy = u'file:///C:/%C3%A7%C3%B1'
else:
path = u'/çñ'
percy = 'file:///%C3%A7%C3%B1'
url = path_to_url(path)
assert url == percy
path2 = url_to_path(url)
assert path == path2
assert type(path) == type(path2)
# path_to_url("c:\\users\\est_install_tarball_from_loca0\a48a_6f154a82dbe3c7")
"""
monkeypatch.setenv("CONDA_BLD_PATH", str(tmp_path))
reset_context()
assert context.bld_path == str(tmp_path)
with make_temp_env() as prefix, make_temp_channel(["flask-2.1.3"]) as channel:
run_command(Commands.INSTALL, prefix, "-c", channel, "flask=2.1.3", "--json")
assert package_is_installed(prefix, channel + "::" + "flask")
flask_fname = [
p for p in PrefixData(prefix).iter_records() if p["name"] == "flask"
][0]["fn"]
run_command(Commands.REMOVE, prefix, "flask")
assert not package_is_installed(prefix, "flask=0")
# Regression test for 2970
# install from build channel as a tarball
tar_path = Path(PackageCacheData.first_writable().pkgs_dir, flask_fname)
if not tar_path.is_file():
tar_path = tar_path.with_suffix(".tar.bz2")
# create a temporary conda-bld
conda_bld_sub = tmp_path / context.subdir
conda_bld_sub.mkdir(exist_ok=True)
tar_bld_path = str(conda_bld_sub / tar_path.name)
copyfile(tar_path, tar_bld_path)
run_command(Commands.INSTALL, prefix, tar_bld_path)
assert package_is_installed(prefix, "flask")
# Regression test for #462
with make_temp_env(tar_bld_path) as prefix2:
assert package_is_installed(prefix2, "flask")
def test_tarball_install(clear_package_cache: None):
with make_temp_env("bzip2") as prefix:
# We have a problem. If bzip2 is extracted already but the tarball is missing then this fails.
bzip2_data = [
p for p in PrefixData(prefix).iter_records() if p["name"] == "bzip2"
][0]
bzip2_fname = bzip2_data["fn"]
tar_old_path = join(PackageCacheData.first_writable().pkgs_dir, bzip2_fname)
if not isfile(tar_old_path):
log.warning(
"Installing bzip2 failed to save the compressed package, downloading it 'manually' .."
)
# Downloading to the package cache causes some internal inconsistency here:
#
# File "/Users/rdonnelly/conda/conda/conda/common/path.py", line 72, in url_to_path
# raise CondaError("You can only turn absolute file: urls into paths (not %s)" % url)
# conda.CondaError: You can only turn absolute file: urls into paths (not https://repo.anaconda.com/pkgs/main/osx-64/bzip2-1.0.6-h1de35cc_5.tar.bz2)
#
# .. so download to the root of the prefix instead.
tar_old_path = join(prefix, bzip2_fname)
from conda.gateways.connection.download import download
download(
"https://repo.anaconda.com/pkgs/main/"
+ bzip2_data.subdir
+ "/"
+ bzip2_fname,
tar_old_path,
None,
)
assert isfile(tar_old_path), f"Failed to cache:\n{tar_old_path}"
# It would be nice to be able to do this, but the cache folder name comes from
# the file name and that is then all out of whack with the metadata.
# tar_new_path = join(prefix, '家' + bzip2_fname)
tar_new_path = join(prefix, bzip2_fname)
run_command(Commands.RUN, prefix, cp_or_copy, tar_old_path, tar_new_path)
assert isfile(
tar_new_path
), f"Failed to copy:\n{tar_old_path}\nto:\n{tar_new_path}"
run_command(Commands.INSTALL, prefix, tar_new_path)
assert package_is_installed(prefix, "bzip2")
def test_tarball_install_and_bad_metadata(clear_package_cache: None):
with make_temp_env("python=3.10.9", "flask=1.1.1", "--json") as prefix:
assert package_is_installed(prefix, "flask==1.1.1")
flask_data = [
p for p in PrefixData(prefix).iter_records() if p["name"] == "flask"
][0]
run_command(Commands.REMOVE, prefix, "flask")
assert not package_is_installed(prefix, "flask==1.1.1")
assert package_is_installed(prefix, "python")
flask_fname = flask_data["fn"]
tar_old_path = join(PackageCacheData.first_writable().pkgs_dir, flask_fname)
# if a .tar.bz2 is already in the file cache, it's fine. Accept it or the .conda file here.
if not isfile(tar_old_path):
tar_old_path = tar_old_path.replace(".conda", ".tar.bz2")
assert isfile(tar_old_path)
with pytest.raises(DryRunExit):
run_command(Commands.INSTALL, prefix, tar_old_path, "--dry-run")
assert not package_is_installed(prefix, "flask=1.*")
# regression test for #2886 (part 1 of 2)
# install tarball from package cache, default channel
run_command(Commands.INSTALL, prefix, tar_old_path)
assert package_is_installed(prefix, "flask=1.*")
# regression test for #2626
# install tarball with full path, outside channel
tar_new_path = join(prefix, flask_fname)
copyfile(tar_old_path, tar_new_path)
run_command(Commands.INSTALL, prefix, tar_new_path)
assert package_is_installed(prefix, "flask=1")
# regression test for #2626
# install tarball with relative path, outside channel
run_command(Commands.REMOVE, prefix, "flask")
assert not package_is_installed(prefix, "flask=1.1.1")
tar_new_path = relpath(tar_new_path)
run_command(Commands.INSTALL, prefix, tar_new_path)
assert package_is_installed(prefix, "flask=1")
# regression test for #2886 (part 2 of 2)
# install tarball from package cache, local channel
run_command(Commands.REMOVE, prefix, "flask", "--json")
assert not package_is_installed(prefix, "flask=1")
run_command(Commands.INSTALL, prefix, tar_old_path)
# The last install was from the `local::` channel
assert package_is_installed(prefix, "flask")
# regression test for #2599
# ignore json files in conda-meta that don't conform to name-version-build.json
if not on_win:
# xz is only a python dependency on unix
xz_prec = next(PrefixData(prefix).query("xz"))
dist_name = xz_prec.dist_str().split("::")[-1]
xz_prefix_data_json_path = join(prefix, "conda-meta", dist_name + ".json")
copyfile(xz_prefix_data_json_path, join(prefix, "conda-meta", "xz.json"))
rm_rf(xz_prefix_data_json_path)
assert not lexists(xz_prefix_data_json_path)
PrefixData._cache_ = {}
assert not package_is_installed(prefix, "xz")
@pytest.mark.skipif(on_win, reason="windows python doesn't depend on readline")
def test_update_with_pinned_packages(clear_package_cache: None):
# regression test for #6914
with make_temp_env(
"-c", "https://repo.anaconda.com/pkgs/free", "python=2.7.12"
) as prefix:
assert package_is_installed(prefix, "readline=6.2")
# removing the history allows python to be updated too
open(join(prefix, "conda-meta", "history"), "w").close()
PrefixData._cache_.clear()
run_command(Commands.UPDATE, prefix, "readline", no_capture=True)
assert package_is_installed(prefix, "readline")
assert not package_is_installed(prefix, "readline=6.2")
assert package_is_installed(prefix, "python=2.7")
assert not package_is_installed(prefix, "python=2.7.12")
def test_pinned_override_with_explicit_spec(clear_package_cache: None):
with make_temp_env("python=3.9") as prefix:
run_command(
Commands.CONFIG, prefix, "--add", "pinned_packages", "python=3.9.16"
)
run_command(Commands.INSTALL, prefix, "python=3.10", no_capture=True)
assert package_is_installed(prefix, "python=3.10")
def test_remove_all(clear_package_cache: None):
with make_temp_env("python") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, "python")
# regression test for #2154
with pytest.raises(PackagesNotFoundError) as exc:
run_command(Commands.REMOVE, prefix, "python", "foo", "numpy")
exception_string = repr(exc.value)
assert "PackagesNotFoundError" in exception_string
assert "- numpy" in exception_string
assert "- foo" in exception_string
run_command(Commands.REMOVE, prefix, "--all")
assert path_is_clean(prefix)
@pytest.mark.skipif(
on_win, reason="windows usually doesn't support symlinks out-of-the box"
)
@patch("conda.core.link.hardlink_supported", side_effect=lambda x, y: False)
def test_allow_softlinks(hardlink_supported_mock, clear_package_cache: None):
hardlink_supported_mock._result_cache.clear()
with env_var(
"CONDA_ALLOW_SOFTLINKS",
"true",
stack_callback=conda_tests_ctxt_mgmt_def_pol,
):
with make_temp_env("pip") as prefix:
assert islink(
join(
prefix,
get_python_site_packages_short_path(
get_python_version_for_prefix(prefix)
),
"pip",
"__init__.py",
)
)
hardlink_supported_mock._result_cache.clear()
@pytest.mark.skipif(on_win, reason="nomkl not present on windows")
def test_remove_features(clear_package_cache: None):
with make_temp_env("python=2", "numpy=1.13", "nomkl") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, "numpy")
assert package_is_installed(prefix, "nomkl")
assert not package_is_installed(prefix, "mkl")
# A consequence of discontinuing use of the 'features' key and instead
# using direct dependencies is that removing the feature means that
# packages associated with the track_features base package are completely removed
# and not replaced with equivalent non-variant packages as before.
run_command(Commands.REMOVE, prefix, "--features", "nomkl")
# assert package_is_installed(prefix, 'numpy') # removed per above comment
assert not package_is_installed(prefix, "nomkl")
# assert package_is_installed(prefix, 'mkl') # removed per above comment
@pytest.mark.skipif(
on_win and context.bits == 32, reason="no 32-bit windows python on conda-forge"
)
@pytest.mark.flaky(reruns=2)
def test_dash_c_usage_replacing_python(clear_package_cache: None):
# Regression test for #2606
with make_temp_env("-c", "conda-forge", "python=3.10", no_capture=True) as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, "conda-forge::python=3.10")
run_command(Commands.INSTALL, prefix, "decorator")
assert package_is_installed(prefix, "conda-forge::python=3.10")
with make_temp_env("--clone", prefix) as clone_prefix:
assert package_is_installed(clone_prefix, "conda-forge::python=3.10")
assert package_is_installed(clone_prefix, "decorator")
# Regression test for #2645
fn = glob(join(prefix, "conda-meta", "python-3.10*.json"))[-1]
with open(fn) as f:
data = json.load(f)
for field in ("url", "channel", "schannel"):
if field in data: