Exemple #1
0
    def decorator(fn):
        _validate_and_modify_signature(fn)

        try:
            # FIXME: we should deprecate initializing from a decorator
            # with a dictionary, it isn't useful. leaving it for now
            if isinstance(source, Mapping):
                env_dict = EnvDict(source)
            else:
                # when the decorator is called without args, look for
                # 'env.yaml'
                env_dict = EnvDict.find(source or 'env.yaml')
        except Exception as e:
            raise RuntimeError('Failed to resolve environment using '
                               '@with_env decorator in function "{}". '
                               'Tried to call Env with argument: {}'.format(
                                   _get_function_name_w_module(fn),
                                   source)) from e

        fn._env_dict = env_dict

        @wraps(fn)
        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

        return wrapper
Exemple #2
0
def test_find(tmp_directory):
    path = Path('some', 'dir')
    path.mkdir(parents=True)
    Path('some', 'env.yaml').write_text('key: value')
    expected_here = str(Path('some').resolve())

    os.chdir(path)

    env = EnvDict.find('env.yaml')

    assert env.cwd == str(Path('.').resolve())
    assert env.here == expected_here