| @@ -2,10 +2,14 @@ |
| 2 | 2 | /// (gen_server style). It is linked to the web server that starts it, so |
| 3 | 3 | /// the supervisor restarts both if either crashes. |
| 4 | 4 | |
| 5 | | −import std/actor.{Continue} |
| 5 | +import std/actor.{Continue, Stop} |
| 6 | 6 | import std/dict.{type Dict} |
| 7 | 7 | import std/process.{type Subject, type proc} |
| 8 | +import std/option |
| 8 | 9 | import std/random |
| 10 | +import std/result |
| 11 | +import std/string |
| 12 | +import std/test.{assert, assert_equal} |
| 9 | 13 | import argon2 |
| 10 | 14 | import app.{type User, type RegisterError, User, NameTaken} |
| 11 | 15 | |
| @@ -56,3 +60,50 @@ fn on_message(state: State, msg: Msg) -> actor.Next<State> / <proc, io, ffi> { |
| 56 | 60 | }, |
| 57 | 61 | } |
| 58 | 62 | } |
| 63 | + |
| 64 | +// The tests below call `on_message` directly, with a reply subject of the |
| 65 | +// test's own, and read the reply back. |
| 66 | + |
| 67 | +/// The reply `send` gets, and the state after it. |
| 68 | +fn ask(state: State, send: fn(Subject<r>) -> Msg) -> (r, State) / <proc, io, ffi> { |
| 69 | + let reply = process.subject() |
| 70 | + match on_message(state, send(reply)) { |
| 71 | + Continue(next) -> |
| 72 | + match process.receive(reply, 0) { |
| 73 | + Some(answer) -> (answer, next), |
| 74 | + None -> panic("no reply"), |
| 75 | + }, |
| 76 | + Stop -> panic("the store stopped"), |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +/// A store with one user, `ada`, whose hash is "h1". |
| 81 | +fn with_ada() -> State { |
| 82 | + State(dict.insert(dict.empty(), "ada", User("ada", "h1")), dict.empty()) |
| 83 | +} |
| 84 | + |
| 85 | +@test |
| 86 | +fn a_taken_name_keeps_its_first_user() -> () / <proc, io, ffi> { |
| 87 | + let (added, state) = ask(with_ada(), AddUser(User("ada", "h2"), _)) |
| 88 | + assert(added |> result.is_error, "refused") |
| 89 | + let (found, _) = ask(state, FindUser("ada", _)) |
| 90 | + assert_equal(found |> option.map(fn(u) { u.password_hash }), Some("h1")) |
| 91 | +} |
| 92 | + |
| 93 | +@test |
| 94 | +fn a_new_user_can_be_found() -> () / <proc, io, ffi> { |
| 95 | + let (added, state) = ask(with_ada(), AddUser(User("bob", "h2"), _)) |
| 96 | + assert(added |> result.is_ok, "added") |
| 97 | + let (found, _) = ask(state, FindUser("bob", _)) |
| 98 | + assert_equal(found |> option.map(fn(u) { u.password_hash }), Some("h2")) |
| 99 | +} |
| 100 | + |
| 101 | +@test |
| 102 | +fn a_new_session_names_its_user() -> () / <proc, io, ffi> { |
| 103 | + let (token, state) = ask(with_ada(), NewSession("ada", _)) |
| 104 | + assert_equal(string.length(token), 32) |
| 105 | + let (user, _) = ask(state, SessionUser(token, _)) |
| 106 | + assert_equal(user, Some("ada")) |
| 107 | + let (nobody, _) = ask(state, SessionUser("not" <> token, _)) |
| 108 | + assert_equal(nobody, None) |
| 109 | +} |