#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3


from winswitch.globals import HOSTNAME
from winswitch.util.simple_logger import Logger
from winswitch.net.net_util import do_get_bind_ifacemask, get_bind_IPs, get_iface, is_localhost, get_interfaces, if_nametoindex, if_indextoname, get_port_mapper

logger=Logger("net_util_test", log_colour=Logger.RED, _debug=True)

def test_get_bind_IPs():
	logger.log()
	bind_ips = get_bind_IPs()
	assert bind_ips
	assert len(bind_ips)>0

def test_do_get_bind_ifacemask():
	logger.log()
	found = False
	for iface in ["lo", "eth0"]:
		mask = do_get_bind_ifacemask(iface)
		logger.log("() mask(%s)=%s" % (iface, mask))
		if mask:
			found = True
	assert found

def test_get_iface():
	logger.log()
	found = False
	for ip in ["127.0.0.1", None, "blah", "192.168.3.1", "10.0.0.0", "1.2.3.4"]:
		iface = get_iface(ip)
		logger.log("() iface(%s)=%s" % (ip, iface))
		if iface:
			found = True
	assert found

def test_is_localhost():
	logger.log()
	assert not is_localhost(None)
	assert not is_localhost("blah")
	assert not is_localhost(None)
	assert is_localhost("127.0.0.1")
	assert is_localhost("localhost")
	assert is_localhost(HOSTNAME)
	for ip in get_bind_IPs():
		assert is_localhost(ip)

def test_port_mapper():
	logger.log()
	pass

def	test_get_interfaces():
	ifaces = get_interfaces()
	logger.debug("() interfaces=%s" % str(ifaces))
	assert ifaces
	assert len(ifaces)>0

def test_if_nametoindex():
	for iface in get_interfaces():
		index = if_nametoindex(iface)
		logger.debug("() index(%s)=%s" % (iface, index))

def test_if_indextoname():
	for iface in get_interfaces():
		index = if_nametoindex(iface)
		back = if_indextoname(index)
		logger.debug("() name(%s)=%s" % (index, back))
		assert back == iface

def test_load_blacklisted_ports():
	get_port_mapper().load_blacklisted_ports()


def main():
	test_get_bind_IPs()
	test_do_get_bind_ifacemask()
	test_get_iface()
	test_is_localhost()
	test_port_mapper()
	test_get_interfaces()
	test_if_nametoindex()
	test_if_indextoname()
	test_load_blacklisted_ports()

if __name__ == "__main__":
	main()