1.9 KiB · text 5af55d9
defmodule GitGud.WebhooksTest do
use GitGud.DataCase, async: true
alias GitGud.Webhooks
import GitGud.ForgeFixtures
setup do
{_user, repo} = repository_fixture()
{:ok, repo: repo}
end
test "creates a webhook with auto-generated secret", %{repo: repo} do
assert {:ok, hook} = Webhooks.create_webhook(repo, %{"url" => "https://example.com/hook"})
assert byte_size(hook.secret) == 32
assert hook.enabled
assert hook.events == []
end
test "rejects non-http URLs", %{repo: repo} do
assert {:error, cs} = Webhooks.create_webhook(repo, %{"url" => "ftp://nope"})
assert "must be http(s)" in errors_on(cs).url
end
test "rejects unknown events", %{repo: repo} do
assert {:error, cs} =
Webhooks.create_webhook(repo, %{
"url" => "https://example.com",
"events" => ["push", "no_such_event"]
})
assert "has an invalid entry" in errors_on(cs).events
end
test "sign uses HMAC-SHA256", _ctx do
sig = Webhooks.sign(<<1, 2, 3>>, "hello")
assert String.starts_with?(sig, "sha256=")
assert sig == Webhooks.sign(<<1, 2, 3>>, "hello")
refute sig == Webhooks.sign(<<1, 2, 4>>, "hello")
end
test "notify enqueues one job per matching enabled hook", %{repo: repo} do
{:ok, _} = Webhooks.create_webhook(repo, %{"url" => "https://a", "events" => ["push"]})
{:ok, _} = Webhooks.create_webhook(repo, %{"url" => "https://b", "events" => []})
{:ok, _} = Webhooks.create_webhook(repo, %{"url" => "https://c", "events" => ["issue"]})
Oban.Testing.with_testing_mode(:manual, fn ->
:ok = Webhooks.notify(repo, "push", %{"x" => 1})
end)
# Hooks "a" (subscribed to push) and "b" (subscribes to all) match;
# "c" subscribes only to issue.
jobs = all_enqueued()
assert length(jobs) == 2
end
defp all_enqueued do
Oban.Repo.all(Oban.config(), Oban.Job)
end
end