1# -*- coding: utf-8 -*-
2#
3# Copyright (c) 2017 F5 Networks Inc.
4# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6from __future__ import (absolute_import, division, print_function)
7__metaclass__ = type
8
9import os
10import json
11import pytest
12import sys
13
14if sys.version_info < (2, 7):
15    pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
16
17from ansible.module_utils.basic import AnsibleModule
18
19from ansible_collections.f5networks.f5_modules.plugins.modules.bigip_policy_rule import (
20    ModuleParameters, ApiParameters, ModuleManager, ArgumentSpec
21)
22from ansible_collections.f5networks.f5_modules.tests.unit.compat import unittest
23from ansible_collections.f5networks.f5_modules.tests.unit.compat.mock import Mock, patch
24from ansible_collections.f5networks.f5_modules.tests.unit.modules.utils import set_module_args
25
26
27fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
28fixture_data = {}
29
30
31def load_fixture(name):
32    path = os.path.join(fixture_path, name)
33
34    if path in fixture_data:
35        return fixture_data[path]
36
37    with open(path) as f:
38        data = f.read()
39
40    try:
41        data = json.loads(data)
42    except Exception:
43        pass
44
45    fixture_data[path] = data
46    return data
47
48
49class TestParameters(unittest.TestCase):
50    def test_module_parameters_policy(self):
51        args = dict(
52            policy='Policy - Foo'
53        )
54        p = ModuleParameters(params=args)
55        assert p.policy == 'Policy - Foo'
56
57    def test_module_parameters_actions(self):
58        args = dict(
59            actions=[
60                dict(
61                    type='forward',
62                    pool='pool-svrs'
63                )
64            ]
65        )
66        p = ModuleParameters(params=args)
67        assert len(p.actions) == 1
68
69    def test_module_parameters_conditions(self):
70        args = dict(
71            conditions=[
72                dict(
73                    type='http_uri',
74                    path_begins_with_any=['/ABC']
75                )
76            ]
77        )
78        p = ModuleParameters(params=args)
79        assert len(p.conditions) == 1
80
81    def test_module_parameters_name(self):
82        args = dict(
83            name='rule1'
84        )
85        p = ModuleParameters(params=args)
86        assert p.name == 'rule1'
87
88    def test_api_parameters(self):
89        args = load_fixture('load_ltm_policy_draft_rule_http-uri_forward.json')
90        p = ApiParameters(params=args)
91        assert len(p.actions) == 1
92        assert len(p.conditions) == 1
93
94
95class TestManager(unittest.TestCase):
96    def setUp(self):
97        self.spec = ArgumentSpec()
98        self.p2 = patch('ansible_collections.f5networks.f5_modules.plugins.modules.bigip_policy_rule.tmos_version')
99        self.p3 = patch('ansible_collections.f5networks.f5_modules.plugins.modules.bigip_policy_rule.send_teem')
100        self.m2 = self.p2.start()
101        self.m2.return_value = '14.1.0'
102        self.m3 = self.p3.start()
103        self.m3.return_value = True
104
105    def tearDown(self):
106        self.p2.stop()
107        self.p3.stop()
108
109    def test_create_policy_rule_no_existence(self, *args):
110        set_module_args(dict(
111            name="rule1",
112            state='present',
113            policy='policy1',
114            actions=[
115                dict(
116                    type='forward',
117                    pool='baz'
118                )
119            ],
120            conditions=[
121                dict(
122                    type='http_uri',
123                    path_begins_with_any=['/ABC']
124                )
125            ],
126            provider=dict(
127                server='localhost',
128                password='password',
129                user='admin'
130            )
131        ))
132
133        module = AnsibleModule(
134            argument_spec=self.spec.argument_spec,
135            supports_check_mode=self.spec.supports_check_mode
136        )
137
138        # Override methods to force specific logic in the module to happen
139        mm = ModuleManager(module=module)
140        mm.exists = Mock(return_value=False)
141        mm.publish_on_device = Mock(return_value=True)
142        mm.draft_exists = Mock(return_value=False)
143        mm._create_existing_policy_draft_on_device = Mock(return_value=True)
144        mm.create_on_device = Mock(return_value=True)
145
146        results = mm.exec_module()
147
148        assert results['changed'] is True
149
150    def test_create_policy_rule_idempotent_check(self, *args):
151        set_module_args(dict(
152            name="rule1",
153            state='present',
154            policy='policy1',
155            actions=[
156                dict(
157                    type='forward',
158                    pool='baz'
159                )
160            ],
161            conditions=[
162                dict(
163                    type='http_uri',
164                    path_begins_with_any=['/ABC']
165                )
166            ],
167            provider=dict(
168                server='localhost',
169                password='password',
170                user='admin'
171            )
172        ))
173
174        current = ApiParameters(params=load_fixture('load_ltm_policy_draft_rule_http-uri_forward.json'))
175        module = AnsibleModule(
176            argument_spec=self.spec.argument_spec,
177            supports_check_mode=self.spec.supports_check_mode
178        )
179
180        # Override methods to force specific logic in the module to happen
181        mm = ModuleManager(module=module)
182        mm.exists = Mock(return_value=True)
183        mm.read_current_from_device = Mock(return_value=current)
184        mm.draft_exists = Mock(return_value=False)
185        mm.update_on_device = Mock(return_value=True)
186        mm._create_existing_policy_draft_on_device = Mock(return_value=True)
187        mm.publish_on_device = Mock(return_value=True)
188
189        results = mm.exec_module()
190
191        assert results['changed'] is True
192