コード例 #1
0
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
コード例 #2
0
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
コード例 #3
0
ファイル: decorators.py プロジェクト: israelrico007/ploomber
        def wrapper(*args, **kwargs):
            to_replace = {
                k: v
                for k, v in kwargs.items() if k.startswith('env__')
            }

            for key in to_replace.keys():
                kwargs.pop(key)

            env_dict_new = env_dict._replace_flatten_keys(to_replace)

            try:
                Env._init_from_decorator(env_dict_new,
                                         _get_function_name_w_module(fn))
            except Exception as e:
                current = Env.load()
                raise RuntimeError('Failed to initialize environment using '
                                   '@with_env decorator in function "{}". '
                                   'Current environment: {}'.format(
                                       _get_function_name_w_module(fn),
                                       repr(current))) from e

            Env._ref = _get_function_name_w_module(fn)

            try:
                res = fn(Env.load(), *args, **kwargs)
            except Exception as e:
                Env.end()
                raise e

            Env.end()

            return res
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
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)
コード例 #7
0
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'
コード例 #8
0
def test_load_env_decorator(cleanup_env):
    Env({'a': 10})

    @load_env
    def fn(env):
        return env.a

    assert fn() == 10
コード例 #9
0
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
コード例 #10
0
ファイル: test_env.py プロジェクト: israelrico007/ploomber
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'}"
コード例 #11
0
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)
コード例 #12
0
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)
コード例 #13
0
def test_can_create_env_from_dict(cleanup_env):
    e = Env({'a': 1})
    assert e.a == 1
コード例 #14
0
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')
コード例 #15
0
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}})
コード例 #16
0
def test_init_with_absolute_path(cleanup_env, tmp_directory):
    Path('env.yaml').write_text('a: 1')
    assert Env(Path(tmp_directory, 'env.yaml'))
コード例 #17
0
def test_path_expandsuser(cleanup_env):
    env = Env({'path': {'home': '~'}})
    assert env.path.home == Path('~').expanduser()
コード例 #18
0
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())
コード例 #19
0
def test_init_with_arbitrary_name(cleanup_env, tmp_directory):
    Path('some_environment.yaml').write_text('a: 1')
    assert Env('some_environment.yaml')
コード例 #20
0
def test_expand_version(cleanup_env):
    env = Env({'_module': 'test_pkg', 'version': '{{version}}'})
    assert env.version == 'VERSION'
コード例 #21
0
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()
コード例 #22
0
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
コード例 #23
0
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
コード例 #24
0
def test_load_env_default_name(tmp_directory, cleanup_env):
    Path('env.yaml').write_text(yaml.dump({'a': 1}))
    Env()
コード例 #25
0
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)
コード例 #26
0
def test_can_instantiate_env_if_located_in_sample_dir(tmp_sample_dir,
                                                      cleanup_env):
    Env()
コード例 #27
0
def test_init_with_null_value(cleanup_env, tmp_directory):
    Path('env.yaml').write_text('a: null')
    assert Env('env.yaml')
コード例 #28
0
def test_raise_file_not_found_if(cleanup_env):
    with pytest.raises(FileNotFoundError):
        Env('env.non_existing.yaml')
コード例 #29
0
def test_cannot_start_env_if_one_exists_already(cleanup_env):
    Env({'a': 1})

    with pytest.raises(RuntimeError):
        Env({'a': 2})
コード例 #30
0
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()