Refactor micromamba test_actiavation to use isolated fixtures

This commit is contained in:
AntoinePrv 2022-09-05 11:51:10 +02:00
parent 613328af41
commit 241c5f4f0e
2 changed files with 208 additions and 295 deletions

View File

@ -1,23 +1,13 @@
import os import os
import pathlib import pathlib
import random import random
import shutil
import string import string
from typing import Generator from typing import Generator
import pytest import pytest
from . import helpers
def random_str(n: int = 10) -> str:
"""Return random characters and digits."""
return "".join(random.choices(string.ascii_uppercase + string.digits, k=n))
@pytest.fixture(params=[random_str, "some ™∞¢3 spaces §∞©ƒ√≈ç", "long_prefix_" * 20])
def tmp_env_name(request) -> str:
"""Return the explicit or implicit parametrization."""
if callable(request.param):
return request.param()
return request.param
@pytest.fixture @pytest.fixture
@ -39,8 +29,72 @@ def tmp_home(tmp_path: pathlib.Path) -> Generator[pathlib.Path, None, None]:
yield pathlib.Path.home() yield pathlib.Path.home()
@pytest.fixture(scope="session")
def tmp_pkgs_dirs(tmp_path_factory: pytest.TempPathFactory) -> pathlib.Path:
"""A common package cache for mamba downloads.
The directory is not used automatically when calling this fixture.
"""
return tmp_path_factory.mktemp("pkgs_dirs")
@pytest.fixture(params=[False])
def shared_pkgs_dirs(request) -> bool:
"""A dummy fixture to control the use of shared package dir."""
return request.param
@pytest.fixture @pytest.fixture
def tmp_root_prefix(tmp_path: pathlib.Path) -> Generator[pathlib.Path, None, None]: def tmp_clean_env(
tmp_pkgs_dirs: pathlib.Path, shared_pkgs_dirs: bool
) -> Generator[None, None, None]:
"""Remove all Conda/Mamba activation artifacts from environment."""
saved_environ = {}
for k, v in os.environ.items():
if k.startswith(("CONDA", "_CONDA", "MAMBA", "_MAMBA")):
saved_environ[k] = v
del os.environ[k]
def keep_in_path(
p: str, prefix: str | None = saved_environ.get("CONDA_PREFIX")
) -> bool:
if "condabin" in p:
return False
if prefix is not None:
p = str(pathlib.Path(p).expanduser().resolve())
prefix = str(pathlib.Path(prefix).expanduser().resolve())
return not p.startswith(prefix)
return True
path_list = os.environ["PATH"].split(os.pathsep)
path_list = [p for p in path_list if keep_in_path(p)]
os.environ["PATH"] = os.pathsep.join(path_list)
if shared_pkgs_dirs:
os.environ["CONDA_PKGS_DIRS"] = str(tmp_pkgs_dirs)
yield None
os.environ.update(saved_environ)
def random_str(n: int = 10) -> str:
"""Return random characters and digits."""
return "".join(random.choices(string.ascii_uppercase + string.digits, k=n))
@pytest.fixture(params=[random_str, "some ™∞¢3 spaces §∞©ƒ√≈ç", "long_prefix_" * 20])
def tmp_env_name(request) -> str:
"""Return the explicit or implicit parametrization."""
if callable(request.param):
return request.param()
return request.param
@pytest.fixture
def tmp_root_prefix(
tmp_path: pathlib.Path, tmp_clean_env: None
) -> Generator[pathlib.Path, None, None]:
"""Change the micromamba root directory to a tmp folder for the duration of a test.""" """Change the micromamba root directory to a tmp folder for the duration of a test."""
old_root_prefix = os.environ.get("MAMBA_ROOT_PREFIX") old_root_prefix = os.environ.get("MAMBA_ROOT_PREFIX")
new_root_prefix = tmp_path / "mamba" new_root_prefix = tmp_path / "mamba"
@ -53,6 +107,15 @@ def tmp_root_prefix(tmp_path: pathlib.Path) -> Generator[pathlib.Path, None, Non
del os.environ["MAMBA_ROOT_PREFIX"] del os.environ["MAMBA_ROOT_PREFIX"]
@pytest.fixture
def tmp_empty_env(
tmp_root_prefix: pathlib.Path, tmp_env_name: str
) -> Generator[pathlib.Path, None, None]:
"""An empty envirnment created under a temporary root prefix."""
helpers.create("-n", tmp_env_name, no_dry_run=True)
yield tmp_root_prefix
@pytest.fixture @pytest.fixture
def tmp_prefix( def tmp_prefix(
tmp_root_prefix: pathlib.Path, tmp_env_name: str tmp_root_prefix: pathlib.Path, tmp_env_name: str

View File

@ -25,29 +25,6 @@ elif platform.system() == "Windows":
running_os = "win" running_os = "win"
@pytest.fixture
def keep_cache(existing_cache):
yield True
@pytest.fixture
def clean_env(keep_cache):
clean_env = os.environ.copy()
clean_env = {
k: v
for k, v in clean_env.items()
if not k.startswith(("CONDA", "MAMBA"))
or (k == "CONDA_PKGS_DIRS" and keep_cache)
}
path = clean_env.get("PATH")
elems = path.split(os.pathsep)
elems = [e for e in elems if not "condabin" in e]
clean_env["PATH"] = os.pathsep.join(elems)
yield clean_env
suffixes = { suffixes = {
"cmd.exe": ".bat", "cmd.exe": ".bat",
"bash": ".sh", "bash": ".sh",
@ -137,42 +114,9 @@ regkey = "HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\\AutoRun"
bkup_winreg_value = None bkup_winreg_value = None
@pytest.fixture
def clean_shell_files():
global bkup_winreg_value
for f in shell_files:
if f.exists():
f_bkup = Path(str(f) + ".mamba_test_backup")
if f_bkup.exists():
f_bkup.unlink()
f.rename(f_bkup)
f.touch()
if plat == "win":
try:
regvalue = read_windows_registry(regkey)
bkup_winreg_value = regvalue
except:
print("Could not read registry value")
regvalue = ("", 1)
print("setting registry to ", regvalue[1])
write_windows_registry(regkey, "", regvalue[1])
yield shell_files
for f in shell_files:
f_bkup = Path(str(f) + ".mamba_test_backup")
if f_bkup.exists():
if f.exists():
f.unlink()
f_bkup.rename(str(f_bkup)[: -len(".mamba_test_backup")])
if plat == "win":
print("setting registry to ", regvalue[0], regvalue[1])
write_windows_registry(regkey, regvalue[0], regvalue[1])
def find_path_in_str(p, s): def find_path_in_str(p, s):
if isinstance(p, Path):
p = str(p)
if p in s: if p in s:
return True return True
if p.replace("\\", "\\\\") in s: if p.replace("\\", "\\\\") in s:
@ -293,47 +237,6 @@ def shvar(v, interpreter):
class TestActivation: class TestActivation:
current_root_prefix = os.environ["MAMBA_ROOT_PREFIX"]
current_prefix = os.environ["CONDA_PREFIX"]
env_name = random_string()
root_prefix = os.path.expanduser(os.path.join("~", "tmproot" + random_string()))
other_root_prefix = os.path.expanduser(
os.path.join("~", "tmproot" + random_string())
)
prefix = os.path.join(root_prefix, "envs", env_name)
long_prefix = os.path.join(
root_prefix, *["some_very_long_prefix" for i in range(20)], env_name
)
@staticmethod
@pytest.fixture(scope="class")
def new_root_prefix(existing_cache):
os.environ["MAMBA_ROOT_PREFIX"] = TestActivation.root_prefix
os.environ["CONDA_PREFIX"] = TestActivation.prefix
create("-n", "base", no_dry_run=True)
create("xtensor", "-n", TestActivation.env_name, no_dry_run=True)
yield
os.environ["MAMBA_ROOT_PREFIX"] = TestActivation.current_root_prefix
os.environ["CONDA_PREFIX"] = TestActivation.current_prefix
if os.path.exists(TestActivation.root_prefix):
if platform.system() == "Windows":
p = r"\\?\ ".strip() + TestActivation.root_prefix
else:
p = TestActivation.root_prefix
# shutil.rmtree(p)
if os.path.exists(TestActivation.other_root_prefix):
if platform.system() == "Windows":
p = r"\\?\ ".strip() + TestActivation.other_root_prefix
else:
p = TestActivation.other_root_prefix
# shutil.rmtree(p)
@staticmethod @staticmethod
def to_dict(out, interpreter="bash"): def to_dict(out, interpreter="bash"):
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
@ -360,36 +263,39 @@ class TestActivation:
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
def test_shell_init( def test_shell_init(
self, tmp_path, interpreter, clean_shell_files, new_root_prefix self,
tmp_home,
tmp_root_prefix,
tmp_path,
interpreter,
): ):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
umamba = get_umamba() umamba = get_umamba()
env = {"MAMBA_ROOT_PREFIX": self.root_prefix} run_dir = tmp_path / "rundir"
call = lambda s: call_interpreter(s, tmp_path, interpreter) run_dir.mkdir()
call = lambda s: call_interpreter(s, run_dir, interpreter)
rpv = shvar("MAMBA_ROOT_PREFIX", interpreter) rpv = shvar("MAMBA_ROOT_PREFIX", interpreter)
s = [f"echo {rpv}"] s = [f"echo {rpv}"]
stdout, stderr = call(s) stdout, stderr = call(s)
assert stdout == self.root_prefix assert stdout == str(tmp_root_prefix)
# TODO remove root prefix here
s = [f"{umamba} shell init -p {rpv} {xonsh_shell_args(interpreter)}"] s = [f"{umamba} shell init -p {rpv} {xonsh_shell_args(interpreter)}"]
stdout, stderr = call(s) stdout, stderr = call(s)
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
value = read_windows_registry(regkey) value = read_windows_registry(regkey)
assert "mamba_hook.bat" in value[0] assert "mamba_hook.bat" in value[0]
assert find_path_in_str(self.root_prefix, value[0]) assert find_path_in_str(tmp_root_prefix, value[0])
prev_text = value[0] prev_text = value[0]
else: else:
path = Path(paths[plat][interpreter]).expanduser() path = Path(paths[plat][interpreter]).expanduser()
with open(path) as fi: with open(path) as fi:
x = fi.read() x = fi.read()
print(x)
assert "micromamba" in x assert "micromamba" in x
assert find_path_in_str(self.root_prefix, x) assert find_path_in_str(tmp_root_prefix, x)
prev_text = x prev_text = x
s = [f"{umamba} shell init -p {rpv} {xonsh_shell_args(interpreter)}"] s = [f"{umamba} shell init -p {rpv} {xonsh_shell_args(interpreter)}"]
@ -398,7 +304,7 @@ class TestActivation:
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
value = read_windows_registry(regkey) value = read_windows_registry(regkey)
assert "mamba_hook.bat" in value[0] assert "mamba_hook.bat" in value[0]
assert find_path_in_str(self.root_prefix, value[0]) assert find_path_in_str(tmp_root_prefix, value[0])
assert prev_text == value[0] assert prev_text == value[0]
assert not "&" in value[0] assert not "&" in value[0]
else: else:
@ -414,7 +320,7 @@ class TestActivation:
value = read_windows_registry(regkey) value = read_windows_registry(regkey)
assert "mamba_hook.bat" in value[0] assert "mamba_hook.bat" in value[0]
assert find_path_in_str(self.root_prefix, value[0]) assert find_path_in_str(tmp_root_prefix, value[0])
assert value[0].startswith("echo 'test' & ") assert value[0].startswith("echo 'test' & ")
assert "&" in value[0] assert "&" in value[0]
@ -437,53 +343,57 @@ class TestActivation:
assert "mamba" in x assert "mamba" in x
assert text == x assert text == x
other_root_prefix = tmp_path / "prefix"
other_root_prefix.mkdir()
s = [ s = [
f"{umamba} shell init -p {self.other_root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell init -p {other_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
stdout, stderr = call(s) stdout, stderr = call(s)
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
x = read_windows_registry(regkey)[0] x = read_windows_registry(regkey)[0]
assert "mamba" in x assert "mamba" in x
assert find_path_in_str(self.other_root_prefix, x) assert find_path_in_str(other_root_prefix, x)
assert not find_path_in_str(self.root_prefix, x) assert not find_path_in_str(tmp_root_prefix, x)
else: else:
with open(path) as fi: with open(path) as fi:
x = fi.read() x = fi.read()
assert "mamba" in x assert "mamba" in x
assert find_path_in_str(self.other_root_prefix, x) assert find_path_in_str(other_root_prefix, x)
assert not find_path_in_str(self.root_prefix, x) assert not find_path_in_str(tmp_root_prefix, x)
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
def test_shell_init_deinit_root_prefix_files( def test_shell_init_deinit_root_prefix_files(
self, tmp_path, interpreter, clean_shell_files, new_root_prefix self,
tmp_root_prefix,
tmp_path,
interpreter,
): ):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
umamba = get_umamba() umamba = get_umamba()
root_prefix_path = Path(self.root_prefix)
if interpreter == "bash" or interpreter == "zsh": if interpreter == "bash" or interpreter == "zsh":
files = [root_prefix_path / "etc" / "profile.d" / "micromamba.sh"] files = [tmp_root_prefix / "etc" / "profile.d" / "micromamba.sh"]
elif interpreter == "cmd.exe": elif interpreter == "cmd.exe":
files = [ files = [
root_prefix_path / "condabin" / "mamba_hook.bat", tmp_root_prefix / "condabin" / "mamba_hook.bat",
root_prefix_path / "condabin" / "micromamba.bat", tmp_root_prefix / "condabin" / "micromamba.bat",
root_prefix_path / "condabin" / "_mamba_activate.bat", tmp_root_prefix / "condabin" / "_mamba_activate.bat",
root_prefix_path / "condabin" / "activate.bat", tmp_root_prefix / "condabin" / "activate.bat",
] ]
elif interpreter == "powershell": elif interpreter == "powershell":
files = [ files = [
root_prefix_path / "condabin" / "mamba_hook.ps1", tmp_root_prefix / "condabin" / "mamba_hook.ps1",
root_prefix_path / "condabin" / "Mamba.psm1", tmp_root_prefix / "condabin" / "Mamba.psm1",
] ]
elif interpreter == "fish": elif interpreter == "fish":
files = [root_prefix_path / "etc" / "fish" / "conf.d" / "mamba.fish"] files = [tmp_root_prefix / "etc" / "fish" / "conf.d" / "mamba.fish"]
elif interpreter == "xonsh": elif interpreter == "xonsh":
files = [root_prefix_path / "etc" / "profile.d" / "mamba.xsh"] files = [tmp_root_prefix / "etc" / "profile.d" / "mamba.xsh"]
elif interpreter in ["csh", "tcsh"]: elif interpreter in ["csh", "tcsh"]:
files = [root_prefix_path / "etc" / "profile.d" / "micromamba.csh"] files = [tmp_root_prefix / "etc" / "profile.d" / "micromamba.csh"]
else: else:
raise ValueError(f"Unknown shell {interpreter}") raise ValueError(f"Unknown shell {interpreter}")
@ -491,7 +401,7 @@ class TestActivation:
return call_interpreter(command, tmp_path, interpreter) return call_interpreter(command, tmp_path, interpreter)
s = [ s = [
f"{umamba} shell init -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell init -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
@ -499,7 +409,7 @@ class TestActivation:
assert file.exists() assert file.exists()
s = [ s = [
f"{umamba} shell deinit -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell deinit -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
@ -507,7 +417,10 @@ class TestActivation:
assert not file.exists() assert not file.exists()
def test_shell_init_deinit_contents_cmdexe( def test_shell_init_deinit_contents_cmdexe(
self, tmp_path, clean_shell_files, new_root_prefix self,
tmp_home,
tmp_root_prefix,
tmp_path,
): ):
interpreter = "cmd.exe" interpreter = "cmd.exe"
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
@ -520,19 +433,19 @@ class TestActivation:
prev_value = read_windows_registry(regkey) prev_value = read_windows_registry(regkey)
assert "mamba_hook.bat" not in prev_value[0] assert "mamba_hook.bat" not in prev_value[0]
assert not find_path_in_str(self.root_prefix, prev_value[0]) assert not find_path_in_str(tmp_root_prefix, prev_value[0])
s = [ s = [
f"{umamba} shell init -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell init -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
value_after_init = read_windows_registry(regkey) value_after_init = read_windows_registry(regkey)
assert "mamba_hook.bat" in value_after_init[0] assert "mamba_hook.bat" in value_after_init[0]
assert find_path_in_str(self.root_prefix, value_after_init[0]) assert find_path_in_str(tmp_root_prefix, value_after_init[0])
s = [ s = [
f"{umamba} shell deinit -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell deinit -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
@ -541,7 +454,11 @@ class TestActivation:
@pytest.mark.parametrize("interpreter", get_interpreters(exclude=["cmd.exe"])) @pytest.mark.parametrize("interpreter", get_interpreters(exclude=["cmd.exe"]))
def test_shell_init_deinit_contents( def test_shell_init_deinit_contents(
self, tmp_path, interpreter, clean_shell_files, new_root_prefix self,
tmp_home,
tmp_root_prefix,
tmp_path,
interpreter,
): ):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
@ -562,10 +479,10 @@ class TestActivation:
assert "#region mamba initialize" not in prev_rc_contents assert "#region mamba initialize" not in prev_rc_contents
else: else:
assert "# >>> mamba initialize >>>" not in prev_rc_contents assert "# >>> mamba initialize >>>" not in prev_rc_contents
assert not find_path_in_str(self.root_prefix, prev_rc_contents) assert not find_path_in_str(tmp_root_prefix, prev_rc_contents)
s = [ s = [
f"{umamba} shell init -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell init -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
@ -575,10 +492,10 @@ class TestActivation:
assert "#region mamba initialize" in rc_contents_after_init assert "#region mamba initialize" in rc_contents_after_init
else: else:
assert "# >>> mamba initialize >>>" in rc_contents_after_init assert "# >>> mamba initialize >>>" in rc_contents_after_init
assert find_path_in_str(self.root_prefix, rc_contents_after_init) assert find_path_in_str(tmp_root_prefix, rc_contents_after_init)
s = [ s = [
f"{umamba} shell deinit -p {self.root_prefix} {xonsh_shell_args(interpreter)}" f"{umamba} shell deinit -p {tmp_root_prefix} {xonsh_shell_args(interpreter)}"
] ]
call(s) call(s)
@ -590,22 +507,17 @@ class TestActivation:
assert rc_contents_after_deinit == prev_rc_contents assert rc_contents_after_deinit == prev_rc_contents
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
def test_activation( def test_env_activation(self, tmp_home, tmp_root_prefix, tmp_path, interpreter):
self, tmp_path, interpreter, clean_shell_files, new_root_prefix, clean_env
):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
umamba = get_umamba() umamba = get_umamba()
s = [f"{umamba} shell init -p {self.root_prefix}"] s = [f"{umamba} shell init -p {tmp_root_prefix}"]
stdout, stderr = call_interpreter(s, tmp_path, interpreter) stdout, stderr = call_interpreter(s, tmp_path, interpreter)
call = lambda s: call_interpreter( call = lambda s: call_interpreter(s, tmp_path, interpreter, interactive=True)
s, tmp_path, interpreter, interactive=True, env=clean_env
)
rp = Path(self.root_prefix)
evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter) evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter)
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
@ -624,20 +536,17 @@ class TestActivation:
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert "condabin" in res["PATH"] assert "condabin" in res["PATH"]
assert self.root_prefix in res["PATH"] assert str(tmp_root_prefix) in res["PATH"]
assert f"CONDA_PREFIX={self.root_prefix}" in stdout.splitlines() assert f"CONDA_PREFIX={tmp_root_prefix}" in stdout.splitlines()
assert f"CONDA_SHLVL=1" in stdout.splitlines() assert f"CONDA_SHLVL=1" in stdout.splitlines()
# throw with non-existent # throw with non-existent
s = ["micromamba activate nonexistent"]
if plat != "win": if plat != "win":
with pytest.raises(subprocess.CalledProcessError): with pytest.raises(subprocess.CalledProcessError):
stdout, stderr = call(s) stdout, stderr = call(["micromamba activate nonexistent"])
s1 = ["micromamba create -n abc -y"] call(["micromamba create -n abc -y"])
s2 = ["micromamba create -n xyz -y"] call(["micromamba create -n xyz -y"])
call(s1)
call(s2)
s = [ s = [
"micromamba activate", "micromamba activate",
@ -646,45 +555,10 @@ class TestActivation:
] + evars ] + evars
stdout, stderr = call(s) stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert find_path_in_str(tmp_root_prefix / "condabin", res["PATH"])
assert find_path_in_str(str(rp / "condabin"), res["PATH"]) assert not find_path_in_str(tmp_root_prefix / "bin", res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"]) assert find_path_in_str(tmp_root_prefix / "envs" / "xyz", res["PATH"])
assert find_path_in_str(str(rp / "envs" / "xyz"), res["PATH"]) assert not find_path_in_str(tmp_root_prefix / "envs" / "abc", res["PATH"])
assert not find_path_in_str(str(rp / "envs" / "abc"), res["PATH"])
# long paths
s = [
f"micromamba create -p {TestActivation.long_prefix} xtensor six -v -y -c conda-forge"
]
call(s)
assert os.path.exists(TestActivation.long_prefix)
s = [
"micromamba activate",
f"micromamba activate -p {TestActivation.long_prefix}",
] + evars
# currently skipping longprefix _activation_ check with cmd.exe as it fails
# on CI for mysterious reasons
if not (plat == "win" and interpreter == "cmd.exe"):
stdout, stderr = call(s)
res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"])
assert find_path_in_str(TestActivation.long_prefix, res["PATH"])
s = [
"micromamba activate",
"micromamba activate abc",
"micromamba activate xyz --stack",
] + evars
stdout, stderr = call(s)
res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"])
assert find_path_in_str(str(rp / "envs" / "abc"), res["PATH"])
assert find_path_in_str(str(rp / "envs" / "xyz"), res["PATH"])
s = [ s = [
"micromamba activate", "micromamba activate",
@ -693,28 +567,37 @@ class TestActivation:
] + evars ] + evars
stdout, stderr = call(s) stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"]) assert find_path_in_str(tmp_root_prefix / "condabin", res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"]) assert not find_path_in_str(tmp_root_prefix / "bin", res["PATH"])
assert find_path_in_str(str(rp / "envs" / "xyz"), res["PATH"]) assert find_path_in_str(tmp_root_prefix / "envs" / "xyz", res["PATH"])
assert find_path_in_str(str(rp / "envs" / "abc"), res["PATH"]) assert find_path_in_str(tmp_root_prefix / "envs" / "abc", res["PATH"])
stdout, stderr = call(["micromamba deactivate"] + evars)
res = TestActivation.to_dict(stdout)
assert find_path_in_str(tmp_root_prefix / "condabin", res["PATH"])
assert not find_path_in_str(tmp_root_prefix / "bin", res["PATH"])
assert not find_path_in_str(tmp_root_prefix / "envs" / "xyz", res["PATH"])
assert not find_path_in_str(tmp_root_prefix / "envs" / "abc", res["PATH"])
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
def test_activation_envvars( def test_activation_envvars(
self, tmp_path, interpreter, clean_shell_files, new_root_prefix, clean_env self,
tmp_home,
tmp_clean_env,
tmp_root_prefix,
tmp_path,
interpreter,
): ):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
umamba = get_umamba() umamba = get_umamba()
s = [f"{umamba} shell init -p {self.root_prefix}"] s = [f"{umamba} shell init -p {tmp_root_prefix}"]
stdout, stderr = call_interpreter(s, tmp_path, interpreter) stdout, stderr = call_interpreter(s, tmp_path, interpreter)
call = lambda s: call_interpreter( call = lambda s: call_interpreter(s, tmp_path, interpreter, interactive=True)
s, tmp_path, interpreter, interactive=True, env=clean_env
)
rp = Path(self.root_prefix)
evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter) evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter)
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
@ -723,14 +606,9 @@ class TestActivation:
assert fp.exists() assert fp.exists()
if interpreter in ["bash", "zsh", "powershell", "cmd.exe"]: if interpreter in ["bash", "zsh", "powershell", "cmd.exe"]:
print("Creating __def__") call(["micromamba create -n def -y"])
s1 = ["micromamba create -n def -y"]
call(s1)
s = [ stdout, stderr = call(["micromamba activate def"] + evars)
"micromamba activate def",
] + evars
stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
abc_prefix = pathlib.Path(res["CONDA_PREFIX"]) abc_prefix = pathlib.Path(res["CONDA_PREFIX"])
@ -751,14 +629,11 @@ class TestActivation:
) )
) )
s = ( stdout, stderr = call(
[ ["micromamba activate def"]
"micromamba activate def",
]
+ evars + evars
+ extract_vars(["TEST", "HELLO", "WORKING", "AAA"], interpreter) + extract_vars(["TEST", "HELLO", "WORKING", "AAA"], interpreter)
) )
stdout, stderr = call(s)
# assert that env vars are in the same order # assert that env vars are in the same order
activation_script, stderr = call( activation_script, stderr = call(
@ -798,11 +673,8 @@ class TestActivation:
activation_script, stderr = call( activation_script, stderr = call(
["micromamba shell activate -s bash -n def"] ["micromamba shell activate -s bash -n def"]
) )
print(activation_script) stdout, stderr = call(
s = ( ["micromamba activate def"]
[
"micromamba activate def",
]
+ evars + evars
+ extract_vars( + extract_vars(
[ [
@ -817,7 +689,6 @@ class TestActivation:
interpreter, interpreter,
) )
) )
stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert res["HELLO"] == "world" assert res["HELLO"] == "world"
@ -829,22 +700,24 @@ class TestActivation:
assert res["TEST"] == "Test" assert res["TEST"] == "Test"
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
@pytest.mark.parametrize("shared_pkgs_dirs", [True], indirect=True)
def test_unicode_activation( def test_unicode_activation(
self, tmp_path, interpreter, clean_shell_files, new_root_prefix, clean_env self,
tmp_home,
tmp_root_prefix,
tmp_path,
interpreter,
): ):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
umamba = get_umamba() umamba = get_umamba()
s = [f"{umamba} shell init -p {self.root_prefix}"] s = [f"{umamba} shell init -p {tmp_root_prefix}"]
stdout, stderr = call_interpreter(s, tmp_path, interpreter) stdout, stderr = call_interpreter(s, tmp_path, interpreter)
call = lambda s: call_interpreter( call = lambda s: call_interpreter(s, tmp_path, interpreter, interactive=True)
s, tmp_path, interpreter, interactive=True, env=clean_env
)
rp = Path(self.root_prefix)
evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter) evars = extract_vars(["CONDA_PREFIX", "CONDA_SHLVL", "PATH"], interpreter)
if interpreter == "cmd.exe": if interpreter == "cmd.exe":
@ -863,8 +736,8 @@ class TestActivation:
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert "condabin" in res["PATH"] assert "condabin" in res["PATH"]
assert self.root_prefix in res["PATH"] assert str(tmp_root_prefix) in res["PATH"]
assert f"CONDA_PREFIX={self.root_prefix}" in stdout.splitlines() assert f"CONDA_PREFIX={tmp_root_prefix}" in stdout.splitlines()
assert f"CONDA_SHLVL=1" in stdout.splitlines() assert f"CONDA_SHLVL=1" in stdout.splitlines()
# throw with non-existent # throw with non-existent
@ -886,32 +759,15 @@ class TestActivation:
call(s2) call(s2)
call(s3) call(s3)
assert (rp / "envs" / u1 / "conda-meta").is_dir() for u in [u1, u2, u3]:
assert (rp / "envs" / u2 / "conda-meta").is_dir() assert (tmp_root_prefix / f"envs/{u}/conda-meta").is_dir()
assert (rp / "envs" / u3 / "conda-meta").is_dir() assert (tmp_root_prefix / f"envs/{u}/conda-meta/history").exists()
assert (rp / "envs" / u1 / "conda-meta" / "history").exists() if plat == "win":
assert (rp / "envs" / u2 / "conda-meta" / "history").exists() include_dir = tmp_root_prefix / f"envs/{u}/Library/include"
assert (rp / "envs" / u3 / "conda-meta" / "history").exists() else:
if plat == "win": include_dir = tmp_root_prefix / f"envs/{u}/include"
assert (
rp / "envs" / u1 / "Library" / "include" / "xtensor" / "xtensor.hpp" assert (include_dir / "xtensor/xtensor.hpp").exists()
).exists()
assert (
rp / "envs" / u2 / "Library" / "include" / "xtensor" / "xtensor.hpp"
).exists()
assert (
rp / "envs" / u3 / "Library" / "include" / "xtensor" / "xtensor.hpp"
).exists()
else:
assert (
rp / "envs" / u1 / "include" / "xtensor" / "xtensor.hpp"
).exists()
assert (
rp / "envs" / u2 / "include" / "xtensor" / "xtensor.hpp"
).exists()
assert (
rp / "envs" / u3 / "include" / "xtensor" / "xtensor.hpp"
).exists()
# unicode activation on win: todo # unicode activation on win: todo
if plat == "win": if plat == "win":
@ -925,10 +781,10 @@ class TestActivation:
stdout, stderr = call(s) stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "condabin"), res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"]) assert not find_path_in_str(str(tmp_root_prefix / "bin"), res["PATH"])
assert find_path_in_str(str(rp / "envs" / u2), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "envs" / u2), res["PATH"])
assert not find_path_in_str(str(rp / "envs" / u1), res["PATH"]) assert not find_path_in_str(str(tmp_root_prefix / "envs" / u1), res["PATH"])
s = [ s = [
"micromamba activate", "micromamba activate",
@ -937,10 +793,10 @@ class TestActivation:
] + evars ] + evars
stdout, stderr = call(s) stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "condabin"), res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"]) assert not find_path_in_str(str(tmp_root_prefix / "bin"), res["PATH"])
assert find_path_in_str(str(rp / "envs" / u1), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "envs" / u1), res["PATH"])
assert find_path_in_str(str(rp / "envs" / u2), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "envs" / u2), res["PATH"])
s = [ s = [
"micromamba activate", "micromamba activate",
@ -948,34 +804,28 @@ class TestActivation:
] + evars ] + evars
stdout, stderr = call(s) stdout, stderr = call(s)
res = TestActivation.to_dict(stdout) res = TestActivation.to_dict(stdout)
assert find_path_in_str(str(rp / "condabin"), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "condabin"), res["PATH"])
assert not find_path_in_str(str(rp / "bin"), res["PATH"]) assert not find_path_in_str(str(tmp_root_prefix / "bin"), res["PATH"])
assert find_path_in_str(str(rp / "envs" / u3), res["PATH"]) assert find_path_in_str(str(tmp_root_prefix / "envs" / u3), res["PATH"])
@pytest.mark.parametrize("interpreter", get_interpreters()) @pytest.mark.parametrize("interpreter", get_interpreters())
def test_activate_path(self, tmp_path, interpreter, new_root_prefix): def test_activate_path(self, tmp_empty_env, tmp_env_name, interpreter, tmp_path):
if interpreter not in valid_interpreters: if interpreter not in valid_interpreters:
pytest.skip(f"{interpreter} not available") pytest.skip(f"{interpreter} not available")
test_dir = tmp_path / self.env_name # Activate env name
os.mkdir(test_dir) res = shell("activate", tmp_env_name, "-s", interpreter)
create("-n", self.env_name)
res = shell("activate", self.env_name, "-s", interpreter)
dict_res = self.to_dict(res, interpreter) dict_res = self.to_dict(res, interpreter)
assert any([str(self.prefix) in p for p in dict_res.values()]) assert any([str(tmp_empty_env) in p for p in dict_res.values()])
res = shell("activate", self.prefix, "-s", interpreter) # Activate path
res = shell("activate", str(tmp_empty_env), "-s", interpreter)
dict_res = self.to_dict(res, interpreter) dict_res = self.to_dict(res, interpreter)
assert any([str(self.prefix) in p for p in dict_res.values()]) assert any([str(tmp_empty_env) in p for p in dict_res.values()])
prefix_short = self.prefix.replace(os.path.expanduser("~"), "~") # Activate path with home
prefix_short = str(tmp_empty_env).replace(os.path.expanduser("~"), "~")
res = shell("activate", prefix_short, "-s", interpreter) res = shell("activate", prefix_short, "-s", interpreter)
dict_res = self.to_dict(res, interpreter) dict_res = self.to_dict(res, interpreter)
assert any([str(self.prefix) in p for p in dict_res.values()]) assert any([str(tmp_empty_env) in p for p in dict_res.values()])
res = shell("activate", test_dir, "-s", interpreter)
dict_res = self.to_dict(res, interpreter)
assert any([str(test_dir) in p for p in dict_res.values()])