webhook/app/test/test.py

68 lines
2.2 KiB
Python
Raw Normal View History

2021-07-26 09:01:59 +00:00
from fastapi import FastAPI, Request, Depends
from fastapi.testclient import TestClient
import hmac
2021-07-28 09:51:48 +00:00
from app.main import app
2022-02-20 05:52:15 +00:00
from app.dependencies import auth_hook, auth_web
2021-07-28 09:51:48 +00:00
from os import environ, getenv
2021-07-26 09:01:59 +00:00
import json
environ['WEBHOOK_SECRET'] = "dfsgdsjghhgdaehlsdfjhjkdh"
environ["BRANCH"] = "master"
environ["TOKEN"] = "assdcvfgvh"
2021-07-28 09:51:48 +00:00
secret_key = getenv('WEBHOOK_SECRET')
2021-07-26 09:01:59 +00:00
client = TestClient(app)
@app.post("/test_auth", dependencies=[Depends(auth_hook)])
async def auth_test_handler(request: Request):
return 200
@app.get("/test_web", dependencies=[Depends(auth_web)])
async def web_test_hnadler(request: Request):
return 200
def test_auth():
payload = {"Hello":"World"}
msg = json.dumps(payload).encode()
mac = hmac.new(secret_key.encode(), msg=msg, digestmod='sha1').hexdigest()
response = client.post("/test_auth", json= payload, headers={"X-Hub-Signature": "sha1="+mac})
assert response.status_code == 200
response = client.post("/test_auth", headers={"X-Hub-Signature": "sha1="+mac})
assert response.status_code == 204
assert response.text == '{"detail":"Missing or bad content"}'
response = client.post("/test_auth", json= payload, headers={"X-Hub-Signature": "sha="+mac})
assert response.status_code == 400
assert response.text == '{"detail":"Invalid signature"}'
response = client.post("/test_auth", json=payload)
assert response.status_code == 400
assert response.text == '{"detail":"Missing signature"}'
response = client.post("/test_auth", json= payload, headers={"X-Hub-Signature": "sha1="+mac+"a"})
assert response.status_code == 403
assert response.text == '{"detail":"Unauthorized"}'
2022-02-20 05:52:15 +00:00
# def test_branch():
# payload = {"ref": "refs/heads/master"}
# response = client.post("/test_ref", json= payload)
# assert response.status_code == 202
2021-07-26 09:01:59 +00:00
2022-02-20 05:52:15 +00:00
# payload = {"ref": "refs/heads/test"}
# response = client.post("/test_ref", json= payload)
# assert response.status_code == 403
2021-07-26 09:01:59 +00:00
def test_web():
2021-07-28 09:51:48 +00:00
response = client.get('/test_web?token={}'.format(getenv("TOKEN")))
2021-07-26 09:01:59 +00:00
assert response.status_code == 200
response = client.get('/test_web')
assert response.status_code == 400
response = client.get('/test_web?token=a')
assert response.status_code == 403