def test_module_command_PostResource_fail_when_get_return_false(self): set_module_args({ 'category': 'Raw', 'command': 'PostResource', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', 'resource_uri': '/redfish/v1/Systems/1/Bios/Actions/Bios.ChangePassword', 'request_body': { 'PasswordName': 'UefiAdminPassword', 'NewPassword': '******' } }) with patch.object(module.XCCRedfishUtils, 'get_request') as mock_get_request: mock_get_request.return_value = {'ret': False, 'msg': '404 error'} with patch.object(module.XCCRedfishUtils, 'post_request') as mock_post_request: mock_post_request.return_value = {'ret': True} with self.assertRaises(AnsibleFailJson) as result: module.main()
def test_module_command_PatchResource_pass(self): set_module_args({ 'category': 'Raw', 'command': 'PatchResource', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', 'resource_uri': '/redfish/v1/testuri', 'request_body': { 'teststr': 'yyyy' } }) with patch.object(module.XCCRedfishUtils, 'get_request') as mock_get_request: mock_get_request.return_value = { 'ret': True, 'data': { 'teststr': 'xxxx', '@odata.etag': '27f6eb13fa1c28a2711' } } with patch.object(module.XCCRedfishUtils, 'patch_request') as mock_patch_request: mock_patch_request.return_value = { 'ret': True, 'data': { 'teststr': 'yyyy', '@odata.etag': '322e0d45d9572723c98' } } with self.assertRaises(AnsibleExitJson) as result: module.main()
def patch_keycloak_api(get_authentication_flow_by_alias=None, copy_auth_flow=None, create_empty_auth_flow=None, get_executions_representation=None, delete_authentication_flow_by_id=None): """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server Patches the `login` and `_post_json` methods Keyword arguments are passed to the mock object that patches `_post_json` No arguments are passed to the mock object that patches `login` because no tests require it Example:: with patch_ipa(return_value={}) as (mock_login, mock_post): ... """ obj = keycloak_authentication.KeycloakAPI with patch.object(obj, 'get_authentication_flow_by_alias', side_effect=get_authentication_flow_by_alias) \ as mock_get_authentication_flow_by_alias: with patch.object(obj, 'copy_auth_flow', side_effect=copy_auth_flow) \ as mock_copy_auth_flow: with patch.object(obj, 'create_empty_auth_flow', side_effect=create_empty_auth_flow) \ as mock_create_empty_auth_flow: with patch.object(obj, 'get_executions_representation', return_value=get_executions_representation) \ as mock_get_executions_representation: with patch.object(obj, 'delete_authentication_flow_by_id', side_effect=delete_authentication_flow_by_id) \ as mock_delete_authentication_flow_by_id: yield mock_get_authentication_flow_by_alias, mock_copy_auth_flow, mock_create_empty_auth_flow, \ mock_get_executions_representation, mock_delete_authentication_flow_by_id
def test_module_command_VirtualMediaEject_pass(self): set_module_args({ 'category': 'Manager', 'command': 'VirtualMediaEject', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', 'timeout': 30, 'virtual_media': { 'image_url': "nfs://10.245.52.18:/home/nfs/bootable-sr635-20210111-autorun.iso", } }) with patch.object( module.XCCRedfishUtils, '_find_managers_resource') as mock__find_managers_resource: mock__find_managers_resource.return_value = { 'ret': True, 'changed': True, 'msg': 'success' } with patch.object( module.XCCRedfishUtils, 'virtual_media_eject') as mock_virtual_media_eject: mock_virtual_media_eject.return_value = { 'ret': True, 'changed': True, 'msg': 'success' } with self.assertRaises(AnsibleExitJson) as result: module.main()
def test_scaleway_remove_pn(capfd): set_module_args({ "state": "absent", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "region": "par2", "name": "new_network_name", "tags": ["newtag"] }) os.environ['SCW_API_TOKEN'] = 'notrealtoken' with patch.object(Scaleway, 'get') as mock_scw_get: mock_scw_get.return_value = response_with_new_network() with patch.object(Scaleway, 'delete') as mock_scw_delete: mock_scw_delete.return_value = response_delete() with pytest.raises(SystemExit) as results: scaleway_private_network.main() mock_scw_delete.assert_any_call( 'private-networks/c123b4cd-ef5g-678h-90i1-jk2345678l90') mock_scw_get.assert_any_call('private-networks', params={ 'name': 'new_network_name', 'order_by': 'name_asc', 'page': 1, 'page_size': 10 }) out, err = capfd.readouterr() del os.environ['SCW_API_TOKEN'] assert not err assert json.loads(out)['changed']
def test_scaleway_create_pn(capfd): set_module_args({ "state": "present", "project": "a123b4cd-ef5g-678h-90i1-jk2345678l90", "region": "par2", "name": "new_network_name", "tags": ["tag1"] }) os.environ['SCW_API_TOKEN'] = 'notrealtoken' with patch.object(Scaleway, 'get') as mock_scw_get: mock_scw_get.return_value = response_with_zero_network() with patch.object(Scaleway, 'post') as mock_scw_post: mock_scw_post.return_value = response_create_new() with pytest.raises(SystemExit) as results: scaleway_private_network.main() mock_scw_post.assert_any_call( path='private-networks/', data={ 'name': 'new_network_name', 'project_id': 'a123b4cd-ef5g-678h-90i1-jk2345678l90', 'tags': ['tag1'] }) mock_scw_get.assert_any_call('private-networks', params={ 'name': 'new_network_name', 'order_by': 'name_asc', 'page': 1, 'page_size': 10 }) out, err = capfd.readouterr() del os.environ['SCW_API_TOKEN']
def test_module_command_PatchResource_fail_when_required_args_missing( self): set_module_args({ 'category': 'Raw', 'command': 'PatchResource', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', }) with patch.object(module.XCCRedfishUtils, 'get_request') as mock_get_request: mock_get_request.return_value = { 'ret': True, 'data': { 'teststr': 'xxxx', '@odata.etag': '27f6eb13fa1c28a2711' } } with patch.object(module.XCCRedfishUtils, 'patch_request') as mock_patch_request: mock_patch_request.return_value = { 'ret': True, 'data': { 'teststr': 'xxxx' } } with self.assertRaises(AnsibleFailJson) as result: module.main()
def patch_keycloak_api(get_realm_role, create_realm_role=None, update_realm_role=None, delete_realm_role=None): """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server Patches the `login` and `_post_json` methods Keyword arguments are passed to the mock object that patches `_post_json` No arguments are passed to the mock object that patches `login` because no tests require it Example:: with patch_ipa(return_value={}) as (mock_login, mock_post): ... """ obj = keycloak_role.KeycloakAPI with patch.object(obj, 'get_realm_role', side_effect=get_realm_role) as mock_get_realm_role: with patch.object( obj, 'create_realm_role', side_effect=create_realm_role) as mock_create_realm_role: with patch.object( obj, 'update_realm_role', side_effect=update_realm_role) as mock_update_realm_role: with patch.object(obj, 'delete_realm_role', side_effect=delete_realm_role ) as mock_delete_realm_role: yield mock_get_realm_role, mock_create_realm_role, mock_update_realm_role, mock_delete_realm_role
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.community.general.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 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.community.general.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 setUp(self): super(TestOnyxInterfaceModule, self).setUp() self.mock_get_config = patch.object( onyx_l2_interface.OnyxL2InterfaceModule, "_get_switchport_config") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_l2_interface.OnyxL2InterfaceModule, "_get_os_version") self.get_version = self.mock_get_version.start()
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.community.general.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(TestOnyxMagpModule, self).setUp() self.mock_get_config = patch.object(onyx_magp.OnyxMagpModule, "_get_magp_config") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object(onyx_magp.OnyxMagpModule, "_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.community.general.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.community.general.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start()
def test_module_command_PostResource_fail_when_requestbody_mismatch_with_data_from_actioninfo_uri( self): set_module_args({ 'category': 'Raw', 'command': 'PostResource', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', 'resource_uri': '/redfish/v1/Systems/1/Bios/Actions/Bios.ChangePassword', 'request_body': { 'PasswordName': 'UefiAdminPassword', 'NewPassword': '******' } }) with patch.object(module.XCCRedfishUtils, 'get_request') as mock_get_request: mock_get_request.return_value = { 'ret': True, 'data': { 'Parameters': [], 'Actions': { '#Bios.ChangePassword': { '@Redfish.ActionInfo': "/redfish/v1/Systems/1/Bios/ChangePasswordActionInfo", 'target': "/redfish/v1/Systems/1/Bios/Actions/Bios.ChangePassword", 'title': "ChangePassword", '*****@*****.**': ["UefiAdminPassword", "UefiPowerOnPassword"] }, '#Bios.ResetBios': { 'title': "ResetBios", 'target': "/redfish/v1/Systems/1/Bios/Actions/Bios.ResetBios" } }, } } with patch.object(module.XCCRedfishUtils, 'post_request') as mock_post_request: mock_post_request.return_value = {'ret': True} with self.assertRaises(AnsibleFailJson) as result: module.main()
def setUp(self): super(TestOnyxOspfModule, self).setUp() self._ospf_exists = True self.mock_get_config = patch.object(onyx_ospf.OnyxOspfModule, "_get_ospf_config") self.get_config = self.mock_get_config.start() self.mock_get_interfaces_config = patch.object( onyx_ospf.OnyxOspfModule, "_get_ospf_interfaces_config") self.get_interfaces_config = self.mock_get_interfaces_config.start() self.mock_load_config = patch( 'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start()
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_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 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.community.general.plugins.module_utils.network.onyx.onyx.load_config' ) self.load_config = self.mock_load_config.start()
def test_upgrade_success(self): """ Upgrade was successful """ rc = 0 stdout = """ SHA256.sig 100% |*************************************| 2141 00:00 Signature Verified INSTALL.amd64 100% |************************************| 43512 00:00 base67.tgz 100% |*************************************| 238 MB 02:16 bsd 100% |*************************************| 18117 KB 00:24 bsd.mp 100% |*************************************| 18195 KB 00:17 bsd.rd 100% |*************************************| 10109 KB 00:14 comp67.tgz 100% |*************************************| 74451 KB 00:53 game67.tgz 100% |*************************************| 2745 KB 00:03 man67.tgz 100% |*************************************| 7464 KB 00:04 xbase67.tgz 100% |*************************************| 22912 KB 00:30 xfont67.tgz 100% |*************************************| 39342 KB 00:28 xserv67.tgz 100% |*************************************| 16767 KB 00:24 xshare67.tgz 100% |*************************************| 4499 KB 00:06 Verifying sets. Fetching updated firmware. Will upgrade on next reboot """ stderr = "" with patch.object(basic.AnsibleModule, "run_command") as run_command: run_command.return_value = (rc, stdout, stderr) with self.assertRaises(AnsibleExitJson) as result: self.module.main() self.assertTrue(result.exception.args[0]['changed'])
def test_ensure_change_event_created_with_full_data(self): set_module_args({ 'integration_key': 'test', 'summary': 'Testing', 'source': 'My Ansible Script', 'user': '******', 'repo': 'github.com/ansible/ansible', 'revision': '8c67432', 'environment': 'production', 'link_url': 'https://pagerduty.com', 'link_text': 'PagerDuty' }) with patch.object(pagerduty_change, 'fetch_url') as fetch_url_mock: fetch_url_mock.return_value = (None, {"status": 202}) with self.assertRaises(AnsibleExitJson): self.module.main() assert fetch_url_mock.call_count == 1 url = fetch_url_mock.call_args[0][1] json_data = fetch_url_mock.call_args[1]['data'] data = json.loads(json_data) assert url == 'https://events.pagerduty.com/v2/change/enqueue' assert data['routing_key'] == 'test' assert data['payload']['summary'] == 'Testing' assert data['payload']['source'] == 'My Ansible Script' assert data['payload']['custom_details']['user'] == 'ansible' assert data['payload']['custom_details'][ 'repo'] == 'github.com/ansible/ansible' assert data['payload']['custom_details']['revision'] == '8c67432' assert data['payload']['custom_details'][ 'environment'] == 'production' assert data['links'][0]['href'] == 'https://pagerduty.com' assert data['links'][0]['text'] == 'PagerDuty'
def test_hana_userstore_query(self): """Check that result is processed with userstore.""" set_module_args({ 'sid': "HDB", 'instance': "01", 'encrypted': False, 'host': "localhost", 'user': "******", 'userstore': True, 'database': "HDB", 'query': "SELECT * FROM users;" }) with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, 'username,name\n testuser,test user \n myuser, my user \n', '' with self.assertRaises(AnsibleExitJson) as result: hana_query.main() self.assertEqual(result.exception.args[0]['query_result'], [[ { 'username': '******', 'name': 'test user' }, { 'username': '******', 'name': 'my user' }, ]]) self.assertEqual(run_command.call_count, 1)
def patch_keycloak_api(get_components=None, get_component=None, create_component=None, update_component=None, delete_component=None): """Mock context manager for patching the methods in KeycloakAPI """ obj = keycloak_user_federation.KeycloakAPI with patch.object(obj, 'get_components', side_effect=get_components) \ as mock_get_components: with patch.object(obj, 'get_component', side_effect=get_component) \ as mock_get_component: with patch.object(obj, 'create_component', side_effect=create_component) \ as mock_create_component: with patch.object(obj, 'update_component', side_effect=update_component) \ as mock_update_component: with patch.object(obj, 'delete_component', side_effect=delete_component) \ as mock_delete_component: yield mock_get_components, mock_get_component, mock_create_component, mock_update_component, mock_delete_component
def test_edit_message(self): set_module_args({ 'token': 'xoxa-123456789abcdef', 'msg': 'test2', 'message_id': '12345' }) with patch.object(slack, "fetch_url") as fetch_url_mock: mock_response = Mock() mock_response.read.return_value = '{"messages":[{"ts":"12345","msg":"test1"}]}' fetch_url_mock.side_effect = [ (mock_response, { "status": 200 }), (mock_response, { "status": 200 }), ] with self.assertRaises(AnsibleExitJson): self.module.main() self.assertTrue(fetch_url_mock.call_count, 2) self.assertEquals(fetch_url_mock.call_args[1]['url'], "https://slack.com/api/chat.update") call_data = json.loads(fetch_url_mock.call_args[1]['data']) self.assertEquals(call_data['ts'], "12345")
def setUp(self): """Setup.""" super(Testhana_query, self).setUp() self.module = hana_query 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 test_module_command_GetCollectionResource_pass_when_get_collection( self): set_module_args({ 'category': 'Raw', 'command': 'GetCollectionResource', 'baseuri': '10.245.39.251', 'username': '******', 'password': '******', 'resource_uri': '/redfish/v1/testuri', }) with patch.object(module.XCCRedfishUtils, 'get_request') as mock_get_request: mock_get_request.return_value = { 'ret': True, 'data': { 'Members': [{ '@odata.id': '/redfish/v1/testuri/1' }], '*****@*****.**': 1 } } with self.assertRaises(AnsibleExitJson) as result: module.main()
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 __getResult(self, cmd_fun): with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: mock_run_command.side_effect = cmd_fun with self.assertRaises(AnsibleExitJson) as result: module.main() return result
def patch_keycloak_api(get_group_by_name=None, get_client_id=None, get_client_role_by_name=None, get_client_rolemapping_by_id=None, get_client_available_rolemappings=None, get_client_composite_rolemappings=None, add_group_rolemapping=None, delete_group_rolemapping=None): """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server Patches the `login` and `_post_json` methods Keyword arguments are passed to the mock object that patches `_post_json` No arguments are passed to the mock object that patches `login` because no tests require it Example:: with patch_ipa(return_value={}) as (mock_login, mock_post): ... """ obj = keycloak_client_rolemapping.KeycloakAPI with patch.object(obj, 'get_group_by_name', side_effect=get_group_by_name) as mock_get_group_by_name: with patch.object(obj, 'get_client_id', side_effect=get_client_id) as mock_get_client_id: with patch.object(obj, 'get_client_role_by_name', side_effect=get_client_role_by_name ) as mock_get_client_role_by_name: with patch.object(obj, 'get_client_rolemapping_by_id', side_effect=get_client_rolemapping_by_id ) as mock_get_client_rolemapping_by_id: with patch.object( obj, 'get_client_available_rolemappings', side_effect=get_client_available_rolemappings ) as mock_get_client_available_rolemappings: with patch.object( obj, 'get_client_composite_rolemappings', side_effect=get_client_composite_rolemappings ) as mock_get_client_composite_rolemappings: with patch.object(obj, 'add_group_rolemapping', side_effect=add_group_rolemapping ) as mock_add_group_rolemapping: with patch.object( obj, 'delete_group_rolemapping', side_effect=delete_group_rolemapping ) as mock_delete_group_rolemapping: yield mock_get_group_by_name, mock_get_client_id, mock_get_client_role_by_name, mock_add_group_rolemapping, \ mock_get_client_rolemapping_by_id, mock_get_client_available_rolemappings, mock_get_client_composite_rolemappings, \ mock_delete_group_rolemapping