atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
4347977b819220280d64f9e914967717329b830a
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/tests.rsRust1134 lines37.5 KB
1
use std::{
2
    sync::Arc,
3
    time::{Duration, Instant},
4
};
5
6
use axum::{
7
    Router,
8
    body::{Body, to_bytes},
9
    http::{Method, Request, StatusCode, Version, header},
10
    response::Response,
11
};
12
use serde_json::Value;
13
use tower::ServiceExt;
14
15
use crate::{
16
    AppState, Config,
17
    game::{Floor, MumVisit, Run, Story, balance::BRANCH_TURN, balance::SUSPICION_LIMIT},
18
    router,
19
};
20
21
async fn send(
22
    app: &Router,
23
    method: &str,
24
    uri: &str,
25
    headers: &[(&str, &str)],
26
    body: &str,
27
) -> Response {
28
    let mut request = Request::builder()
29
        .method(Method::from_bytes(method.as_bytes()).unwrap())
30
        .uri(uri);
31
    for (name, value) in headers {
32
        request = request.header(*name, *value);
33
    }
34
    app.clone()
35
        .oneshot(request.body(Body::from(body.to_owned())).unwrap())
36
        .await
37
        .unwrap()
38
}
39
40
async fn json(response: Response) -> Value {
41
    serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap()
42
}
43
44
async fn text(response: Response) -> String {
45
    String::from_utf8(
46
        to_bytes(response.into_body(), usize::MAX)
47
            .await
48
            .unwrap()
49
            .to_vec(),
50
    )
51
    .unwrap()
52
}
53
54
fn header<'a>(response: &'a Response, name: &str) -> &'a str {
55
    response.headers()[name].to_str().unwrap()
56
}
57
58
fn fixture() -> Run {
59
    Run::new("cafebabe".into(), "cafe".into(), 69)
60
}
61
62
fn seeded_with(floor: Floor, setup: impl FnOnce(&mut Run)) -> Router {
63
    let state = Arc::new(AppState::default());
64
    let mut run = fixture();
65
    run.floor = floor;
66
    setup(&mut run);
67
    state.insert(run);
68
    router(state)
69
}
70
71
fn seeded(floor: Floor) -> (Router, String) {
72
    let state = Arc::new(AppState::default());
73
    let mut run = fixture();
74
    run.floor = floor;
75
    let etag = run.origin_etag();
76
    state.insert(run);
77
    (router(state), etag)
78
}
79
80
fn app() -> Router {
81
    crate::app(Config::default())
82
}
83
84
fn mum_at_the_door(run: &mut Run) {
85
    run.mum = Some(MumVisit {
86
        errand: "She heard a noise.",
87
        nonce: "abc".into(),
88
        strikes: 0,
89
        knocked: false,
90
    });
91
}
92
93
#[tokio::test]
94
async fn creating_a_run_returns_location_and_etag() {
95
    let response = send(&app(), "POST", "/runs?seed=1", &[], "").await;
96
    assert_eq!(response.status(), StatusCode::CREATED);
97
    assert!(header(&response, "location").starts_with("/runs/"));
98
    assert!(response.headers().contains_key(header::ETAG));
99
    assert_eq!(header(&response, "server"), "jelqd/0.6.9");
100
}
101
102
#[tokio::test]
103
async fn bodies_do_not_repeat_the_headers() {
104
    let (app, _) = seeded(Floor::Bedroom);
105
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
106
    assert!(response.headers().contains_key("x-eq"));
107
    let body = json(response).await;
108
    for stat in [
109
        "eq",
110
        "girth",
111
        "foreskin",
112
        "stamina",
113
        "cash",
114
        "self_reported_length",
115
    ] {
116
        assert!(body.get(stat).is_none(), "{stat} is already a header");
117
    }
118
}
119
120
#[tokio::test]
121
async fn jelqing_cold_fails_the_precondition() {
122
    let (app, _) = seeded(Floor::Bedroom);
123
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=stretch", &[], "").await;
124
    assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED);
125
    assert_eq!(
126
        header(&response, "content-type"),
127
        "application/problem+json"
128
    );
129
}
130
131
#[tokio::test]
132
async fn wet_without_lube_is_unsupported_media() {
133
    let (app, _) = seeded(Floor::Bedroom);
134
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
135
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &[], "").await;
136
    assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
137
    let images = send(
138
        &app,
139
        "JELQ",
140
        "/runs/cafebabe?technique=wet",
141
        &[("content-type", "image/jpeg")],
142
        "",
143
    )
144
    .await;
145
    assert_eq!(json(images).await["detail"], "No.");
146
}
147
148
#[tokio::test]
149
async fn unknown_methods_are_not_implemented() {
150
    let (app, _) = seeded(Floor::Bedroom);
151
    let response = send(&app, "MILK", "/runs/cafebabe", &[], "").await;
152
    assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);
153
    let teapot = send(&app, "BREW", "/runs/cafebabe", &[], "").await;
154
    assert_eq!(teapot.status(), StatusCode::IM_A_TEAPOT);
155
}
156
157
#[tokio::test]
158
async fn the_clinic_does_not_advertise_jelq() {
159
    let (app, _) = seeded(Floor::Clinic);
160
    let options = send(&app, "OPTIONS", "/runs/cafebabe", &[], "").await;
161
    assert!(!header(&options, "allow").contains("JELQ"));
162
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &[], "").await;
163
    assert_eq!(jelq.status(), StatusCode::METHOD_NOT_ALLOWED);
164
    assert!(!header(&jelq, "allow").contains("JELQ"));
165
    let (bedroom, _) = seeded(Floor::Bedroom);
166
    let options = send(&bedroom, "OPTIONS", "/runs/cafebabe", &[], "").await;
167
    assert!(header(&options, "allow").contains("JELQ"));
168
}
169
170
#[tokio::test]
171
async fn patch_only_accepts_the_truth() {
172
    let (app, _) = seeded(Floor::Bedroom);
173
    let patch = [("content-type", "application/json-patch+json")];
174
    let replace = send(
175
        &app,
176
        "PATCH",
177
        "/runs/cafebabe",
178
        &patch,
179
        r#"[{"op":"replace","path":"/length","value":12}]"#,
180
    )
181
    .await;
182
    assert_eq!(replace.status(), StatusCode::UNPROCESSABLE_ENTITY);
183
    let lie = send(
184
        &app,
185
        "PATCH",
186
        "/runs/cafebabe",
187
        &patch,
188
        r#"[{"op":"test","path":"/length","value":40}]"#,
189
    )
190
    .await;
191
    assert_eq!(
192
        json(lie).await["type"],
193
        "https://jelq.dev/problems/exaggeration"
194
    );
195
}
196
197
#[tokio::test]
198
async fn deleting_the_foreskin_requires_certainty() {
199
    let (app, _) = seeded(Floor::Bedroom);
200
    let response = send(&app, "DELETE", "/runs/cafebabe/foreskin", &[], "").await;
201
    assert_eq!(response.status(), StatusCode::PRECONDITION_REQUIRED);
202
    let look = send(&app, "GET", "/runs/cafebabe/foreskin", &[], "").await;
203
    assert_eq!(look.status(), StatusCode::OK);
204
    let etag = header(&look, "etag").to_owned();
205
    assert!(text(look).await.contains('~'));
206
    let response = send(
207
        &app,
208
        "DELETE",
209
        "/runs/cafebabe/foreskin",
210
        &[("if-match", &etag)],
211
        "",
212
    )
213
    .await;
214
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
215
    let response = send(&app, "GET", "/runs/cafebabe/foreskin", &[], "").await;
216
    assert_eq!(response.status(), StatusCode::GONE);
217
}
218
219
#[tokio::test]
220
async fn length_is_chunked_until_the_ruler() {
221
    let (app, _) = seeded(Floor::Bedroom);
222
    let lie = send(&app, "GET", "/runs/cafebabe/length", &[], "").await;
223
    assert!(!lie.headers().contains_key(header::CONTENT_LENGTH));
224
    let app = seeded_with(Floor::Bedroom, |run| run.items.ruler = true);
225
    let truth = send(&app, "GET", "/runs/cafebabe/length", &[], "").await;
226
    let declared: usize = header(&truth, "content-length").parse().unwrap();
227
    let body = text(truth).await;
228
    assert_eq!(body.len(), declared);
229
    assert!(body.starts_with("8=") && body.ends_with('D'));
230
}
231
232
#[tokio::test]
233
async fn length_supports_inch_ranges() {
234
    let (app, _) = seeded(Floor::Bedroom);
235
    let response = send(
236
        &app,
237
        "GET",
238
        "/runs/cafebabe/length",
239
        &[("range", "inches=0-1")],
240
        "",
241
    )
242
    .await;
243
    assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
244
    assert!(header(&response, "content-range").starts_with("inches 0.00-1.00/"));
245
    assert_eq!(text(response).await.len(), 25);
246
    let absurd = send(
247
        &app,
248
        "GET",
249
        "/runs/cafebabe/length",
250
        &[("range", "inches=40-50")],
251
        "",
252
    )
253
    .await;
254
    assert_eq!(absurd.status(), StatusCode::RANGE_NOT_SATISFIABLE);
255
    let malformed = send(
256
        &app,
257
        "GET",
258
        "/runs/cafebabe/length",
259
        &[("range", "inches=6.17")],
260
        "",
261
    )
262
    .await;
263
    assert_eq!(malformed.status(), StatusCode::OK);
264
    let suffix = send(
265
        &app,
266
        "GET",
267
        "/runs/cafebabe/length",
268
        &[("range", "inches=-1")],
269
        "",
270
    )
271
    .await;
272
    assert_eq!(suffix.status(), StatusCode::PARTIAL_CONTENT);
273
    assert!(text(suffix).await.ends_with('D'));
274
    for (range, status) in [
275
        ("inches=1-", StatusCode::PARTIAL_CONTENT),
276
        ("inches=40-", StatusCode::RANGE_NOT_SATISFIABLE),
277
        ("inches=-0", StatusCode::RANGE_NOT_SATISFIABLE),
278
        ("inches=2-1", StatusCode::OK),
279
        ("inches=NaN-2", StatusCode::OK),
280
        ("inches=0-inf", StatusCode::OK),
281
    ] {
282
        let response = send(
283
            &app,
284
            "GET",
285
            "/runs/cafebabe/length",
286
            &[("range", range)],
287
            "",
288
        )
289
        .await;
290
        assert_eq!(response.status(), status, "{range}");
291
    }
292
}
293
294
#[tokio::test]
295
async fn the_clinic_escalates_toward_honesty() {
296
    let (app, _) = seeded(Floor::Clinic);
297
    let mut hints = Vec::new();
298
    for _ in 0..3 {
299
        let response = send(
300
            &app,
301
            "GET",
302
            "/runs/cafebabe/diagnosis",
303
            &[("authorization", "Excuse \"changing\"")],
304
            "",
305
        )
306
        .await;
307
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
308
        hints.push(header(&response, "www-authenticate").to_owned());
309
    }
310
    assert!(hints[2].contains("Be honest."));
311
}
312
313
#[tokio::test]
314
async fn the_true_ending_is_not_modified() {
315
    let (early, _) = seeded(Floor::Bedroom);
316
    let response = send(&early, "GET", "/runs/cafebabe/diagnosis", &[], "").await;
317
    assert_eq!(response.status(), StatusCode::TOO_EARLY);
318
319
    let (app, etag) = seeded(Floor::Clinic);
320
    assert!(
321
        !etag.contains("cafebabe"),
322
        "the origin ETag must not be derivable from the id"
323
    );
324
    let response = send(
325
        &app,
326
        "GET",
327
        "/runs/cafebabe/diagnosis",
328
        &[
329
            ("authorization", "Bearer honesty"),
330
            ("if-none-match", &etag),
331
        ],
332
        "",
333
    )
334
    .await;
335
    assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
336
    assert_eq!(header(&response, "x-diagnosis"), "normal");
337
}
338
339
#[tokio::test]
340
async fn mum_accepts_a_known_excuse() {
341
    let app = seeded_with(Floor::Bedroom, mum_at_the_door);
342
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
343
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
344
    assert_eq!(header(&response, "via"), "1.1 mum");
345
    let response = send(
346
        &app,
347
        "GET",
348
        "/runs/cafebabe",
349
        &[("authorization", "Excuse \"homework\"")],
350
        "",
351
    )
352
    .await;
353
    assert_eq!(response.status(), StatusCode::OK);
354
}
355
356
#[tokio::test]
357
async fn mum_runs_out_of_patience() {
358
    let app = seeded_with(Floor::Bedroom, mum_at_the_door);
359
    let lie = [("authorization", "Excuse \"it is for science\"")];
360
    for _ in 0..2 {
361
        let response = send(&app, "GET", "/runs/cafebabe", &lie, "").await;
362
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
363
    }
364
    let caught = send(&app, "GET", "/runs/cafebabe", &lie, "").await;
365
    assert_eq!(caught.status(), StatusCode::GONE);
366
    assert_eq!(
367
        json(caught).await["type"],
368
        "https://jelq.dev/problems/caught"
369
    );
370
}
371
372
#[tokio::test]
373
async fn mum_remembers_excuses_by_christmas() {
374
    let app = seeded_with(Floor::Nans, |run| {
375
        mum_at_the_door(run);
376
        run.heard.push("homework".into());
377
    });
378
    let basic = send(
379
        &app,
380
        "GET",
381
        "/runs/cafebabe",
382
        &[("authorization", "Excuse \"changing\"")],
383
        "",
384
    )
385
    .await;
386
    assert_eq!(basic.status(), StatusCode::UNAUTHORIZED);
387
    assert!(header(&basic, "www-authenticate").starts_with("Digest"));
388
    let replay = send(
389
        &app,
390
        "GET",
391
        "/runs/cafebabe",
392
        &[(
393
            "authorization",
394
            "Digest username=\"homework\", nonce=\"abc\"",
395
        )],
396
        "",
397
    )
398
    .await;
399
    assert_eq!(
400
        json(replay).await["type"],
401
        "https://jelq.dev/problems/excuse-replayed"
402
    );
403
    let fresh = send(
404
        &app,
405
        "GET",
406
        "/runs/cafebabe",
407
        &[(
408
            "authorization",
409
            "Digest username=\"wrapping presents\", nonce=\"abc\"",
410
        )],
411
        "",
412
    )
413
    .await;
414
    assert_eq!(fresh.status(), StatusCode::OK);
415
}
416
417
#[tokio::test]
418
async fn a_pulled_muscle_is_a_true_excuse() {
419
    let app = seeded_with(Floor::Nans, |run| {
420
        mum_at_the_door(run);
421
        run.conditions.pulled_muscle = true;
422
        run.heard.push("pulled a muscle".into());
423
    });
424
    let response = send(
425
        &app,
426
        "GET",
427
        "/runs/cafebabe",
428
        &[(
429
            "authorization",
430
            "Digest username=\"pulled a muscle\", nonce=\"abc\"",
431
        )],
432
        "",
433
    )
434
    .await;
435
    assert_eq!(response.status(), StatusCode::OK);
436
    assert!(header(&response, "x-stamina").ends_with("/7"));
437
}
438
439
#[tokio::test]
440
async fn floors_end_when_they_end() {
441
    let app = seeded_with(Floor::Bedroom, |_| {});
442
    let early = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
443
    assert_eq!(early.status(), StatusCode::TOO_EARLY);
444
    let app = seeded_with(Floor::Bedroom, |run| run.here.turns = 6);
445
    let next = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
446
    assert!(
447
        next.status() == StatusCode::SEE_OTHER || next.status() == StatusCode::CONFLICT,
448
        "either the floor changed or the zip did"
449
    );
450
}
451
452
#[tokio::test]
453
async fn pump_bro_upsells() {
454
    let closed = seeded_with(Floor::Bedroom, |_| {});
455
    let response = send(&closed, "GET", "/runs/cafebabe/shop", &[], "").await;
456
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
457
458
    let app = seeded_with(Floor::ChangingRoom, |_| {});
459
    let pump = send(&app, "POST", "/runs/cafebabe/shop/pump", &[], "").await;
460
    assert_eq!(pump.status(), StatusCode::UPGRADE_REQUIRED);
461
    assert_eq!(header(&pump, "upgrade"), "pump-pro/2.0");
462
    let pro = send(&app, "POST", "/runs/cafebabe/shop/pump-pro", &[], "").await;
463
    assert_eq!(pro.status(), StatusCode::CREATED);
464
    let broke = send(&app, "POST", "/runs/cafebabe/shop/extender", &[], "").await;
465
    assert_eq!(broke.status(), StatusCode::PAYMENT_REQUIRED);
466
}
467
468
#[tokio::test]
469
async fn only_the_key_opens_the_cage() {
470
    let app = seeded_with(Floor::ChangingRoom, |run| run.items.cage = true);
471
    send(&app, "POST", "/runs/cafebabe/shop/ice-pack", &[], "").await;
472
    let still = send(
473
        &app,
474
        "GET",
475
        "/runs/cafebabe/inventory/chastity-cage",
476
        &[],
477
        "",
478
    )
479
    .await;
480
    assert_eq!(still.status(), StatusCode::OK);
481
    send(&app, "POST", "/runs/cafebabe/shop/cage-key", &[], "").await;
482
    let gone = send(
483
        &app,
484
        "GET",
485
        "/runs/cafebabe/inventory/chastity-cage",
486
        &[],
487
        "",
488
    )
489
    .await;
490
    assert_eq!(gone.status(), StatusCode::NOT_FOUND);
491
}
492
493
#[tokio::test]
494
async fn combos_are_multi_status_xml() {
495
    let app = seeded_with(Floor::Bathroom, |run| {
496
        run.foreskin = Some(1.0);
497
        run.items.blinds = true;
498
    });
499
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
500
    let response = send(
501
        &app,
502
        "JELQ",
503
        "/runs/cafebabe?technique=wet,stretch",
504
        &[("content-type", "application/baby-oil")],
505
        "",
506
    )
507
    .await;
508
    assert_eq!(response.status(), StatusCode::MULTI_STATUS);
509
    assert!(text(response).await.contains("<D:multistatus"));
510
}
511
512
#[tokio::test]
513
async fn the_elder_is_stale() {
514
    let app = seeded_with(Floor::Forum, |run| run.length = 5.0);
515
    let unverified = send(&app, "GET", "/runs/cafebabe/elder", &[], "").await;
516
    assert_eq!(
517
        unverified.status(),
518
        StatusCode::PROXY_AUTHENTICATION_REQUIRED
519
    );
520
    let lie = send(
521
        &app,
522
        "GET",
523
        "/runs/cafebabe/elder",
524
        &[("proxy-authorization", "Ruler 9")],
525
        "",
526
    )
527
    .await;
528
    assert_eq!(lie.status(), StatusCode::BAD_REQUEST);
529
    let csv = send(
530
        &app,
531
        "GET",
532
        "/runs/cafebabe/elder",
533
        &[("proxy-authorization", "Ruler 5.0")],
534
        "",
535
    )
536
    .await;
537
    assert_eq!(csv.status(), StatusCode::OK);
538
    let stale = send(
539
        &app,
540
        "GET",
541
        "/runs/cafebabe/elder",
542
        &[("if-modified-since", "Mon, 15 Jun 2009 00:00:00 GMT")],
543
        "",
544
    )
545
    .await;
546
    assert_eq!(stale.status(), StatusCode::NOT_MODIFIED);
547
}
548
549
#[tokio::test]
550
async fn the_displayed_length_is_accepted_as_honest() {
551
    let app = seeded_with(Floor::Forum, |run| run.length = 5.2496);
552
    let response = send(
553
        &app,
554
        "GET",
555
        "/runs/cafebabe/elder",
556
        &[("proxy-authorization", "Ruler 5.25")],
557
        "",
558
    )
559
    .await;
560
    assert_eq!(response.status(), StatusCode::OK);
561
}
562
563
#[tokio::test]
564
async fn the_hotel_has_a_captive_portal() {
565
    let app = seeded_with(Floor::Hotel, |_| {});
566
    let blocked = send(&app, "GET", "/runs/cafebabe", &[], "").await;
567
    assert_eq!(
568
        blocked.status(),
569
        StatusCode::NETWORK_AUTHENTICATION_REQUIRED
570
    );
571
    let accepted = send(&app, "POST", "/runs/cafebabe/portal", &[], "").await;
572
    assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
573
    let online = send(&app, "GET", "/runs/cafebabe", &[], "").await;
574
    assert_eq!(online.status(), StatusCode::OK);
575
}
576
577
#[tokio::test]
578
async fn the_internet_never_forgets() {
579
    let app = seeded_with(Floor::Bedroom, |run| {
580
        run.filmed_at = Some(std::time::SystemTime::now());
581
    });
582
    let footage = send(&app, "GET", "/runs/cafebabe/footage", &[], "").await;
583
    assert_eq!(footage.status(), StatusCode::OK);
584
    assert_eq!(
585
        header(&footage, "cache-control"),
586
        "public, max-age=31536000, immutable"
587
    );
588
    assert!(footage.headers().contains_key(header::AGE));
589
    let delete = send(&app, "DELETE", "/runs/cafebabe/footage", &[], "").await;
590
    assert_eq!(delete.status(), StatusCode::METHOD_NOT_ALLOWED);
591
    assert!(!header(&delete, "allow").contains("DELETE"));
592
}
593
594
#[tokio::test]
595
async fn forged_ruler_cookies_are_lies() {
596
    let forged = send(
597
        &app(),
598
        "GET",
599
        "/leaderboard?sort=content-length",
600
        &[("cookie", "ruler=1")],
601
        "",
602
    )
603
    .await;
604
    assert_eq!(forged.status(), StatusCode::BAD_REQUEST);
605
}
606
607
#[tokio::test]
608
async fn listings_never_reveal_the_private_id() {
609
    let app = app();
610
    let created = send(&app, "POST", "/runs", &[], "").await;
611
    let location = header(&created, "location").to_owned();
612
    let board = text(send(&app, "GET", "/leaderboard", &[], "").await).await;
613
    let private = location.trim_start_matches("/runs/");
614
    assert!(!board.contains(private));
615
    let entry: Value = serde_json::from_str(&board).unwrap();
616
    let public = entry["entries"][0]["public_id"].as_str().unwrap();
617
    let guess = send(&app, "DELETE", &format!("/runs/{public}"), &[], "").await;
618
    assert_eq!(guess.status(), StatusCode::NOT_FOUND);
619
}
620
621
#[tokio::test]
622
async fn seeded_runs_are_unranked() {
623
    let app = app();
624
    send(&app, "POST", "/runs?seed=7", &[], "").await;
625
    let board = json(send(&app, "GET", "/leaderboard", &[], "").await).await;
626
    assert_eq!(board["entries"].as_array().unwrap().len(), 0);
627
    let all = json(send(&app, "GET", "/leaderboard?seeded=include", &[], "").await).await;
628
    assert_eq!(all["entries"][0]["ranked"], false);
629
}
630
631
#[tokio::test]
632
async fn idle_runs_are_evicted_and_the_server_has_a_limit() {
633
    let forgetful = crate::app(Config {
634
        idle_ttl: Duration::ZERO,
635
        ..Config::default()
636
    });
637
    let first = send(&forgetful, "POST", "/runs", &[], "").await;
638
    let location = header(&first, "location").to_owned();
639
    send(&forgetful, "POST", "/runs", &[], "").await;
640
    let gone = send(&forgetful, "GET", &location, &[], "").await;
641
    assert_eq!(gone.status(), StatusCode::NOT_FOUND);
642
643
    let tiny = crate::app(Config {
644
        max_runs: 1,
645
        ..Config::default()
646
    });
647
    send(&tiny, "POST", "/runs", &[], "").await;
648
    let full = send(&tiny, "POST", "/runs", &[], "").await;
649
    assert_eq!(full.status(), StatusCode::SERVICE_UNAVAILABLE);
650
}
651
652
#[tokio::test]
653
async fn shame_from_two_runs_adds_up() {
654
    let state = Arc::new(AppState::default());
655
    state.insert(fixture());
656
    state.insert(Run::new("deadbeef".into(), "dead".into(), 7));
657
    let app = router(state);
658
    let first = send(&app, "TRACE", "/runs/cafebabe", &[], "").await;
659
    assert_eq!(header(&first, "x-shame"), "1");
660
    let cookie = header(&first, "set-cookie")
661
        .split(';')
662
        .next()
663
        .unwrap()
664
        .to_owned();
665
    let second = send(&app, "TRACE", "/runs/deadbeef", &[("cookie", &cookie)], "").await;
666
    assert_eq!(header(&second, "x-shame"), "2");
667
}
668
669
#[tokio::test]
670
async fn the_root_negotiates() {
671
    let app = app();
672
    let browser = send(&app, "GET", "/", &[("accept", "text/html,*/*")], "").await;
673
    assert_eq!(browser.status(), StatusCode::SEE_OTHER);
674
    assert_eq!(header(&browser, "location"), "/ui/");
675
    let curl = send(&app, "GET", "/", &[("accept", "*/*")], "").await;
676
    assert_eq!(json(curl).await["ui"], "/ui/");
677
    let page = send(&app, "GET", "/ui/", &[], "").await;
678
    assert_eq!(page.status(), StatusCode::OK);
679
}
680
681
#[tokio::test]
682
async fn the_ui_replays_what_browsers_cannot_send() {
683
    let app = app();
684
    let envelope =
685
        r#"{"method": "TRACE", "path": "/graveyard", "headers": [["X-Confession", "I did it"]]}"#;
686
    let traced = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
687
    assert_eq!(traced["status"], 405);
688
    let envelope = r#"{"method": "GET", "path": "/", "headers": [["Accept", "text/html"]]}"#;
689
    let redirected = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
690
    assert_eq!(redirected["status"], 303);
691
    assert_eq!(redirected["reason"], "See Other");
692
}
693
694
#[tokio::test]
695
async fn the_ui_decodes_gzip_for_display() {
696
    let app = seeded_with(Floor::Bedroom, |run| run.items.ring = true);
697
    let envelope =
698
        r#"{"method": "GET", "path": "/runs/cafebabe", "headers": [["Accept-Encoding", "gzip"]]}"#;
699
    let shown = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
700
    assert!(
701
        shown["body"]
702
            .as_str()
703
            .unwrap()
704
            .contains("\"public_id\":\"cafe\"")
705
    );
706
    let encoding = shown["headers"]
707
        .as_array()
708
        .unwrap()
709
        .iter()
710
        .any(|h| h[0] == "content-encoding" && h[1] == "gzip");
711
    assert!(encoding);
712
}
713
714
#[tokio::test]
715
async fn http_1_0_gets_the_pdf_treatment() {
716
    let request = Request::builder()
717
        .uri("/graveyard")
718
        .version(Version::HTTP_10)
719
        .body(Body::empty())
720
        .unwrap();
721
    let response = app().oneshot(request).await.unwrap();
722
    assert_eq!(response.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
723
}
724
725
#[tokio::test]
726
async fn mom_speaks_american() {
727
    let app = seeded_with(Floor::Nans, mum_at_the_door);
728
    let us = [("accept-language", "en-US")];
729
    let knock = send(&app, "GET", "/runs/cafebabe", &us, "").await;
730
    assert_eq!(header(&knock, "content-language"), "en-US");
731
    assert_eq!(header(&knock, "via"), "1.1 mom");
732
    assert!(
733
        json(knock).await["detail"]
734
            .as_str()
735
            .unwrap()
736
            .contains("Someone is at the door.")
737
    );
738
    let excuse = [
739
        ("accept-language", "en-US"),
740
        (
741
            "authorization",
742
            "Digest username=\"carving the turkey\", nonce=\"abc\"",
743
        ),
744
    ];
745
    let answered = send(&app, "GET", "/runs/cafebabe", &excuse, "").await;
746
    assert_eq!(answered.status(), StatusCode::OK);
747
    let floor = json(send(&app, "GET", "/runs/cafebabe/floor", &us, "").await).await;
748
    assert_eq!(floor["name"], "Grandma's house for Thanksgiving");
749
}
750
751
#[tokio::test]
752
async fn the_default_locale_is_british() {
753
    let (app, _) = seeded(Floor::Nans);
754
    let floor = send(&app, "GET", "/runs/cafebabe/floor", &[], "").await;
755
    assert_eq!(header(&floor, "content-language"), "en-GB");
756
    assert!(header(&floor, "vary").contains("Accept-Language"));
757
    assert_eq!(json(floor).await["name"], "Nan's house at Christmas");
758
}
759
760
fn advertised(response: &Response) -> Vec<String> {
761
    header(response, "link")
762
        .split(", <")
763
        .filter(|entry| entry.contains("rels/technique"))
764
        .filter_map(|entry| {
765
            entry
766
                .split("title=\"")
767
                .nth(1)?
768
                .split('"')
769
                .next()
770
                .map(str::to_owned)
771
        })
772
        .collect()
773
}
774
775
#[tokio::test]
776
async fn links_offer_only_usable_techniques() {
777
    let app = seeded_with(Floor::Bedroom, |run| run.foreskin = Some(1.0));
778
    let cold = send(&app, "GET", "/runs/cafebabe", &[], "").await;
779
    assert_eq!(advertised(&cold), ["warmup", "ice"]);
780
    let warm = send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
781
    let usable = advertised(&warm);
782
    assert!(usable.contains(&"wet".to_owned()) && usable.contains(&"dry".to_owned()));
783
    assert!(!usable.contains(&"uli".to_owned()), "uli needs the forum");
784
    assert!(!usable.contains(&"pump".to_owned()), "pump needs a pump");
785
    assert!(
786
        header(&warm, "link").contains("title=\"wet\"; allow=\"JELQ\"; lubricant=\"required\"")
787
    );
788
789
    let (forum, _) = seeded(Floor::Forum);
790
    let response = send(&forum, "GET", "/runs/cafebabe", &[], "").await;
791
    assert!(advertised(&response).is_empty());
792
}
793
794
fn linked_rels(response: &Response) -> Vec<String> {
795
    header(response, "link")
796
        .split(", <")
797
        .filter_map(|entry| {
798
            entry
799
                .split("rels/")
800
                .nth(1)?
801
                .split('"')
802
                .next()
803
                .map(str::to_owned)
804
        })
805
        .filter(|rel| rel != "technique")
806
        .collect()
807
}
808
809
#[tokio::test]
810
async fn links_hide_resources_that_would_do_nothing() {
811
    let (bedroom, _) = seeded(Floor::Bedroom);
812
    let before = linked_rels(&send(&bedroom, "GET", "/runs/cafebabe", &[], "").await);
813
    assert!(before.contains(&"drawer".to_owned()));
814
    assert!(!before.contains(&"diagnosis".to_owned()));
815
    assert!(!before.contains(&"thread".to_owned()));
816
    let searched = send(&bedroom, "POST", "/runs/cafebabe/drawer", &[], "").await;
817
    assert!(!linked_rels(&searched).contains(&"drawer".to_owned()));
818
819
    let (clinic, _) = seeded(Floor::Clinic);
820
    let rels = linked_rels(&send(&clinic, "GET", "/runs/cafebabe", &[], "").await);
821
    assert!(rels.contains(&"diagnosis".to_owned()) && rels.contains(&"thread".to_owned()));
822
}
823
824
#[tokio::test]
825
async fn ignoring_mum_has_consequences() {
826
    let app = seeded_with(Floor::Bedroom, |run| {
827
        mum_at_the_door(run);
828
        run.here.turns = 6;
829
    });
830
    let knock = send(&app, "GET", "/runs/cafebabe", &[], "").await;
831
    assert_eq!(
832
        json(knock).await["type"],
833
        "https://jelq.dev/problems/someone-at-the-door"
834
    );
835
    let leave = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
836
    assert_eq!(
837
        leave.status(),
838
        StatusCode::UNAUTHORIZED,
839
        "no leaving with Mum at the door"
840
    );
841
    send(&app, "GET", "/runs/cafebabe", &[], "").await;
842
    let opened = send(&app, "GET", "/runs/cafebabe", &[], "").await;
843
    assert_eq!(opened.status(), StatusCode::GONE);
844
    assert_eq!(
845
        json(opened).await["type"],
846
        "https://jelq.dev/problems/opened"
847
    );
848
}
849
850
#[tokio::test]
851
async fn caged_drawers_are_noisy_and_eventually_give_up_the_key() {
852
    let app = seeded_with(Floor::ChangingRoom, |run| run.items.cage = true);
853
    let mut statuses = Vec::new();
854
    for _ in 0..12 {
855
        let response = send(&app, "POST", "/runs/cafebabe/drawer", &[], "").await;
856
        statuses.push(response.status());
857
        if response.status() == StatusCode::OK {
858
            break;
859
        }
860
    }
861
    assert_eq!(statuses.last(), Some(&StatusCode::OK), "{statuses:?}");
862
    assert!(
863
        statuses[..statuses.len() - 1]
864
            .iter()
865
            .all(|s| *s == StatusCode::NO_CONTENT)
866
    );
867
}
868
869
#[tokio::test]
870
async fn the_ruler_replaces_the_self_report() {
871
    let app = seeded_with(Floor::Bedroom, |_| {});
872
    let before = send(&app, "GET", "/runs/cafebabe", &[], "").await;
873
    assert!(before.headers().contains_key("x-self-reported-length"));
874
    assert!(!before.headers().contains_key("x-length"));
875
876
    let app = seeded_with(Floor::Bedroom, |run| run.items.ruler = true);
877
    let after = send(&app, "GET", "/runs/cafebabe", &[], "").await;
878
    assert!(!after.headers().contains_key("x-self-reported-length"));
879
    assert!(after.headers().contains_key("x-length"));
880
}
881
882
#[tokio::test]
883
async fn an_open_tab_is_linked_and_jelq_still_answers_with_choices() {
884
    let app = seeded_with(Floor::Bathroom, |run| {
885
        run.story = Story::Pending;
886
        run.warmed_up = true;
887
    });
888
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
889
    let links = header(&response, "link");
890
    assert!(links.contains("/branches/forum>; rel=\"https://jelq.dev/rels/branch\""));
891
    assert!(links.contains("/branches/close-tab>; rel=\"https://jelq.dev/rels/branch\""));
892
    assert!(links.contains("?technique=wet>"));
893
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=edge", &[], "").await;
894
    assert_eq!(jelq.status(), StatusCode::MULTIPLE_CHOICES);
895
}
896
897
#[tokio::test]
898
async fn either_story_choice_is_reachable_during_cooldown() {
899
    for choice in ["forum", "close-tab"] {
900
        let app = seeded_with(Floor::Bathroom, |run| {
901
            run.turn = 9;
902
            run.warmed_up = true;
903
            run.stamina = 1;
904
            run.items.door_locks = 1;
905
        });
906
        let tenth = send(&app, "JELQ", "/runs/cafebabe?technique=edge", &[], "").await;
907
        assert_eq!(tenth.status(), StatusCode::OK);
908
        let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
909
        assert!(!header(&response, "link").contains("?technique="));
910
        let path = format!("/runs/cafebabe/branches/{choice}");
911
        assert!(
912
            header(&response, "link")
913
                .contains(&format!("<{path}>; rel=\"https://jelq.dev/rels/branch\""))
914
        );
915
        let chosen = send(&app, "POST", &path, &[], "").await;
916
        assert_eq!(chosen.status(), StatusCode::SEE_OTHER);
917
        assert!(!header(&chosen, "link").contains("/branches/"));
918
        let repeated = send(&app, "POST", &path, &[], "").await;
919
        assert_eq!(repeated.status(), StatusCode::CONFLICT);
920
    }
921
}
922
923
#[tokio::test]
924
async fn a_door_lock_says_when_it_was_used() {
925
    let app = seeded_with(Floor::Bathroom, |run| {
926
        run.items.door_locks = 1;
927
        run.suspicion = SUSPICION_LIMIT;
928
        run.warmed_up = true;
929
    });
930
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
931
    assert_ne!(response.status(), StatusCode::CONFLICT);
932
    assert!(
933
        response
934
            .headers()
935
            .get_all("warning")
936
            .iter()
937
            .any(|w| w.to_str().unwrap().contains("your brother tried the door"))
938
    );
939
}
940
941
#[tokio::test]
942
async fn shopping_survives_browsing_but_not_jelqing() {
943
    let app = seeded_with(Floor::ChangingRoom, |run| run.cash = 50);
944
    send(&app, "GET", "/runs/cafebabe/shop", &[], "").await;
945
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
946
    assert!(header(&view, "link").contains("shop-item"));
947
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
948
    assert_ne!(jelq.status(), StatusCode::METHOD_NOT_ALLOWED);
949
    let after = send(&app, "GET", "/runs/cafebabe", &[], "").await;
950
    assert!(!header(&after, "link").contains("shop-item"));
951
}
952
953
#[tokio::test]
954
async fn the_thread_announces_itself_at_the_branch() {
955
    let app = seeded_with(Floor::Bathroom, |run| {
956
        run.turn = 8;
957
        run.warmed_up = true;
958
    });
959
    send(
960
        &app,
961
        "JELQ",
962
        "/runs/cafebabe?technique=wet",
963
        &[("content-type", "application/baby-oil")],
964
        "",
965
    )
966
    .await;
967
    let ninth = send(&app, "GET", "/runs/cafebabe", &[], "").await;
968
    assert!(!header(&ninth, "link").contains("/forum/threads/2009"));
969
    let tenth = send(
970
        &app,
971
        "JELQ",
972
        "/runs/cafebabe?technique=wet",
973
        &[("content-type", "application/baby-oil")],
974
        "",
975
    )
976
    .await;
977
    assert!(
978
        tenth
979
            .headers()
980
            .get_all("warning")
981
            .iter()
982
            .any(|w| w.to_str().unwrap().contains("a forum thread from 2009"))
983
    );
984
    assert!(header(&tenth, "link").contains("/forum/threads/2009"));
985
    let announced = send(&app, "GET", "/runs/cafebabe", &[], "").await;
986
    assert!(header(&announced, "link").contains("/forum/threads/2009"));
987
}
988
989
#[tokio::test]
990
async fn reading_the_forum_may_teach_meditation() {
991
    let taught = (0..50u64)
992
        .filter(|seed| {
993
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
994
            run.story = Story::Pending;
995
            run.turn = BRANCH_TURN;
996
            run.choose("forum").is_ok() && run.meditation_taught
997
        })
998
        .count();
999
    assert!(
1000
        taught > 0 && taught < 50,
1001
        "the teach roll should be a coin, it landed {taught}/50"
1002
    );
1003
}
1004
1005
#[tokio::test]
1006
async fn meditation_is_free_but_only_once_per_floor() {
1007
    let app = seeded_with(Floor::Bedroom, |run| run.meditation_taught = true);
1008
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1009
    assert_eq!(response.status(), StatusCode::OK);
1010
    assert_eq!(header(&response, "x-eq"), "10");
1011
    assert_eq!(header(&response, "x-stamina"), "10/10");
1012
    let again = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1013
    assert_eq!(again.status(), StatusCode::CONFLICT);
1014
}
1015
1016
#[tokio::test]
1017
async fn meditation_stays_hidden_until_the_forum_teaches_it() {
1018
    let app = seeded_with(Floor::Bedroom, |_| {});
1019
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1020
    assert!(!header(&view, "link").contains("technique=meditate"));
1021
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1022
    assert_eq!(jelq.status(), StatusCode::FORBIDDEN);
1023
}
1024
1025
fn app_with(floor: Floor, seed: u64, setup: impl FnOnce(&mut Run)) -> Router {
1026
    let state = Arc::new(AppState::default());
1027
    let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1028
    run.floor = floor;
1029
    setup(&mut run);
1030
    state.insert(run);
1031
    router(state)
1032
}
1033
1034
#[tokio::test]
1035
async fn hold_is_offered_only_at_the_edges() {
1036
    let calm = seeded_with(Floor::Bedroom, |_| {});
1037
    let refused = send(&calm, "HOLD", "/runs/cafebabe", &[], "").await;
1038
    assert_eq!(refused.status(), StatusCode::METHOD_NOT_ALLOWED);
1039
    assert!(!header(&refused, "allow").contains("HOLD"));
1040
    let view = send(&calm, "GET", "/runs/cafebabe", &[], "").await;
1041
    assert!(!header(&view, "link").contains("HOLD"));
1042
    let options = send(&calm, "OPTIONS", "/runs/cafebabe", &[], "").await;
1043
    assert!(!header(&options, "allow").contains("HOLD"));
1044
1045
    let winded = seeded_with(Floor::Bedroom, |run| run.stamina = 2);
1046
    let listed = send(&winded, "GET", "/runs/cafebabe", &[], "").await;
1047
    assert!(header(&listed, "link").contains("HOLD"));
1048
    let options = send(&winded, "OPTIONS", "/runs/cafebabe", &[], "").await;
1049
    assert!(header(&options, "allow").contains("HOLD"));
1050
1051
    let hot = seeded_with(Floor::Bedroom, |run| {
1052
        run.eq = 75;
1053
        run.warmed_up = true;
1054
    });
1055
    let held = send(&hot, "HOLD", "/runs/cafebabe", &[], "").await;
1056
    assert_eq!(held.status(), StatusCode::NO_CONTENT);
1057
    assert_eq!(header(&held, "x-stamina"), "10/10");
1058
}
1059
1060
#[tokio::test]
1061
async fn holding_calms_and_sometimes_reflects() {
1062
    let calmed = (0..60u64)
1063
        .filter(|seed| {
1064
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1065
            run.eq = 75;
1066
            run.hold(Instant::now()).is_ok() && run.eq == 60
1067
        })
1068
        .count();
1069
    let reflected = (0..60u64)
1070
        .filter(|seed| {
1071
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1072
            run.eq = 75;
1073
            run.hold(Instant::now()).is_ok() && run.eq == 0
1074
        })
1075
        .count();
1076
    assert!(
1077
        calmed > 40 && reflected > 0 && calmed + reflected == 60,
1078
        "one HOLD in twelve should reflect, got {calmed} calm and {reflected} reflective of 60"
1079
    );
1080
}
1081
1082
#[tokio::test]
1083
async fn leaving_the_band_warms_the_next_floor() {
1084
    let app = seeded_with(Floor::Bedroom, |run| {
1085
        run.eq = 60;
1086
        run.warmed_up = true;
1087
        run.here.turns = 6;
1088
    });
1089
    let left = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
1090
    assert_eq!(left.status(), StatusCode::SEE_OTHER);
1091
    let detail = json(left).await["detail"].as_str().unwrap().to_owned();
1092
    assert!(detail.contains("the warmth came with you"));
1093
1094
    let lube = [("content-type", "application/baby-oil")];
1095
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
1096
    // The shower is a +35 warm-up, so EQ lands in the band and the band bonus rides along.
1097
    // The arrival bonus is the one point the second jelq loses.
1098
    let first = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1099
    assert!(
1100
        header(&first, "server-timing").contains("d20+4"),
1101
        "the first jelq of a warm arrival rolls with +1, got {}",
1102
        header(&first, "server-timing")
1103
    );
1104
    let second = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1105
    assert!(header(&second, "server-timing").contains("d20+3"));
1106
}
1107
1108
#[tokio::test]
1109
async fn greed_multiplies_gains_above_the_band() {
1110
    let lube = [("content-type", "application/baby-oil")];
1111
    for seed in 0..60u64 {
1112
        let app = app_with(Floor::Bedroom, seed, |run| {
1113
            run.eq = 60;
1114
            run.warmed_up = true;
1115
        });
1116
        let in_band = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1117
        let app = app_with(Floor::Bedroom, seed, |run| {
1118
            run.eq = 75;
1119
            run.warmed_up = true;
1120
        });
1121
        let greedy = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1122
        if in_band.status() != StatusCode::OK || greedy.status() != StatusCode::OK {
1123
            continue;
1124
        }
1125
        let steady = json(in_band).await["length"].as_f64().unwrap();
1126
        let eager = json(greedy).await["length"].as_f64().unwrap();
1127
        assert!(
1128
            (eager - steady * 1.5).abs() < 1e-9,
1129
            "seed {seed} gained {eager} above the band against {steady} inside it"
1130
        );
1131
        return;
1132
    }
1133
    panic!("no seed in 60 produced two clean rolls to compare");
1134
}