def test_context_manager(cleanup_env): with Env({'a': 1}) as env: value = env.a # should be able to initialize another env now Env({'a': 2}) assert value == 1
def test_can_initialize_env_after_failed_attempt(cleanup_env): try: # underscores are not allowed, this will fail, but before raising # the exception, the instance (created in __new__) must be discarded Env({'_a': 1}) except ValueError: pass # if we can initialize another object, it means the previous call was # corerctly discarded assert Env({'a': 1}).a == 1
def test_init_with_nonexistent_package(cleanup_env): with pytest.raises(ValueError) as exc_info: Env({'_module': 'i_do_not_exist'}) expected = ('Could not resolve _module "i_do_not_exist", ' 'it is not a valid module nor a directory') assert exc_info.value.args[0] == expected
def test_leading_underscore_in_top_key_raises_error(cleanup_env): msg = ("Error validating env.\nTop-level keys cannot start with " "an underscore, except for {'_module'}. Got: ['_a']") with pytest.raises(ValueError) as exc_info: Env({'_a': 1}) assert exc_info.value.args[0] == msg
def test_path_returns_Path_objects(cleanup_env): env = Env( {'path': { 'a': '/tmp/path/file.txt', 'b': '/another/path/file.csv' }}) assert isinstance(env.path.a, Path) assert isinstance(env.path.b, Path)
def test_load_env_decorator(cleanup_env): Env({'a': 10}) @load_env def fn(env): return env.a assert fn() == 10
def test_expand_git(monkeypatch, cleanup_env): def mockreturn(module_path): return {'git_location': 'some_version_string'} monkeypatch.setattr(repo, 'get_git_info', mockreturn) env = Env({'_module': 'test_pkg', 'git': '{{git}}'}) assert env.git == 'some_version_string'
def test_init_with_file(tmp_directory, cleanup_env): Path('not_a_package').touch() with pytest.raises(ValueError) as exc_info: Env({'_module': 'not_a_package'}) expected = ('Could not resolve _module "not_a_package", ' 'expected a module or a directory but got a file') assert exc_info.value.args[0] == expected
def test_env_repr_and_str_when_loaded_from_file(tmp_directory, cleanup_env): path_env = Path('env.yaml') d = {'user': '******', 'cwd': 'cwd', 'root': 'root'} path_env.write_text(yaml.dump(d)) env = Env() path = str(path_env.resolve()) expected = f"Env({d!r}) (from file: {path})" assert repr(env) == expected assert str(env) == "{'user': '******', 'cwd': 'cwd', 'root': 'root'}"
def test_env_repr_and_str(cleanup_env, monkeypatch): mock = Mock() mock.datetime.now().isoformat.return_value = 'current-timestamp' monkeypatch.setattr(expand, "datetime", mock) env = Env({'user': '******', 'cwd': 'cwd', 'root': 'root'}) d = { 'user': '******', 'cwd': 'cwd', 'now': 'current-timestamp', 'root': 'root' } assert repr(env) == f"Env({d})" assert str(env) == str(d)
def test_env_repr_and_str_when_loaded_from_file(tmp_directory, cleanup_env, monkeypatch): mock = Mock() mock.datetime.now().isoformat.return_value = 'current-timestamp' monkeypatch.setattr(expand, "datetime", mock) path_env = Path('env.yaml') d = { 'user': '******', 'cwd': 'cwd', 'now': 'current-timestamp', 'root': 'root', } path_env.write_text(yaml.dump(d)) env = Env() path = str(path_env.resolve()) expected = f"Env({d!r}) (from file: {path})" assert repr(env) == expected assert str(env) == str(d)
def test_load_env_with_name(tmp_directory, cleanup_env): Path('env.some_name.yaml').write_text(yaml.dump({'a': 1})) Env('env.some_name.yaml')
def test_double_underscore_raises_error(): msg = r"Keys cannot have double underscores, got: \['b\_\_c'\]" with pytest.raises(ValueError, match=msg): Env({'a': {'b__c': 1}})
def test_raise_file_not_found_if(cleanup_env): with pytest.raises(FileNotFoundError): Env('env.non_existing.yaml')
def test_can_instantiate_env_if_located_in_sample_dir(tmp_sample_dir, cleanup_env): Env()
def test_can_create_env_from_dict(cleanup_env): e = Env({'a': 1}) assert e.a == 1
def test_path_expandsuser(cleanup_env): env = Env({'path': {'home': '~'}}) assert env.path.home == Path('~').expanduser()
def test_init_with_absolute_path(cleanup_env, tmp_directory): Path('env.yaml').write_text('a: 1') assert Env(Path(tmp_directory, 'env.yaml'))
def test_init_with_arbitrary_name(cleanup_env, tmp_directory): Path('some_environment.yaml').write_text('a: 1') assert Env('some_environment.yaml')
def test_here_placeholder(tmp_directory, cleanup_env): Path('env.yaml').write_text(yaml.dump({'here': '{{here}}'})) env = Env() assert env.here == str(Path(tmp_directory).resolve())
def test_load_env_default_name(tmp_directory, cleanup_env): Path('env.yaml').write_text(yaml.dump({'a': 1})) Env()
def test_init_with_module_key(cleanup_env): env = Env({'_module': 'test_pkg'}) expected = Path(importlib.util.find_spec('test_pkg').origin).parent assert env._module == expected
def test_module_is_here_placeholder_raises_error_if_init_w_dict(cleanup_env): with pytest.raises(ValueError) as exc_info: Env({'_module': '{{here}}'}) expected = '_module cannot be {{here}} if not loaded from a file' assert exc_info.value.args[0] == expected
def test_automatically_creates_path(cleanup_env, tmp_directory): Env({'path': {'home': 'some_path/'}}) assert Path('some_path').exists() and Path('some_path').is_dir()
def test_includes_path_in_repr_if_init_from_file(cleanup_env, tmp_directory): Path('env.yaml').write_text('a: 1') env = Env('env.yaml') assert 'env.yaml' in repr(env)
def test_module_with_here_placeholder(tmp_directory, cleanup_env): Path('env.yaml').write_text('_module: "{{here}}"') env = Env() assert env._module == Path(tmp_directory).resolve()
def test_init_with_null_value(cleanup_env, tmp_directory): Path('env.yaml').write_text('a: null') assert Env('env.yaml')
def test_expand_version(cleanup_env): env = Env({'_module': 'test_pkg', 'version': '{{version}}'}) assert env.version == 'VERSION'
def test_cannot_start_env_if_one_exists_already(cleanup_env): Env({'a': 1}) with pytest.raises(RuntimeError): Env({'a': 2})
def test_env_repr_and_str(cleanup_env): env = Env({'user': '******', 'cwd': 'cwd', 'root': 'root'}) assert repr(env) == "Env({'user': '******', 'cwd': 'cwd', 'root': 'root'})" assert str(env) == "{'user': '******', 'cwd': 'cwd', 'root': 'root'}"