from yaml import load, SafeLoader
from os import environ
import warnings
import socket
from json import loads
from requests import get

from execute import run


def req(url, ip, verify=True):
    # Monkey patch to force IPv4 resolution
    old_getaddrinfo = socket.getaddrinfo
    def new_getaddrinfo(*args, **kwargs):
        ret = old_getaddrinfo(*args, **kwargs)
        dns = list(ret[0])
        dns[-1] = (ip, dns[-1][1])
        return [dns]
    socket.getaddrinfo = new_getaddrinfo
    ret = get(url, verify=verify)
    ret_code = ret.status_code
    content = ret.content
    socket.getaddrinfo = old_getaddrinfo
    return ret_code, content.decode()


def test_well_known_outside():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/lemonldap.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    url = f'https://{data["address"]}/.well-known/openid-configuration'
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        ret_code, content = req(url, data['ip'], verify=False)
    assert ret_code == 200
    json = loads(content)

    assert data['internal_address'] not in json['token_endpoint']
    assert data['internal_address'] not in json['userinfo_endpoint']
    assert data['internal_address'] not in json['jwks_uri']


def test_well_known_inside():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/lemonldap.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    result = run(data['internal_address'],
                 ['/usr/local/lib/sbin/wget.pl'],
                 )
    json = loads(list(result)[-2])

    assert data['internal_address'] in json['token_endpoint']
    assert data['internal_address'] in json['userinfo_endpoint']
    assert data['internal_address'] in json['jwks_uri']
