pvl/hosts/tests.py
author Tero Marttila <tero.marttila@aalto.fi>
Tue, 24 Feb 2015 18:56:22 +0200
changeset 449 a19438b781d5
parent 447 6f0357759e9b
child 451 d302b4957b07
permissions -rw-r--r--
pvl.hosts.config: cleanup apply_host_config
import ipaddr
import unittest

from pvl.hosts import config
from StringIO import StringIO

class Options(object):
    hosts_charset   = 'utf-8'
    hosts_domain    = None
    hosts_include   = None

class ConfFile(StringIO):
    def __init__(self, name, buffer):
        StringIO.__init__(self, buffer)
        self.name = name

class TestConfig(unittest.TestCase):
    def setUp(self):
        self.options = Options()

    def assertHostsEqual(self, hosts, expected):
        for host, expect in zip(hosts, expected):
            host_str, attrs = expect

            self.assertEquals(str(host), host_str)

            for attr, value in attrs.iteritems():
                self.assertEquals(getattr(host, attr), value)
 
    def testApply(self):
        self.assertHostsEqual(config.apply(self.options, ['etc/hosts/test']), [
                ('foo@test', dict(ip=ipaddr.IPAddress('127.0.0.1'))),
                ('bar@test', dict(ip=ipaddr.IPAddress('127.0.0.2'))),
        ])

    def testApplyHostsError(self):
        with self.assertRaises(config.HostConfigError):
            list(config.apply_hosts(self.options, ['nonexistant']))

    def testApplyHosts(self):
        conf_file = ConfFile('test', """
[foo]
    ip = 127.0.0.1

[bar]
    ip = 127.0.0.2
        """)
        expected = [
                ('foo@test', dict(ip=ipaddr.IPAddress('127.0.0.1'))),
                ('bar@test', dict(ip=ipaddr.IPAddress('127.0.0.2'))),
        ]

        self.assertHostsEqual(config.apply_hosts_file(self.options, conf_file), expected)

    def testApplyHostsExpand(self):
        self.assertHostsEqual(config.apply_host_config(self.options, 'asdf', 'asdf{1-3}', ip='10.100.100.$'), [
                ('asdf1@asdf', dict(ip=ipaddr.IPAddress('10.100.100.1'))),
                ('asdf2@asdf', dict(ip=ipaddr.IPAddress('10.100.100.2'))),
                ('asdf3@asdf', dict(ip=ipaddr.IPAddress('10.100.100.3'))),
        ])

if __name__ == '__main__':
    unittest.main()