def setUp(self): super(TestOnyxLinkaggModule, self).setUp() self.mock_get_config = patch.object( onyx_linkagg.OnyxLinkAggModule, "_get_port_channels") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_linkagg.OnyxLinkAggModule, "_get_os_version") self.get_version = self.mock_get_version.start()
def setUp(self): super(TestIptables, self).setUp() self.mock_get_bin_path = patch.object(basic.AnsibleModule, 'get_bin_path', get_bin_path) self.mock_get_bin_path.start() self.addCleanup(self.mock_get_bin_path.stop ) # ensure that the patching is 'undone' self.mock_get_iptables_version = patch.object(iptables, 'get_iptables_version', get_iptables_version) self.mock_get_iptables_version.start() self.addCleanup(self.mock_get_iptables_version.stop ) # ensure that the patching is 'undone'
def setUp(self): self._ptp_enabled = True self._ntp_enabled = True super(TestOnyxPtpModule, self).setUp() self.mock_get_ptp_config = patch.object(onyx_ptp_global.OnyxPtpGlobalModule, "_show_ptp_config") self.get_ptp_config = self.mock_get_ptp_config.start() self.mock_get_ntp_config = patch.object(onyx_ptp_global.OnyxPtpGlobalModule, "_show_ntp_config") self.get_ntp_config = self.mock_get_ntp_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()
def setUp(self): super(TestOnyxMlagVipModule, self).setUp() self._mlag_enabled = True self.mock_show_mlag = patch.object(onyx_mlag_vip.OnyxMLagVipModule, "_show_mlag") self.show_mlag = self.mock_show_mlag.start() self.mock_show_mlag_vip = patch.object(onyx_mlag_vip.OnyxMLagVipModule, "_show_mlag_vip") self.show_mlag_vip = self.mock_show_mlag_vip.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start()
def setUp(self): super(TestOnyxL3InterfaceModule, self).setUp() self.mock_get_config = patch.object( onyx_l3_interface.OnyxL3InterfaceModule, "_get_interfaces_config") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_l3_interface.OnyxL3InterfaceModule, "_get_os_version") self.get_version = self.mock_get_version.start()
def setUp(self): super(TestOnyxProtocolModule, self).setUp() self.mock_get_config = patch.object(onyx_protocol.OnyxProtocolModule, "_get_protocols") self.get_config = self.mock_get_config.start() self.mock_get_ip_config = patch.object( onyx_protocol.OnyxProtocolModule, "_get_ip_routing") self.get_ip_config = self.mock_get_ip_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start()
def setUp(self): super(TestOnyxVxlanModule, self).setUp() self.mock_get_vxlan_config = patch.object(onyx_vxlan.OnyxVxlanModule, "_show_vxlan_config") self.get_vxlan_config = self.mock_get_vxlan_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start() self.mock_get_nve_detail = patch.object(onyx_vxlan.OnyxVxlanModule, "_show_nve_detail") self.get_nve_detail = self.mock_get_nve_detail.start()
def test_update_lambda_if_code_changed(): set_module_args(base_module_args) (boto3_conn_double, lambda_client_double) = make_mock_connection(code_change_lambda_config) with patch.object(lda, 'boto3_conn', boto3_conn_double): try: lda.main() except SystemExit: pass # guard against calling other than for a lambda connection (e.g. IAM) assert (len(boto3_conn_double.mock_calls) > 0), "boto connections never used" assert (len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly" assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \ "unexpectedly updatede lambda configuration when only code changed" assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \ "lambda function update called multiple times when only one time should be needed" assert(len(lambda_client_double.update_function_code.mock_calls) > 1), \ "failed to update lambda function when code changed" # 3 because after uploading we call into the return from mock to try to find what function version # was returned so the MagicMock actually sees two calls for one update. assert(len(lambda_client_double.update_function_code.mock_calls) < 3), \ "lambda function code update called multiple times when only one time should be needed"
def test_append_rule(self): """Test append a redirection rule""" set_module_args({ 'chain': 'PREROUTING', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'REDIRECT', 'table': 'nat', 'to_destination': '5.5.5.5/32', 'protocol': 'udp', 'destination_port': '22', 'to_ports': '8600' }) commands_results = [(1, '', ''), (0, '', '')] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 2) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'nat', '-C', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'REDIRECT', '--to-destination', '5.5.5.5/32', '--destination-port', '22', '--to-ports', '8600' ]) self.assertEqual(run_command.call_args_list[1][0][0], [ '/sbin/iptables', '-t', 'nat', '-A', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'REDIRECT', '--to-destination', '5.5.5.5/32', '--destination-port', '22', '--to-ports', '8600' ])
def test_policy_table_changed_false(self): """Test flush without parameters and change == false""" set_module_args({ 'policy': 'ACCEPT', 'chain': 'INPUT', '_ansible_check_mode': True, }) commands_results = [ (0, 'Chain INPUT (policy DROP)\n', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) # import pdb # pdb.set_trace() self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-L', 'INPUT', ])
def test_create_flexcache_size_error(self): ''' create flexcache ''' args = { 'volume': 'volume_err', 'size': '50', # 80MB minimum 'size_unit': 'mb', # 80MB minimum 'vserver': 'ansibleSVM', 'aggr_list': 'aggr1', 'origin_volume': 'fc_vol_origin', 'origin_vserver': 'ansibleSVM', } args.update(self.args) set_module_args(args) my_obj = my_module() error = 'Size "50MB" ("52428800B") is too small. Minimum size is "80MB" ("83886080B"). ' if not self.onbox: my_obj.server = MockONTAPConnection(job_error=error) with patch.object(my_module, 'flexcache_create', wraps=my_obj.flexcache_create) as mock_create: with pytest.raises(AnsibleFailJson) as exc: my_obj.apply() print('Create: ' + repr(exc.value)) msg = 'Error when creating flexcache: %s' % error assert exc.value.args[0]['msg'] == msg mock_create.assert_called_with()
def test_delete_flexcache_exists_junctionpath_with_force(self): ''' delete flexcache ''' args = { 'volume': 'volume', 'vserver': 'ansibleSVM', 'junction_path': 'jpath', 'state': 'absent', 'force_offline': 'true', 'force_unmount': 'true' } self.create_flexcache(args['vserver'], args['volume'], args['junction_path']) args.update(self.args) set_module_args(args) my_obj = my_module() if not self.onbox: my_obj.server = MockONTAPConnection('vserver', 'flex') with patch.object(my_module, 'flexcache_delete', wraps=my_obj.flexcache_delete) as mock_delete: with pytest.raises(AnsibleExitJson) as exc: my_obj.apply() print('Delete: ' + repr(exc.value)) assert exc.value.args[0]['changed'] mock_delete.assert_called_with()
def test_jump_tee_gateway(self): """ Using gateway when JUMP is set to TEE """ set_module_args({ 'table': 'mangle', 'chain': 'PREROUTING', 'in_interface': 'eth0', 'protocol': 'udp', 'match': 'state', 'jump': 'TEE', 'ctstate': ['NEW'], 'destination_port': '9521', 'gateway': '192.168.10.1', 'destination': '127.0.0.1' }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'mangle', '-C', 'PREROUTING', '-p', 'udp', '-d', '127.0.0.1', '-m', 'state', '-j', 'TEE', '--gateway', '192.168.10.1', '-i', 'eth0', '--destination-port', '9521', '--state', 'NEW' ])
def test_withwrongargs(self): """ Testing that wrong attribute causing error :return: """ set_module_args({ 'operation': "Upload", 'opsName': 'Uploading_testi', 'MR': "PLMN-PLMN/MRBTS-746", 'abc': 'abc' }) with self.assertRaises(AnsibleFailJson): with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: stdout = 'configuration updated' stderr = '' return_code = 0 mock_run_command.return_value = return_code, stdout, stderr # successful execution with self.assertRaises(AnsibleExitJson) as result: netact_cm_command.main() self.assertTrue(result.exception.args[0] ['changed']) # ensure result is changed self.assertFalse(True) # ensure result is changed
def test_policy_table(self): """Test change policy of a chain""" set_module_args({ 'policy': 'ACCEPT', 'chain': 'INPUT', }) commands_results = [(0, 'Chain INPUT (policy DROP)\n', ''), (0, '', '')] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 2) # import pdb # pdb.set_trace() self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-L', 'INPUT', ]) self.assertEqual(run_command.call_args_list[1][0][0], [ '/sbin/iptables', '-t', 'filter', '-P', 'INPUT', 'ACCEPT', ])
def test_insert_rule_with_wait(self): """Test flush without parameters""" set_module_args({ 'chain': 'OUTPUT', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'ACCEPT', 'action': 'insert', 'wait': '10' }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'OUTPUT', '-w', '10', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'ACCEPT' ])
def test_log_level(self): """ Test various ways of log level flag """ log_levels = [ '0', '1', '2', '3', '4', '5', '6', '7', 'emerg', 'alert', 'crit', 'error', 'warning', 'notice', 'info', 'debug' ] for log_lvl in log_levels: set_module_args({ 'chain': 'INPUT', 'jump': 'LOG', 'log_level': log_lvl, 'source': '1.2.3.4/32', 'log_prefix': '** DROP-this_ip **' }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-s', '1.2.3.4/32', '-j', 'LOG', '--log-prefix', '** DROP-this_ip **', '--log-level', log_lvl ])
def test_update_lambda_if_added_environment_variable(): set_module_args(module_args_with_environment) (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config) with patch.object(lda, 'boto3_conn', boto3_conn_double): try: lda.main() except SystemExit: pass # guard against calling other than for a lambda connection (e.g. IAM) assert (len(boto3_conn_double.mock_calls) > 0), "boto connections never used" assert (len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly" assert(len(lambda_client_double.update_function_configuration.mock_calls) > 0), \ "failed to update lambda function when configuration changed" assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \ "lambda function update called multiple times when only one time should be needed" assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ "updated lambda code when no change should have happened" (update_args, update_kwargs ) = lambda_client_double.update_function_configuration.call_args assert ( len(update_kwargs) > 0 ), "expected update configuration called with keyword args, none found" assert update_kwargs['Environment'][ 'Variables'] == module_args_with_environment['environment_variables']
def test_delete_flexcache_exists_junctionpath_no_force(self): ''' delete flexcache ''' args = { 'volume': 'volume', 'vserver': 'ansibleSVM', 'junction_path': 'jpath', 'state': 'absent', 'force_offline': 'true' } self.create_flexcache(args['vserver'], args['volume'], args['junction_path']) args.update(self.args) set_module_args(args) my_obj = my_module() error = '160:Volume volume on Vserver ansibleSVM must be unmounted before being taken offline or restricted.' if not self.onbox: my_obj.server = MockONTAPConnection('vserver', 'flex', api_error=error) with patch.object(my_module, 'flexcache_delete', wraps=my_obj.flexcache_delete) as mock_delete: with pytest.raises(AnsibleFailJson) as exc: my_obj.apply() print('Delete: ' + repr(exc.value)) msg = 'Error deleting FlexCache : NetApp API failed. Reason - %s' % error assert exc.value.args[0]['msg'] == msg mock_delete.assert_called_with()
def test_ensure_backupPlanName_outputs_correctly(self): """ Testing that command is executed with correct args :return: """ set_module_args({ 'operation': "Provision", 'opsName': 'Provision_test', 'WS': "PLMN-PLMN/MRBTS-746", 'createBackupPlan': "Yes", 'backupPlanName': "backupPlanName" }) with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: stdout = 'configuration updated' stderr = '' return_code = 0 mock_run_command.return_value = return_code, stdout, stderr # successful execution with self.assertRaises(AnsibleExitJson) as result: netact_cm_command.main() print(result.exception.args) self.assertTrue(result.exception.args[0] ['changed']) # ensure result is changed mock_run_command.assert_called_once_with([ '/opt/oss/bin/racclimx.sh', '-op', 'Provision', '-opsName', 'Provision_test', '-WS', 'PLMN-PLMN/MRBTS-746', '-createBackupPlan', 'true', '-backupPlanName', 'backupPlanName' ], check_rc=True)
def test_insert_jump_reject_with_reject(self): """ Using reject_with with a previously defined jump: REJECT results in two Jump statements #18988 """ set_module_args({ 'chain': 'INPUT', 'protocol': 'tcp', 'jump': 'REJECT', 'reject_with': 'tcp-reset', 'ip_version': 'ipv4', }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-p', 'tcp', '-j', 'REJECT', '--reject-with', 'tcp-reset', ])
def test_ensure_command_called(self): """ Testing that command is executed with correct args :return: """ set_module_args({ 'operation': "Upload", 'opsName': 'Uploading_testi', 'DN': "PLMN-PLMN/MRBTS-746", }) with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: stdout = 'configuration updated' stderr = '' return_code = 0 mock_run_command.return_value = return_code, stdout, stderr # successful execution with self.assertRaises(AnsibleExitJson) as result: netact_cm_command.main() print(result.exception.args) self.assertTrue(result.exception.args[0] ['changed']) # ensure result is changed mock_run_command.assert_called_once_with([ '/opt/oss/bin/racclimx.sh', '-op', 'Upload', '-opsName', 'Uploading_testi', '-DN', 'PLMN-PLMN/MRBTS-746' ], check_rc=True)
def test_create_flexcache_multiplier(self): ''' create flexcache with aggregate multiplier''' args = { 'volume': 'volume', 'size': '90', # 80MB minimum 'size_unit': 'mb', # 80MB minimum 'vserver': 'ansibleSVM', 'aggr_list': 'aggr1', 'origin_volume': 'fc_vol_origin', 'origin_vserver': 'ansibleSVM', 'aggr_list_multiplier': '2', } self.delete_flexcache(args['vserver'], args['volume']) args.update(self.args) set_module_args(args) my_obj = my_module() if not self.onbox: my_obj.server = MockONTAPConnection() with patch.object(my_module, 'flexcache_create', wraps=my_obj.flexcache_create) as mock_create: with pytest.raises(AnsibleExitJson) as exc: my_obj.apply() print('Create: ' + repr(exc.value)) assert exc.value.args[0]['changed'] mock_create.assert_called_with()
def test_create_flexcache_time_out(self, mock_sleep): ''' create flexcache ''' args = { 'volume': 'volume_err', 'size': '50', # 80MB minimum 'size_unit': 'mb', # 80MB minimum 'vserver': 'ansibleSVM', 'aggr_list': 'aggr1', 'origin_volume': 'fc_vol_origin', 'origin_vserver': 'ansibleSVM', 'time_out': '2' } args.update(self.args) set_module_args(args) my_obj = my_module() if not self.onbox: my_obj.server = MockONTAPConnection(job_error='time_out') with patch.object(my_module, 'flexcache_create', wraps=my_obj.flexcache_create) as mock_create: with pytest.raises(AnsibleFailJson) as exc: my_obj.apply() print('Create: ' + repr(exc.value)) msg = 'Error when creating flexcache: job completion exceeded expected timer of: %s seconds' \ % args['time_out'] assert exc.value.args[0]['msg'] == msg mock_create.assert_called_with()
def test_successful_message_with_notify(self): """Test failure message""" set_module_args({ 'subscription': 'test', 'token': 'abc', 'room': 'test', 'msg': 'test', 'notify': 'bell' }) with patch.object(campfire, "fetch_url") as fetch_url_mock: fetch_url_mock.return_value = (None, {"status": 200}) with self.assertRaises(AnsibleExitJson): self.module.main() assert fetch_url_mock.call_count == 2 notify_call = fetch_url_mock.mock_calls[0] url = notify_call[1][1] data = notify_call[2]['data'] assert url == 'https://test.campfirenow.com/room/test/speak.xml' assert data == '<message><type>SoundMessage</type><body>bell</body></message>' message_call = fetch_url_mock.mock_calls[1] url = message_call[1][1] data = message_call[2]['data'] assert url == 'https://test.campfirenow.com/room/test/speak.xml' assert data == '<message><body>test</body></message>'
def setUp(self): super(TestOnyxTrafficClassModule, self).setUp() self.mock_get_congestion_control_config = patch.object( onyx_traffic_class.OnyxTrafficClassModule, "_show_interface_congestion_control") self.get_congestion_control_config = self.mock_get_congestion_control_config.start( ) self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start() self.mock_get_dcb_config = patch.object( onyx_traffic_class.OnyxTrafficClassModule, "_show_interface_dcb_ets") self.get_dcb_config = self.mock_get_dcb_config.start()
def test_lookup_single_obj(dummy_credentials): avi_lookup = lookup_loader.get('avi') avi_mock = MagicMock() avi_mock.return_value.get_object_by_name.return_value = data["mock_single_obj"] with patch.object(avi, 'ApiSession', avi_mock): retval = avi_lookup.run([], {}, avi_credentials=dummy_credentials, obj_type="network", obj_name='PG-123') assert retval[0] == data["mock_single_obj"]
def test_lookup_multiple_obj(dummy_credentials): avi_lookup = lookup_loader.get('avi') avi_mock = MagicMock() avi_mock.return_value.get.return_value.json.return_value = data["mock_multiple_obj"] with patch.object(avi, 'ApiSession', avi_mock): retval = avi_lookup.run([], {}, avi_credentials=dummy_credentials, obj_type="network") assert retval == data["mock_multiple_obj"]["results"]
def setUp(self): """Setup.""" super(TestIcinga2Feature, self).setUp() self.module = icinga2_feature self.mock_get_bin_path = patch.object(basic.AnsibleModule, 'get_bin_path', get_bin_path) self.mock_get_bin_path.start() self.addCleanup(self.mock_get_bin_path.stop ) # ensure that the patching is 'undone'
def setUp(self): super(TestOnyxQosModule, self).setUp() self.mock_get_if_qos_config = patch.object( onyx_qos.OnyxQosModule, "_show_interface_qos") self.get_if_qos_config = self.mock_get_if_qos_config.start() self.mock_load_config = patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()