forked from conda/conda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_create.py
2465 lines (2066 loc) · 117 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
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import bz2
from contextlib import contextmanager
from datetime import datetime
from glob import glob
from conda._vendor.toolz.itertoolz import groupby
from conda.gateways.disk.permissions import make_read_only
from conda.models.channel import Channel
from conda.resolve import Resolve
from itertools import chain
import json
from json import loads as json_loads
from logging import DEBUG, INFO, getLogger
import os
from os.path import basename, dirname, exists, isdir, isfile, join, lexists, relpath, islink
from random import sample
import re
from shlex import split
from shutil import copyfile, rmtree
from subprocess import check_call, CalledProcessError, check_output, Popen, PIPE
import sys
from tempfile import gettempdir
from unittest import TestCase
from uuid import uuid4
import pytest
import requests
from conda import CondaError, CondaMultiError, plan, __version__ as CONDA_VERSION, \
CONDA_PACKAGE_ROOT
from conda._vendor.auxlib.entity import EntityEncoder
from conda._vendor.auxlib.ish import dals
from conda.base.constants import CONDA_TARBALL_EXTENSION, PACKAGE_CACHE_MAGIC_FILE, SafetyChecks, \
PREFIX_MAGIC_FILE
from conda.base.context import Context, context, reset_context
from conda.cli.conda_argparse import do_call
from conda.cli.main import generate_parser, init_loggers
from conda.common.compat import PY2, iteritems, itervalues, text_type, ensure_text_type
from conda.common.io import argv, captured, disable_logger, env_var, stderr_log_level, dashlist
from conda.common.path import get_bin_directory_short_path, get_python_site_packages_short_path, \
pyc_path
from conda.common.serialize import yaml_load, json_dump
from conda.common.url import path_to_url
from conda.core.index import get_reduced_index
from conda.core.prefix_data import PrefixData, get_python_version_for_prefix
from conda.core.package_cache_data import PackageCacheData
from conda.core.subdir_data import create_cache_dir
from conda.exceptions import CommandArgumentError, DryRunExit, OperationNotAllowed, \
PackagesNotFoundError, RemoveError, conda_exception_handler, PackageNotInstalledError, \
DisallowedPackageError, UnsatisfiableError, DirectoryNotACondaEnvironmentError
from conda.gateways.anaconda_client import read_binstar_tokens
from conda.gateways.disk.create import mkdir_p
from conda.gateways.disk.delete import rm_rf
from conda.gateways.disk.update import touch
from conda.gateways.logging import TRACE
from conda.gateways.subprocess import subprocess_call
from conda.models.match_spec import MatchSpec
from conda.models.records import PackageRecord
from conda.models.version import VersionOrder
from conda.utils import on_win
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
log = getLogger(__name__)
TRACE, DEBUG, INFO = TRACE, DEBUG, INFO # these are so the imports aren't cleared, but it's easy to switch back and forth
TEST_LOG_LEVEL = DEBUG
stderr_log_level(TEST_LOG_LEVEL, 'conda')
stderr_log_level(TEST_LOG_LEVEL, 'requests')
PYTHON_BINARY = 'python.exe' if on_win else 'bin/python'
BIN_DIRECTORY = 'Scripts' if on_win else 'bin'
UINCODE_CHARACTERS = u"ōγђ家固한"
UINCODE_CHARACTERS = u"áêñßôç"
def escape_for_winpath(p):
return p.replace('\\', '\\\\')
def make_temp_prefix(name=None, create_directory=True):
tempdir = gettempdir()
if PY2:
dirpath = str(uuid4())[:8] if name is None else name
else:
random_unicode = ''.join(sample(UINCODE_CHARACTERS, len(UINCODE_CHARACTERS)))
dirpath = (str(uuid4())[:4] + ' ' + random_unicode) if name is None else name
prefix = join(tempdir, dirpath)
os.makedirs(prefix)
if create_directory:
assert isdir(prefix)
else:
os.removedirs(prefix)
return prefix
class Commands:
CONFIG = "config"
CLEAN = "clean"
CREATE = "create"
INFO = "info"
INSTALL = "install"
LIST = "list"
REMOVE = "remove"
SEARCH = "search"
UPDATE = "update"
def run_command(command, prefix, *arguments, **kwargs):
use_exception_handler = kwargs.get('use_exception_handler', False)
arguments = list(arguments)
p = generate_parser()
if command is Commands.CONFIG:
arguments.append('--file "{0}"'.format(join(prefix, 'condarc')))
if command in (Commands.LIST, Commands.CREATE, Commands.INSTALL,
Commands.REMOVE, Commands.UPDATE):
arguments.append('-p "{0}"'.format(prefix))
if command in (Commands.CREATE, Commands.INSTALL, Commands.REMOVE, Commands.UPDATE):
arguments.extend(["-y", "-q"])
arguments = list(map(escape_for_winpath, arguments))
command_line = "{0} {1}".format(command, " ".join(arguments))
split_command_line = split(command_line)
args = p.parse_args(split_command_line)
context._set_argparse_args(args)
init_loggers(context)
print("\n\nEXECUTING COMMAND >>> $ conda %s\n\n" % command_line, file=sys.stderr)
with stderr_log_level(TEST_LOG_LEVEL, 'conda'), stderr_log_level(TEST_LOG_LEVEL, 'requests'):
with argv(['python_api'] + split_command_line), captured() as c:
if use_exception_handler:
conda_exception_handler(do_call, args, p)
else:
do_call(args, p)
print(c.stderr, file=sys.stderr)
print(c.stdout, file=sys.stderr)
if command is Commands.CONFIG:
reload_config(prefix)
return c.stdout, c.stderr
@contextmanager
def make_temp_env(*packages, **kwargs):
name = kwargs.pop('name', None)
prefix = kwargs.pop('prefix', None) or make_temp_prefix(name)
assert isdir(prefix), prefix
with disable_logger('fetch'), disable_logger('dotupdate'):
try:
# try to clear any config that's been set by other tests
reset_context([os.path.join(prefix+os.sep, 'condarc')])
run_command(Commands.CREATE, prefix, *packages, **kwargs)
yield prefix
finally:
rmtree(prefix, ignore_errors=True)
@contextmanager
def make_temp_package_cache():
prefix = make_temp_prefix()
pkgs_dir = join(prefix, 'pkgs')
mkdir_p(pkgs_dir)
touch(join(pkgs_dir, PACKAGE_CACHE_MAGIC_FILE))
try:
with env_var('CONDA_PKGS_DIRS', pkgs_dir, reset_context):
assert context.pkgs_dirs == (pkgs_dir,)
yield pkgs_dir
finally:
rmtree(prefix, ignore_errors=True)
if pkgs_dir in PackageCacheData._cache_:
del PackageCacheData._cache_[pkgs_dir]
@contextmanager
def make_temp_channel(packages):
package_reqs = [pkg.replace('-', '=') for pkg in packages]
package_names = [pkg.split('-')[0] for pkg in packages]
with make_temp_env(*package_reqs) as prefix:
for package in packages:
assert package_is_installed(prefix, package.replace('-', '='))
data = [p for p in PrefixData(prefix).iter_records() if p['name'] in package_names]
run_command(Commands.REMOVE, prefix, *package_names)
for package in packages:
assert not package_is_installed(prefix, package.replace('-', '='))
assert package_is_installed(prefix, 'python')
repodata = {'info': {}, 'packages': {}}
tarfiles = {}
for package_data in data:
pkg_data = package_data
fname = pkg_data['fn']
tarfiles[fname] = join(PackageCacheData.first_writable().pkgs_dir, fname)
pkg_data = pkg_data.dump()
for field in ('url', 'channel', 'schannel'):
pkg_data.pop(field, None)
repodata['packages'][fname] = PackageRecord(**pkg_data)
with make_temp_env() as channel:
subchan = join(channel, context.subdir)
noarch_dir = join(channel, 'noarch')
channel = path_to_url(channel)
os.makedirs(subchan)
os.makedirs(noarch_dir)
for fname, tar_old_path in tarfiles.items():
tar_new_path = join(subchan, fname)
copyfile(tar_old_path, tar_new_path)
with open(join(subchan, 'repodata.json'), 'w') as f:
f.write(json.dumps(repodata, cls=EntityEncoder))
with open(join(noarch_dir, 'repodata.json'), 'w') as f:
f.write(json.dumps({}, cls=EntityEncoder))
yield channel
def create_temp_location():
tempdirdir = gettempdir()
dirname = str(uuid4())[:8]
return join(tempdirdir, dirname)
@contextmanager
def tempdir():
prefix = create_temp_location()
try:
os.makedirs(prefix)
yield prefix
finally:
if lexists(prefix):
rm_rf(prefix)
def reload_config(prefix):
prefix_condarc = join(prefix+os.sep, 'condarc')
reset_context([prefix_condarc])
def package_is_installed(prefix, spec):
spec = MatchSpec(spec)
prefix_recs = tuple(PrefixData(prefix).query(spec))
if len(prefix_recs) > 1:
raise AssertionError("Multiple packages installed.%s"
% (dashlist(prec.dist_str() for prec in prefix_recs)))
return bool(len(prefix_recs))
def get_conda_list_tuple(prefix, package_name):
stdout, stderr = run_command(Commands.LIST, prefix)
stdout_lines = stdout.split('\n')
package_line = next((line for line in stdout_lines
if line.lower().startswith(package_name + " ")), None)
return package_line.split()
def get_shortcut_dir():
assert on_win
user_mode = 'user' if exists(join(sys.prefix, u'.nonadmin')) else 'system'
try:
from menuinst.win32 import dirs_src as win_locations
return win_locations[user_mode]["start"][0]
except ImportError:
try:
from menuinst.win32 import dirs as win_locations
return win_locations[user_mode]["start"]
except ImportError:
raise
@pytest.mark.integration
class IntegrationTests(TestCase):
def setUp(self):
PackageCacheData.clear()
def test_install_python2_and_search(self):
with env_var('CONDA_ALLOW_NON_CHANNEL_URLS', 'true', reset_context):
with make_temp_env("python=2") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, 'python=2')
# 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
def test_create_install_update_remove_smoketest(self):
with make_temp_env("python=3.5") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, 'python=3')
run_command(Commands.INSTALL, prefix, 'flask=0.10')
assert package_is_installed(prefix, 'flask=0.10.1')
assert package_is_installed(prefix, 'python=3')
run_command(Commands.INSTALL, prefix, '--force-reinstall', 'flask=0.10')
assert package_is_installed(prefix, 'flask=0.10.1')
assert package_is_installed(prefix, 'python=3')
run_command(Commands.UPDATE, prefix, 'flask')
assert not package_is_installed(prefix, 'flask=0.10.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_safety_checks(self):
# 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")
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 = text_type(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 = dals("""
The path 'site-packages/spiffy_test_app/__init__.py'
has a sha256 mismatch.
reported sha256: 1234567890123456789012345678901234567890123456789012345678901234
actual sha256: 32d822669b582f82da97225f69e3ef01ab8b63094e447a9acca148a6e79afbed
""")
assert message1 in error_message
assert message2 in error_message
with open(join(prefix, 'condarc'), 'a') as fh:
fh.write("safety_checks: warn\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(self):
# 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.5 --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.5 --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=0.10 --json')
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, 'flask=0.10.1')
assert package_is_installed(prefix, 'python=3')
# Test force reinstall
stdout, stderr = run_command(Commands.INSTALL, prefix, '--force-reinstall', 'flask=0.10', '--json')
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, 'flask=0.10.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=0.10.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=0.*')
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(self):
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(self):
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(self):
with make_temp_env("-c conda-test flask") 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)
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)
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(self):
# 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)
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(self):
with make_temp_env("-c conda-test itsdangerous python=3") 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)
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)
assert isfile(join(prefix, py_file))
assert isfile(join(prefix, pyc_file_py2))
def test_noarch_generic_package(self):
with make_temp_env("-c conda-test font-ttf-inconsolata") as prefix:
assert isfile(join(prefix, 'fonts', 'Inconsolata-Regular.ttf'))
def test_override_channels(self):
with pytest.raises(OperationNotAllowed):
with env_var('CONDA_OVERRIDE_CHANNELS_ENABLED', 'no', reset_context):
with make_temp_env("--override-channels python") as prefix:
assert prefix
with pytest.raises(CommandArgumentError):
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(self):
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]
expected_output = """# packages in environment at %s:
#
# Name Version Build Channel
""" % prefix
self.assertEqual(stdout, expected_output)
self.assertEqual(stderr, '')
revision_output = run_command(Commands.LIST, prefix, '--revisions')
stdout = revision_output[0]
stderr = revision_output[1]
assert stderr == ''
self.assertIsInstance(stdout, str)
@pytest.mark.skipif(on_win and context.subdir == "win-32", reason="conda-forge doesn't do win-32")
def test_strict_channel_priority(self):
stdout, stderr = run_command(
Commands.CREATE, "/",
"-c conda-forge -c defaults python=3.6 fiona --strict-channel-priority --dry-run --json",
use_exception_handler=True
)
assert not stderr
json_obj = json_loads(stdout)
channel_groups = groupby("channel",json_obj["actions"]["LINK"])
# conda-forge should be the only channel in the solution on unix
assert list(channel_groups) == ["conda-forge"]
def test_strict_resolve_get_reduced_index(self):
channels = (Channel("defaults"),)
specs = (MatchSpec("anaconda"),)
index = get_reduced_index(None, channels, context.subdirs, specs)
r = Resolve(index, channels=channels)
with env_var("CONDA_CHANNEL_PRIORITY", "strict", reset_context):
reduced_index = r.get_reduced_index(specs)
channel_name_groups = {
name: {prec.channel.name for prec in group}
for name, group in iteritems(groupby("name", reduced_index))
}
channel_name_groups = {
name: channel_names for name, channel_names in iteritems(channel_name_groups)
if len(channel_names) > 1
}
assert {} == channel_name_groups
def test_list_with_pip_no_binary(self):
from conda.exports import rm_rf as _rm_rf
with make_temp_env("python=3.5 pip") as prefix:
check_call(PYTHON_BINARY + " -m pip install --no-binary flask flask==0.10.1",
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("3.5")))
assert prefix not in PrefixData._cache_
def test_list_with_pip_wheel(self):
from conda.exports import rm_rf as _rm_rf
with make_temp_env("python=3.6 pip") as prefix:
check_call(PYTHON_BINARY + " -m pip install flask==0.10.1",
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.5")
assert package_is_installed(prefix, 'python=3.5')
# 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.5")), "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_install_tarball_from_local_channel(self):
# Regression test for #2812
# install from local channel
with make_temp_env() as prefix, make_temp_channel(["flask-0.10.1"]) as channel:
run_command(Commands.INSTALL, prefix, '-c', channel, 'flask=0.10.1', '--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 = join(PackageCacheData.first_writable().pkgs_dir, flask_fname)
conda_bld = join(dirname(PackageCacheData.first_writable().pkgs_dir), 'conda-bld')
conda_bld_sub = join(conda_bld, context.subdir)
if not isdir(conda_bld_sub):
os.makedirs(conda_bld_sub)
tar_bld_path = join(conda_bld_sub, basename(tar_path))
copyfile(tar_path, tar_bld_path)
# CondaFileNotFoundError: '/home/travis/virtualenv/python2.7.9/conda-bld/linux-64/flask-0.10.1-py27_2.tar.bz2'.
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_and_bad_metadata(self):
with make_temp_env("python flask=0.10.1 --json") as prefix:
assert package_is_installed(prefix, 'flask==0.10.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==0.10.1')
assert package_is_installed(prefix, 'python')
flask_fname = flask_data['fn']
tar_old_path = join(PackageCacheData.first_writable().pkgs_dir, flask_fname)
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=0.*')
# 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=0.*')
# 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, '"%s"' % tar_new_path)
assert package_is_installed(prefix, 'flask=0')
# regression test for #2626
# install tarball with relative path, outside channel
run_command(Commands.REMOVE, prefix, 'flask')
assert not package_is_installed(prefix, 'flask=0.10.1')
tar_new_path = relpath(tar_new_path)
run_command(Commands.INSTALL, prefix, '"%s"' % tar_new_path)
assert package_is_installed(prefix, 'flask=0')
# 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=0')
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(self):
# regression test for #6914
with make_temp_env("python=2.7.12") as prefix:
assert package_is_installed(prefix, "readline=6.2")
open(join(prefix, 'conda-meta', 'history'), 'w').close()
PrefixData._cache_.clear()
run_command(Commands.UPDATE, prefix, "readline")
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_remove_all(self):
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')
assert repr(exc.value) == dals("""
PackagesNotFoundError: The following packages are missing from the target environment:
- foo
- numpy
""")
run_command(Commands.REMOVE, prefix, '--all')
assert not exists(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(self, hardlink_supported_mock):
hardlink_supported_mock._result_cache.clear()
with env_var("CONDA_ALLOW_SOFTLINKS", "true", reset_context):
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(self):
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.skipif(on_win and datetime.now() <= datetime(2018, 11, 1), reason="conda-forge repodata needs vc patching")
def test_dash_c_usage_replacing_python(self):
# Regression test for #2606
with make_temp_env("-c conda-forge python=3.5") as prefix:
assert exists(join(prefix, PYTHON_BINARY))
assert package_is_installed(prefix, 'conda-forge::python=3.5')
run_command(Commands.INSTALL, prefix, "decorator")
assert package_is_installed(prefix, 'conda-forge::python=3.5')
with make_temp_env('--clone "%s"' % prefix) as clone_prefix:
assert package_is_installed(clone_prefix, 'conda-forge::python=3.5')
assert package_is_installed(clone_prefix, "decorator")
# Regression test for #2645
fn = glob(join(prefix, 'conda-meta', 'python-3.5*.json'))[-1]
with open(fn) as f:
data = json.load(f)
for field in ('url', 'channel', 'schannel'):
if field in data:
del data[field]
with open(fn, 'w') as f:
json.dump(data, f)
PrefixData._cache_ = {}
with make_temp_env('-c conda-forge --clone "%s"' % prefix) as clone_prefix:
assert package_is_installed(clone_prefix, 'python=3.5')
assert package_is_installed(clone_prefix, 'decorator')
def test_install_prune_flag(self):
with make_temp_env("python=3 flask") as prefix:
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')
assert package_is_installed(prefix, 'itsdangerous')
assert package_is_installed(prefix, 'python=3')
run_command(Commands.INSTALL, prefix, 'pytz --prune')
assert not package_is_installed(prefix, 'itsdangerous')
assert package_is_installed(prefix, 'pytz')
assert package_is_installed(prefix, 'python=3')
@pytest.mark.skipif(on_win, reason="readline is only a python dependency on unix")
def test_remove_force_remove_flag(self):
with make_temp_env("python") as prefix:
assert package_is_installed(prefix, 'readline')
assert package_is_installed(prefix, 'python')
run_command(Commands.REMOVE, prefix, 'readline --force-remove')
assert not package_is_installed(prefix, 'readline')
assert package_is_installed(prefix, 'python')
def test_install_force_reinstall_flag(self):
with make_temp_env("python") as prefix:
stdout, stderr = run_command(Commands.INSTALL, prefix,
"--json --dry-run --force-reinstall python",
use_exception_handler=True)
output_obj = json.loads(stdout.strip())
unlink_actions = output_obj['actions']['UNLINK']
link_actions = output_obj['actions']['LINK']
assert len(unlink_actions) == len(link_actions) == 1
assert unlink_actions[0] == link_actions[0]
assert unlink_actions[0]['name'] == 'python'
def test_create_no_deps_flag(self):
with make_temp_env("python=2 flask --no-deps") as prefix:
assert package_is_installed(prefix, 'flask')
assert package_is_installed(prefix, 'python=2')
assert not package_is_installed(prefix, 'openssl')
assert not package_is_installed(prefix, 'itsdangerous')
def test_create_only_deps_flag(self):
with make_temp_env("python=2 flask --only-deps") as prefix:
assert not package_is_installed(prefix, 'flask')
assert package_is_installed(prefix, 'python')
if not on_win:
# python on windows doesn't actually have real dependencies
assert package_is_installed(prefix, 'openssl')
assert package_is_installed(prefix, 'itsdangerous')
def test_install_update_deps_flag(self):
with make_temp_env("flask==0.12 jinja2==2.8") as prefix:
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask==0.12")
assert package_is_installed(prefix, "jinja2=2.8")
run_command(Commands.INSTALL, prefix, "flask --update-deps")
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask>0.12")
assert package_is_installed(prefix, "jinja2>2.8")
def test_install_only_deps_flag(self):
with make_temp_env("flask==0.12 jinja2==2.8") as prefix:
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask==0.12")
assert package_is_installed(prefix, "jinja2=2.8")
run_command(Commands.INSTALL, prefix, "flask --only-deps")
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask==0.12")
assert package_is_installed(prefix, "jinja2=2.8")
with make_temp_env("flask==0.12 --only-deps") as prefix:
assert not package_is_installed(prefix, "flask")
def test_install_update_deps_only_deps_flags(self):
with make_temp_env("flask==0.12 jinja2==2.8") as prefix:
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask==0.12")
assert package_is_installed(prefix, "jinja2=2.8")
run_command(Commands.INSTALL, prefix, "flask python=3.6 --update-deps --only-deps")
assert package_is_installed(prefix, "python=3.6")
assert package_is_installed(prefix, "flask==0.12")
assert package_is_installed(prefix, "jinja2>2.8")
@pytest.mark.skipif(on_win, reason="tensorflow package used in test not available on Windows")
def test_install_freeze_installed_flag(self):
with make_temp_env("bleach=2") as prefix:
assert package_is_installed(prefix, "bleach=2")
with pytest.raises(UnsatisfiableError):
run_command(Commands.INSTALL, prefix,
"conda-forge::tensorflow>=1.4 --dry-run --freeze-installed")
@pytest.mark.xfail(on_win and datetime.now() < datetime(2018, 11, 1),
reason="need to talk with @msarahan about blas patches on Windows",
strict=True)
def test_install_features(self):
with make_temp_env("python=2 numpy=1.13 nomkl") as prefix:
assert package_is_installed(prefix, "numpy")
assert package_is_installed(prefix, "nomkl")
assert not package_is_installed(prefix, "mkl")
numpy_prec = PrefixData(prefix).get("numpy")
assert "nomkl" in numpy_prec.build
with make_temp_env("python=2 numpy=1.13") as prefix:
assert package_is_installed(prefix, "numpy")
assert not package_is_installed(prefix, "nomkl")
assert package_is_installed(prefix, "mkl")
numpy_prec = PrefixData(prefix).get("numpy")
assert "nomkl" not in numpy_prec.build
run_command(Commands.INSTALL, prefix, "nomkl")
assert package_is_installed(prefix, "numpy")
assert package_is_installed(prefix, "nomkl")
assert package_is_installed(prefix, "mkl") # it's fine for mkl to still be here I guess
numpy_prec = PrefixData(prefix).get("numpy")
assert "nomkl" in numpy_prec.build
run_command(Commands.INSTALL, prefix, "nomkl --prune")
assert not package_is_installed(prefix, "mkl")
assert not package_is_installed(prefix, "mkl_fft")
assert not package_is_installed(prefix, "mkl_random")
def test_clone_offline_simple(self):
with make_temp_env("python flask=0.10.1") as prefix:
assert package_is_installed(prefix, 'flask=0.10.1')
assert package_is_installed(prefix, 'python')
with make_temp_env('--clone "%s"' % prefix, "--offline") as clone_prefix:
assert context.offline
assert package_is_installed(clone_prefix, 'flask=0.10.1')
assert package_is_installed(clone_prefix, 'python')
with env_var('CONDA_DISALLOWED_PACKAGES', 'python', reset_context):
with pytest.raises(DisallowedPackageError) as exc:
with make_temp_env('--clone "%s"' % prefix, "--offline"):
pass
assert exc.value.dump_map()['package_ref']['name'] == 'python'
def test_conda_config_describe(self):
with make_temp_env() as prefix:
stdout, stderr = run_command(Commands.CONFIG, prefix, "--describe")
assert not stderr
skip_categories = ('CLI-only', 'Hidden and Undocumented')
documented_parameter_names = chain.from_iterable((
parameter_names for category, parameter_names in iteritems(context.category_map)
if category not in skip_categories
))
for param_name in documented_parameter_names:
assert re.search(r'^# # %s \(' % param_name, stdout, re.MULTILINE), param_name
stdout, stderr = run_command(Commands.CONFIG, prefix, "--describe --json")
assert not stderr
json_obj = json.loads(stdout.strip())
assert len(json_obj) >= 42
assert 'description' in json_obj[0]
with env_var('CONDA_QUIET', 'yes', reset_context):
stdout, stderr = run_command(Commands.CONFIG, prefix, "--show-sources")
assert not stderr
assert 'envvars' in stdout.strip()
stdout, stderr = run_command(Commands.CONFIG, prefix, "--show-sources --json")
assert not stderr
json_obj = json.loads(stdout.strip())