Test your app#
Run your app's tests without a browser, a phone or a node.
| Level | 1: A person approves with a passkey. |
| Class | read: Nothing changes. The approval can be reused until it ends or the person withdraws it. |
from app import app
client = app.test_client()
def test_a_request_without_a_passport_is_refused():
r = client.get("/notes")
assert r.status_code == 401
assert r.json["type"] == "https://allowedby.org/errors/passport_required"
def test_agents_see_the_sentence_the_person_approves():
r = client.get("/.well-known/allowedby")
assert r.json["templates"]["notes:read"]["summary"]["en"] == "Read your notes"
def test_deleting_needs_an_approval_of_that_exact_request():
r = client.get("/openapi.json")
assert r.json["paths"]["/notes/{id}"]["delete"]["x-allowedby"]["class"] == "write-hard"import assert from "node:assert/strict";
import { test } from "node:test";
import { AllowedBy } from "@allowedby/sdk";
import { TestNode } from "@allowedby/sdk/testing";
import { routes, templates } from "./app.mjs";
const origin = "https://notes.example";
const node = await TestNode.create(); // a node in memory, whose people approve on demand
const aby = new AllowedBy({
origin,
node: node.origin,
fetch: node.fetch,
autoRefresh: false,
org: { legal_name: "Notes Ltd", country: "FR" },
routes,
templates,
});
await aby.refresh();
const agent = await node.agent();
test("an agent the person did not approve is refused", async () => {
const headers = await agent.sign("GET", `${origin}/notes`);
const { refusal } = await aby.check({ method: "GET", path: "/notes", headers });
assert.equal(refusal.status, 401);
assert.match(refusal.headers["WWW-Authenticate"], /error="grant_required"/);
});
test("an approved agent is accepted, and the app knows the person", async () => {
const capabilities = [{ cap: "notes:read", constraints: { scope: "note:*" } }];
const grant = await node.grant(agent, { audience: origin, capabilities });
const headers = await agent.sign("GET", `${origin}/notes`, { allowedBy: grant });
const { context } = await aby.check({ method: "GET", path: "/notes", headers });
assert.equal(context.humanId, await node.humanId(origin));
});import (
"context"
"net/http/httptest"
"testing"
"github.com/yannUpTo/allowedby/sdks/go/allowedbytest"
)
const origin = "https://notes.example"
func TestNotes(t *testing.T) {
node := allowedbytest.NewNode(t) // a node on a local test server, whose people approve on demand
aby, app, err := newApp(origin, node.URL())
if err != nil {
t.Fatal(err)
}
defer aby.Close()
if err := aby.Refresh(context.Background()); err != nil {
t.Fatal(err)
}
agent := node.NewAgent()
// An agent the person did not approve is refused.
res := httptest.NewRecorder()
app.ServeHTTP(res, agent.Request("GET", origin+"/notes", nil, agent.Passport))
if res.Code != 401 {
t.Fatalf("without an approval: %d", res.Code)
}
// An approved agent gets the person's notes.
grant := node.Grant(agent, allowedbytest.GrantSpec{Origin: origin, Capability: "notes:read", Scope: "note:*",
Class: "read", Level: 1})
res = httptest.NewRecorder()
app.ServeHTTP(res, agent.Request("GET", origin+"/notes", nil, grant))
if res.Code != 200 {
t.Fatalf("with an approval: %d %s", res.Code, res.Body)
}
}class NotesAppTest {
static final String ORIGIN = "https://notes.example";
static TestNode node; // a node on a local port, whose people approve on demand
static AllowedBy aby;
@BeforeAll
static void start() throws Exception {
node = TestNode.start();
AllowedBy.Builder builder = AllowedBy.builder().origin(ORIGIN).node(node.origin).org("Notes Ltd", "FR");
new NotesApp().read().customize(builder); // the app's own route and template
aby = builder.build();
aby.refresh();
}
@Test
void anAgentThePersonDidNotApproveIsRefused() {
TestNode.Agent agent = node.agent();
Map<String, String> headers = agent.sign("GET", ORIGIN + "/notes", agent.passport, null);
Outcome outcome = aby.process(Request.of("GET", "/notes", null, headers, null));
assertEquals(401, outcome.getResponse().getStatus());
}
@Test
void anApprovedAgentIsAccepted() {
TestNode.Agent agent = node.agent();
String grant = node.grant(agent, ORIGIN).cap("notes:read", Map.of("scope", "note:*")).build();
Map<String, String> headers = agent.sign("GET", ORIGIN + "/notes", grant, null);
Outcome outcome = aby.process(Request.of("GET", "/notes", null, headers, null));
assertTrue(outcome.isAllowed());
}
@AfterAll
static void stop() {
aby.close();
node.close();
}
}using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class NotesTests(WebApplicationFactory<Program> app) : IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task A_request_without_a_passport_is_refused()
{
var response = await app.CreateClient().GetAsync("/notes");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Contains("passport_required", response.Headers.WwwAuthenticate.ToString());
}
[Fact]
public async Task Agents_see_the_sentence_the_person_approves()
{
var json = await app.CreateClient().GetStringAsync("/.well-known/allowedby");
using var discovery = JsonDocument.Parse(json);
var sentence = discovery.RootElement.GetProperty("templates").GetProperty("notes:read").GetProperty("summary");
Assert.Equal("Read your notes", sentence.GetProperty("en").GetString());
}
}use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Slim\Psr7\Factory\ServerRequestFactory;
final class AppTest extends TestCase
{
public function testARequestWithoutAPassportIsRefused(): void
{
$response = $this->get('/notes');
self::assertSame(401, $response->getStatusCode());
self::assertStringContainsString('passport_required', $response->getHeaderLine('WWW-Authenticate'));
}
public function testAgentsSeeTheSentenceThePersonApproves(): void
{
$discovery = json_decode((string) $this->get('/.well-known/allowedby')->getBody(), true);
self::assertSame('Read your notes', $discovery['templates']['notes:read']['summary']['en']);
}
private function get(string $path): ResponseInterface
{
$app = require __DIR__.'/../app.php';
return $app->handle((new ServerRequestFactory())->createServerRequest('GET', $path));
}
}require "minitest/autorun"
require "allowedby/testing"
require_relative "app"
class NotesTest < Minitest::Test
ORIGIN = "https://notes.example"
def setup
@node = AllowedBy::Testing::Node.new # a node in memory, whose people approve on demand
@aby = AllowedBy.new(
origin: ORIGIN, node: @node.origin, http: @node, start: false,
org: { legal_name: "Notes Ltd", country: "FR" }, routes: ROUTES, templates: TEMPLATES
)
@aby.verifier.refresh
@agent = @node.agent
end
def test_an_agent_the_person_did_not_approve_is_refused
_, (status, headers) = @aby.check("GET", "/notes", @agent.headers("GET", "#{ORIGIN}/notes"))
assert_equal 401, status
assert_match(/error="grant_required"/, headers["www-authenticate"])
end
def test_an_approved_agent_is_accepted_and_the_app_knows_the_person
capabilities = [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }]
grant = @node.grant(@agent, audience: ORIGIN, capabilities: capabilities)
context, = @aby.check("GET", "/notes", @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant))
assert_equal @node.human_id(ORIGIN), context.human_id
end
end#[cfg(test)]
mod tests {
use super::*;
use allowedby::{Outcome, Request};
fn service() -> Service {
let (aby, _) = notes_app("https://notes.example", "https://node.example.org");
Service::new(aby.background_refresh(false)).expect("a valid configuration")
}
#[test]
fn a_request_without_a_passport_is_refused() {
let Outcome::Respond(refusal) = service().handle(&Request::new("GET", "/notes")) else {
panic!("accepted");
};
assert_eq!(refusal.status, 401);
assert!(refusal.header("WWW-Authenticate").is_some_and(|h| h.contains("passport_required")));
}
#[test]
fn agents_see_the_sentence_the_person_approves() {
let discovery = service().well_known();
assert_eq!(discovery["templates"]["notes:read"]["summary"]["en"], "Read your notes");
}
}What the test proves#
- the app's tests pass without a browser