atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
14de3e1e8dc2a460103dbac0f56b745af96da78e
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/tests.rsRust1632 lines53.9 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::{
18
        Floor, MumVisit, Run, Story,
19
        balance::{BRANCH_TURN, STORAGE_GIRTH, SUSPICION_LIMIT},
20
    },
21
    router,
22
};
23
24
async fn send(
25
    app: &Router,
26
    method: &str,
27
    uri: &str,
28
    headers: &[(&str, &str)],
29
    body: &str,
30
) -> Response {
31
    let mut request = Request::builder()
32
        .method(Method::from_bytes(method.as_bytes()).unwrap())
33
        .uri(uri);
34
    for (name, value) in headers {
35
        request = request.header(*name, *value);
36
    }
37
    app.clone()
38
        .oneshot(request.body(Body::from(body.to_owned())).unwrap())
39
        .await
40
        .unwrap()
41
}
42
43
async fn json(response: Response) -> Value {
44
    serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap()
45
}
46
47
async fn text(response: Response) -> String {
48
    String::from_utf8(
49
        to_bytes(response.into_body(), usize::MAX)
50
            .await
51
            .unwrap()
52
            .to_vec(),
53
    )
54
    .unwrap()
55
}
56
57
fn header<'a>(response: &'a Response, name: &str) -> &'a str {
58
    response.headers()[name].to_str().unwrap()
59
}
60
61
fn fixture() -> Run {
62
    Run::new("cafebabe".into(), "cafe".into(), 69)
63
}
64
65
fn seeded_with(floor: Floor, setup: impl FnOnce(&mut Run)) -> Router {
66
    let state = Arc::new(AppState::default());
67
    let mut run = fixture();
68
    run.floor = floor;
69
    setup(&mut run);
70
    state.insert(run);
71
    router(state)
72
}
73
74
fn seeded(floor: Floor) -> (Router, String) {
75
    let state = Arc::new(AppState::default());
76
    let mut run = fixture();
77
    run.floor = floor;
78
    let etag = run.origin_etag();
79
    state.insert(run);
80
    (router(state), etag)
81
}
82
83
fn app() -> Router {
84
    crate::app(Config::default())
85
}
86
87
fn mum_at_the_door(run: &mut Run) {
88
    run.mum = Some(MumVisit {
89
        errand: "She heard a noise.",
90
        nonce: "abc".into(),
91
        strikes: 0,
92
        knocked: false,
93
    });
94
}
95
96
#[tokio::test]
97
async fn creating_a_run_returns_location_and_etag() {
98
    let response = send(&app(), "POST", "/runs?seed=1", &[], "").await;
99
    assert_eq!(response.status(), StatusCode::CREATED);
100
    assert!(header(&response, "location").starts_with("/runs/"));
101
    assert!(response.headers().contains_key(header::ETAG));
102
    assert_eq!(header(&response, "server"), "jelqd/0.6.9");
103
}
104
105
#[tokio::test]
106
async fn bodies_do_not_repeat_the_headers() {
107
    let (app, _) = seeded(Floor::Bedroom);
108
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
109
    assert!(response.headers().contains_key("x-eq"));
110
    let body = json(response).await;
111
    for stat in [
112
        "eq",
113
        "girth",
114
        "foreskin",
115
        "stamina",
116
        "cash",
117
        "self_reported_length",
118
    ] {
119
        assert!(body.get(stat).is_none(), "{stat} is already a header");
120
    }
121
}
122
123
#[tokio::test]
124
async fn jelqing_cold_fails_the_precondition() {
125
    let (app, _) = seeded(Floor::Bedroom);
126
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=stretch", &[], "").await;
127
    assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED);
128
    assert_eq!(
129
        header(&response, "content-type"),
130
        "application/problem+json"
131
    );
132
}
133
134
#[tokio::test]
135
async fn wet_without_lube_is_unsupported_media() {
136
    let (app, _) = seeded(Floor::Bedroom);
137
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
138
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &[], "").await;
139
    assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
140
    let images = send(
141
        &app,
142
        "JELQ",
143
        "/runs/cafebabe?technique=wet",
144
        &[("content-type", "image/jpeg")],
145
        "",
146
    )
147
    .await;
148
    assert_eq!(json(images).await["detail"], "No.");
149
}
150
151
#[tokio::test]
152
async fn unknown_methods_are_not_implemented() {
153
    let (app, _) = seeded(Floor::Bedroom);
154
    let response = send(&app, "MILK", "/runs/cafebabe", &[], "").await;
155
    assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);
156
    let teapot = send(&app, "BREW", "/runs/cafebabe", &[], "").await;
157
    assert_eq!(teapot.status(), StatusCode::IM_A_TEAPOT);
158
}
159
160
#[tokio::test]
161
async fn the_clinic_does_not_advertise_jelq() {
162
    let (app, _) = seeded(Floor::Clinic);
163
    let options = send(&app, "OPTIONS", "/runs/cafebabe", &[], "").await;
164
    assert!(!header(&options, "allow").contains("JELQ"));
165
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &[], "").await;
166
    assert_eq!(jelq.status(), StatusCode::METHOD_NOT_ALLOWED);
167
    assert!(!header(&jelq, "allow").contains("JELQ"));
168
    let (bedroom, _) = seeded(Floor::Bedroom);
169
    let options = send(&bedroom, "OPTIONS", "/runs/cafebabe", &[], "").await;
170
    assert!(header(&options, "allow").contains("JELQ"));
171
}
172
173
#[tokio::test]
174
async fn patch_only_accepts_the_truth() {
175
    let (app, _) = seeded(Floor::Bedroom);
176
    let patch = [("content-type", "application/json-patch+json")];
177
    let replace = send(
178
        &app,
179
        "PATCH",
180
        "/runs/cafebabe",
181
        &patch,
182
        r#"[{"op":"replace","path":"/length","value":12}]"#,
183
    )
184
    .await;
185
    assert_eq!(replace.status(), StatusCode::UNPROCESSABLE_ENTITY);
186
    let lie = send(
187
        &app,
188
        "PATCH",
189
        "/runs/cafebabe",
190
        &patch,
191
        r#"[{"op":"test","path":"/length","value":40}]"#,
192
    )
193
    .await;
194
    assert_eq!(
195
        json(lie).await["type"],
196
        "https://jelq.dev/problems/exaggeration"
197
    );
198
}
199
200
#[tokio::test]
201
async fn deleting_the_foreskin_requires_certainty() {
202
    let (app, _) = seeded(Floor::Bedroom);
203
    let response = send(&app, "DELETE", "/runs/cafebabe/foreskin", &[], "").await;
204
    assert_eq!(response.status(), StatusCode::PRECONDITION_REQUIRED);
205
    let look = send(&app, "GET", "/runs/cafebabe/foreskin", &[], "").await;
206
    assert_eq!(look.status(), StatusCode::OK);
207
    let etag = header(&look, "etag").to_owned();
208
    assert!(text(look).await.contains('~'));
209
    let response = send(
210
        &app,
211
        "DELETE",
212
        "/runs/cafebabe/foreskin",
213
        &[("if-match", &etag)],
214
        "",
215
    )
216
    .await;
217
    assert_eq!(response.status(), StatusCode::NO_CONTENT);
218
    let response = send(&app, "GET", "/runs/cafebabe/foreskin", &[], "").await;
219
    assert_eq!(response.status(), StatusCode::GONE);
220
}
221
222
#[tokio::test]
223
async fn length_is_chunked_until_the_ruler() {
224
    let (app, _) = seeded(Floor::Bedroom);
225
    let lie = send(&app, "GET", "/runs/cafebabe/length", &[], "").await;
226
    assert!(!lie.headers().contains_key(header::CONTENT_LENGTH));
227
    let app = seeded_with(Floor::Bedroom, |run| run.items.ruler = true);
228
    let truth = send(&app, "GET", "/runs/cafebabe/length", &[], "").await;
229
    let declared: usize = header(&truth, "content-length").parse().unwrap();
230
    let body = text(truth).await;
231
    assert_eq!(body.len(), declared);
232
    assert!(body.starts_with("8=") && body.ends_with('D'));
233
}
234
235
#[tokio::test]
236
async fn length_supports_inch_ranges() {
237
    let (app, _) = seeded(Floor::Bedroom);
238
    let response = send(
239
        &app,
240
        "GET",
241
        "/runs/cafebabe/length",
242
        &[("range", "inches=0-1")],
243
        "",
244
    )
245
    .await;
246
    assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
247
    assert!(header(&response, "content-range").starts_with("inches 0.00-1.00/"));
248
    assert_eq!(text(response).await.len(), 25);
249
    let absurd = send(
250
        &app,
251
        "GET",
252
        "/runs/cafebabe/length",
253
        &[("range", "inches=40-50")],
254
        "",
255
    )
256
    .await;
257
    assert_eq!(absurd.status(), StatusCode::RANGE_NOT_SATISFIABLE);
258
    let malformed = send(
259
        &app,
260
        "GET",
261
        "/runs/cafebabe/length",
262
        &[("range", "inches=6.17")],
263
        "",
264
    )
265
    .await;
266
    assert_eq!(malformed.status(), StatusCode::OK);
267
    let suffix = send(
268
        &app,
269
        "GET",
270
        "/runs/cafebabe/length",
271
        &[("range", "inches=-1")],
272
        "",
273
    )
274
    .await;
275
    assert_eq!(suffix.status(), StatusCode::PARTIAL_CONTENT);
276
    assert!(text(suffix).await.ends_with('D'));
277
    for (range, status) in [
278
        ("inches=1-", StatusCode::PARTIAL_CONTENT),
279
        ("inches=40-", StatusCode::RANGE_NOT_SATISFIABLE),
280
        ("inches=-0", StatusCode::RANGE_NOT_SATISFIABLE),
281
        ("inches=2-1", StatusCode::OK),
282
        ("inches=NaN-2", StatusCode::OK),
283
        ("inches=0-inf", StatusCode::OK),
284
    ] {
285
        let response = send(
286
            &app,
287
            "GET",
288
            "/runs/cafebabe/length",
289
            &[("range", range)],
290
            "",
291
        )
292
        .await;
293
        assert_eq!(response.status(), status, "{range}");
294
    }
295
}
296
297
#[tokio::test]
298
async fn the_clinic_escalates_toward_honesty() {
299
    let (app, _) = seeded(Floor::Clinic);
300
    let mut hints = Vec::new();
301
    for _ in 0..3 {
302
        let response = send(
303
            &app,
304
            "GET",
305
            "/runs/cafebabe/diagnosis",
306
            &[("authorization", "Excuse \"changing\"")],
307
            "",
308
        )
309
        .await;
310
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
311
        hints.push(header(&response, "www-authenticate").to_owned());
312
    }
313
    assert!(hints[2].contains("Be honest."));
314
}
315
316
#[tokio::test]
317
async fn the_true_ending_is_not_modified() {
318
    let (early, _) = seeded(Floor::Bedroom);
319
    let response = send(&early, "GET", "/runs/cafebabe/diagnosis", &[], "").await;
320
    assert_eq!(response.status(), StatusCode::TOO_EARLY);
321
322
    let (app, etag) = seeded(Floor::Clinic);
323
    assert!(
324
        !etag.contains("cafebabe"),
325
        "the origin ETag must not be derivable from the id"
326
    );
327
    let response = send(
328
        &app,
329
        "GET",
330
        "/runs/cafebabe/diagnosis",
331
        &[
332
            ("authorization", "Bearer honesty"),
333
            ("if-none-match", &etag),
334
        ],
335
        "",
336
    )
337
    .await;
338
    assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
339
    assert_eq!(header(&response, "x-diagnosis"), "normal");
340
}
341
342
#[tokio::test]
343
async fn mum_accepts_a_known_excuse() {
344
    let app = seeded_with(Floor::Bedroom, mum_at_the_door);
345
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
346
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
347
    assert_eq!(header(&response, "via"), "1.1 mum");
348
    let response = send(
349
        &app,
350
        "GET",
351
        "/runs/cafebabe",
352
        &[("authorization", "Excuse \"homework\"")],
353
        "",
354
    )
355
    .await;
356
    assert_eq!(response.status(), StatusCode::OK);
357
}
358
359
#[tokio::test]
360
async fn mum_runs_out_of_patience() {
361
    let app = seeded_with(Floor::Bedroom, mum_at_the_door);
362
    let lie = [("authorization", "Excuse \"it is for science\"")];
363
    for _ in 0..2 {
364
        let response = send(&app, "GET", "/runs/cafebabe", &lie, "").await;
365
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
366
    }
367
    let caught = send(&app, "GET", "/runs/cafebabe", &lie, "").await;
368
    assert_eq!(caught.status(), StatusCode::GONE);
369
    assert_eq!(
370
        json(caught).await["type"],
371
        "https://jelq.dev/problems/caught"
372
    );
373
}
374
375
#[tokio::test]
376
async fn mum_remembers_excuses_by_christmas() {
377
    let app = seeded_with(Floor::Nans, |run| {
378
        mum_at_the_door(run);
379
        run.heard.push("homework".into());
380
    });
381
    let basic = send(
382
        &app,
383
        "GET",
384
        "/runs/cafebabe",
385
        &[("authorization", "Excuse \"changing\"")],
386
        "",
387
    )
388
    .await;
389
    assert_eq!(basic.status(), StatusCode::UNAUTHORIZED);
390
    assert!(header(&basic, "www-authenticate").starts_with("Digest"));
391
    let replay = send(
392
        &app,
393
        "GET",
394
        "/runs/cafebabe",
395
        &[(
396
            "authorization",
397
            "Digest username=\"homework\", nonce=\"abc\"",
398
        )],
399
        "",
400
    )
401
    .await;
402
    assert_eq!(
403
        json(replay).await["type"],
404
        "https://jelq.dev/problems/excuse-replayed"
405
    );
406
    let fresh = send(
407
        &app,
408
        "GET",
409
        "/runs/cafebabe",
410
        &[(
411
            "authorization",
412
            "Digest username=\"wrapping presents\", nonce=\"abc\"",
413
        )],
414
        "",
415
    )
416
    .await;
417
    assert_eq!(fresh.status(), StatusCode::OK);
418
}
419
420
#[tokio::test]
421
async fn a_pulled_muscle_is_a_true_excuse() {
422
    let app = seeded_with(Floor::Nans, |run| {
423
        mum_at_the_door(run);
424
        run.conditions.pulled_muscle = true;
425
        run.heard.push("pulled a muscle".into());
426
    });
427
    let response = send(
428
        &app,
429
        "GET",
430
        "/runs/cafebabe",
431
        &[(
432
            "authorization",
433
            "Digest username=\"pulled a muscle\", nonce=\"abc\"",
434
        )],
435
        "",
436
    )
437
    .await;
438
    assert_eq!(response.status(), StatusCode::OK);
439
    assert!(header(&response, "x-stamina").ends_with("/7"));
440
}
441
442
#[tokio::test]
443
async fn floors_end_when_they_end() {
444
    let app = seeded_with(Floor::Bedroom, |_| {});
445
    let early = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
446
    assert_eq!(early.status(), StatusCode::TOO_EARLY);
447
    let app = seeded_with(Floor::Bedroom, |run| run.here.turns = 6);
448
    let next = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
449
    assert!(
450
        next.status() == StatusCode::SEE_OTHER || next.status() == StatusCode::CONFLICT,
451
        "either the floor changed or the zip did"
452
    );
453
}
454
455
#[tokio::test]
456
async fn pump_bro_upsells() {
457
    let closed = seeded_with(Floor::Bedroom, |_| {});
458
    let response = send(&closed, "GET", "/runs/cafebabe/shop", &[], "").await;
459
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
460
461
    let app = seeded_with(Floor::ChangingRoom, |_| {});
462
    let pump = send(&app, "POST", "/runs/cafebabe/shop/pump", &[], "").await;
463
    assert_eq!(pump.status(), StatusCode::UPGRADE_REQUIRED);
464
    assert_eq!(header(&pump, "upgrade"), "pump-pro/2.0");
465
    let pro = send(&app, "POST", "/runs/cafebabe/shop/pump-pro", &[], "").await;
466
    assert_eq!(pro.status(), StatusCode::CREATED);
467
    let broke = send(&app, "POST", "/runs/cafebabe/shop/extender", &[], "").await;
468
    assert_eq!(broke.status(), StatusCode::PAYMENT_REQUIRED);
469
}
470
471
#[tokio::test]
472
async fn only_the_key_opens_the_cage() {
473
    let app = seeded_with(Floor::ChangingRoom, |run| run.items.cage = true);
474
    send(&app, "POST", "/runs/cafebabe/shop/ice-pack", &[], "").await;
475
    let still = send(
476
        &app,
477
        "GET",
478
        "/runs/cafebabe/inventory/chastity-cage",
479
        &[],
480
        "",
481
    )
482
    .await;
483
    assert_eq!(still.status(), StatusCode::OK);
484
    send(&app, "POST", "/runs/cafebabe/shop/cage-key", &[], "").await;
485
    let gone = send(
486
        &app,
487
        "GET",
488
        "/runs/cafebabe/inventory/chastity-cage",
489
        &[],
490
        "",
491
    )
492
    .await;
493
    assert_eq!(gone.status(), StatusCode::NOT_FOUND);
494
}
495
496
#[tokio::test]
497
async fn combos_are_multi_status_xml() {
498
    let app = seeded_with(Floor::Bathroom, |run| {
499
        run.foreskin = Some(1.0);
500
        run.items.blinds = true;
501
    });
502
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
503
    let response = send(
504
        &app,
505
        "JELQ",
506
        "/runs/cafebabe?technique=wet,stretch",
507
        &[("content-type", "application/baby-oil")],
508
        "",
509
    )
510
    .await;
511
    assert_eq!(response.status(), StatusCode::MULTI_STATUS);
512
    assert!(text(response).await.contains("<D:multistatus"));
513
}
514
515
#[tokio::test]
516
async fn the_elder_is_stale() {
517
    let app = seeded_with(Floor::Forum, |run| run.length = 5.0);
518
    let unverified = send(&app, "GET", "/runs/cafebabe/elder", &[], "").await;
519
    assert_eq!(
520
        unverified.status(),
521
        StatusCode::PROXY_AUTHENTICATION_REQUIRED
522
    );
523
    let lie = send(
524
        &app,
525
        "GET",
526
        "/runs/cafebabe/elder",
527
        &[("proxy-authorization", "Ruler 9")],
528
        "",
529
    )
530
    .await;
531
    assert_eq!(lie.status(), StatusCode::BAD_REQUEST);
532
    let csv = send(
533
        &app,
534
        "GET",
535
        "/runs/cafebabe/elder",
536
        &[("proxy-authorization", "Ruler 5.0")],
537
        "",
538
    )
539
    .await;
540
    assert_eq!(csv.status(), StatusCode::OK);
541
    let stale = send(
542
        &app,
543
        "GET",
544
        "/runs/cafebabe/elder",
545
        &[("if-modified-since", "Mon, 15 Jun 2009 00:00:00 GMT")],
546
        "",
547
    )
548
    .await;
549
    assert_eq!(stale.status(), StatusCode::NOT_MODIFIED);
550
}
551
552
#[tokio::test]
553
async fn the_displayed_length_is_accepted_as_honest() {
554
    let app = seeded_with(Floor::Forum, |run| run.length = 5.2496);
555
    let response = send(
556
        &app,
557
        "GET",
558
        "/runs/cafebabe/elder",
559
        &[("proxy-authorization", "Ruler 5.25")],
560
        "",
561
    )
562
    .await;
563
    assert_eq!(response.status(), StatusCode::OK);
564
}
565
566
#[tokio::test]
567
async fn the_hotel_has_a_captive_portal() {
568
    let app = seeded_with(Floor::Hotel, |_| {});
569
    let blocked = send(&app, "GET", "/runs/cafebabe", &[], "").await;
570
    assert_eq!(
571
        blocked.status(),
572
        StatusCode::NETWORK_AUTHENTICATION_REQUIRED
573
    );
574
    let accepted = send(&app, "POST", "/runs/cafebabe/portal", &[], "").await;
575
    assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
576
    let online = send(&app, "GET", "/runs/cafebabe", &[], "").await;
577
    assert_eq!(online.status(), StatusCode::OK);
578
}
579
580
#[tokio::test]
581
async fn the_internet_never_forgets() {
582
    let app = seeded_with(Floor::Bedroom, |run| {
583
        run.filmed_at = Some(std::time::SystemTime::now());
584
    });
585
    let footage = send(&app, "GET", "/runs/cafebabe/footage", &[], "").await;
586
    assert_eq!(footage.status(), StatusCode::OK);
587
    assert_eq!(
588
        header(&footage, "cache-control"),
589
        "public, max-age=31536000, immutable"
590
    );
591
    assert!(footage.headers().contains_key(header::AGE));
592
    let delete = send(&app, "DELETE", "/runs/cafebabe/footage", &[], "").await;
593
    assert_eq!(delete.status(), StatusCode::METHOD_NOT_ALLOWED);
594
    assert!(!header(&delete, "allow").contains("DELETE"));
595
}
596
597
#[tokio::test]
598
async fn forged_ruler_cookies_are_lies() {
599
    let forged = send(
600
        &app(),
601
        "GET",
602
        "/leaderboard?sort=content-length",
603
        &[("cookie", "ruler=1")],
604
        "",
605
    )
606
    .await;
607
    assert_eq!(forged.status(), StatusCode::BAD_REQUEST);
608
}
609
610
#[tokio::test]
611
async fn listings_never_reveal_the_private_id() {
612
    let app = app();
613
    let created = send(&app, "POST", "/runs", &[], "").await;
614
    let location = header(&created, "location").to_owned();
615
    let board = text(send(&app, "GET", "/leaderboard", &[], "").await).await;
616
    let private = location.trim_start_matches("/runs/");
617
    assert!(!board.contains(private));
618
    let entry: Value = serde_json::from_str(&board).unwrap();
619
    let public = entry["entries"][0]["public_id"].as_str().unwrap();
620
    let guess = send(&app, "DELETE", &format!("/runs/{public}"), &[], "").await;
621
    assert_eq!(guess.status(), StatusCode::NOT_FOUND);
622
}
623
624
#[tokio::test]
625
async fn seeded_runs_are_unranked() {
626
    let app = app();
627
    send(&app, "POST", "/runs?seed=7", &[], "").await;
628
    let board = json(send(&app, "GET", "/leaderboard", &[], "").await).await;
629
    assert_eq!(board["entries"].as_array().unwrap().len(), 0);
630
    let all = json(send(&app, "GET", "/leaderboard?seeded=include", &[], "").await).await;
631
    assert_eq!(all["entries"][0]["ranked"], false);
632
}
633
634
#[tokio::test]
635
async fn idle_runs_are_evicted_and_the_server_has_a_limit() {
636
    let forgetful = crate::app(Config {
637
        idle_ttl: Duration::ZERO,
638
        ..Config::default()
639
    });
640
    let first = send(&forgetful, "POST", "/runs", &[], "").await;
641
    let location = header(&first, "location").to_owned();
642
    send(&forgetful, "POST", "/runs", &[], "").await;
643
    let gone = send(&forgetful, "GET", &location, &[], "").await;
644
    assert_eq!(gone.status(), StatusCode::NOT_FOUND);
645
646
    let tiny = crate::app(Config {
647
        max_runs: 1,
648
        ..Config::default()
649
    });
650
    send(&tiny, "POST", "/runs", &[], "").await;
651
    let full = send(&tiny, "POST", "/runs", &[], "").await;
652
    assert_eq!(full.status(), StatusCode::SERVICE_UNAVAILABLE);
653
}
654
655
#[tokio::test]
656
async fn shame_from_two_runs_adds_up() {
657
    let state = Arc::new(AppState::default());
658
    state.insert(fixture());
659
    state.insert(Run::new("deadbeef".into(), "dead".into(), 7));
660
    let app = router(state);
661
    let first = send(&app, "TRACE", "/runs/cafebabe", &[], "").await;
662
    assert_eq!(header(&first, "x-shame"), "1");
663
    let cookie = header(&first, "set-cookie")
664
        .split(';')
665
        .next()
666
        .unwrap()
667
        .to_owned();
668
    let second = send(&app, "TRACE", "/runs/deadbeef", &[("cookie", &cookie)], "").await;
669
    assert_eq!(header(&second, "x-shame"), "2");
670
}
671
672
#[tokio::test]
673
async fn the_root_negotiates() {
674
    let app = app();
675
    let browser = send(&app, "GET", "/", &[("accept", "text/html,*/*")], "").await;
676
    assert_eq!(browser.status(), StatusCode::SEE_OTHER);
677
    assert_eq!(header(&browser, "location"), "/ui/");
678
    let curl = send(&app, "GET", "/", &[("accept", "*/*")], "").await;
679
    assert_eq!(json(curl).await["ui"], "/ui/");
680
    let page = send(&app, "GET", "/ui/", &[], "").await;
681
    assert_eq!(page.status(), StatusCode::OK);
682
}
683
684
#[tokio::test]
685
async fn the_ui_replays_what_browsers_cannot_send() {
686
    let app = app();
687
    let envelope =
688
        r#"{"method": "TRACE", "path": "/graveyard", "headers": [["X-Confession", "I did it"]]}"#;
689
    let traced = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
690
    assert_eq!(traced["status"], 405);
691
    let envelope = r#"{"method": "GET", "path": "/", "headers": [["Accept", "text/html"]]}"#;
692
    let redirected = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
693
    assert_eq!(redirected["status"], 303);
694
    assert_eq!(redirected["reason"], "See Other");
695
}
696
697
#[tokio::test]
698
async fn the_ui_decodes_gzip_for_display() {
699
    let app = seeded_with(Floor::Bedroom, |run| run.items.ring = true);
700
    let envelope =
701
        r#"{"method": "GET", "path": "/runs/cafebabe", "headers": [["Accept-Encoding", "gzip"]]}"#;
702
    let shown = json(send(&app, "POST", "/ui/send", &[], envelope).await).await;
703
    assert!(
704
        shown["body"]
705
            .as_str()
706
            .unwrap()
707
            .contains("\"public_id\":\"cafe\"")
708
    );
709
    let encoding = shown["headers"]
710
        .as_array()
711
        .unwrap()
712
        .iter()
713
        .any(|h| h[0] == "content-encoding" && h[1] == "gzip");
714
    assert!(encoding);
715
}
716
717
#[tokio::test]
718
async fn http_1_0_gets_the_pdf_treatment() {
719
    let request = Request::builder()
720
        .uri("/graveyard")
721
        .version(Version::HTTP_10)
722
        .body(Body::empty())
723
        .unwrap();
724
    let response = app().oneshot(request).await.unwrap();
725
    assert_eq!(response.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
726
}
727
728
#[tokio::test]
729
async fn mom_speaks_american() {
730
    let app = seeded_with(Floor::Nans, mum_at_the_door);
731
    let us = [("accept-language", "en-US")];
732
    let knock = send(&app, "GET", "/runs/cafebabe", &us, "").await;
733
    assert_eq!(header(&knock, "content-language"), "en-US");
734
    assert_eq!(header(&knock, "via"), "1.1 mom");
735
    assert!(
736
        json(knock).await["detail"]
737
            .as_str()
738
            .unwrap()
739
            .contains("Someone is at the door.")
740
    );
741
    let excuse = [
742
        ("accept-language", "en-US"),
743
        (
744
            "authorization",
745
            "Digest username=\"carving the turkey\", nonce=\"abc\"",
746
        ),
747
    ];
748
    let answered = send(&app, "GET", "/runs/cafebabe", &excuse, "").await;
749
    assert_eq!(answered.status(), StatusCode::OK);
750
    let floor = json(send(&app, "GET", "/runs/cafebabe/floor", &us, "").await).await;
751
    assert_eq!(floor["name"], "Grandma's house for Thanksgiving");
752
}
753
754
#[tokio::test]
755
async fn the_default_locale_is_british() {
756
    let (app, _) = seeded(Floor::Nans);
757
    let floor = send(&app, "GET", "/runs/cafebabe/floor", &[], "").await;
758
    assert_eq!(header(&floor, "content-language"), "en-GB");
759
    assert!(header(&floor, "vary").contains("Accept-Language"));
760
    assert_eq!(json(floor).await["name"], "Nan's house at Christmas");
761
}
762
763
fn advertised(response: &Response) -> Vec<String> {
764
    header(response, "link")
765
        .split(", <")
766
        .filter(|entry| entry.contains("rels/technique"))
767
        .filter_map(|entry| {
768
            entry
769
                .split("title=\"")
770
                .nth(1)?
771
                .split('"')
772
                .next()
773
                .map(str::to_owned)
774
        })
775
        .collect()
776
}
777
778
#[tokio::test]
779
async fn links_offer_only_usable_techniques() {
780
    let app = seeded_with(Floor::Bedroom, |run| run.foreskin = Some(1.0));
781
    let cold = send(&app, "GET", "/runs/cafebabe", &[], "").await;
782
    assert_eq!(advertised(&cold), ["warmup", "ice"]);
783
    let warm = send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
784
    let usable = advertised(&warm);
785
    assert!(usable.contains(&"wet".to_owned()) && usable.contains(&"dry".to_owned()));
786
    assert!(!usable.contains(&"uli".to_owned()), "uli needs the forum");
787
    assert!(!usable.contains(&"pump".to_owned()), "pump needs a pump");
788
    assert!(
789
        header(&warm, "link").contains("title=\"wet\"; allow=\"JELQ\"; lubricant=\"required\"")
790
    );
791
792
    let (forum, _) = seeded(Floor::Forum);
793
    let response = send(&forum, "GET", "/runs/cafebabe", &[], "").await;
794
    assert!(advertised(&response).is_empty());
795
}
796
797
fn linked_rels(response: &Response) -> Vec<String> {
798
    header(response, "link")
799
        .split(", <")
800
        .filter_map(|entry| {
801
            entry
802
                .split("rels/")
803
                .nth(1)?
804
                .split('"')
805
                .next()
806
                .map(str::to_owned)
807
        })
808
        .filter(|rel| rel != "technique")
809
        .collect()
810
}
811
812
#[tokio::test]
813
async fn links_hide_resources_that_would_do_nothing() {
814
    let (bedroom, _) = seeded(Floor::Bedroom);
815
    let before = linked_rels(&send(&bedroom, "GET", "/runs/cafebabe", &[], "").await);
816
    assert!(before.contains(&"drawer".to_owned()));
817
    assert!(!before.contains(&"diagnosis".to_owned()));
818
    assert!(!before.contains(&"thread".to_owned()));
819
    let searched = send(&bedroom, "POST", "/runs/cafebabe/drawer", &[], "").await;
820
    assert!(!linked_rels(&searched).contains(&"drawer".to_owned()));
821
822
    let (clinic, _) = seeded(Floor::Clinic);
823
    let rels = linked_rels(&send(&clinic, "GET", "/runs/cafebabe", &[], "").await);
824
    assert!(rels.contains(&"diagnosis".to_owned()) && rels.contains(&"thread".to_owned()));
825
}
826
827
#[tokio::test]
828
async fn ignoring_mum_has_consequences() {
829
    let app = seeded_with(Floor::Bedroom, |run| {
830
        mum_at_the_door(run);
831
        run.here.turns = 6;
832
    });
833
    let knock = send(&app, "GET", "/runs/cafebabe", &[], "").await;
834
    assert_eq!(
835
        json(knock).await["type"],
836
        "https://jelq.dev/problems/someone-at-the-door"
837
    );
838
    let leave = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
839
    assert_eq!(
840
        leave.status(),
841
        StatusCode::UNAUTHORIZED,
842
        "no leaving with Mum at the door"
843
    );
844
    send(&app, "GET", "/runs/cafebabe", &[], "").await;
845
    let opened = send(&app, "GET", "/runs/cafebabe", &[], "").await;
846
    assert_eq!(opened.status(), StatusCode::GONE);
847
    assert_eq!(
848
        json(opened).await["type"],
849
        "https://jelq.dev/problems/opened"
850
    );
851
}
852
853
#[tokio::test]
854
async fn caged_drawers_are_noisy_and_eventually_give_up_the_key() {
855
    let app = seeded_with(Floor::ChangingRoom, |run| run.items.cage = true);
856
    let mut statuses = Vec::new();
857
    for _ in 0..12 {
858
        let response = send(&app, "POST", "/runs/cafebabe/drawer", &[], "").await;
859
        statuses.push(response.status());
860
        if response.status() == StatusCode::OK {
861
            break;
862
        }
863
    }
864
    assert_eq!(statuses.last(), Some(&StatusCode::OK), "{statuses:?}");
865
    assert!(
866
        statuses[..statuses.len() - 1]
867
            .iter()
868
            .all(|s| *s == StatusCode::NO_CONTENT)
869
    );
870
}
871
872
#[tokio::test]
873
async fn the_ruler_replaces_the_self_report() {
874
    let app = seeded_with(Floor::Bedroom, |_| {});
875
    let before = send(&app, "GET", "/runs/cafebabe", &[], "").await;
876
    assert!(before.headers().contains_key("x-self-reported-length"));
877
    assert!(!before.headers().contains_key("x-length"));
878
879
    let app = seeded_with(Floor::Bedroom, |run| run.items.ruler = true);
880
    let after = send(&app, "GET", "/runs/cafebabe", &[], "").await;
881
    assert!(!after.headers().contains_key("x-self-reported-length"));
882
    assert!(after.headers().contains_key("x-length"));
883
}
884
885
#[tokio::test]
886
async fn an_open_tab_is_linked_and_jelq_still_answers_with_choices() {
887
    let app = seeded_with(Floor::Bathroom, |run| {
888
        run.story = Story::Pending;
889
        run.warmed_up = true;
890
    });
891
    let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
892
    let links = header(&response, "link");
893
    assert!(links.contains("/branches/forum>; rel=\"https://jelq.dev/rels/branch\""));
894
    assert!(links.contains("/branches/close-tab>; rel=\"https://jelq.dev/rels/branch\""));
895
    assert!(links.contains("?technique=wet>"));
896
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=edge", &[], "").await;
897
    assert_eq!(jelq.status(), StatusCode::MULTIPLE_CHOICES);
898
}
899
900
#[tokio::test]
901
async fn either_story_choice_is_reachable_during_cooldown() {
902
    for choice in ["forum", "close-tab"] {
903
        let app = seeded_with(Floor::Bathroom, |run| {
904
            run.turn = 9;
905
            run.warmed_up = true;
906
            run.stamina = 1;
907
            run.items.door_locks = 1;
908
        });
909
        let tenth = send(&app, "JELQ", "/runs/cafebabe?technique=edge", &[], "").await;
910
        assert_eq!(tenth.status(), StatusCode::OK);
911
        let response = send(&app, "GET", "/runs/cafebabe", &[], "").await;
912
        assert!(!header(&response, "link").contains("?technique="));
913
        let path = format!("/runs/cafebabe/branches/{choice}");
914
        assert!(
915
            header(&response, "link")
916
                .contains(&format!("<{path}>; rel=\"https://jelq.dev/rels/branch\""))
917
        );
918
        let chosen = send(&app, "POST", &path, &[], "").await;
919
        assert_eq!(chosen.status(), StatusCode::SEE_OTHER);
920
        assert!(!header(&chosen, "link").contains("/branches/"));
921
        let repeated = send(&app, "POST", &path, &[], "").await;
922
        assert_eq!(repeated.status(), StatusCode::CONFLICT);
923
    }
924
}
925
926
#[tokio::test]
927
async fn a_door_lock_says_when_it_was_used() {
928
    let app = seeded_with(Floor::Bathroom, |run| {
929
        run.items.door_locks = 1;
930
        run.suspicion = SUSPICION_LIMIT;
931
        run.warmed_up = true;
932
    });
933
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
934
    assert_ne!(response.status(), StatusCode::CONFLICT);
935
    assert!(
936
        response
937
            .headers()
938
            .get_all("warning")
939
            .iter()
940
            .any(|w| w.to_str().unwrap().contains("your brother tried the door"))
941
    );
942
}
943
944
#[tokio::test]
945
async fn shopping_survives_browsing_but_not_jelqing() {
946
    let app = seeded_with(Floor::ChangingRoom, |run| run.cash = 50);
947
    send(&app, "GET", "/runs/cafebabe/shop", &[], "").await;
948
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
949
    assert!(header(&view, "link").contains("shop-item"));
950
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
951
    assert_ne!(jelq.status(), StatusCode::METHOD_NOT_ALLOWED);
952
    let after = send(&app, "GET", "/runs/cafebabe", &[], "").await;
953
    assert!(!header(&after, "link").contains("shop-item"));
954
}
955
956
#[tokio::test]
957
async fn the_thread_announces_itself_at_the_branch() {
958
    let app = seeded_with(Floor::Bathroom, |run| {
959
        run.turn = 8;
960
        run.warmed_up = true;
961
        run.items.baby_oil = 9;
962
    });
963
    send(
964
        &app,
965
        "JELQ",
966
        "/runs/cafebabe?technique=wet",
967
        &[("content-type", "application/baby-oil")],
968
        "",
969
    )
970
    .await;
971
    let ninth = send(&app, "GET", "/runs/cafebabe", &[], "").await;
972
    assert!(!header(&ninth, "link").contains("/forum/threads/2009"));
973
    let tenth = send(
974
        &app,
975
        "JELQ",
976
        "/runs/cafebabe?technique=wet",
977
        &[("content-type", "application/baby-oil")],
978
        "",
979
    )
980
    .await;
981
    assert!(
982
        tenth
983
            .headers()
984
            .get_all("warning")
985
            .iter()
986
            .any(|w| w.to_str().unwrap().contains("a forum thread from 2009"))
987
    );
988
    assert!(header(&tenth, "link").contains("/forum/threads/2009"));
989
    let announced = send(&app, "GET", "/runs/cafebabe", &[], "").await;
990
    assert!(header(&announced, "link").contains("/forum/threads/2009"));
991
}
992
993
#[tokio::test]
994
async fn reading_the_forum_may_teach_meditation() {
995
    let taught = (0..50u64)
996
        .filter(|seed| {
997
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
998
            run.story = Story::Pending;
999
            run.turn = BRANCH_TURN;
1000
            run.choose("forum").is_ok() && run.meditation_taught
1001
        })
1002
        .count();
1003
    assert!(
1004
        taught > 0 && taught < 50,
1005
        "the teach roll should be a coin, it landed {taught}/50"
1006
    );
1007
}
1008
1009
#[tokio::test]
1010
async fn meditation_is_free_but_only_once_per_floor() {
1011
    let app = seeded_with(Floor::Bedroom, |run| run.meditation_taught = true);
1012
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1013
    assert_eq!(response.status(), StatusCode::OK);
1014
    assert_eq!(header(&response, "x-eq"), "10");
1015
    assert_eq!(header(&response, "x-stamina"), "10/10");
1016
    let again = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1017
    assert_eq!(again.status(), StatusCode::CONFLICT);
1018
}
1019
1020
#[tokio::test]
1021
async fn meditation_stays_hidden_until_the_forum_teaches_it() {
1022
    let app = seeded_with(Floor::Bedroom, |_| {});
1023
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1024
    assert!(!header(&view, "link").contains("technique=meditate"));
1025
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1026
    assert_eq!(jelq.status(), StatusCode::FORBIDDEN);
1027
}
1028
1029
fn app_with(floor: Floor, seed: u64, setup: impl FnOnce(&mut Run)) -> Router {
1030
    let state = Arc::new(AppState::default());
1031
    let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1032
    run.floor = floor;
1033
    setup(&mut run);
1034
    state.insert(run);
1035
    router(state)
1036
}
1037
1038
#[tokio::test]
1039
async fn hold_is_offered_only_at_the_edges() {
1040
    let calm = seeded_with(Floor::Bedroom, |_| {});
1041
    let refused = send(&calm, "HOLD", "/runs/cafebabe", &[], "").await;
1042
    assert_eq!(refused.status(), StatusCode::METHOD_NOT_ALLOWED);
1043
    assert!(!header(&refused, "allow").contains("HOLD"));
1044
    let view = send(&calm, "GET", "/runs/cafebabe", &[], "").await;
1045
    assert!(!header(&view, "link").contains("HOLD"));
1046
    let options = send(&calm, "OPTIONS", "/runs/cafebabe", &[], "").await;
1047
    assert!(!header(&options, "allow").contains("HOLD"));
1048
1049
    let winded = seeded_with(Floor::Bedroom, |run| run.stamina = 2);
1050
    let listed = send(&winded, "GET", "/runs/cafebabe", &[], "").await;
1051
    assert!(header(&listed, "link").contains("HOLD"));
1052
    let options = send(&winded, "OPTIONS", "/runs/cafebabe", &[], "").await;
1053
    assert!(header(&options, "allow").contains("HOLD"));
1054
1055
    let hot = seeded_with(Floor::Bedroom, |run| {
1056
        run.eq = 75;
1057
        run.warmed_up = true;
1058
    });
1059
    let held = send(&hot, "HOLD", "/runs/cafebabe", &[], "").await;
1060
    assert_eq!(held.status(), StatusCode::NO_CONTENT);
1061
    assert_eq!(header(&held, "x-stamina"), "10/10");
1062
}
1063
1064
#[tokio::test]
1065
async fn holding_calms_and_sometimes_reflects() {
1066
    let calmed = (0..60u64)
1067
        .filter(|seed| {
1068
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1069
            run.eq = 75;
1070
            run.hold(Instant::now()).is_ok() && run.eq == 60
1071
        })
1072
        .count();
1073
    let reflected = (0..60u64)
1074
        .filter(|seed| {
1075
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1076
            run.eq = 75;
1077
            run.hold(Instant::now()).is_ok() && run.eq == 0
1078
        })
1079
        .count();
1080
    assert!(
1081
        calmed > 40 && reflected > 0 && calmed + reflected == 60,
1082
        "one HOLD in twelve should reflect, got {calmed} calm and {reflected} reflective of 60"
1083
    );
1084
}
1085
1086
#[tokio::test]
1087
async fn leaving_the_band_warms_the_next_floor() {
1088
    let app = seeded_with(Floor::Bedroom, |run| {
1089
        run.eq = 60;
1090
        run.warmed_up = true;
1091
        run.here.turns = 6;
1092
        run.items.baby_oil = 9;
1093
    });
1094
    let left = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
1095
    assert_eq!(left.status(), StatusCode::SEE_OTHER);
1096
    let detail = json(left).await["detail"].as_str().unwrap().to_owned();
1097
    assert!(detail.contains("the warmth came with you"));
1098
1099
    let lube = [("content-type", "application/baby-oil")];
1100
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
1101
    // The shower is a +35 warm-up, so EQ lands in the band and the band bonus rides along.
1102
    // The arrival bonus is the one point the second jelq loses.
1103
    let first = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1104
    assert!(
1105
        header(&first, "server-timing").contains("d20+4"),
1106
        "the first jelq of a warm arrival rolls with +1, got {}",
1107
        header(&first, "server-timing")
1108
    );
1109
    let second = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1110
    assert!(header(&second, "server-timing").contains("d20+3"));
1111
}
1112
1113
#[tokio::test]
1114
async fn greed_multiplies_gains_above_the_band() {
1115
    let lube = [("content-type", "application/baby-oil")];
1116
    for seed in 0..60u64 {
1117
        let app = app_with(Floor::Bedroom, seed, |run| {
1118
            run.eq = 60;
1119
            run.warmed_up = true;
1120
        });
1121
        let in_band = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1122
        let app = app_with(Floor::Bedroom, seed, |run| {
1123
            run.eq = 75;
1124
            run.warmed_up = true;
1125
        });
1126
        let greedy = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1127
        if in_band.status() != StatusCode::OK || greedy.status() != StatusCode::OK {
1128
            continue;
1129
        }
1130
        let steady = json(in_band).await["length"].as_f64().unwrap();
1131
        let eager = json(greedy).await["length"].as_f64().unwrap();
1132
        assert!(
1133
            (eager - steady * 1.5).abs() < 1e-9,
1134
            "seed {seed} gained {eager} above the band against {steady} inside it"
1135
        );
1136
        return;
1137
    }
1138
    panic!("no seed in 60 produced two clean rolls to compare");
1139
}
1140
1141
#[tokio::test]
1142
async fn the_kitchen_is_only_on_the_home_floors() {
1143
    let absent = seeded_with(Floor::Bathroom, |_| {});
1144
    let no_kitchen = send(&absent, "POST", "/runs/cafebabe/kitchen", &[], "").await;
1145
    assert_eq!(no_kitchen.status(), StatusCode::NOT_FOUND);
1146
    let view = send(&absent, "GET", "/runs/cafebabe", &[], "").await;
1147
    assert!(!header(&view, "link").contains("/kitchen"));
1148
1149
    let app = seeded_with(Floor::Bedroom, |_| {});
1150
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1151
    assert!(header(&view, "link").contains("/kitchen"));
1152
    let raid = send(&app, "POST", "/runs/cafebabe/kitchen", &[], "").await;
1153
    assert_ne!(raid.status(), StatusCode::NOT_FOUND);
1154
}
1155
1156
#[tokio::test]
1157
async fn raids_cost_the_turn_and_the_fridge_pays_out_sometimes() {
1158
    let mut bounties = std::collections::BTreeSet::new();
1159
    let mut told = 0;
1160
    for seed in 0..80u64 {
1161
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1162
        let Ok(outcome) = run.raid_kitchen() else {
1163
            panic!("the first raid should never fail");
1164
        };
1165
        assert_eq!(run.turn, 1, "a raid costs the floor turn");
1166
        assert!(!run.here.melon_offered, "no melon at starting EQ");
1167
        if outcome.status == StatusCode::NO_CONTENT {
1168
            bounties.insert("empty");
1169
        } else {
1170
            bounties.insert("loot");
1171
        }
1172
        told += u32::from(run.kitchen_tellings);
1173
    }
1174
    assert!(bounties.contains("loot") && bounties.contains("empty"));
1175
    assert!(
1176
        (0..80).any(|seed| {
1177
            let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1178
            run.raid_kitchen().is_ok() && run.kitchen_tellings == 0
1179
        }),
1180
        "most raids go unremarked"
1181
    );
1182
    assert!(told > 0, "someone should have been told across 80 raids");
1183
}
1184
1185
#[tokio::test]
1186
async fn the_watermelon_offers_itself_above_ninety() {
1187
    let mut offered = 0;
1188
    let mut caught = 0;
1189
    let mut survived = 0;
1190
    for seed in 0..120u64 {
1191
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1192
        run.eq = 95;
1193
        let Ok(outcome) = run.raid_kitchen() else {
1194
            continue;
1195
        };
1196
        if outcome.status != StatusCode::MULTIPLE_CHOICES {
1197
            continue;
1198
        }
1199
        offered += 1;
1200
        let gains = run.length;
1201
        let disgrace = run.shame;
1202
        if run.commit_melon().is_err() {
1203
            caught += 1;
1204
            assert_eq!(run.ended.as_ref().unwrap().cause.slug(), "watermelon");
1205
        } else {
1206
            survived += 1;
1207
            assert_eq!(run.eq, 0);
1208
            assert_eq!(run.shame, disgrace + 5);
1209
            assert_eq!(run.length, gains, "the gains are kept");
1210
        }
1211
    }
1212
    assert!(
1213
        offered > 20,
1214
        "the melon should appear in two fifths of raids"
1215
    );
1216
    assert!(caught > 0 && survived > 0, "caught is one in three");
1217
}
1218
1219
#[tokio::test]
1220
async fn the_kitchen_closes_after_two_tellings() {
1221
    let mut closed = None;
1222
    for seed in 0..300u64 {
1223
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1224
        let first = run.raid_kitchen();
1225
        let second = run.raid_kitchen();
1226
        if second.is_err() && first.is_ok() {
1227
            assert_eq!(run.kitchen_tellings, 2);
1228
            let Err(third) = run.raid_kitchen() else {
1229
                panic!("the kitchen should be gone");
1230
            };
1231
            assert_eq!(third.status(), StatusCode::GONE);
1232
            closed = Some(seed);
1233
            break;
1234
        }
1235
    }
1236
    assert!(
1237
        closed.is_some(),
1238
        "two tellings should occur within 300 seeds"
1239
    );
1240
}
1241
1242
#[tokio::test]
1243
async fn lubes_run_out_but_spit_never_does() {
1244
    let app = seeded_with(Floor::Bedroom, |run| {
1245
        run.warmed_up = true;
1246
        run.items.baby_oil = 1;
1247
    });
1248
    let lube = [("content-type", "application/baby-oil")];
1249
    let first = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1250
    assert_ne!(first.status(), StatusCode::PRECONDITION_FAILED);
1251
    let second = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1252
    assert_eq!(second.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
1253
1254
    let spit = [("content-type", "text/plain; charset=spit")];
1255
    for _ in 0..3 {
1256
        let wet = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &spit, "").await;
1257
        assert_ne!(wet.status(), StatusCode::PRECONDITION_FAILED);
1258
    }
1259
}
1260
1261
#[tokio::test]
1262
async fn energy_drinks_add_three_stamina() {
1263
    let app = seeded_with(Floor::Bedroom, |run| {
1264
        run.stamina = 2;
1265
        run.items.energy_drinks = 1;
1266
    });
1267
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1268
    assert!(header(&view, "link").contains("technique=energy"));
1269
    let drink = send(&app, "JELQ", "/runs/cafebabe?technique=energy", &[], "").await;
1270
    assert_eq!(drink.status(), StatusCode::OK);
1271
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1272
    assert_eq!(header(&view, "x-stamina"), "5/10");
1273
    let again = send(&app, "JELQ", "/runs/cafebabe?technique=energy", &[], "").await;
1274
    assert_eq!(again.status(), StatusCode::FAILED_DEPENDENCY);
1275
}
1276
1277
#[tokio::test]
1278
async fn the_working_supplement_resets_stamina() {
1279
    let mut worked = 0;
1280
    let mut bunk = 0;
1281
    for seed in 0..60u64 {
1282
        let app = app_with(Floor::Bedroom, seed, |run| {
1283
            run.stamina = 1;
1284
            run.items.supplements = 1;
1285
        });
1286
        let taken = send(&app, "JELQ", "/runs/cafebabe?technique=supplement", &[], "").await;
1287
        if taken.status() == StatusCode::OK {
1288
            worked += 1;
1289
            let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1290
            assert_eq!(header(&view, "x-stamina"), "10/10");
1291
        } else {
1292
            assert_eq!(taken.status(), StatusCode::BAD_GATEWAY);
1293
            bunk += 1;
1294
        }
1295
    }
1296
    assert!(worked > 0 && bunk > 0, "one in five should work too well");
1297
}
1298
1299
#[tokio::test]
1300
async fn dry_jelqs_build_friction_and_real_lube_does_not() {
1301
    let app = seeded_with(Floor::Bedroom, |run| {
1302
        run.warmed_up = true;
1303
    });
1304
    let dry = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
1305
    assert_eq!(header(&dry, "x-friction"), "2/10");
1306
    let lube = [("content-type", "application/baby-oil")];
1307
    let wet = send(
1308
        &app,
1309
        "JELQ",
1310
        "/runs/cafebabe?technique=wet&intensity=5",
1311
        &lube,
1312
        "",
1313
    )
1314
    .await;
1315
    assert_eq!(header(&wet, "x-friction"), "2/10");
1316
    let spit = [("content-type", "text/plain; charset=spit")];
1317
    let glisten = send(
1318
        &app,
1319
        "JELQ",
1320
        "/runs/cafebabe?technique=wet&intensity=5",
1321
        &spit,
1322
        "",
1323
    )
1324
    .await;
1325
    assert_eq!(header(&glisten, "x-friction"), "3/10");
1326
}
1327
1328
#[tokio::test]
1329
async fn switching_grips_makes_the_friction_cheaper() {
1330
    let app = seeded_with(Floor::Bedroom, |run| {
1331
        run.warmed_up = true;
1332
    });
1333
    let dry = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
1334
    assert_eq!(header(&dry, "x-friction"), "2/10");
1335
    send(
1336
        &app,
1337
        "GET",
1338
        "/runs/cafebabe/grip",
1339
        &[("upgrade", "underhand"), ("connection", "upgrade")],
1340
        "",
1341
    )
1342
    .await;
1343
    let switched = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
1344
    assert_eq!(header(&switched, "x-friction"), "3/10");
1345
    let settled = send(&app, "JELQ", "/runs/cafebabe?technique=dry", &[], "").await;
1346
    assert_eq!(header(&settled, "x-friction"), "5/10");
1347
}
1348
1349
#[tokio::test]
1350
async fn holding_and_meditating_shed_friction() {
1351
    let app = seeded_with(Floor::Bedroom, |run| {
1352
        run.eq = 80;
1353
        run.friction = 5;
1354
    });
1355
    let held = send(&app, "HOLD", "/runs/cafebabe", &[], "").await;
1356
    assert_eq!(held.status(), StatusCode::NO_CONTENT);
1357
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1358
    assert_eq!(header(&view, "x-friction"), "3/10");
1359
1360
    let taught = seeded_with(Floor::Bedroom, |run| {
1361
        run.meditation_taught = true;
1362
        run.friction = 5;
1363
    });
1364
    let calmed = send(
1365
        &taught,
1366
        "JELQ",
1367
        "/runs/cafebabe?technique=meditate",
1368
        &[],
1369
        "",
1370
    )
1371
    .await;
1372
    assert_eq!(calmed.status(), StatusCode::OK);
1373
    let view = send(&taught, "GET", "/runs/cafebabe", &[], "").await;
1374
    assert_eq!(header(&view, "x-friction"), "3/10");
1375
}
1376
1377
#[tokio::test]
1378
async fn a_friction_burn_halves_the_gains() {
1379
    let lube = [("content-type", "application/baby-oil")];
1380
    let path = "/runs/cafebabe?technique=wet&intensity=5";
1381
    for seed in 0..60u64 {
1382
        let steady = app_with(Floor::Bedroom, seed, |run| {
1383
            run.warmed_up = true;
1384
            run.eq = 60;
1385
            run.items.baby_oil = 9;
1386
        });
1387
        let hurt_app = app_with(Floor::Bedroom, seed, |run| {
1388
            run.warmed_up = true;
1389
            run.eq = 60;
1390
            run.items.baby_oil = 9;
1391
            run.conditions.friction_burn = true;
1392
        });
1393
        let calm = send(&steady, "JELQ", path, &lube, "").await;
1394
        let hurt = send(&hurt_app, "JELQ", path, &lube, "").await;
1395
        if calm.status() != StatusCode::OK || hurt.status() != StatusCode::OK {
1396
            continue;
1397
        }
1398
        let calm_gain = json(calm).await["length"].as_f64().unwrap();
1399
        let hurt_gain = json(hurt).await["length"].as_f64().unwrap();
1400
        assert!(
1401
            (hurt_gain * 2.0 - calm_gain).abs() < 1e-9,
1402
            "seed {seed} burned {hurt_gain} against {calm_gain}"
1403
        );
1404
        return;
1405
    }
1406
    panic!("no seed in 60 produced two clean rolls to compare");
1407
}
1408
1409
#[tokio::test]
1410
async fn the_burn_warns_and_the_ice_treats_it() {
1411
    let app = seeded_with(Floor::Bedroom, |run| {
1412
        run.warmed_up = true;
1413
        run.eq = 60;
1414
        run.items.baby_oil = 9;
1415
        run.friction = 7;
1416
        run.conditions.friction_burn = true;
1417
    });
1418
    let lube = [("content-type", "application/baby-oil")];
1419
    let jelq = send(
1420
        &app,
1421
        "JELQ",
1422
        "/runs/cafebabe?technique=wet&intensity=5",
1423
        &lube,
1424
        "",
1425
    )
1426
    .await;
1427
    let warnings: Vec<_> = jelq
1428
        .headers()
1429
        .get_all("warning")
1430
        .iter()
1431
        .filter_map(|w| w.to_str().ok())
1432
        .collect();
1433
    assert!(warnings.contains(&"199 - \"friction burn\""));
1434
    send(&app, "JELQ", "/runs/cafebabe?technique=ice", &[], "").await;
1435
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1436
    let warnings: Vec<_> = view
1437
        .headers()
1438
        .get_all("warning")
1439
        .iter()
1440
        .filter_map(|w| w.to_str().ok())
1441
        .collect();
1442
    assert!(!warnings.contains(&"199 - \"friction burn\""));
1443
}
1444
1445
#[tokio::test]
1446
async fn the_burn_shifts_the_rupture_tiers() {
1447
    async fn ruptures(burned: bool) -> u32 {
1448
        let mut gone = 0;
1449
        for seed in 0..400u64 {
1450
            let app = app_with(Floor::Bedroom, seed, |run| {
1451
                run.warmed_up = true;
1452
                run.eq = 60;
1453
                run.items.baby_oil = 9;
1454
                run.conditions.friction_burn = burned;
1455
            });
1456
            let lube = [("content-type", "application/baby-oil")];
1457
            let jelq = send(
1458
                &app,
1459
                "JELQ",
1460
                "/runs/cafebabe?technique=wet&intensity=5",
1461
                &lube,
1462
                "",
1463
            )
1464
            .await;
1465
            if jelq.status() == StatusCode::INTERNAL_SERVER_ERROR {
1466
                gone += 1;
1467
            }
1468
        }
1469
        gone
1470
    }
1471
    let burned = ruptures(true).await;
1472
    let calm = ruptures(false).await;
1473
    assert!(
1474
        burned >= 8 && calm <= 4,
1475
        "burned {burned} ruptures against {calm}"
1476
    );
1477
}
1478
1479
#[tokio::test]
1480
async fn meditation_respects_the_priapism_floor() {
1481
    let app = seeded_with(Floor::Bedroom, |run| {
1482
        run.meditation_taught = true;
1483
        run.eq = 80;
1484
        run.conditions.priapism_turns = 3;
1485
    });
1486
    let calmed = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1487
    assert_eq!(calmed.status(), StatusCode::OK);
1488
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1489
    assert_eq!(header(&view, "x-eq"), "75");
1490
}
1491
1492
#[tokio::test]
1493
async fn the_kitchen_pays_out_at_the_documented_odds() {
1494
    let mut oil = 0;
1495
    let mut drinks = 0;
1496
    let mut packs = 0;
1497
    for seed in 0..600u64 {
1498
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1499
        run.kitchen_tellings = 0;
1500
        let held = (
1501
            run.items.coconut_oil,
1502
            run.items.energy_drinks,
1503
            run.items.ice_packs,
1504
        );
1505
        let _ = run.raid_kitchen();
1506
        oil += u32::from(run.items.coconut_oil > held.0);
1507
        drinks += u32::from(run.items.energy_drinks > held.1);
1508
        packs += u32::from(run.items.ice_packs > held.2);
1509
    }
1510
    assert!((170..=230).contains(&oil), "coconut {oil} in 600");
1511
    assert!((90..=150).contains(&drinks), "energy {drinks} in 600");
1512
    assert!((45..=105).contains(&packs), "ice {packs} in 600");
1513
}
1514
1515
#[tokio::test]
1516
async fn a_refused_jelq_leaves_the_lube_alone() {
1517
    let app = seeded_with(Floor::Bedroom, |run| {
1518
        run.warmed_up = true;
1519
        run.items.extender = true;
1520
        run.girth = STORAGE_GIRTH + 1.0;
1521
    });
1522
    let lube = [("content-type", "application/baby-oil")];
1523
    let full = send(
1524
        &app,
1525
        "JELQ",
1526
        "/runs/cafebabe?technique=wet&intensity=5",
1527
        &lube,
1528
        "",
1529
    )
1530
    .await;
1531
    assert_eq!(full.status(), StatusCode::INSUFFICIENT_STORAGE);
1532
    let inv = send(&app, "GET", "/runs/cafebabe/inventory", &[], "").await;
1533
    let body = json(inv).await;
1534
    let held = body["items"].as_array().unwrap();
1535
    assert!(held.iter().any(|i| i["name"] == "baby-oil"));
1536
}
1537
1538
#[tokio::test]
1539
async fn an_empty_bottle_is_declined_before_the_enemy_stirs() {
1540
    let control = seeded_with(Floor::ChangingRoom, |run| {
1541
        run.warmed_up = true;
1542
        run.suspicion = SUSPICION_LIMIT;
1543
    });
1544
    let lube = [("content-type", "application/baby-oil")];
1545
    let caught = send(
1546
        &control,
1547
        "JELQ",
1548
        "/runs/cafebabe?technique=wet&intensity=5",
1549
        &lube,
1550
        "",
1551
    )
1552
    .await;
1553
    assert_eq!(caught.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
1554
1555
    let app = seeded_with(Floor::ChangingRoom, |run| {
1556
        run.warmed_up = true;
1557
        run.suspicion = SUSPICION_LIMIT;
1558
        run.items.baby_oil = 0;
1559
    });
1560
    let refused = send(
1561
        &app,
1562
        "JELQ",
1563
        "/runs/cafebabe?technique=wet&intensity=5",
1564
        &lube,
1565
        "",
1566
    )
1567
    .await;
1568
    assert_eq!(refused.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
1569
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1570
    assert_eq!(header(&view, "x-suspicion"), "5/5");
1571
    assert_eq!(header(&view, "x-shame"), "0");
1572
}
1573
1574
#[tokio::test]
1575
async fn the_top_tier_rolls_a_single_third() {
1576
    let mut ruptures = 0;
1577
    let mut early = 0;
1578
    for seed in 0..400u64 {
1579
        let app = app_with(Floor::Bedroom, seed, |run| {
1580
            run.warmed_up = true;
1581
            run.eq = 96;
1582
            run.items.baby_oil = 9;
1583
            run.items.blinds = true;
1584
        });
1585
        let lube = [("content-type", "application/baby-oil")];
1586
        let jelq = send(
1587
            &app,
1588
            "JELQ",
1589
            "/runs/cafebabe?technique=wet&intensity=5",
1590
            &lube,
1591
            "",
1592
        )
1593
        .await;
1594
        match jelq.status() {
1595
            StatusCode::INTERNAL_SERVER_ERROR => ruptures += 1,
1596
            StatusCode::TOO_EARLY => early += 1,
1597
            other => panic!("seed {seed} ended in {other}"),
1598
        }
1599
    }
1600
    assert!(
1601
        (90..=175).contains(&ruptures),
1602
        "ruptures {ruptures} of 400 against {early} early"
1603
    );
1604
    assert!(
1605
        (225..=310).contains(&early),
1606
        "early {early} of 400 against {ruptures} ruptures"
1607
    );
1608
}
1609
1610
#[tokio::test]
1611
async fn priapism_holds_the_floor_through_every_reset() {
1612
    let exit = seeded_with(Floor::Bedroom, |run| {
1613
        run.warmed_up = true;
1614
        run.eq = 90;
1615
        run.here.turns = 99;
1616
        run.conditions.priapism_turns = 3;
1617
    });
1618
    let out = send(&exit, "POST", "/runs/cafebabe/floor", &[], "").await;
1619
    assert_eq!(out.status(), StatusCode::SEE_OTHER);
1620
    let view = send(&exit, "GET", "/runs/cafebabe", &[], "").await;
1621
    assert_eq!(header(&view, "x-eq"), "75");
1622
1623
    let melon = seeded_with(Floor::Bedroom, |run| {
1624
        run.eq = 95;
1625
        run.here.melon_offered = true;
1626
        run.conditions.priapism_turns = 2;
1627
    });
1628
    let bite = send(&melon, "POST", "/runs/cafebabe/kitchen/watermelon", &[], "").await;
1629
    assert_eq!(bite.status(), StatusCode::OK);
1630
    let view = send(&melon, "GET", "/runs/cafebabe", &[], "").await;
1631
    assert_eq!(header(&view, "x-eq"), "75");
1632
}