rougail-user-data-environment/tests/test_load.py
2024-10-01 18:16:00 +02:00

174 lines
6 KiB
Python

from .custom import CustomOption
from pathlib import Path
from os import getcwd, listdir, makedirs
import os
from os.path import isfile, join, isdir, dirname
from pathlib import Path
from json import load, dump
from pytest import fixture, raises
from ruamel.yaml import YAML
from dotenv import load_dotenv
from rougail import RougailConfig, Rougail
from rougail.user_data_environment.data import RougailUserDataEnvironment
dico_dirs = Path('../rougail/tests/dictionaries')
#env_test_folder = '00_6string'
# path configuration
#_here = Path(__file__).resolve().parent
#envtest = _here / 'tests' / 'envvars'
#test_ok = [dico_dirs / env_test_folder]
#let's save the original environment
save = os.environ.copy()
test_ok = set()
excludes = set()
test_ok -= excludes
for test in dico_dirs.iterdir():
if (test / 'tiramisu').is_dir() and test.name not in excludes:
test_ok.add(test)
test_ok = list(test_ok)
test_ok.sort()
@fixture(scope="module", params=test_ok)
def test_dir(request):
return request.param
def _test_dictionaries(test_dir):
"rougail config settings"
rougailconfig = RougailConfig.copy()
rougailconfig['step.user_data'] = ['environment']
rougailconfig['main_namespace'] = None
dirs = [str(test_dir / 'dictionaries' / 'rougail')]
rougailconfig['custom_types']['custom'] = CustomOption
rougailconfig['main_dictionaries'] = dirs
return rougailconfig
def test_dictionaries_warning(test_dir):
"tests the env output"
current_dirname = test_dir.name
rougailconfig = _test_dictionaries(test_dir)
# populate tests if not already exists
dest_dir = Path('tests') / 'envvars' / test_dir.name
populate(dest_dir, rougailconfig)
# loads the config in the tiramisu's meaning
config = Rougail(rougailconfig).run() #Config(optiondescription["option_0"])
config_dict = dict(config.value.get())
user_datas = {'errors': [],
'warnings': [],
}
# loading the env file
envfile = dest_dir / 'env'/ 'all.env'
load_dotenv(envfile)
# loads the environment variables in the tiramisu config
environment = RougailUserDataEnvironment(config,
rougailconfig=rougailconfig,
user_datas=user_datas,
)
environment.run()
#expected output
with open(Path('tests') / 'envvars' / current_dirname / 'makedict' / 'all.env') as json_file:
expected = load(json_file)
# here is the effective test
config_dict = dict(option_value(config.value.get()))
assert expected == config_dict
#teardown: set the original environement again
os.environ = save.copy()
def populate(dest_dir, rougailconfig):
for level in ['all', 'mandatories']:
environment_file = dest_dir / 'env' / f'{level}.env'
makedict_file = dest_dir / 'makedict' / f'{level}.env'
environment_file.parent.mkdir(parents=True, exist_ok=True)
makedict_file.parent.mkdir(parents=True, exist_ok=True)
if not environment_file.is_file() or not makedict_file.is_file():
config = Rougail(rougailconfig).run()
if level == 'all':
root_config = config.unrestraint
else:
root_config = config.unrestraint.value.mandatory()
values = []
for variable in get_variables(root_config):
var = get_value(variable)
if var is None:
var = ""
values.append('ROUGAIL_' + variable.path().upper() + '="' + var + '"')
if not environment_file.is_file():
with environment_file.open('w') as envfh:
envfh.write('\n'.join(values) + '\n')
if not makedict_file.is_file():
with makedict_file.open('w') as envfh:
config_dict = dict(option_value(config.value.get()))
dump(config_dict, envfh, indent=4)
envfh.write('\n')
def get_value(variable):
tests = variable.information.get('test', None)
if not tests:
if variable.type() == 'integer':
tests = [1, 2, 3]
elif variable.type() == 'float':
tests = [1.1, 2.2, 3.3]
elif variable.type() == 'port':
tests = ['80', '443']
elif variable.type() == 'boolean':
tests = [True]
elif variable.type() == 'domain name':
tests = ['domain1.lan', 'domain2.lan']
elif variable.type() == 'choice':
tests = variable.value.list()
else:
tests = ['string1', 'string2', 'string3']
if not variable.ismulti() or (variable.isfollower() and variable.ismulti() is True):
tests = tests[0]
variable.value.set(tests)
if isinstance(tests, list):
tests = ','.join([str(test) for test in tests])
else:
tests = str(tests)
return tests
def get_variables(config):
for key in config:
if key.isoptiondescription():
yield from get_variables(key)
else:
yield key
def option_value(parent, key_is_option=False):
for option, value in parent.items():
if option.isoptiondescription():
if not key_is_option and option.isleadership():
ret = []
for idx, datas in enumerate(option_value(value, key_is_option=True)):
sub_option, sub_value = datas
if not idx:
sub_option = sub_option.path()
key = sub_option
for val in sub_value:
ret.append({sub_option: val})
else:
index = sub_option.index()
sub_option = sub_option.path()
ret[index][sub_option] = sub_value
yield key, ret
else:
yield from option_value(value, key_is_option)
elif key_is_option:
yield option, value
else:
yield option.path(), value