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