Last active
June 14, 2022 13:22
-
-
Save Tattoo/528eb25428ac16cb6d2e063960514cdc to your computer and use it in GitHub Desktop.
Simple example script to send a message to Slack in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''Simple example script below is quite straightforward. | |
Although Slack recommends integrating to it by writing Apps[1], | |
the old-school webhook integration still works as well | |
[1] https://api.slack.com/start/overview | |
''' | |
import json | |
import os | |
import sys | |
from requests import codes, post | |
from robot.api import ExecutionResult | |
# Get the Slack webhook url (https://api.slack.com/messaging/webhooks) from environment variable so we do not expose it needlessly | |
URL = os.environ.get('SLACK_URL', None) | |
if URL is None: | |
raise Exception('$SLACK_URL env var not defined D:') | |
# message template used for the message | |
TEXT = '''MOI | |
Updating the following dependencies have resulted in {test_status}: | |
{deps} | |
''' | |
def post_to_slack(message): | |
r = post(URL, data=json.dumps({'text': message})) | |
if r.status_code != codes.ok: # only output something if there's a failure | |
print(r.json()) | |
r.raise_for_status() # in case of erroneous response, throw an exception | |
def main(robot_output, new_requirements, original_requirements): | |
# parse test execution status from output.xml using Robot Framework’s API (https://robot-framework.readthedocs.io/en/stable/) | |
robot_result = ExecutionResult(robot_output) | |
test_run_passed = bool(robot_result.statistics.total.failed == 0) | |
# read in both requirement files: the old, known dependencies and the ones used in the test execution | |
with open(new_requirements, 'r') as f: | |
new_requirements = f.readlines() | |
# separate dependency name and version to make comparing dependencies easier | |
new_requirements = [line.split('==') for line in new_requirements] | |
with open(original_requirements, 'r') as f: | |
old_requirements = f.readlines() | |
old_requirements = sorted(line.split('==') for line in old_requirements) | |
# new_requirements now has more dependencies than old_requirements | |
# only retain original *main level* dependecies | |
# others are sub-dependencies we do not want | |
new_requirements = sorted(filter(lambda req: req[0] in [r[0] for r in old_requirements], | |
new_requirements)) | |
# format the message to be posted to Slack | |
msg = TEXT.format(test_status='PASS' if test_run_passed else 'FAIL', | |
deps='\n'.join(f'{"==".join(dep[0])} => {"==".join(dep[1])}' | |
for dep in zip(old_requirements, | |
new_requirements))) | |
post_to_slack(msg) | |
if __name__ == '__main__': | |
main(*sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment