import testinfra.utils.ansible_runner

def test_packages(host):
  package = host.package('haproxy')
  assert package.is_installed

def test_config_file(host):
  path = host.file('/etc/haproxy/haproxy.cfg')
  assert path.exists
  assert path.is_file
  assert path.user == 'root'
  assert path.group == 'root'
  assert path.mode == 0o640
  assert path.contains('server host1 127.0.0.1:443 ssl verify none check maxconn 1000 inter 15s')
  assert path.contains('resolvers dns')

def test_certificate_file(host):
  path = host.file('/etc/haproxy/www-example-com.pem')
  assert path.exists
  assert path.is_file
  assert path.user == 'root'
  assert path.group == 'root'
  assert path.mode == 0o600
  assert path.contains('test')
  
def test_ips_list_file(host):
  path = host.file('/etc/haproxy/blacklist.list')
  assert path.exists
  assert path.is_file
  assert path.user == 'root'
  assert path.group == 'root'
  assert path.mode == 0o644
  assert path.contains('172.10.0.0/16\n192.168.1.1')

def test_service(host):
  service = host.service('haproxy')
  assert service.is_running
  assert service.is_enabled

def test_sockets(host):
  for port in [80, 5000]:
    socket = host.socket('tcp://0.0.0.0:%d' % (port))
    assert socket.is_listening

def test_auth(host):
  cmd = host.run('curl -v -u admin:password http://127.0.0.1/auth/')
  assert cmd.succeeded
  assert cmd.stdout == 'Good'
  cmd = host.run('curl -v -u admin:badpassword http://127.0.0.1/auth/')
  assert cmd.succeeded
  assert '401 Unauthorized' in cmd.stdout