atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
0a0bfee8329e7283a802b33eb4365c2bf4c433b9
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/tests.rsRust1294 lines43.3 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
        run.items.baby_oil = 9;
959
    });
960
    send(
961
        &app,
962
        "JELQ",
963
        "/runs/cafebabe?technique=wet",
964
        &[("content-type", "application/baby-oil")],
965
        "",
966
    )
967
    .await;
968
    let ninth = send(&app, "GET", "/runs/cafebabe", &[], "").await;
969
    assert!(!header(&ninth, "link").contains("/forum/threads/2009"));
970
    let tenth = send(
971
        &app,
972
        "JELQ",
973
        "/runs/cafebabe?technique=wet",
974
        &[("content-type", "application/baby-oil")],
975
        "",
976
    )
977
    .await;
978
    assert!(
979
        tenth
980
            .headers()
981
            .get_all("warning")
982
            .iter()
983
            .any(|w| w.to_str().unwrap().contains("a forum thread from 2009"))
984
    );
985
    assert!(header(&tenth, "link").contains("/forum/threads/2009"));
986
    let announced = send(&app, "GET", "/runs/cafebabe", &[], "").await;
987
    assert!(header(&announced, "link").contains("/forum/threads/2009"));
988
}
989
990
#[tokio::test]
991
async fn reading_the_forum_may_teach_meditation() {
992
    let taught = (0..50u64)
993
        .filter(|seed| {
994
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
995
            run.story = Story::Pending;
996
            run.turn = BRANCH_TURN;
997
            run.choose("forum").is_ok() && run.meditation_taught
998
        })
999
        .count();
1000
    assert!(
1001
        taught > 0 && taught < 50,
1002
        "the teach roll should be a coin, it landed {taught}/50"
1003
    );
1004
}
1005
1006
#[tokio::test]
1007
async fn meditation_is_free_but_only_once_per_floor() {
1008
    let app = seeded_with(Floor::Bedroom, |run| run.meditation_taught = true);
1009
    let response = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1010
    assert_eq!(response.status(), StatusCode::OK);
1011
    assert_eq!(header(&response, "x-eq"), "10");
1012
    assert_eq!(header(&response, "x-stamina"), "10/10");
1013
    let again = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1014
    assert_eq!(again.status(), StatusCode::CONFLICT);
1015
}
1016
1017
#[tokio::test]
1018
async fn meditation_stays_hidden_until_the_forum_teaches_it() {
1019
    let app = seeded_with(Floor::Bedroom, |_| {});
1020
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1021
    assert!(!header(&view, "link").contains("technique=meditate"));
1022
    let jelq = send(&app, "JELQ", "/runs/cafebabe?technique=meditate", &[], "").await;
1023
    assert_eq!(jelq.status(), StatusCode::FORBIDDEN);
1024
}
1025
1026
fn app_with(floor: Floor, seed: u64, setup: impl FnOnce(&mut Run)) -> Router {
1027
    let state = Arc::new(AppState::default());
1028
    let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1029
    run.floor = floor;
1030
    setup(&mut run);
1031
    state.insert(run);
1032
    router(state)
1033
}
1034
1035
#[tokio::test]
1036
async fn hold_is_offered_only_at_the_edges() {
1037
    let calm = seeded_with(Floor::Bedroom, |_| {});
1038
    let refused = send(&calm, "HOLD", "/runs/cafebabe", &[], "").await;
1039
    assert_eq!(refused.status(), StatusCode::METHOD_NOT_ALLOWED);
1040
    assert!(!header(&refused, "allow").contains("HOLD"));
1041
    let view = send(&calm, "GET", "/runs/cafebabe", &[], "").await;
1042
    assert!(!header(&view, "link").contains("HOLD"));
1043
    let options = send(&calm, "OPTIONS", "/runs/cafebabe", &[], "").await;
1044
    assert!(!header(&options, "allow").contains("HOLD"));
1045
1046
    let winded = seeded_with(Floor::Bedroom, |run| run.stamina = 2);
1047
    let listed = send(&winded, "GET", "/runs/cafebabe", &[], "").await;
1048
    assert!(header(&listed, "link").contains("HOLD"));
1049
    let options = send(&winded, "OPTIONS", "/runs/cafebabe", &[], "").await;
1050
    assert!(header(&options, "allow").contains("HOLD"));
1051
1052
    let hot = seeded_with(Floor::Bedroom, |run| {
1053
        run.eq = 75;
1054
        run.warmed_up = true;
1055
    });
1056
    let held = send(&hot, "HOLD", "/runs/cafebabe", &[], "").await;
1057
    assert_eq!(held.status(), StatusCode::NO_CONTENT);
1058
    assert_eq!(header(&held, "x-stamina"), "10/10");
1059
}
1060
1061
#[tokio::test]
1062
async fn holding_calms_and_sometimes_reflects() {
1063
    let calmed = (0..60u64)
1064
        .filter(|seed| {
1065
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1066
            run.eq = 75;
1067
            run.hold(Instant::now()).is_ok() && run.eq == 60
1068
        })
1069
        .count();
1070
    let reflected = (0..60u64)
1071
        .filter(|seed| {
1072
            let mut run = Run::new("cafebabe".into(), "cafe".into(), *seed);
1073
            run.eq = 75;
1074
            run.hold(Instant::now()).is_ok() && run.eq == 0
1075
        })
1076
        .count();
1077
    assert!(
1078
        calmed > 40 && reflected > 0 && calmed + reflected == 60,
1079
        "one HOLD in twelve should reflect, got {calmed} calm and {reflected} reflective of 60"
1080
    );
1081
}
1082
1083
#[tokio::test]
1084
async fn leaving_the_band_warms_the_next_floor() {
1085
    let app = seeded_with(Floor::Bedroom, |run| {
1086
        run.eq = 60;
1087
        run.warmed_up = true;
1088
        run.here.turns = 6;
1089
        run.items.baby_oil = 9;
1090
    });
1091
    let left = send(&app, "POST", "/runs/cafebabe/floor", &[], "").await;
1092
    assert_eq!(left.status(), StatusCode::SEE_OTHER);
1093
    let detail = json(left).await["detail"].as_str().unwrap().to_owned();
1094
    assert!(detail.contains("the warmth came with you"));
1095
1096
    let lube = [("content-type", "application/baby-oil")];
1097
    send(&app, "JELQ", "/runs/cafebabe?technique=warmup", &[], "").await;
1098
    // The shower is a +35 warm-up, so EQ lands in the band and the band bonus rides along.
1099
    // The arrival bonus is the one point the second jelq loses.
1100
    let first = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1101
    assert!(
1102
        header(&first, "server-timing").contains("d20+4"),
1103
        "the first jelq of a warm arrival rolls with +1, got {}",
1104
        header(&first, "server-timing")
1105
    );
1106
    let second = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1107
    assert!(header(&second, "server-timing").contains("d20+3"));
1108
}
1109
1110
#[tokio::test]
1111
async fn greed_multiplies_gains_above_the_band() {
1112
    let lube = [("content-type", "application/baby-oil")];
1113
    for seed in 0..60u64 {
1114
        let app = app_with(Floor::Bedroom, seed, |run| {
1115
            run.eq = 60;
1116
            run.warmed_up = true;
1117
        });
1118
        let in_band = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1119
        let app = app_with(Floor::Bedroom, seed, |run| {
1120
            run.eq = 75;
1121
            run.warmed_up = true;
1122
        });
1123
        let greedy = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1124
        if in_band.status() != StatusCode::OK || greedy.status() != StatusCode::OK {
1125
            continue;
1126
        }
1127
        let steady = json(in_band).await["length"].as_f64().unwrap();
1128
        let eager = json(greedy).await["length"].as_f64().unwrap();
1129
        assert!(
1130
            (eager - steady * 1.5).abs() < 1e-9,
1131
            "seed {seed} gained {eager} above the band against {steady} inside it"
1132
        );
1133
        return;
1134
    }
1135
    panic!("no seed in 60 produced two clean rolls to compare");
1136
}
1137
1138
#[tokio::test]
1139
async fn the_kitchen_is_only_on_the_home_floors() {
1140
    let absent = seeded_with(Floor::Bathroom, |_| {});
1141
    let no_kitchen = send(&absent, "POST", "/runs/cafebabe/kitchen", &[], "").await;
1142
    assert_eq!(no_kitchen.status(), StatusCode::NOT_FOUND);
1143
    let view = send(&absent, "GET", "/runs/cafebabe", &[], "").await;
1144
    assert!(!header(&view, "link").contains("/kitchen"));
1145
1146
    let app = seeded_with(Floor::Bedroom, |_| {});
1147
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1148
    assert!(header(&view, "link").contains("/kitchen"));
1149
    let raid = send(&app, "POST", "/runs/cafebabe/kitchen", &[], "").await;
1150
    assert_ne!(raid.status(), StatusCode::NOT_FOUND);
1151
}
1152
1153
#[tokio::test]
1154
async fn raids_cost_the_turn_and_the_fridge_pays_out_sometimes() {
1155
    let mut bounties = std::collections::BTreeSet::new();
1156
    let mut told = 0;
1157
    for seed in 0..80u64 {
1158
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1159
        let Ok(outcome) = run.raid_kitchen() else {
1160
            panic!("the first raid should never fail");
1161
        };
1162
        assert_eq!(run.turn, 1, "a raid costs the floor turn");
1163
        assert!(!run.here.melon_offered, "no melon at starting EQ");
1164
        if outcome.status == StatusCode::NO_CONTENT {
1165
            bounties.insert("empty");
1166
        } else {
1167
            bounties.insert("loot");
1168
        }
1169
        told += u32::from(run.kitchen_tellings);
1170
    }
1171
    assert!(bounties.contains("loot") && bounties.contains("empty"));
1172
    assert!(
1173
        (0..80).any(|seed| {
1174
            let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1175
            run.raid_kitchen().is_ok() && run.kitchen_tellings == 0
1176
        }),
1177
        "most raids go unremarked"
1178
    );
1179
    assert!(told > 0, "someone should have been told across 80 raids");
1180
}
1181
1182
#[tokio::test]
1183
async fn the_watermelon_offers_itself_above_ninety() {
1184
    let mut offered = 0;
1185
    let mut caught = 0;
1186
    let mut survived = 0;
1187
    for seed in 0..120u64 {
1188
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1189
        run.eq = 95;
1190
        let Ok(outcome) = run.raid_kitchen() else {
1191
            continue;
1192
        };
1193
        if outcome.status != StatusCode::MULTIPLE_CHOICES {
1194
            continue;
1195
        }
1196
        offered += 1;
1197
        let gains = run.length;
1198
        let disgrace = run.shame;
1199
        if run.commit_melon().is_err() {
1200
            caught += 1;
1201
            assert_eq!(run.ended.as_ref().unwrap().cause.slug(), "watermelon");
1202
        } else {
1203
            survived += 1;
1204
            assert_eq!(run.eq, 0);
1205
            assert_eq!(run.shame, disgrace + 5);
1206
            assert_eq!(run.length, gains, "the gains are kept");
1207
        }
1208
    }
1209
    assert!(
1210
        offered > 20,
1211
        "the melon should appear in two fifths of raids"
1212
    );
1213
    assert!(caught > 0 && survived > 0, "caught is one in three");
1214
}
1215
1216
#[tokio::test]
1217
async fn the_kitchen_closes_after_two_tellings() {
1218
    let mut closed = None;
1219
    for seed in 0..300u64 {
1220
        let mut run = Run::new("cafebabe".into(), "cafe".into(), seed);
1221
        let first = run.raid_kitchen();
1222
        let second = run.raid_kitchen();
1223
        if second.is_err() && first.is_ok() {
1224
            assert_eq!(run.kitchen_tellings, 2);
1225
            let Err(third) = run.raid_kitchen() else {
1226
                panic!("the kitchen should be gone");
1227
            };
1228
            assert_eq!(third.status(), StatusCode::GONE);
1229
            closed = Some(seed);
1230
            break;
1231
        }
1232
    }
1233
    assert!(
1234
        closed.is_some(),
1235
        "two tellings should occur within 300 seeds"
1236
    );
1237
}
1238
1239
#[tokio::test]
1240
async fn lubes_run_out_but_spit_never_does() {
1241
    let app = seeded_with(Floor::Bedroom, |run| {
1242
        run.warmed_up = true;
1243
        run.items.baby_oil = 1;
1244
    });
1245
    let lube = [("content-type", "application/baby-oil")];
1246
    let first = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1247
    assert_ne!(first.status(), StatusCode::PRECONDITION_FAILED);
1248
    let second = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &lube, "").await;
1249
    assert_eq!(second.status(), StatusCode::PRECONDITION_FAILED);
1250
1251
    let spit = [("content-type", "text/plain; charset=spit")];
1252
    for _ in 0..3 {
1253
        let wet = send(&app, "JELQ", "/runs/cafebabe?technique=wet", &spit, "").await;
1254
        assert_ne!(wet.status(), StatusCode::PRECONDITION_FAILED);
1255
    }
1256
}
1257
1258
#[tokio::test]
1259
async fn energy_drinks_add_three_stamina() {
1260
    let app = seeded_with(Floor::Bedroom, |run| {
1261
        run.stamina = 2;
1262
        run.items.energy_drinks = 1;
1263
    });
1264
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1265
    assert!(header(&view, "link").contains("technique=energy"));
1266
    let drink = send(&app, "JELQ", "/runs/cafebabe?technique=energy", &[], "").await;
1267
    assert_eq!(drink.status(), StatusCode::OK);
1268
    let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1269
    assert_eq!(header(&view, "x-stamina"), "5/10");
1270
    let again = send(&app, "JELQ", "/runs/cafebabe?technique=energy", &[], "").await;
1271
    assert_eq!(again.status(), StatusCode::FAILED_DEPENDENCY);
1272
}
1273
1274
#[tokio::test]
1275
async fn the_working_supplement_resets_stamina() {
1276
    let mut worked = 0;
1277
    let mut bunk = 0;
1278
    for seed in 0..60u64 {
1279
        let app = app_with(Floor::Bedroom, seed, |run| {
1280
            run.stamina = 1;
1281
            run.items.supplements = 1;
1282
        });
1283
        let taken = send(&app, "JELQ", "/runs/cafebabe?technique=supplement", &[], "").await;
1284
        if taken.status() == StatusCode::OK {
1285
            worked += 1;
1286
            let view = send(&app, "GET", "/runs/cafebabe", &[], "").await;
1287
            assert_eq!(header(&view, "x-stamina"), "10/10");
1288
        } else {
1289
            assert_eq!(taken.status(), StatusCode::BAD_GATEWAY);
1290
            bunk += 1;
1291
        }
1292
    }
1293
    assert!(worked > 0 && bunk > 0, "one in five should work too well");
1294
}