import pytest

from util.config.validators import ConfigValidationException
from util.config.validators.validate_jwt import JWTAuthValidator
from util.morecollections import AttrDict

from test.test_external_jwt_authn import fake_jwt


@pytest.mark.parametrize('unvalidated_config', [
  ({}),
  ({'AUTHENTICATION_TYPE': 'Database'}),
])
def test_validate_noop(unvalidated_config):
  JWTAuthValidator.validate(unvalidated_config, None, None)


@pytest.mark.parametrize('unvalidated_config', [
  ({'AUTHENTICATION_TYPE': 'JWT'}),
  ({'AUTHENTICATION_TYPE': 'JWT', 'JWT_AUTH_ISSUER': 'foo'}),
  ({'AUTHENTICATION_TYPE': 'JWT', 'JWT_VERIFY_ENDPOINT': 'foo'}),
])
def test_invalid_config(unvalidated_config):
  with pytest.raises(ConfigValidationException):
    JWTAuthValidator.validate(unvalidated_config, None, None)


@pytest.mark.parametrize('username, password, expected_exception', [
  ('invaliduser', 'invalidpass', ConfigValidationException),
  ('cool.user', 'invalidpass', ConfigValidationException),
  ('invaliduser', 'somepass', ConfigValidationException),
  ('cool.user', 'password', None),
])
def test_validated_jwt(username, password, expected_exception):
  with fake_jwt() as jwt_auth:
    config = {}
    config['AUTHENTICATION_TYPE'] = 'JWT'
    config['JWT_AUTH_ISSUER'] = jwt_auth.issuer
    config['JWT_VERIFY_ENDPOINT'] = jwt_auth.verify_url
    config['JWT_QUERY_ENDPOINT'] = jwt_auth.query_url
    config['JWT_GETUSER_ENDPOINT'] = jwt_auth.getuser_url

    if expected_exception is not None:
      with pytest.raises(ConfigValidationException):
        JWTAuthValidator.validate(config, AttrDict(dict(username=username)), password,
                                  public_key_path=jwt_auth.public_key_path)
    else:
        JWTAuthValidator.validate(config, AttrDict(dict(username=username)), password,
                                  public_key_path=jwt_auth.public_key_path)