-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
test_create.py
3179 lines (2696 loc) · 155 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
from contextlib import contextmanager
from datetime import datetime
from glob import glob
from conda._vendor.auxlib.compat import Utf8NamedTemporaryFile
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 abspath, basename, dirname, exists, isdir, isfile, join, lexists, relpath, islink
from random import sample
import re
from shutil import copyfile, rmtree
from subprocess import check_call, check_output, Popen, PIPE
import sys
from tempfile import gettempdir
from textwrap import dedent
from unittest import TestCase
from unittest.mock import Mock, patch, ANY
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._vendor.toolz import concatv
from conda.base.constants import CONDA_PACKAGE_EXTENSIONS, PACKAGE_CACHE_MAGIC_FILE, SafetyChecks, \
PREFIX_MAGIC_FILE, DEFAULT_AGGRESSIVE_UPDATE_PACKAGES
from conda.base.context import Context, context, reset_context, conda_tests_ctxt_mgmt_def_pol
from conda.cli.conda_argparse import do_call
from conda.cli.main import generate_parser, init_loggers
from conda.common.compat import (ensure_text_type, iteritems, string_types, text_type,
encode_arguments)
from conda.common.io import argv, captured, disable_logger, env_var, stderr_log_level, dashlist, env_vars
from conda.common.path import get_bin_directory_short_path, get_python_site_packages_short_path, \
pyc_path
from conda.common.serialize import yaml_round_trip_load, json_dump
from conda.common.url import path_to_url
from conda.core.index import get_reduced_index, get_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, DirectoryNotACondaEnvironmentError, EnvironmentLocationNotFound, \
CondaValueError
from conda.gateways.anaconda_client import read_binstar_tokens
from conda.gateways.disk.create import mkdir_p, extract_tarball
from conda.gateways.disk.delete import rm_rf, path_is_clean
from conda.gateways.disk.update import touch
from conda.gateways.logging import TRACE
from conda.gateways.subprocess import subprocess_call, subprocess_call_with_clean_env, Response
from conda.models.match_spec import MatchSpec
from conda.models.records import PackageRecord
from conda.models.version import VersionOrder
from conda.resolve import exactness_and_number_of_deps
from conda.utils import massage_arguments, on_win
from .cases import BaseTestCase
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'
UNICODE_CHARACTERS = u"ōγђ家固한áêñßôç"
# UNICODE_CHARACTERS_RESTRICTED_PY2 = u"ÀÁÂÃÄÅ"
UNICODE_CHARACTERS_RESTRICTED_PY2 = u"abcdef"
# UNICODE_CHARACTERS_RESTRICTED_PY3 = u"áêñßôç"
UNICODE_CHARACTERS_RESTRICTED_PY3 = u"abcdef"
which_or_where = "which" if not on_win else "where"
cp_or_copy = "cp" if not on_win else "copy"
env_or_set = "env" if not on_win else "set"
# UNICODE_CHARACTERS = u"12345678abcdef"
# UNICODE_CHARACTERS_RESTRICTED = UNICODE_CHARACTERS
# We basically do not work at all with Unicode on Python 2 still!
# if sys.version_info[0] == 2:
# UNICODE_CHARACTERS = UNICODE_CHARACTERS_RESTRICTED
# When testing for bugs, you may want to change this to a _,
# for example to see if a bug is related to spaces in prefixes.
SPACER_CHARACTER = ' '
def escape_for_winpath(p):
return p.replace('\\', '\\\\')
from conda._vendor.auxlib.decorators import memoize
@memoize
def running_a_python_capable_of_unicode_subprocessing():
name = None
# try:
# UNICODE_CHARACTERS + os.sep +
with Utf8NamedTemporaryFile(mode="w",
suffix=UNICODE_CHARACTERS + ".bat",
delete=False) as batch_file:
batch_file.write('@echo Hello World\n')
batch_file.write('@exit 0\n')
name = batch_file.name
if name:
try:
out = check_output(name, cwd=dirname(name), stderr=None, shell=False)
out = out.decode("utf-8") if hasattr(out, 'decode') else out
if out.startswith('Hello World'):
return True
return False
except Exception as _:
return False
finally:
os.unlink(name)
return False
tmpdir_in_use = None
@pytest.fixture(autouse=True)
def set_tmpdir(tmpdir):
global tmpdir_in_use
if not tmpdir:
return tmpdir_in_use
td = tmpdir.strpath
assert os.sep in td
tmpdir_in_use = td
def _get_temp_prefix(name=None, use_restricted_unicode=False):
tmpdir = tmpdir_in_use or gettempdir()
capable = running_a_python_capable_of_unicode_subprocessing()
if not capable or use_restricted_unicode:
RESTRICTED = UNICODE_CHARACTERS_RESTRICTED_PY2 \
if (sys.version_info[0] == 2) \
else UNICODE_CHARACTERS_RESTRICTED_PY3
random_unicode = ''.join(sample(RESTRICTED, len(RESTRICTED)))
else:
random_unicode = ''.join(sample(UNICODE_CHARACTERS, len(UNICODE_CHARACTERS)))
tmpdir_name = os.environ.get("CONDA_TEST_TMPDIR_NAME",
(str(uuid4())[:4] + SPACER_CHARACTER + random_unicode) if name is None else name)
prefix = join(tmpdir, tmpdir_name)
# Exit immediately if we cannot use hardlinks, on Windows, we get permissions errors if we use
# sys.executable so instead use the pdb files.
src = sys.executable.replace('.exe', '.pdb') if on_win else sys.executable
dst = os.path.join(tmpdir, os.path.basename(sys.executable))
from conda.gateways.disk.link import link
try:
link(src, dst)
except (IOError, OSError) as e:
print("\nWARNING :: You are testing `conda` with `tmpdir`:-\n {}\n"
" not on the same FS as `sys.prefix`:\n {}\n"
" this will be slow and unlike the majority of end-user installs.\n"
" Please pass `--basetemp=<somewhere-else>` instead.".format(tmpdir, sys.prefix))
try:
rm_rf(dst)
except Exception as e:
print(e)
pass
return prefix
def make_temp_prefix(name=None, use_restricted_unicode=False, _temp_prefix=None):
'''
When the env. you are creating will be used to install Python 2.7 on Windows
only a restricted amount of Unicode will work, and probably only those chars
in your current codepage, so the characters in UNICODE_CHARACTERS_RESTRICTED
should probably be randomly generated from that instead. The problem here is
that the current codepage needs to be able to handle 'sys.prefix' otherwise
ntpath will fall over.
'''
if not _temp_prefix:
_temp_prefix = _get_temp_prefix(name=name,
use_restricted_unicode=use_restricted_unicode)
try:
os.makedirs(_temp_prefix)
except:
pass
assert isdir(_temp_prefix)
return _temp_prefix
def FORCE_temp_prefix(name=None, use_restricted_unicode=False):
_temp_prefix = _get_temp_prefix(name=name,
use_restricted_unicode=use_restricted_unicode)
rm_rf(_temp_prefix)
os.makedirs(_temp_prefix)
assert isdir(_temp_prefix)
return _temp_prefix
class Commands:
COMPARE = "compare"
CONFIG = "config"
CLEAN = "clean"
CREATE = "create"
INFO = "info"
INSTALL = "install"
LIST = "list"
REMOVE = "remove"
SEARCH = "search"
UPDATE = "update"
RUN = "run"
@contextmanager
def temp_chdir(target_dir):
curdir = os.getcwd()
if not target_dir:
target_dir = curdir
try:
os.chdir(target_dir)
yield
finally:
os.chdir(curdir)
def run_command(command, prefix, *arguments, **kwargs):
assert isinstance(arguments, tuple), "run_command() arguments must be tuples"
arguments = massage_arguments(arguments)
use_exception_handler = kwargs.get('use_exception_handler', False)
# These commands require 'dev' mode to be enabled during testing because
# they end up calling run_script() in link.py and that uses wrapper scripts for e.g. activate.
# Setting `dev` means that, in these scripts, conda is executed via:
# `sys.prefix/bin/python -m conda` (or the Windows equivalent).
# .. and the source code for `conda` is put on `sys.path` via `PYTHONPATH` (a bit gross but
# less so than always requiring `cwd` to be the root of the conda source tree in every case).
# If you do not want this to happen for some test you must pass dev=False as a kwarg, though
# for nearly all tests, you want to make sure you are running *this* conda and not some old
# conda (it was random which you'd get depending on the initial values of PATH and PYTHONPATH
# - and likely more variables - before `dev` came along). Setting CONDA_EXE is not enough
# either because in the 4.5 days that would just run whatever Python was found first on PATH.
command_defaults_to_dev = command in (Commands.CREATE, Commands.INSTALL, Commands.REMOVE, Commands.RUN)
dev = kwargs.get('dev', True if command_defaults_to_dev else False)
debug = kwargs.get("debug_wrapper_scripts", False)
p = generate_parser()
if command is Commands.CONFIG:
arguments.append('--file')
arguments.append(join(prefix, 'condarc'))
if command in (Commands.LIST, Commands.COMPARE, Commands.CREATE, Commands.INSTALL,
Commands.REMOVE, Commands.UPDATE, Commands.RUN):
arguments.insert(0, '-p')
arguments.insert(1, prefix)
if command in (Commands.CREATE, Commands.INSTALL, Commands.REMOVE, Commands.UPDATE):
arguments.extend(["-y", "-q"])
arguments.insert(0, command)
if dev:
arguments.insert(1, '--dev')
if debug:
arguments.insert(1, '--debug-wrapper-scripts')
# It would be nice at this point to re-use:
# from conda.cli.python_api import run_command as python_api_run_command
# python_api_run_command
# .. but that does not support no_capture and probably more stuff.
args = p.parse_args(arguments)
context._set_argparse_args(args)
init_loggers(context)
cap_args = tuple() if not kwargs.get("no_capture") else (None, None)
# list2cmdline is not exact, but it is only informational.
print("\n\nEXECUTING COMMAND >>> $ conda %s\n\n" % ' '.join(arguments), file=sys.stderr)
with stderr_log_level(TEST_LOG_LEVEL, 'conda'), stderr_log_level(TEST_LOG_LEVEL, 'requests'):
arguments = encode_arguments(arguments)
is_run = arguments[0] == 'run'
if is_run:
cap_args = (None, None)
with argv(['python_api'] + arguments), captured(*cap_args) as c:
if use_exception_handler:
result = conda_exception_handler(do_call, args, p)
else:
result = do_call(args, p)
if is_run:
stdout = result.stdout
stderr = result.stderr
result = result.rc
else:
stdout = c.stdout
stderr = c.stderr
print(stdout, file=sys.stdout)
print(stderr, file=sys.stderr)
# Unfortunately there are other ways to change context, such as Commands.CREATE --offline.
# You will probably end up playing whack-a-bug here adding more and more the tuple here.
if command in (Commands.CONFIG,):
reset_context([os.path.join(prefix + os.sep, 'condarc')], args)
return stdout, stderr, result
@contextmanager
def make_temp_env(*packages, **kwargs):
name = kwargs.pop('name', None)
use_restricted_unicode = kwargs.pop('use_restricted_unicode', False)
prefix = (kwargs.pop('prefix', None) or
_get_temp_prefix(name=name,
use_restricted_unicode=use_restricted_unicode))
clean_prefix = kwargs.pop('clean_prefix', None)
if clean_prefix:
if os.path.exists(prefix):
rm_rf(prefix)
if not isdir(prefix):
make_temp_prefix(name, use_restricted_unicode, prefix)
with disable_logger('fetch'), disable_logger('dotupdate'):
try:
# try to clear any config that's been set by other tests
# CAUTION :: This does not partake in the context stack management code
# of env_{var,vars,unmodified} and, when used in conjunction
# with that code, this *must* be called first.
reset_context([os.path.join(prefix+os.sep, 'condarc')])
run_command(Commands.CREATE, prefix, *packages, **kwargs)
yield prefix
finally:
if not 'CONDA_TEST_SAVE_TEMPS' in os.environ:
rmtree(prefix, ignore_errors=True)
else:
log.warning('CONDA_TEST_SAVE_TEMPS :: retaining make_temp_env {}'.format(prefix))
@contextmanager
def make_temp_package_cache():
prefix = make_temp_prefix(use_restricted_unicode=on_win)
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, stack_callback=conda_tests_ctxt_mgmt_def_pol):
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]
import urllib
try:
import urllib.parse as urlparse
except:
from urlparse import urlparse
def fixurl(url):
# turn string into unicode
if not isinstance(url,unicode):
url = url.decode('utf8')
# parse it
parsed = urlparse.urlsplit(url)
# divide the netloc further
userpass,at,hostport = parsed.netloc.rpartition('@')
user,colon1,pass_ = userpass.partition(':')
host,colon2,port = hostport.partition(':')
# encode each component
scheme = parsed.scheme.encode('utf8')
user = urllib.quote(user.encode('utf8'))
colon1 = colon1.encode('utf8')
pass_ = urllib.quote(pass_.encode('utf8'))
at = at.encode('utf8')
host = host.encode('idna')
colon2 = colon2.encode('utf8')
port = port.encode('utf8')
path = '/'.join( # could be encoded slashes!
urllib.quote(urllib.unquote(pce).encode('utf8'),'')
for pce in parsed.path.split('/')
)
query = urllib.quote(urllib.unquote(parsed.query).encode('utf8'),'=&?/')
fragment = urllib.quote(urllib.unquote(parsed.fragment).encode('utf8'))
# put it back together
netloc = ''.join((user,colon1,pass_,at,host,colon2,port))
return urlparse.urlunsplit((scheme,netloc,path,query,fragment))
@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('-', '='))
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():
return _get_temp_prefix()
@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(BaseTestCase):
def setUp(self):
PackageCacheData.clear()
def test_install_python2_and_search(self):
with Utf8NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as env_txt:
log.warning("Creating empty temporary environment txt file {}".format(env_txt))
environment_txt = env_txt.name
with patch('conda.core.envs_manager.get_user_environments_txt_file',
return_value=environment_txt) as _:
with make_temp_env("python=2", use_restricted_unicode=on_win) as prefix:
with env_var('CONDA_ALLOW_NON_CHANNEL_URLS', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol):
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(self):
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(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.12')
assert package_is_installed(prefix, 'flask=0.12.2')
assert package_is_installed(prefix, 'python=3')
run_command(Commands.INSTALL, prefix, '--force-reinstall', 'flask=0.12.2')
assert package_is_installed(prefix, 'flask=0.12.2')
assert package_is_installed(prefix, 'python=3')
run_command(Commands.UPDATE, prefix, 'flask')
assert not package_is_installed(prefix, 'flask=0.12.2')
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(self):
# 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(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")
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 = 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("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(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.12', '--json')
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, 'flask=0.12.2')
assert package_is_installed(prefix, 'python=3')
# Test force reinstall
stdout, stderr, _ = run_command(Commands.INSTALL, prefix, '--force-reinstall', 'flask=0.12', '--json')
assert_json_parsable(stdout)
assert not stderr
assert package_is_installed(prefix, 'flask=0.12.2')
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.12.2')
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).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)
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).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(self):
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(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', stack_callback=conda_tests_ctxt_mgmt_def_pol):
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, string_types)
@pytest.mark.skipif(reason="conda-forge doesn't have a full set of packages")
def test_strict_channel_priority(self):
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("channel", json_obj["actions"]["LINK"])
channel_groups = sorted(list(channel_groups))
assert 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, '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 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
# 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.7"
with make_temp_env("python="+py_ver, "pip") as prefix:
evs = dict({"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==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(py_ver)))
assert prefix not in PrefixData._cache_
def test_list_with_pip_wheel(self):
from conda.exports import rm_rf as _rm_rf
py_ver = "3.7"
with make_temp_env("python="+py_ver, "pip") as prefix:
evs = dict({"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==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", no_capture=True)
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_compare_success(self):
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(
"""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(self):
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(
"""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(self):
# 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")
'''
with make_temp_env() as prefix, make_temp_channel(["flask-0.12.2"]) as channel:
run_command(Commands.INSTALL, prefix, '-c', channel, 'flask=0.12.2', '--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)
if not os.path.isfile(tar_path):
tar_path = tar_path.replace('.conda', '.tar.bz2')
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)
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')