class InterfaceTestCase(BaseFeatureCase):

    @mock.patch('pyhpecw7.comware.HPCOM7')
    @mock.patch.object(Interface, '_get_iface_index')
    @mock.patch.object(Interface, '_is_ethernet_is_routed')
    def setUp(self, mock_is_eth, mock_get_index, mock_device):
        self.device = mock_device

        mock_get_index.return_value = IFACE_INDEX

        mock_is_eth.return_value = True, False
        self.eth_iface = Interface(self.device, ETH_IFACE)

        mock_is_eth.return_value = False, True
        self.lo_iface = Interface(self.device, LOGICAL_IFACE)

    def test_init(self):
        self.assertTrue(self.eth_iface.is_ethernet)
        self.assertFalse(self.eth_iface.is_routed)

        self.assertFalse(self.lo_iface.is_ethernet)
        self.assertTrue(self.lo_iface.is_routed)

        self.assertEqual(self.eth_iface.iface_index, IFACE_INDEX)
        self.assertEqual(self.lo_iface.iface_index, IFACE_INDEX)

        self.assertEqual(self.eth_iface.iface_type, 'FortyGigE')
        self.assertEqual(self.lo_iface.iface_type, 'LoopBack')

    def test_get_index(self):
        expected_get, get_reply = self.xml_get_and_reply('interface_index')
        self.device.get.return_value = get_reply

        expected = '9'
        result = self.eth_iface._get_iface_index()

        self.assertEqual(result, expected)
        self.assert_get_request(expected_get)

    def test_is_eth_is_routed(self):
        expected_get, get_reply = self.xml_get_and_reply('interface_is_eth')
        self.device.get.return_value = get_reply

        expected = True, True
        result = self.eth_iface._is_ethernet_is_routed()

        self.assertEqual(result, expected)
        self.assert_get_request(expected_get)

    def test_get_defaults(self):
        eth_defaults = self.eth_iface.get_default_config()
        lo_defaults = self.lo_iface.get_default_config()

        eth_expected = dict(description=ETH_IFACE + ' Interface', admin='up', speed='auto', duplex='auto', type='bridged')
        lo_expected = dict(description=LOGICAL_IFACE + ' Interface', admin='up', type='routed')

        self.assertEqual(eth_defaults, eth_expected)
        self.assertEqual(lo_defaults, lo_expected)

    def test_param_check(self):
        with self.assertRaises(InterfaceParamsError):
            self.lo_iface.param_check(speed='1000')

        self.eth_iface.iface_exists = False
        with self.assertRaises(InterfaceAbsentError):
            self.eth_iface.param_check(admin='up')

        self.eth_iface.iface_type = None
        with self.assertRaises(InterfaceTypeError):
            self.eth_iface.param_check(admin='up')

    def test_get_config(self):
        expected_get, get_reply = self.xml_get_and_reply('interface')
        self.device.get.return_value = get_reply

        expected = {'admin': 'up', 'duplex': 'auto', 'speed': 'auto', 'description': 'FortyGigE1/0/3 Interface', 'type': 'routed'}

        iface = self.eth_iface.get_config()

        self.assertEqual(iface, expected)
        self.assert_get_request(expected_get)

    def test_logical_iface(self):
        expected = self.read_action_xml('interface_logical')

        self.lo_iface._logical_iface()
        self.assert_action_request(expected)

        self.lo_iface._logical_iface(stage=True)
        self.assert_stage_request(expected, 'action')

    def test_logical_iface_remove(self):
        expected = self.read_action_xml('interface_logical_remove')
        self.lo_iface._logical_iface(remove=True)
        self.assert_action_request(expected)

    def test_build_config_default(self):
        expected = self.read_action_xml('interface_default')

        self.eth_iface._build_config('default', admin='up', duplex='half')
        self.assert_action_request(expected)

        self.eth_iface._build_config('default', stage=True, admin='up', duplex='half')
        self.assert_stage_request(expected, 'action')

    def test_build_config_present(self):
        expected = self.read_config_xml('interface')

        self.eth_iface._build_config('present', admin='up', duplex='half')
        self.assert_config_request(expected)

        self.eth_iface._build_config('present', stage=True, admin='up', duplex='half')
        self.assert_stage_request(expected, 'edit_config')

    def test_build_config_remove(self):
        expected = self.read_action_xml('interface_default')

        self.eth_iface._build_config('absent', admin='up', duplex='half')
        self.assert_action_request(expected)

        self.eth_iface._build_config('absent', stage=True, admin='up', duplex='half')
        self.assert_stage_request(expected, 'action')

    @mock.patch.object(Interface, '_logical_iface')
    def test_remove(self, mock_logical):
        self.lo_iface.remove_logical()
        mock_logical.assert_called_with(remove=True, stage=False)

        self.lo_iface.remove_logical(stage=True)
        mock_logical.assert_called_with(remove=True, stage=True)

    @mock.patch.object(Interface, '_logical_iface')
    def test_create(self, mock_logical):
        self.lo_iface.create_logical()
        mock_logical.assert_called_with(stage=False)

        self.lo_iface.create_logical(stage=True)
        mock_logical.assert_called_with(stage=True)

    @mock.patch.object(Interface, '_build_config')
    def test_build(self, mock_build):
        self.eth_iface.build(admin='up')
        mock_build.assert_called_with(state='present', stage=False, admin='up')

        self.eth_iface.build(admin='up', stage=True)
        mock_build.assert_called_with(state='present', stage=True, admin='up')

    @mock.patch.object(Interface, '_build_config')
    def test_default(self, mock_build):
        self.eth_iface.default()
        mock_build.assert_called_with(state='default', stage=False)

        self.eth_iface.default(stage=True)
        mock_build.assert_called_with(state='default', stage=True)
Beispiel #2
0
def main():
    module = AnsibleModule(argument_spec=dict(
        vrid=dict(required=True, type='str'),
        interface=dict(required=True),
        vip=dict(required=False),
        priority=dict(required=False, type='str'),
        auth_mode=dict(required=False, choices=['simple', 'md5']),
        key_type=dict(required=False, choices=['cipher', 'plain']),
        key=dict(required=False, type='str'),
        preempt=dict(required=False, choices=['yes', 'no']),
        state=dict(choices=['present', 'absent', 'shutdown', 'undoshutdown'],
                   default='present'),
        port=dict(default=830, type='int'),
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True),
    ),
                           supports_check_mode=True)
    if not HAS_PYHP:
        module.fail_json(msg='There was a problem loading from the pyhpecw7 ' +
                         'module.',
                         error=str(ie))

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    hostname = socket.gethostbyname(module.params['hostname'])

    device_args = dict(host=hostname,
                       username=username,
                       password=password,
                       port=port)

    device = HPCOM7(**device_args)

    vrid = module.params['vrid']
    interface = module.params['interface'].lower()
    vip = module.params['vip']
    priority = module.params['priority']
    preempt = module.params['preempt']
    auth_mode = module.params['auth_mode']
    key_type = module.params['key_type']
    key = module.params['key']

    if auth_mode:
        if not key_type or not key:
            module.fail_json(msg='params key_type and key are required')
    if key_type or key:
        if not auth_mode:
            module.fail_json(msg='auth_mode is required when setting auth')

    state = module.params['state']

    changed = False

    args = dict(vrid=vrid,
                priority=priority,
                preempt=preempt,
                vip=vip,
                interface=interface,
                auth_mode=auth_mode,
                key_type=key_type,
                key=key)

    proposed = dict((k, v) for k, v in args.iteritems() if v is not None)

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='error opening device conn')

    try:
        vrrp = VRRP(device, interface, vrid)
        vrrp_interface = Interface(device, interface)
    except PYHPError as e:
        safe_fail(module, device, msg=str(e))

    if not vrrp_interface.iface_exists:
        safe_fail(module, device, msg='interface does not exist.')
    is_eth, is_rtd = vrrp_interface._is_ethernet_is_routed()
    if not is_rtd:
        safe_fail(module,
                  device,
                  msg='interface needs to be a layer 3 interface')

    try:
        existing = vrrp.get_config()
    except PYHPError as e:
        safe_fail(module,
                  device,
                  msg=str(e),
                  descr='could not get existing config')

    if state == 'present':
        delta = dict(
            set(proposed.iteritems()).difference(existing.iteritems()))
        if delta or auth_mode or \
                existing.get('admin') == 'down':
            delta['vrid'] = vrid
            if delta.get('key'):
                delta['auth_mode'] = auth_mode
                delta['key_type'] = key_type
            vrrp.build(stage=True, state=state, **delta)
    elif state == 'absent':
        if existing:
            vrrp.remove(stage=True)
    elif state == 'shutdown':
        if existing.get('admin') == 'Up':
            vrrp.shutdown(stage=True)
    elif state == 'undoshutdown':
        if existing.get('admin') == 'Down':
            vrrp.undoshutdown(stage=True)

    commands = None
    end_state = existing
    response = None

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            device.close()
            safe_exit(module, device, changed=True, commands=commands)
        else:
            try:
                response = device.execute_staged()
                end_state = vrrp.get_config()
            except PYHPError as e:
                safe_fail(module,
                          device,
                          msg=str(e),
                          descr='error during execution')
            changed = True

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['state'] = state
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = end_state
    results['response'] = response

    safe_exit(module, device, **results)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            vrid=dict(required=True, type='str'),
            interface=dict(required=True),
            vip=dict(required=False),
            priority=dict(required=False, type='str'),
            auth_mode=dict(required=False, choices=['simple', 'md5']),
            key_type=dict(required=False, choices=['cipher', 'plain']),
            key=dict(required=False, type='str'),
            preempt=dict(required=False, choices=['yes', 'no']),
            state=dict(choices=['present', 'absent', 'shutdown',
                                'undoshutdown'],
                       default='present'),
            port=dict(default=830, type='int'),
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
        ),
        supports_check_mode=True
    )
    if not HAS_PYHP:
        module.fail_json(msg='There was a problem loading from the pyhpecw7 '
                         + 'module.', error=str(ie))

    username = module.params['username']
    password = module.params['password']
    port = module.params['port']
    hostname = socket.gethostbyname(module.params['hostname'])

    device_args = dict(host=hostname, username=username,
                       password=password, port=port)

    device = HPCOM7(**device_args)

    vrid = module.params['vrid']
    interface = module.params['interface'].lower()
    vip = module.params['vip']
    priority = module.params['priority']
    preempt = module.params['preempt']
    auth_mode = module.params['auth_mode']
    key_type = module.params['key_type']
    key = module.params['key']

    if auth_mode:
        if not key_type or not key:
            module.fail_json(msg='params key_type and key are required')
    if key_type or key:
        if not auth_mode:
            module.fail_json(msg='auth_mode is required when setting auth')

    state = module.params['state']

    changed = False

    args = dict(vrid=vrid, priority=priority, preempt=preempt,
                vip=vip, interface=interface, auth_mode=auth_mode,
                key_type=key_type, key=key)

    proposed = dict((k, v) for k, v in args.iteritems() if v is not None)

    try:
        device.open()
    except ConnectionError as e:
        safe_fail(module, device, msg=str(e),
                  descr='error opening device conn')

    try:
        vrrp = VRRP(device, interface, vrid)
        vrrp_interface = Interface(device, interface)
    except PYHPError as e:
        safe_fail(module, device, msg=str(e))

    if not vrrp_interface.iface_exists:
        safe_fail(module, device, msg='interface does not exist.')
    is_eth, is_rtd = vrrp_interface._is_ethernet_is_routed()
    if not is_rtd:
        safe_fail(module, device,
                  msg='interface needs to be a layer 3 interface')

    try:
        existing = vrrp.get_config()
    except PYHPError as e:
        safe_fail(module, device, msg=str(e),
                  descr='could not get existing config')

    if state == 'present':
        delta = dict(set(proposed.iteritems()).difference(
            existing.iteritems()))
        if delta or auth_mode or \
                existing.get('admin') == 'down':
            delta['vrid'] = vrid
            if delta.get('key'):
                delta['auth_mode'] = auth_mode
                delta['key_type'] = key_type
            vrrp.build(stage=True, state=state, **delta)
    elif state == 'absent':
        if existing:
            vrrp.remove(stage=True)
    elif state == 'shutdown':
        if existing.get('admin') == 'Up':
            vrrp.shutdown(stage=True)
    elif state == 'undoshutdown':
        if existing.get('admin') == 'Down':
            vrrp.undoshutdown(stage=True)

    commands = None
    end_state = existing
    response = None

    if device.staged:
        commands = device.staged_to_string()
        if module.check_mode:
            device.close()
            safe_exit(module, device, changed=True,
                      commands=commands)
        else:
            try:
                response = device.execute_staged()
                end_state = vrrp.get_config()
            except PYHPError as e:
                safe_fail(module, device, msg=str(e),
                          descr='error during execution')
            changed = True

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['state'] = state
    results['commands'] = commands
    results['changed'] = changed
    results['end_state'] = end_state
    results['response'] = response

    safe_exit(module, device, **results)