1# (c) 2019, NetApp, Inc
2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4''' unit tests ONTAP Ansible module: aws_netapp_cvs_snapshots'''
5
6from __future__ import (absolute_import, division, print_function)
7__metaclass__ = type
8import json
9import pytest
10
11
12from units.compat import unittest
13from units.compat.mock import patch, Mock
14from ansible.module_utils import basic
15from ansible.module_utils._text import to_bytes
16from requests import Response
17from ansible.modules.cloud.amazon.aws_netapp_cvs_snapshots \
18    import AwsCvsNetappSnapshot as snapshot_module
19
20
21def set_module_args(args):
22    """prepare arguments so that they will be picked up during module creation"""
23    args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
24    basic._ANSIBLE_ARGS = to_bytes(args)  # pylint: disable=protected-access
25
26
27class AnsibleExitJson(Exception):
28    """Exception class to be raised by module.exit_json and caught by the test case"""
29    pass
30
31
32class AnsibleFailJson(Exception):
33    """Exception class to be raised by module.fail_json and caught by the test case"""
34    pass
35
36
37def exit_json(*args, **kwargs):  # pylint: disable=unused-argument
38    """function to patch over exit_json; package return data into an exception"""
39    if 'changed' not in kwargs:
40        kwargs['changed'] = False
41    raise AnsibleExitJson(kwargs)
42
43
44def fail_json(*args, **kwargs):  # pylint: disable=unused-argument
45    """function to patch over fail_json; package return data into an exception"""
46    kwargs['failed'] = True
47    raise AnsibleFailJson(kwargs)
48
49
50class TestMyModule(unittest.TestCase):
51    ''' a group of related Unit Tests '''
52
53    def setUp(self):
54        self.mock_module_helper = patch.multiple(basic.AnsibleModule,
55                                                 exit_json=exit_json,
56                                                 fail_json=fail_json)
57        self.mock_module_helper.start()
58        self.addCleanup(self.mock_module_helper.stop)
59
60    def set_default_args_fail_check(self):
61        return dict({
62            'name': 'TestFilesystem',
63            'fileSystemId': 'standard',
64            'from_name': 'from_TestFilesystem',
65            'region': 'us-east-1',
66            'api_url': 'hostname.com',
67            'api_key': 'myapikey',
68            'secret_key': 'mysecretkey'
69        })
70
71    def set_default_args_pass_check(self):
72        return dict({
73            'state': 'present',
74            'name': 'testSnapshot',
75            'fileSystemId': 'standard',
76            'from_name': 'from_TestFilesystem',
77            'region': 'us-east-1',
78            'api_url': 'hostname.com',
79            'api_key': 'myapikey',
80            'secret_key': 'mysecretkey'
81        })
82
83    def set_args_create_aws_netapp_cvs_snapshots(self):
84        return dict({
85            'state': 'present',
86            'name': 'testSnapshot',
87            'fileSystemId': '123-4213-432-432',
88            'region': 'us-east-1',
89            'api_url': 'hostname.com',
90            'api_key': 'myapikey',
91            'secret_key': 'mysecretkey'
92        })
93
94    def set_args_delete_aws_netapp_cvs_snapshots(self):
95        return dict({
96            'state': 'absent',
97            'name': 'testSnapshot',
98            'region': 'us-east-1',
99            'api_url': 'hostname.com',
100            'api_key': 'myapikey',
101            'secret_key': 'mysecretkey'
102        })
103
104    def test_module_fail_when_required_args_missing(self):
105        ''' required arguments are reported as errors '''
106        with pytest.raises(AnsibleFailJson) as exc:
107            set_module_args(self.set_default_args_fail_check())
108            snapshot_module()
109        print('Info: test_module_fail_when_required_args_missing: %s' % exc.value.args[0]['msg'])
110
111    def test_module_fail_when_required_args_present(self):
112        ''' required arguments are reported as errors '''
113        with pytest.raises(AnsibleExitJson) as exc:
114            set_module_args(self.set_default_args_pass_check())
115            snapshot_module()
116            exit_json(changed=True, msg="Induced arguments check")
117        print('Info: test_module_fail_when_required_args_present: %s' % exc.value.args[0]['msg'])
118        assert exc.value.args[0]['changed']
119
120    @patch('ansible.modules.cloud.amazon.aws_netapp_cvs_snapshots.AwsCvsNetappSnapshot.getSnapshotId')
121    @patch('ansible.modules.cloud.amazon.aws_netapp_cvs_snapshots.AwsCvsNetappSnapshot.getfilesystemId')
122    @patch('ansible.module_utils.netapp.AwsCvsRestAPI.post')
123    def test_create_aws_netapp_cvs_snapshots_pass(self, get_post_api, getfilesystemId, getSnapshotId):
124        set_module_args(self.set_args_create_aws_netapp_cvs_snapshots())
125        my_obj = snapshot_module()
126        getfilesystemId.return_value = 'fiesystemName'
127        getSnapshotId.return_value = None
128        get_post_api.return_value = None, None
129        with pytest.raises(AnsibleExitJson) as exc:
130            my_obj.apply()
131        print('Info: test_create_aws_netapp_cvs_snapshots_pass: %s' % repr(exc.value.args[0]))
132        assert exc.value.args[0]['changed']
133
134    @patch('ansible.modules.cloud.amazon.aws_netapp_cvs_snapshots.AwsCvsNetappSnapshot.getSnapshotId')
135    @patch('ansible.module_utils.netapp.AwsCvsRestAPI.delete')
136    def test_delete_aws_netapp_cvs_snapshots_pass(self, get_post_api, getSnapshotId):
137        set_module_args(self.set_args_delete_aws_netapp_cvs_snapshots())
138        my_obj = snapshot_module()
139        getSnapshotId.return_value = "1f63b3d0-4fd4-b4fe-1ed6-c62f5f20d975"
140        get_post_api.return_value = None, None
141        with pytest.raises(AnsibleExitJson) as exc:
142            my_obj.apply()
143        print('Info: test_create_aws_netapp_cvs_snapshots_pass: %s' % repr(exc.value.args[0]))
144        assert exc.value.args[0]['changed']
145