atagen

jelq

public

an http based roguelike rpg about jelqing

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