mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-08-14 10:01:43 -07:00
Move modules and module_utils unit tests to correct place (#81)
* Move modules and module_utils unit tests to correct place. * Update ignore.txt * Fix imports. * Fix typos. * Fix more typos.
This commit is contained in:
parent
ab3c2120fb
commit
be191cce6c
1170 changed files with 732 additions and 751 deletions
0
tests/unit/plugins/modules/monitoring/__init__.py
Normal file
0
tests/unit/plugins/modules/monitoring/__init__.py
Normal file
|
@ -0,0 +1,147 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from urllib3.response import HTTPResponse
|
||||
|
||||
from ansible_collections.community.general.tests.unit.compat.mock import patch
|
||||
from ansible.module_utils._text import to_bytes
|
||||
from ansible_collections.community.general.plugins.modules.monitoring import circonus_annotation
|
||||
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
|
||||
|
||||
|
||||
class TestCirconusAnnotation(ModuleTestCase):
|
||||
|
||||
def setUp(self):
|
||||
super(TestCirconusAnnotation, self).setUp()
|
||||
self.module = circonus_annotation
|
||||
|
||||
def tearDown(self):
|
||||
super(TestCirconusAnnotation, self).tearDown()
|
||||
|
||||
def test_without_required_parameters(self):
|
||||
"""Failure must occurs when all parameters are missing"""
|
||||
with self.assertRaises(AnsibleFailJson):
|
||||
set_module_args({})
|
||||
self.module.main()
|
||||
|
||||
def test_add_annotation(self):
|
||||
"""Check that result is changed"""
|
||||
set_module_args({
|
||||
'category': 'test category',
|
||||
'description': 'test description',
|
||||
'title': 'test title',
|
||||
'api_key': str(uuid.uuid4()),
|
||||
})
|
||||
|
||||
cid = '/annotation/100000'
|
||||
|
||||
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
|
||||
data = {
|
||||
'_cid': cid,
|
||||
'_created': 1502146995,
|
||||
'_last_modified': 1502146995,
|
||||
'_last_modified_by': '/user/1000',
|
||||
'category': 'test category',
|
||||
'description': 'test description',
|
||||
'rel_metrics': [],
|
||||
'start': 1502145480,
|
||||
'stop': None,
|
||||
'title': 'test title',
|
||||
}
|
||||
raw = to_bytes(json.dumps(data))
|
||||
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
|
||||
resp.status = 200
|
||||
resp.reason = 'OK'
|
||||
resp.headers = {'X-Circonus-API-Version': '2.00'}
|
||||
return self.build_response(request, resp)
|
||||
|
||||
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
self.module.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
self.assertEqual(result.exception.args[0]['annotation']['_cid'], cid)
|
||||
self.assertEqual(send.call_count, 1)
|
||||
|
||||
def test_add_annotation_unicode(self):
|
||||
"""Check that result is changed.
|
||||
Note: it seems there is a bug which prevent to create an annotation
|
||||
with a non-ASCII category if this category already exists, in such
|
||||
case an Internal Server Error (500) occurs."""
|
||||
set_module_args({
|
||||
'category': 'new catégorÿ',
|
||||
'description': 'test description',
|
||||
'title': 'test title',
|
||||
'api_key': str(uuid.uuid4()),
|
||||
})
|
||||
|
||||
cid = '/annotation/100000'
|
||||
|
||||
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
|
||||
data = {
|
||||
'_cid': '/annotation/100000',
|
||||
'_created': 1502236928,
|
||||
'_last_modified': 1502236928,
|
||||
'_last_modified_by': '/user/1000',
|
||||
# use res['annotation']['category'].encode('latin1').decode('utf8')
|
||||
'category': u'new cat\xc3\xa9gor\xc3\xbf',
|
||||
'description': 'test description',
|
||||
'rel_metrics': [],
|
||||
'start': 1502236927,
|
||||
'stop': 1502236927,
|
||||
'title': 'test title',
|
||||
}
|
||||
|
||||
raw = to_bytes(json.dumps(data), encoding='latin1')
|
||||
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
|
||||
resp.status = 200
|
||||
resp.reason = 'OK'
|
||||
resp.headers = {'X-Circonus-API-Version': '2.00'}
|
||||
return self.build_response(request, resp)
|
||||
|
||||
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
self.module.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
self.assertEqual(result.exception.args[0]['annotation']['_cid'], cid)
|
||||
self.assertEqual(send.call_count, 1)
|
||||
|
||||
def test_auth_failure(self):
|
||||
"""Check that an error is raised when authentication failed"""
|
||||
set_module_args({
|
||||
'category': 'test category',
|
||||
'description': 'test description',
|
||||
'title': 'test title',
|
||||
'api_key': str(uuid.uuid4()),
|
||||
})
|
||||
|
||||
cid = '/annotation/100000'
|
||||
|
||||
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
|
||||
data = {
|
||||
'_cid': cid,
|
||||
'_created': 1502146995,
|
||||
'_last_modified': 1502146995,
|
||||
'_last_modified_by': '/user/1000',
|
||||
'category': 'test category',
|
||||
'description': 'test description',
|
||||
'rel_metrics': [],
|
||||
'start': 1502145480,
|
||||
'stop': None,
|
||||
'title': 'test title',
|
||||
}
|
||||
raw = to_bytes(json.dumps(data))
|
||||
resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
|
||||
resp.status = 403
|
||||
resp.reason = 'Forbidden'
|
||||
resp.headers = {'X-Circonus-API-Version': '2.00'}
|
||||
return self.build_response(request, resp)
|
||||
|
||||
with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
|
||||
with self.assertRaises(AnsibleFailJson) as result:
|
||||
self.module.main()
|
||||
self.assertTrue(result.exception.args[0]['failed'])
|
||||
self.assertTrue(re.match(r'\b403\b', result.exception.args[0]['reason']))
|
||||
self.assertEqual(send.call_count, 1)
|
|
@ -0,0 +1,96 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2018, Ansible Project
|
||||
# Copyright (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
|
||||
#
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from ansible_collections.community.general.plugins.modules.monitoring import icinga2_feature
|
||||
from ansible_collections.community.general.tests.unit.plugins.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
|
||||
from ansible_collections.community.general.tests.unit.compat.mock import patch
|
||||
from ansible.module_utils import basic
|
||||
|
||||
|
||||
def get_bin_path(*args, **kwargs):
|
||||
"""Function to return path of icinga2 binary."""
|
||||
return "/bin/icinga2"
|
||||
|
||||
|
||||
class TestIcinga2Feature(ModuleTestCase):
|
||||
"""Main class for testing icinga2_feature module."""
|
||||
|
||||
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 tearDown(self):
|
||||
"""Teardown."""
|
||||
super(TestIcinga2Feature, self).tearDown()
|
||||
|
||||
def test_without_required_parameters(self):
|
||||
"""Failure must occurs when all parameters are missing."""
|
||||
with self.assertRaises(AnsibleFailJson):
|
||||
set_module_args({})
|
||||
self.module.main()
|
||||
|
||||
def test_enable_feature(self):
|
||||
"""Check that result is changed."""
|
||||
set_module_args({
|
||||
'name': 'api',
|
||||
})
|
||||
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
|
||||
run_command.return_value = 0, '', '' # successful execution, no output
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
icinga2_feature.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
|
||||
self.assertEqual(run_command.call_count, 2)
|
||||
self.assertEqual(run_command.call_args[0][0][-1], 'api')
|
||||
|
||||
def test_enable_feature_with_check_mode(self):
|
||||
"""Check that result is changed in check mode."""
|
||||
set_module_args({
|
||||
'name': 'api',
|
||||
'_ansible_check_mode': True,
|
||||
})
|
||||
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
|
||||
run_command.return_value = 0, '', '' # successful execution, no output
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
icinga2_feature.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
|
||||
self.assertEqual(run_command.call_count, 1)
|
||||
|
||||
def test_disable_feature(self):
|
||||
"""Check that result is changed."""
|
||||
set_module_args({
|
||||
'name': 'api',
|
||||
'state': 'absent'
|
||||
})
|
||||
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
|
||||
run_command.return_value = 0, '', '' # successful execution, no output
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
icinga2_feature.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
|
||||
self.assertEqual(run_command.call_count, 2)
|
||||
self.assertEqual(run_command.call_args[0][0][-1], 'api')
|
||||
|
||||
def test_disable_feature_with_check_mode(self):
|
||||
"""Check that result is changed in check mode."""
|
||||
set_module_args({
|
||||
'name': 'api',
|
||||
'state': 'absent',
|
||||
'_ansible_check_mode': True,
|
||||
})
|
||||
with patch.object(basic.AnsibleModule, 'run_command') as run_command:
|
||||
run_command.return_value = 0, '', '' # successful execution, no output
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
icinga2_feature.main()
|
||||
self.assertTrue(result.exception.args[0]['changed'])
|
||||
|
||||
self.assertEqual(run_command.call_count, 1)
|
123
tests/unit/plugins/modules/monitoring/test_pagerduty.py
Normal file
123
tests/unit/plugins/modules/monitoring/test_pagerduty.py
Normal file
|
@ -0,0 +1,123 @@
|
|||
from ansible_collections.community.general.tests.unit.compat import unittest
|
||||
from ansible_collections.community.general.plugins.modules.monitoring import pagerduty
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class PagerDutyTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.pd = pagerduty.PagerDutyRequest(module=pagerduty, name='name', user='user', token='token')
|
||||
|
||||
def _assert_ongoing_maintenance_windows(self, module, url, headers):
|
||||
self.assertEqual('https://api.pagerduty.com/maintenance_windows?filter=ongoing', url)
|
||||
return object(), {'status': 200}
|
||||
|
||||
def _assert_ongoing_window_with_v1_compatible_header(self, module, url, headers, data=None, method=None):
|
||||
self.assertDictContainsSubset(
|
||||
{'Accept': 'application/vnd.pagerduty+json;version=2'},
|
||||
headers,
|
||||
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
|
||||
)
|
||||
return object(), {'status': 200}
|
||||
|
||||
def _assert_create_a_maintenance_window_url(self, module, url, headers, data=None, method=None):
|
||||
self.assertEqual('https://api.pagerduty.com/maintenance_windows', url)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_a_maintenance_window_http_method(self, module, url, headers, data=None, method=None):
|
||||
self.assertEqual('POST', method)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_a_maintenance_window_from_header(self, module, url, headers, data=None, method=None):
|
||||
self.assertDictContainsSubset(
|
||||
{'From': 'requester_id'},
|
||||
headers,
|
||||
'From:requester_id HTTP header not found'
|
||||
)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_window_with_v1_compatible_header(self, module, url, headers, data=None, method=None):
|
||||
self.assertDictContainsSubset(
|
||||
{'Accept': 'application/vnd.pagerduty+json;version=2'},
|
||||
headers,
|
||||
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
|
||||
)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_window_payload(self, module, url, headers, data=None, method=None):
|
||||
payload = json.loads(data)
|
||||
window_data = payload['maintenance_window']
|
||||
self.assertTrue('start_time' in window_data, '"start_time" is requiered attribute')
|
||||
self.assertTrue('end_time' in window_data, '"end_time" is requiered attribute')
|
||||
self.assertTrue('services' in window_data, '"services" is requiered attribute')
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_window_single_service(self, module, url, headers, data=None, method=None):
|
||||
payload = json.loads(data)
|
||||
window_data = payload['maintenance_window']
|
||||
services = window_data['services']
|
||||
self.assertEqual(
|
||||
[{'id': 'service_id', 'type': 'service_reference'}],
|
||||
services
|
||||
)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_create_window_multiple_service(self, module, url, headers, data=None, method=None):
|
||||
payload = json.loads(data)
|
||||
window_data = payload['maintenance_window']
|
||||
services = window_data['services']
|
||||
print(services)
|
||||
self.assertEqual(
|
||||
[
|
||||
{'id': 'service_id_1', 'type': 'service_reference'},
|
||||
{'id': 'service_id_2', 'type': 'service_reference'},
|
||||
{'id': 'service_id_3', 'type': 'service_reference'},
|
||||
],
|
||||
services
|
||||
)
|
||||
return object(), {'status': 201}
|
||||
|
||||
def _assert_absent_maintenance_window_url(self, module, url, headers, method=None):
|
||||
self.assertEqual('https://api.pagerduty.com/maintenance_windows/window_id', url)
|
||||
return object(), {'status': 204}
|
||||
|
||||
def _assert_absent_window_with_v1_compatible_header(self, module, url, headers, method=None):
|
||||
self.assertDictContainsSubset(
|
||||
{'Accept': 'application/vnd.pagerduty+json;version=2'},
|
||||
headers,
|
||||
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
|
||||
)
|
||||
return object(), {'status': 204}
|
||||
|
||||
def test_ongoing_maintenance_windos_url(self):
|
||||
self.pd.ongoing(http_call=self._assert_ongoing_maintenance_windows)
|
||||
|
||||
def test_ongoing_maintenance_windos_compatibility_header(self):
|
||||
self.pd.ongoing(http_call=self._assert_ongoing_window_with_v1_compatible_header)
|
||||
|
||||
def test_create_maintenance_window_url(self):
|
||||
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_url)
|
||||
|
||||
def test_create_maintenance_window_http_method(self):
|
||||
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_http_method)
|
||||
|
||||
def test_create_maintenance_from_header(self):
|
||||
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_a_maintenance_window_from_header)
|
||||
|
||||
def test_create_maintenance_compatibility_header(self):
|
||||
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_window_with_v1_compatible_header)
|
||||
|
||||
def test_create_maintenance_request_payload(self):
|
||||
self.pd.create('requester_id', 'service', 1, 0, 'desc', http_call=self._assert_create_window_payload)
|
||||
|
||||
def test_create_maintenance_for_single_service(self):
|
||||
self.pd.create('requester_id', 'service_id', 1, 0, 'desc', http_call=self._assert_create_window_single_service)
|
||||
|
||||
def test_create_maintenance_for_multiple_services(self):
|
||||
self.pd.create('requester_id', ['service_id_1', 'service_id_2', 'service_id_3'], 1, 0, 'desc', http_call=self._assert_create_window_multiple_service)
|
||||
|
||||
def test_absent_maintenance_window_url(self):
|
||||
self.pd.absent('window_id', http_call=self._assert_absent_maintenance_window_url)
|
||||
|
||||
def test_absent_maintenance_compatibility_header(self):
|
||||
self.pd.absent('window_id', http_call=self._assert_absent_window_with_v1_compatible_header)
|
|
@ -0,0 +1,39 @@
|
|||
from ansible_collections.community.general.tests.unit.compat import unittest
|
||||
from ansible_collections.community.general.plugins.modules.monitoring import pagerduty_alert
|
||||
|
||||
|
||||
class PagerDutyAlertsTest(unittest.TestCase):
|
||||
def _assert_incident_api(self, module, url, method, headers):
|
||||
self.assertTrue('https://api.pagerduty.com/incidents' in url, 'url must contain REST API v2 network path')
|
||||
self.assertTrue('service_ids%5B%5D=service_id' in url, 'url must contain service id to filter incidents')
|
||||
self.assertTrue('sort_by=incident_number%3Adesc' in url, 'url should contain sorting parameter')
|
||||
self.assertTrue('time_zone=UTC' in url, 'url should contain time zone parameter')
|
||||
return Response(), {'status': 200}
|
||||
|
||||
def _assert_compatibility_header(self, module, url, method, headers):
|
||||
self.assertDictContainsSubset(
|
||||
{'Accept': 'application/vnd.pagerduty+json;version=2'},
|
||||
headers,
|
||||
'Accept:application/vnd.pagerduty+json;version=2 HTTP header not found'
|
||||
)
|
||||
return Response(), {'status': 200}
|
||||
|
||||
def _assert_incident_key(self, module, url, method, headers):
|
||||
self.assertTrue('incident_key=incident_key_value' in url, 'url must contain incident key')
|
||||
return Response(), {'status': 200}
|
||||
|
||||
def test_incident_url(self):
|
||||
pagerduty_alert.check(None, 'name', 'state', 'service_id', 'integration_key', 'api_key', http_call=self._assert_incident_api)
|
||||
|
||||
def test_compatibility_header(self):
|
||||
pagerduty_alert.check(None, 'name', 'state', 'service_id', 'integration_key', 'api_key', http_call=self._assert_compatibility_header)
|
||||
|
||||
def test_incident_key_in_url_when_it_is_given(self):
|
||||
pagerduty_alert.check(
|
||||
None, 'name', 'state', 'service_id', 'integration_key', 'api_key', incident_key='incident_key_value', http_call=self._assert_incident_key
|
||||
)
|
||||
|
||||
|
||||
class Response(object):
|
||||
def read(self):
|
||||
return '{"incidents":[{"id": "incident_id", "status": "triggered"}]}'
|
Loading…
Add table
Add a link
Reference in a new issue