def test_get_configuration_pass(self): """Validate get configuration does not throw exception when normal request is returned.""" initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90 } expected = { "auditLogMaxRecords": 1000, "auditLogLevel": "writeOnly", "auditLogFullPolicy": "overWrite", "auditLogWarningThresholdPct": 90 } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with mock.patch(self.REQ_FUNC, return_value=(200, expected)): body = audit_log.get_configuration() self.assertTrue(body == expected)
def test_update_configuration_delete_skip_fail(self): """Verify 422 and no force results in AnsibleJsonFail exception.""" body = { "auditLogMaxRecords": 1000, "auditLogLevel": "writeOnly", "auditLogFullPolicy": "overWrite", "auditLogWarningThresholdPct": 90 } initial = { "max_records": 2000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90, "force": False } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with self.assertRaisesRegexp( AnsibleFailJson, r"Failed to update audit-log configuration!"): with mock.patch(self.REQ_FUNC, side_effect=[(200, body), Exception(422, {"errorMessage": "error"}), (200, None), (200, None)]): audit_log.update_configuration()
def test_update_configuration_delete_pass(self): """Verify 422 and force successfully returns True.""" body = { "auditLogMaxRecords": 1000, "auditLogLevel": "writeOnly", "auditLogFullPolicy": "overWrite", "auditLogWarningThresholdPct": 90 } initial = { "max_records": 2000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90, "force": True } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with mock.patch(self.REQ_FUNC, side_effect=[(200, body), (422, { u"invalidFieldsIfKnown": None, u"errorMessage": u"Configuration change...", u"localizedMessage": u"Configuration change...", u"retcode": u"auditLogImmediateFullCondition", u"codeType": u"devicemgrerror" }), (200, None), (200, None)]): self.assertTrue(audit_log.update_configuration())
def test_clear_single_configuration(self): self._set_args() # No changes are required if the domains are empty config = 'abc' ldap = self._make_ldap_instance() with mock.patch.object(ldap, 'get_configuration', return_value=config): with mock.patch(self.REQ_FUNC, return_value=(204, None)) as req: msg, result = ldap.clear_single_configuration() self.assertTrue(result) # Valid check_mode makes no changes req.reset_mock() ldap.check_mode = True msg, result = ldap.clear_single_configuration() self.assertTrue(result) self.assertFalse(req.called) # When domains exist, we need to clear ldap = self._make_ldap_instance() with mock.patch.object(ldap, 'get_configuration', return_value=None): with mock.patch(self.REQ_FUNC, return_value=(204, None)) as req: msg, result = ldap.clear_single_configuration() self.assertFalse(result) self.assertFalse(req.called)
def test_get_configuration_failure(self): self._set_args() with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, side_effect=Exception): ldap = self._make_ldap_instance() ldap.get_configuration('') # We expect this for any code not in [200, 404] with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, return_value=(401, '')): ldap = self._make_ldap_instance() result = ldap.get_configuration('') self.assertIsNone(result)
def test_get_configuration(self): self._set_args() resp = dict(result=None) with mock.patch(self.REQ_FUNC, return_value=(200, resp)): ldap = self._make_ldap_instance() result = ldap.get_configuration('') self.assertEqual(resp, result) with mock.patch(self.REQ_FUNC, return_value=(404, resp)): ldap = self._make_ldap_instance() result = ldap.get_configuration('') self.assertIsNone(result)
def test_get_name_fail(self): """Ensure we can successfully set the name""" self._set_args() expected = dict(name='y', status='offline') namer = GlobalSettings() with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, side_effect=Exception()) as req: name = namer.get_name() with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: update = namer.update_name()
def test_test_configuration_fail(self): """Validate test_configuration fails when request exception is thrown.""" initial = {"state": "present", "ssid": "1", "address": "192.168.1.1", "port": "514", "protocol": "udp", "components": ["auditLog"]} self._set_args(initial) syslog = Syslog() with self.assertRaisesRegexp(AnsibleFailJson, r"We failed to send test message!"): with mock.patch(self.REQ_FUNC, side_effect=Exception()): with mock.patch("time.sleep", return_value=None): # mocking sleep is not working syslog.test_configuration(self.REQUIRED_PARAMS)
def test_update_configuration_asup_disable(self): """Validate retrieving the ASUP configuration""" self._set_args(dict(asup='disabled')) expected = dict() initial = dict(asupCapable=True, asupEnabled=True, onDemandEnabled=False, remoteDiagsEnabled=False, schedule=dict(daysOfWeek=[], dailyMinTime=0, weeklyMinTime=0, dailyMaxTime=24, weeklyMaxTime=24)) asup = Asup() with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: with mock.patch.object(asup, 'get_configuration', return_value=initial): updated = asup.update_configuration() self.assertTrue(updated) self.assertTrue(req.called) # Ensure it was called with the right arguments called_with = req.call_args body = json.loads(called_with[1]['data']) self.assertFalse(body['asupEnabled'])
def test_update(self): """Validate updating ASUP with valid schedule passes""" initial = dict(asupCapable=True, onDemandCapable=True, asupEnabled=True, onDemandEnabled=False, remoteDiagsEnabled=False, schedule=dict(daysOfWeek=[], dailyMinTime=0, weeklyMinTime=0, dailyMaxTime=24, weeklyMaxTime=24)) self._set_args( dict(state="enabled", active=True, days=["sunday", "monday", "tuesday"], start=10, end=20)) asup = Asup() with self.assertRaisesRegexp(AnsibleExitJson, r"ASUP settings have been updated"): with mock.patch(self.REQ_FUNC, return_value=(200, dict(asupCapable=True))): with mock.patch.object(asup, "get_configuration", return_value=initial): asup.update()
def test_is_embedded(self): """Ensure we can properly detect the type of Web Services instance we're utilizing.""" self._set_args() result = dict(runningAsProxy=False) with mock.patch(self.REQ_FUNC, return_value=(200, result)): ldap = Ldap() embedded = ldap.is_embedded() self.assertTrue(embedded) result = dict(runningAsProxy=True) with mock.patch(self.REQ_FUNC, return_value=(200, result)): ldap = Ldap() embedded = ldap.is_embedded() self.assertFalse(embedded)
def test_send_test_email(self): """Ensure we send a test email if test=True""" self._set_args(test=True) alerts = Alerts() with mock.patch(self.REQ_FUNC, return_value=(200, dict(response='emailSentOK'))) as req: alerts.send_test_email() self.assertTrue(req.called)
def test_get_full_configuration_failure(self): self._set_args() resp = dict(result=None) with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, side_effect=Exception): ldap = self._make_ldap_instance() ldap.get_full_configuration()
def test_is_embedded_fail(self): """Ensure we fail gracefully when fetching the About data.""" self._set_args() with self.assertRaises(AnsibleFailJson): with mock.patch(self.REQ_FUNC, side_effect=Exception): ldap = Ldap() ldap.is_embedded()
def test_send_test_email_check(self): """Ensure we handle check_mode correctly""" self._set_args(test=True) alerts = Alerts() alerts.check_mode = True with mock.patch(self.REQ_FUNC) as req: with mock.patch.object(alerts, 'update_configuration', return_value=True): alerts.send_test_email() self.assertFalse(req.called)
def test_send_test_email_fail_connection(self): """Ensure we fail cleanly if we hit a connection failure""" self._set_args(test=True) alerts = Alerts() with self.assertRaisesRegexp(AnsibleFailJson, r"failed to send"): with mock.patch(self.REQ_FUNC, side_effect=Exception) as req: alerts.send_test_email() self.assertTrue(req.called)
def test_get_config_on_demand_capable_false(self): """Ensure we fail correctly if ASUP is not available on this platform""" self._set_args() expected = dict(asupCapable=True, onDemandCapable=False) asup = Asup() # Expecting an update with self.assertRaisesRegexp(AnsibleFailJson, r"not supported"): with mock.patch(self.REQ_FUNC, return_value=(200, expected)): asup.get_configuration()
def test_get_config(self): """Validate retrieving the ASUP configuration""" self._set_args() expected = dict(asupCapable=True, onDemandCapable=True) asup = Asup() with mock.patch(self.REQ_FUNC, return_value=(200, expected)): config = asup.get_configuration() self.assertEqual(config, expected)
def test_get_name(self): """Ensure we can successfully set the name""" self._set_args() expected = dict(name='y', status='online') namer = GlobalSettings() with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: name = namer.get_name() self.assertEqual(name, expected['name'])
def setUp(self): self.mock_module = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) self.mock_module.start() self.mock_sleep = patch('time.sleep') self.mock_sleep.start() set_module_args({}) self.addCleanup(self.mock_module.stop) self.addCleanup(self.mock_sleep.stop)
def test_send_test_email_fail(self): """Ensure we fail if the test returned a failure status""" self._set_args(test=True) alerts = Alerts() ret_msg = 'fail' with self.assertRaisesRegexp(AnsibleFailJson, ret_msg): with mock.patch(self.REQ_FUNC, return_value=(200, dict(response=ret_msg))) as req: alerts.send_test_email() self.assertTrue(req.called)
def test_delete_log_messages_fail(self): """Verify AnsibleJsonFail exception is thrown.""" initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90 } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with self.assertRaisesRegexp(AnsibleFailJson, r"Failed to delete audit-log messages!"): with mock.patch(self.REQ_FUNC, return_value=Exception()): audit_log.delete_log_messages()
def test_get_configuration(self): """Validate retrieving the current configuration""" self._set_args(state='enabled', server='localhost', sender='[email protected]', recipients=['[email protected]']) expected = 'result' alerts = Alerts() # Expecting an update with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: actual = alerts.get_configuration() self.assertEqual(expected, actual) self.assertEqual(req.call_count, 1)
def test_is_proxy_fail(self): """Verify that AnsibleJsonFail exception is thrown when exception occurs.""" initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90 } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with self.assertRaisesRegexp( AnsibleFailJson, r"Failed to retrieve the webservices about information"): with mock.patch(self.REQ_FUNC, return_value=Exception()): audit_log.is_proxy()
def test_is_proxy_pass(self): """Verify that True is returned when proxy is used to communicate with storage.""" initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90, "api_url": "https://10.1.1.10/devmgr/v2" } self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): self.assertTrue(audit_log.is_proxy())
def test_build_configuration_pass(self): """Validate configuration changes will force an update.""" response = { "auditLogMaxRecords": 1000, "auditLogLevel": "writeOnly", "auditLogFullPolicy": "overWrite", "auditLogWarningThresholdPct": 90 } initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90 } changes = [{ "max_records": 50000 }, { "log_level": "all" }, { "full_policy": "preventSystemAccess" }, { "threshold": 75 }] for change in changes: initial_with_changes = initial.copy() initial_with_changes.update(change) self._set_args(**initial_with_changes) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": True })): audit_log = AuditLog() with mock.patch(self.REQ_FUNC, return_value=(200, response)): update = audit_log.build_configuration() self.assertTrue(update)
def test_set_name(self): """Ensure we can successfully set the name""" self._set_args(dict(name="x")) expected = dict(name='y', status='online') namer = GlobalSettings() # Expecting an update with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: with mock.patch.object(namer, 'get_name', return_value='y'): update = namer.update_name() self.assertTrue(update) # Expecting no update with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: with mock.patch.object(namer, 'get_name', return_value='x'): update = namer.update_name() self.assertFalse(update) # Expecting an update, but no actual calls, since we're using check_mode=True namer.check_mode = True with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req: with mock.patch.object(namer, 'get_name', return_value='y'): update = namer.update_name() self.assertEqual(0, req.called) self.assertTrue(update)
def test_update_configuration_request_exception(self): """Validate exception handling when request throws an exception.""" config_response = dict(asupEnabled=True, onDemandEnabled=True, remoteDiagsEnabled=True, schedule=dict(daysOfWeek=[], dailyMinTime=0, weeklyMinTime=0, dailyMaxTime=24, weeklyMaxTime=24)) self._set_args(dict(state="enabled")) asup = Asup() with self.assertRaises(Exception): with mock.patch.object(asup, 'get_configuration', return_value=config_response): with mock.patch(self.REQ_FUNC, side_effect=Exception): asup.update_configuration()
def test_threshold_argument_pass(self): """Verify AuditLog arument's max_records and threshold upper and lower boundaries.""" initial = { "max_records": 1000, "log_level": "writeOnly", "full_policy": "overWrite", "threshold": 90 } threshold_set = (60, 75, 90) for threshold in threshold_set: initial["threshold"] = threshold self._set_args(**initial) with mock.patch(self.REQ_FUNC, return_value=(200, { "runningAsProxy": False })): audit_log = AuditLog() self.assertTrue(audit_log.threshold == threshold)
def test_update_configuration(self): self._set_args() config = dict(id='abc') body = dict(id='xyz') ldap = self._make_ldap_instance() with mock.patch.object(ldap, 'make_configuration', return_value=body): with mock.patch.object(ldap, 'get_configuration', return_value=config): with mock.patch(self.REQ_FUNC, return_value=(200, None)) as req: msg, result = ldap.update_configuration() self.assertTrue(result) # Valid check_mode makes no changes req.reset_mock() ldap.check_mode = True msg, result = ldap.update_configuration() self.assertTrue(result) self.assertFalse(req.called)