Fix pep8 errors for unit test files

Fix pep8 errors for unit test files

Change-Id: Ib9704be17ce82b1f6414549365b087ee34a39499
This commit is contained in:
Yang Hongyang 2016-02-06 16:47:09 +08:00
parent 0dc45a3fd8
commit aa07af17e6
9 changed files with 66 additions and 50 deletions

View File

@ -35,6 +35,7 @@ SYSTEM_CONFIG = {
'hostname': 'foohostname', 'hostname': 'foohostname',
} }
class SystemAPITestCase(unittest.TestCase): class SystemAPITestCase(unittest.TestCase):
""" """
This test case contains the unit tests for the Python server implementation This test case contains the unit tests for the Python server implementation
@ -60,7 +61,9 @@ class SystemAPITestCase(unittest.TestCase):
'unsupported platform' 'unsupported platform'
) )
def test_get_interface(self): def test_get_interface(self):
with mock.patch.object(v1.system.manager.router, 'get_interface') as get_if: with mock.patch.object(
v1.system.manager.router, 'get_interface'
) as get_if:
get_if.return_value = 'ge1' get_if.return_value = 'ge1'
result = self.test_app.get('/v1/system/interface/ge1') result = self.test_app.get('/v1/system/interface/ge1')
get_if.assert_called_once_with('ge1') get_if.assert_called_once_with('ge1')
@ -74,7 +77,9 @@ class SystemAPITestCase(unittest.TestCase):
'unsupported platform' 'unsupported platform'
) )
def test_get_interfaces(self): def test_get_interfaces(self):
with mock.patch.object(v1.system.manager.router, 'get_interfaces') as get_ifs: with mock.patch.object(
v1.system.manager.router, 'get_interfaces'
) as get_ifs:
get_ifs.return_value = ['ge0', 'ge1'] get_ifs.return_value = ['ge0', 'ge1']
result = self.test_app.get('/v1/system/interfaces') result = self.test_app.get('/v1/system/interfaces')
get_ifs.assert_called_once_with() get_ifs.assert_called_once_with()
@ -150,13 +155,12 @@ class SystemAPITestCase(unittest.TestCase):
not distutils.spawn.find_executable('ip'), not distutils.spawn.find_executable('ip'),
'unsupported platform' 'unsupported platform'
) )
@mock.patch('astara_router.api.v1.system._get_cache') @mock.patch('astara_router.api.v1.system._get_cache')
@mock.patch('astara_router.models.SystemConfiguration') @mock.patch('astara_router.models.SystemConfiguration')
@mock.patch.object(v1.system.manager, 'update_config') @mock.patch.object(v1.system.manager, 'update_config')
def test_put_configuration_returns_200(self, mock_update, def test_put_configuration_returns_200(
fake_system_config, fake_cache): self, mock_update, fake_system_config, fake_cache
):
fake_cache.return_value = 'fake_cache' fake_cache.return_value = 'fake_cache'
sys_config_obj = mock.Mock() sys_config_obj = mock.Mock()
sys_config_obj.validate = mock.Mock() sys_config_obj.validate = mock.Mock()
@ -175,7 +179,8 @@ class SystemAPITestCase(unittest.TestCase):
self.assertEqual(result.status_code, 200) self.assertEqual(result.status_code, 200)
self.assertTrue(json.loads(result.data)) self.assertTrue(json.loads(result.data))
mock_update.assert_called_with( mock_update.assert_called_with(
cache='fake_cache', service_configs=[], system_config=sys_config_obj) cache='fake_cache', service_configs=[],
system_config=sys_config_obj)
@mock.patch('astara_router.manager.Manager.config', @mock.patch('astara_router.manager.Manager.config',
new_callable=mock.PropertyMock, return_value={}) new_callable=mock.PropertyMock, return_value={})
@ -183,8 +188,10 @@ class SystemAPITestCase(unittest.TestCase):
@mock.patch('astara_router.models.RouterConfiguration') @mock.patch('astara_router.models.RouterConfiguration')
@mock.patch('astara_router.models.SystemConfiguration') @mock.patch('astara_router.models.SystemConfiguration')
@mock.patch.object(v1.system.manager, 'update_config') @mock.patch.object(v1.system.manager, 'update_config')
def test_put_configuration_with_router(self, mock_update, def test_put_configuration_with_router(
fake_system_config, fake_router_config, fake_cache, fake_config): self, mock_update, fake_system_config, fake_router_config,
fake_cache, fake_config
):
fake_config.return_value = 'foo' fake_config.return_value = 'foo'
fake_cache.return_value = 'fake_cache' fake_cache.return_value = 'fake_cache'
sys_config_obj = mock.Mock() sys_config_obj = mock.Mock()
@ -197,7 +204,6 @@ class SystemAPITestCase(unittest.TestCase):
router_config_obj.validate.return_value = [] router_config_obj.validate.return_value = []
fake_router_config.return_value = router_config_obj fake_router_config.return_value = router_config_obj
result = self.test_app.put( result = self.test_app.put(
'/v1/system/config', '/v1/system/config',
data=json.dumps({ data=json.dumps({
@ -222,9 +228,11 @@ class SystemAPITestCase(unittest.TestCase):
@mock.patch('astara_router.models.LoadBalancerConfiguration') @mock.patch('astara_router.models.LoadBalancerConfiguration')
@mock.patch('astara_router.models.SystemConfiguration') @mock.patch('astara_router.models.SystemConfiguration')
@mock.patch.object(v1.system.manager, 'update_config') @mock.patch.object(v1.system.manager, 'update_config')
def test_put_configuration_with_adv_services(self, mock_update, def test_put_configuration_with_adv_services(
self, mock_update,
fake_system_config, fake_lb_config, fake_cache, fake_config, fake_system_config, fake_lb_config, fake_cache, fake_config,
fake_api_settings, fake_mgr_settings, fake_get_config_model): fake_api_settings, fake_mgr_settings, fake_get_config_model
):
fake_api_settings.ENABLED_SERVICES = ['loadbalancer'] fake_api_settings.ENABLED_SERVICES = ['loadbalancer']
fake_mgr_settings.ENABLED_SERVICES = ['loadbalancer'] fake_mgr_settings.ENABLED_SERVICES = ['loadbalancer']
fake_config.return_value = 'foo' fake_config.return_value = 'foo'
@ -266,9 +274,11 @@ class SystemAPITestCase(unittest.TestCase):
@mock.patch('astara_router.models.LoadBalancerConfiguration') @mock.patch('astara_router.models.LoadBalancerConfiguration')
@mock.patch('astara_router.models.SystemConfiguration') @mock.patch('astara_router.models.SystemConfiguration')
@mock.patch.object(v1.system.manager, 'update_config') @mock.patch.object(v1.system.manager, 'update_config')
def test_put_configuration_with_disabled_svc_returns_400(self, mock_update, def test_put_configuration_with_disabled_svc_returns_400(
self, mock_update,
fake_system_config, fake_lb_config, fake_cache, fake_config, fake_system_config, fake_lb_config, fake_cache, fake_config,
fake_api_settings, fake_mgr_settings, fake_get_config_model): fake_api_settings, fake_mgr_settings, fake_get_config_model
):
fake_api_settings.ENABLED_SERVICES = ['foo'] fake_api_settings.ENABLED_SERVICES = ['foo']
fake_mgr_settings.ENABLED_SERVICES = ['foo'] fake_mgr_settings.ENABLED_SERVICES = ['foo']
fake_config.return_value = 'foo' fake_config.return_value = 'foo'

View File

@ -28,9 +28,10 @@ alloc = mock.Mock()
network.address_allocations = [alloc] network.address_allocations = [alloc]
config.networks = [network] config.networks = [network]
def _AF_PACKET_supported(): def _AF_PACKET_supported():
try: try:
from socket import AF_PACKET socket.AF_PACKET
return True return True
except: except:
return False return False

View File

@ -19,7 +19,7 @@ from unittest2 import TestCase
import mock import mock
from astara_router.drivers import hostname, ip from astara_router.drivers import hostname
CONFIG = mock.Mock() CONFIG = mock.Mock()
CONFIG.hostname = 'astara' CONFIG.hostname = 'astara'

View File

@ -143,7 +143,7 @@ class IPTestCase(TestCase):
iface.ifname = 'ge0' iface.ifname = 'ge0'
attr = 'ensure_mapping' attr = 'ensure_mapping'
with mock.patch.object(ip.IPManager, attr) as ensure: with mock.patch.object(ip.IPManager, attr):
mgr = ip.IPManager() mgr = ip.IPManager()
mgr.host_mapping = {'em0': 'ge0'} mgr.host_mapping = {'em0': 'ge0'}
mgr.generic_mapping = {'ge0': 'em0'} mgr.generic_mapping = {'ge0': 'em0'}
@ -156,7 +156,7 @@ class IPTestCase(TestCase):
iface.ifname = 'ge0' iface.ifname = 'ge0'
attr = 'ensure_mapping' attr = 'ensure_mapping'
with mock.patch.object(ip.IPManager, attr) as ensure: with mock.patch.object(ip.IPManager, attr):
mgr = ip.IPManager() mgr = ip.IPManager()
mgr.host_mapping = {'em0': 'ge0'} mgr.host_mapping = {'em0': 'ge0'}
mgr.generic_mapping = {'ge0': 'em0'} mgr.generic_mapping = {'ge0': 'em0'}
@ -172,7 +172,7 @@ class IPTestCase(TestCase):
iface.mtu = 1280 iface.mtu = 1280
attr = 'ensure_mapping' attr = 'ensure_mapping'
with mock.patch.object(ip.IPManager, attr) as ensure: with mock.patch.object(ip.IPManager, attr):
mgr = ip.IPManager() mgr = ip.IPManager()
mgr.host_mapping = {'em0': 'ge0'} mgr.host_mapping = {'em0': 'ge0'}
mgr.generic_mapping = {'ge0': 'em0'} mgr.generic_mapping = {'ge0': 'em0'}
@ -319,15 +319,15 @@ class IPTestCase(TestCase):
old_iface.all_addresses = [b, c] old_iface.all_addresses = [b, c]
old_iface.ifname = 'em0' old_iface.ifname = 'em0'
add = lambda g: ('addr', 'add', '/'.join(map(str, g)), 'dev', 'em0')
delete = lambda g: ('addr', 'del', '/'.join(map(str, g)), 'dev', 'em0')
mgr = ip.IPManager() mgr = ip.IPManager()
with mock.patch.object( with mock.patch.object(
mgr, 'generic_to_host', lambda x: x.replace('ge', 'em') mgr, 'generic_to_host', lambda x: x.replace('ge', 'em')
): ):
mgr._update_set('em0', iface, old_iface, 'all_addresses', add, mgr._update_set(
delete) 'em0', iface, old_iface, 'all_addresses',
lambda g: ('addr', 'add', '/'.join(map(str, g)), 'dev', 'em0'),
lambda g: ('addr', 'del', '/'.join(map(str, g)), 'dev', 'em0')
)
assert self.mock_execute.call_args_list == [ assert self.mock_execute.call_args_list == [
mock.call([ mock.call([
@ -351,11 +351,11 @@ class IPTestCase(TestCase):
old_iface = mock.Mock() old_iface = mock.Mock()
old_iface.all_addresses = [a, b] old_iface.all_addresses = [a, b]
add = lambda g: ('em0', 'add', g)
delete = lambda g: ('em0', 'del', g)
mgr = ip.IPManager() mgr = ip.IPManager()
mgr._update_set('em0', iface, old_iface, 'all_addresses', add, delete) mgr._update_set(
'em0', iface, old_iface, 'all_addresses',
lambda g: ('em0', 'add', g), lambda g: ('em0', 'del', g)
)
self.assertEqual(self.mock_execute.call_count, 0) self.assertEqual(self.mock_execute.call_count, 0)
@ -432,6 +432,7 @@ class TestDisableDAD(TestCase):
finally: finally:
logger.removeHandler(handler) logger.removeHandler(handler)
class ParseTestCase(TestCase): class ParseTestCase(TestCase):
def test_parse_interfaces(self): def test_parse_interfaces(self):
with mock.patch.object(ip, '_parse_interface') as parse: with mock.patch.object(ip, '_parse_interface') as parse:

View File

@ -56,7 +56,8 @@ class HostnameTestCase(TestCase):
def _test_should_restart(self, exp_result): def _test_should_restart(self, exp_result):
config_json = json.dumps(self.config_dict) config_json = json.dumps(self.config_dict)
with mock.patch.object( with mock.patch.object(
__builtin__, 'open', mock.mock_open(read_data=config_json)): __builtin__, 'open', mock.mock_open(read_data=config_json)
):
self.assertEqual( self.assertEqual(
self.mgr.should_restart(self.config), exp_result) self.mgr.should_restart(self.config), exp_result)
@ -78,7 +79,8 @@ class HostnameTestCase(TestCase):
def test_should_restart_true_config_read_err(self): def test_should_restart_true_config_read_err(self):
with mock.patch.object( with mock.patch.object(
__builtin__, 'open', mock.mock_open()) as _o: __builtin__, 'open', mock.mock_open()
) as _o:
_o.side_effect = IOError() _o.side_effect = IOError()
self.assertEqual( self.assertEqual(
self.mgr.should_restart(self.config), True) self.mgr.should_restart(self.config), True)

View File

@ -29,7 +29,8 @@ FAKE_SYSTEM_DICT = {
"interface": { "interface": {
"ifname": "ge1", "ifname": "ge1",
"addresses": [ "addresses": [
"192.168.0.137/24", "fdd6:a1fa:cfa8:6af6:f816:3eff:fea0:8082/64" "192.168.0.137/24",
"fdd6:a1fa:cfa8:6af6:f816:3eff:fea0:8082/64"
] ]
}, },
}, },
@ -75,7 +76,8 @@ FAKE_LOADBALANCER_DICT = {
"ip_address": "fdd6:a1fa:cfa8:6af6:f816:3eff:fea0:8082"} "ip_address": "fdd6:a1fa:cfa8:6af6:f816:3eff:fea0:8082"}
], ],
"id": "352e2867-06c6-4ced-8e81-1c016991fb38", "id": "352e2867-06c6-4ced-8e81-1c016991fb38",
"device_id": "8ac54799-b143-48e5-94d4-e5e989592229"}, "device_id": "8ac54799-b143-48e5-94d4-e5e989592229"
},
"vip_address": "192.168.0.137", "vip_address": "192.168.0.137",
"id": "8ac54799-b143-48e5-94d4-e5e989592229", "id": "8ac54799-b143-48e5-94d4-e5e989592229",
"listeners": [], "listeners": [],
@ -91,8 +93,6 @@ FAKE_LISTENER_DICT = {
'tenant_id': 'd22b149cee9b4eac8349c517eda00b89' 'tenant_id': 'd22b149cee9b4eac8349c517eda00b89'
} }
FAKE_POOL_DICT = { FAKE_POOL_DICT = {
'admin_state_up': True, 'admin_state_up': True,
'healthmonitor': None, 'healthmonitor': None,

View File

@ -19,6 +19,7 @@ config = json.dumps({
} }
}) })
class TestMetadataProxy(unittest.TestCase): class TestMetadataProxy(unittest.TestCase):
@mock.patch('eventlet.monkey_patch', mock.Mock()) @mock.patch('eventlet.monkey_patch', mock.Mock())
@ -41,7 +42,8 @@ class TestMetadataProxy(unittest.TestCase):
any_order=True any_order=True
) )
# call_args need to be order before we can test it # call_args need to be order before we can test it
spawn_args = sorted(spawn.call_args_list, key=lambda y: y[0][2].network_id) spawn_args = sorted(spawn.call_args_list,
key=lambda y: y[0][2].network_id)
server, socket, app = spawn_args[0][0] server, socket, app = spawn_args[0][0]
assert server == eventlet.wsgi.server assert server == eventlet.wsgi.server
assert isinstance(app, metadata_proxy.NetworkMetadataProxyHandler) assert isinstance(app, metadata_proxy.NetworkMetadataProxyHandler)

View File

@ -15,8 +15,6 @@
# under the License. # under the License.
import textwrap
import copy import copy
import mock import mock
import netaddr import netaddr
@ -199,6 +197,7 @@ class FilterRuleModelTestCase(TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
models.FilterRule(action='pass', protocol='made_up_proto') models.FilterRule(action='pass', protocol='made_up_proto')
class AnchorTestCase(TestCase): class AnchorTestCase(TestCase):
def test_anchor(self): def test_anchor(self):
a = models.Anchor('foo', []) a = models.Anchor('foo', [])
@ -335,7 +334,7 @@ class NetworkTestCase(TestCase):
def test_network_type_invalid(self): def test_network_type_invalid(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
n = models.Network('id', None, network_type='invalid') models.Network('id', None, network_type='invalid')
def test_v4_conf_service_valid(self): def test_v4_conf_service_valid(self):
n = models.Network('id', None, v4_conf_service='dhcp') n = models.Network('id', None, v4_conf_service='dhcp')
@ -346,7 +345,7 @@ class NetworkTestCase(TestCase):
def test_v4_conf_service_invalid(self): def test_v4_conf_service_invalid(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
n = models.Network('id', None, v4_conf_service='invalid') models.Network('id', None, v4_conf_service='invalid')
def test_v6_conf_service_valid(self): def test_v6_conf_service_valid(self):
n = models.Network('id', None, v6_conf_service='dhcp') n = models.Network('id', None, v6_conf_service='dhcp')
@ -360,7 +359,7 @@ class NetworkTestCase(TestCase):
def test_v6_conf_service_invalid(self): def test_v6_conf_service_invalid(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
n = models.Network('id', None, v6_conf_service='invalid') models.Network('id', None, v6_conf_service='invalid')
class RouterConfigurationTestCase(TestCase): class RouterConfigurationTestCase(TestCase):
@ -427,14 +426,16 @@ class RouterConfigurationTestCase(TestCase):
name='theanchor', name='theanchor',
rules=[]) rules=[])
c = models.RouterConfiguration(dict(networks=[], anchors=[anchor_dict])) c = models.RouterConfiguration(dict(networks=[],
anchors=[anchor_dict]))
self.assertEqual(len(c.anchors), 1) self.assertEqual(len(c.anchors), 1)
def test_init_anchor(self): def test_init_anchor(self):
test_rule = dict(action='block', source='192.168.1.1/32') test_rule = dict(action='block', source='192.168.1.1/32')
anchor_dict = dict(name='theanchor', rules=[test_rule]) anchor_dict = dict(name='theanchor', rules=[test_rule])
c = models.RouterConfiguration(dict(networks=[], anchors=[anchor_dict])) c = models.RouterConfiguration(dict(networks=[],
anchors=[anchor_dict]))
self.assertEqual(len(c.anchors), 1) self.assertEqual(len(c.anchors), 1)
self.assertEqual(len(c.anchors[0].rules), 1) self.assertEqual(len(c.anchors[0].rules), 1)
self.assertEqual(c.anchors[0].rules[0].action, 'block') self.assertEqual(c.anchors[0].rules[0].action, 'block')
@ -546,7 +547,6 @@ class RouterConfigurationTestCase(TestCase):
self.assertEqual(c.to_dict(), expected) self.assertEqual(c.to_dict(), expected)
class LBListenerTest(TestCase): class LBListenerTest(TestCase):
def test_from_dict(self): def test_from_dict(self):
ldict = copy.copy(fakes.FAKE_LISTENER_DICT) ldict = copy.copy(fakes.FAKE_LISTENER_DICT)