from yaml import load, SafeLoader
from os import environ

from execute import run

EXTERNAL_DOMAIN = 'google.fr'


def test_dns_local():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/dns-local.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    if 'addresses' not in data:
        return
    for address in data['addresses']:
        result = run(data['address'],
                     ['/bin/resolvectl', 'query', address['dns_address']],
                     )
        first = next(result)
        search = f"{address['dns_address']}: {address['dns_ip']}"
        assert first == search or first.startswith(search + " "), f'dns return "{first}" instead of "{search}"'


def test_dns_external():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/dns-local.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    if data['dns_is_only_local']:
        result = run(data['address'],
                     ['/bin/resolvectl', 'query', EXTERNAL_DOMAIN],
                     )
        assert 'resolve call failed' in next(result), f'should not resolved {EXTERNAL_DOMAIN}'
