Browse Source

Added the first testcase.

pull/11/head
Egon Rijpkema 3 years ago
parent
commit
55be9eb3aa
  1. 13
      roles/kill_memory_hogs/files/Pipfile
  2. 2
      roles/kill_memory_hogs/files/kill_hoggs.py
  3. 49
      roles/kill_memory_hogs/files/test_kill_hoggs.py

13
roles/kill_memory_hogs/files/Pipfile

@ -0,0 +1,13 @@ @@ -0,0 +1,13 @@
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
pyaml = "*"
requests = "*"
[dev-packages]
[requires]
python_version = "3.7"

2
roles/kill_memory_hogs/files/kill_hoggs.py

@ -19,7 +19,7 @@ def post_to_slack(message: str): @@ -19,7 +19,7 @@ def post_to_slack(message: str):
message (str): Message to post
"""
with open('/opt/kill_hoggs/kill_hoggs.yml', 'r') as f:
config = yaml.load(f.read())
config = yaml.load(f.read(), Loader=yaml.BaseLoader)
slack_url = config['slack_url']
data = json.dumps({
'channel': '#peregrine-alerts',

49
roles/kill_memory_hogs/files/test_kill_hoggs.py

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
import unittest
from unittest import mock
import kill_hoggs
def mocked_requests_post(*args, **kwargs):
"""
Adapted from an answer here:
https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response
"""
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
self.text = "MOcked successfully."
def json(self):
return self.json_data
if args[0] == 'https://hooks.slack.com/services/normally/random/string':
return MockResponse({"key1": "value1"}, 200)
return MockResponse(None, 404)
dummy_config = '''
---
slack_url: 'https://hooks.slack.com/services/normally/random/string'
'''
class PostToSlackTestcase(unittest.TestCase):
# We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
@mock.patch('requests.post', side_effect=mocked_requests_post)
@mock.patch('builtins.open', mock.mock_open(read_data=dummy_config))
def test_post_to_slack(self, mock_get):
"""
Call post_to_slack and make sure requests.post was called with the right parameters.
"""
kill_hoggs.post_to_slack('Hello world')
# assert that our mocked function was called with the right parameters
self.assertIn(mock_get.call_args_list[0], mock_get.call_args_list)
self.assertIn(mock.call('https://hooks.slack.com/services/normally/random/string', data=b'{"channel": "#peregrine-alerts", "username": "kill-hoggs", "text": "Hello world", "icon_emoji": ":scales:"}', headers={'Content-Type': 'application/json'}), mock_get.call_args_list)
if __name__ == '__main__':
unittest.main()
Loading…
Cancel
Save