rustango 0.57.11

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! ViewSet → OpenAPI: auto-generate path items for the 5 standard CRUD
//! routes a [`ViewSet`] mounts.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::openapi::{OpenApiSpec, Schema};
//! use rustango::serializer::ModelSerializer;
//! use rustango::viewset::ViewSet;
//!
//! let posts_vs = ViewSet::for_model(Post::SCHEMA)
//!     .filter_fields(&["author_id"])
//!     .search_fields(&["title", "body"]);
//!
//! let mut spec = OpenApiSpec::new("Blog API", "1.0")
//!     .add_schema("Post", PostSerializer::openapi_schema());
//!
//! for (path, item) in posts_vs.openapi_paths("/api/posts", "Post") {
//!     spec = spec.add_path(path, item);
//! }
//! ```

use crate::openapi::{Operation, Parameter, PathItem, RequestBody, Response, Schema};

use super::{PaginationStyle, ViewSet};
use crate::core::FieldType;

impl ViewSet {
    /// Generate the OpenAPI path items for this viewset.
    ///
    /// Returns `(path, PathItem)` pairs for the collection (`/{prefix}`) and
    /// the item (`/{prefix}/{pk}`) routes. Skips create/update/destroy when
    /// `read_only()` was called.
    ///
    /// `item_schema_ref` is the name of the schema you registered in the
    /// spec's `components.schemas` (typically the model name, e.g. `"Post"`).
    /// Both create/update bodies and retrieve responses reference it.
    #[must_use]
    pub fn openapi_paths(&self, prefix: &str, item_schema_ref: &str) -> Vec<(String, PathItem)> {
        let prefix = prefix.trim_end_matches('/').to_owned();
        let collection_path = prefix.clone();
        let item_path = format!("{prefix}/{{{}}}", self.pk_param_name());
        let tag = item_schema_ref.to_owned();

        let collection = self.collection_path_item(&tag, item_schema_ref);
        let item = self.item_path_item(&tag, item_schema_ref);

        vec![(collection_path, collection), (item_path, item)]
    }

    fn collection_path_item(&self, tag: &str, item_ref: &str) -> PathItem {
        let mut p = PathItem::new();

        // -------- list (GET)
        let mut list_op = Operation::new()
            .summary(format!("List {tag}"))
            .operation_id(format!("list_{}", snake(tag)))
            .tag(tag)
            .response(
                "200",
                Response::new("paginated list").json_content(self.list_response_schema(item_ref)),
            );
        for param in self.list_query_params() {
            list_op = list_op.parameter(param);
        }
        p = p.get(list_op);

        // -------- create (POST)
        if !self.read_only {
            let create_op = Operation::new()
                .summary(format!("Create {tag}"))
                .operation_id(format!("create_{}", snake(tag)))
                .tag(tag)
                .request_body(RequestBody::json(Schema::ref_(item_ref)))
                .response(
                    "201",
                    Response::new("created").json_content(Schema::ref_(item_ref)),
                )
                .response("400", Response::new("validation error"));
            p = p.post(create_op);
        }

        // -------- query (QUERY, RFC 10008)
        //
        // Gated exactly as the route is (`viewset/mod.rs` mounts
        // `handle_query` under `admin`, because the routing shim
        // lives in the admin-gated `http_query`). Emitting this
        // unconditionally would advertise an operation a
        // `tenancy`-only build does not serve — the inverse of the
        // bug being fixed.
        //
        // The ViewSet has served QUERY since #1112 and the spec never
        // mentioned it, so every generated SDK, gateway and contract
        // test was blind to it (#1401).
        #[cfg(feature = "admin")]
        if self.openapi_query {
            // `parse_query_body_params` collapses the body to
            // `HashMap<String, String>` — scalars stringified, arrays
            // comma-joined — so every criterion is a string whatever
            // the GET parameter's type is.
            let mut criteria = Schema::object();
            for param in self.list_query_params() {
                criteria = criteria.property(param.name.clone(), Schema::string());
            }
            let query_op = Operation::new()
                .summary(format!("Query {tag}"))
                .description(
                    "Same filtered list as GET, with the criteria in the body instead \
                     of the querystring — for filters too long or too structured for a \
                     URL. Values are read as strings: a JSON array is comma-joined, so \
                     `{\"status__in\": [\"a\", \"b\"]}` matches `?status__in=a,b`.",
                )
                .operation_id(format!("query_{}", snake(tag)))
                .tag(tag)
                .request_body(
                    RequestBody::json(criteria.clone())
                        .and_content("application/x-www-form-urlencoded", criteria)
                        .description("Filter criteria. An empty body lists everything."),
                )
                .response(
                    "200",
                    Response::new("paginated list")
                        .json_content(self.list_response_schema(item_ref)),
                )
                .response("413", Response::new("body larger than 1 MiB"))
                .response(
                    "415",
                    Response::new("content type is neither JSON nor urlencoded"),
                )
                .response(
                    "422",
                    Response::new("body is not a JSON object of criteria"),
                );
            p = p.query(query_op);
        }

        p
    }

    fn item_path_item(&self, tag: &str, item_ref: &str) -> PathItem {
        let mut p = PathItem::new().parameter(self.pk_path_param());

        // -------- retrieve (GET)
        let retrieve_op = Operation::new()
            .summary(format!("Retrieve {tag}"))
            .operation_id(format!("retrieve_{}", snake(tag)))
            .tag(tag)
            .response(
                "200",
                Response::new("found").json_content(Schema::ref_(item_ref)),
            )
            .response("404", Response::new("not found"));
        p = p.get(retrieve_op);

        if !self.read_only {
            let update_op = Operation::new()
                .summary(format!("Replace {tag}"))
                .operation_id(format!("update_{}", snake(tag)))
                .tag(tag)
                .request_body(RequestBody::json(Schema::ref_(item_ref)))
                .response(
                    "200",
                    Response::new("updated").json_content(Schema::ref_(item_ref)),
                )
                .response("404", Response::new("not found"));
            p = p.put(update_op);

            let patch_op = Operation::new()
                .summary(format!("Partially update {tag}"))
                .operation_id(format!("partial_update_{}", snake(tag)))
                .tag(tag)
                .request_body(RequestBody::json(Schema::ref_(item_ref)))
                .response(
                    "200",
                    Response::new("updated").json_content(Schema::ref_(item_ref)),
                )
                .response("404", Response::new("not found"));
            p = p.patch(patch_op);

            let destroy_op = Operation::new()
                .summary(format!("Delete {tag}"))
                .operation_id(format!("destroy_{}", snake(tag)))
                .tag(tag)
                .response("204", Response::new("deleted"))
                .response("404", Response::new("not found"));
            p = p.delete(destroy_op);
        }

        p
    }

    fn pk_path_param(&self) -> Parameter {
        let pk_field = self.schema.primary_key();
        let schema = pk_field.map_or_else(Schema::integer, |f| field_type_to_schema(f.ty));
        let name = pk_field.map_or("pk", |f| f.name);
        // The parameter must be spelled the same as the route capture, which
        // `ViewSet::pk_param` can rename (#1194) — otherwise the generated
        // spec documents a path variable the server never binds.
        Parameter::path(self.pk_param_name(), schema).description(format!("Primary key ({name})"))
    }

    fn list_query_params(&self) -> Vec<Parameter> {
        let mut out = Vec::new();
        // Pagination params
        match self.pagination {
            PaginationStyle::PageNumber => {
                out.push(
                    Parameter::query("page", Schema::int32()).description("1-based page number"),
                );
                out.push(
                    Parameter::query("page_size", Schema::int32())
                        .description("Items per page (max 1000)"),
                );
            }
            PaginationStyle::Cursor { .. } => {
                out.push(
                    Parameter::query("cursor", Schema::string())
                        .description("Opaque token from the previous response's `next` field"),
                );
                out.push(
                    Parameter::query("page_size", Schema::int32())
                        .description("Items per page (max 1000)"),
                );
            }
            PaginationStyle::LimitOffset => {
                out.push(
                    Parameter::query("limit", Schema::int32())
                        .description("Items to return (max 1000)"),
                );
                out.push(
                    Parameter::query("offset", Schema::int32())
                        .description("Rows to skip before the window"),
                );
            }
        }
        // Search
        if !self.search_fields.is_empty() {
            out.push(
                Parameter::query("search", Schema::string()).description(format!(
                    "Full-text search across: {}",
                    self.search_fields.join(", ")
                )),
            );
        }
        // Ordering — surface the `?ordering=` parameter when EITHER a
        // default ordering is configured OR an explicit
        // `ordering_fields` whitelist is set (#439). The description
        // enumerates the allowed fields when a whitelist is in play
        // so clients can discover the API surface without reading code.
        if !self.default_ordering.is_empty() || !self.ordering_fields.is_empty() {
            let description = if self.ordering_fields.is_empty() {
                "Comma-separated field names; prefix `-` for DESC".to_owned()
            } else {
                format!(
                    "Comma-separated field names from: {}. Prefix `-` for DESC. \
                     Unknown / off-whitelist names are silently dropped.",
                    self.ordering_fields.join(", "),
                )
            };
            out.push(Parameter::query("ordering", Schema::string()).description(description));
        }
        // One filter param per filter_field. The `__`-suffixed lookups
        // are not listed as separate params — the description names
        // them instead.
        for f in &self.filter_fields {
            let field_schema = self
                .schema
                .field(f)
                .map_or_else(Schema::string, |fs| field_type_to_schema(fs.ty));
            out.push(
                Parameter::query(f.clone(), field_schema).description(format!(
                    "Exact filter. Lookups: `{f}__gt`, `__gte`, `__lt`, `__lte`, \
                         `__ne`, `__in`, `__not_in`, `__contains`, `__icontains`, \
                         `__startswith`, `__istartswith`, `__endswith`, `__iendswith`, \
                         `__isnull`."
                )),
            );
        }
        out
    }

    fn list_response_schema(&self, item_ref: &str) -> Schema {
        let items = Schema::array_of(Schema::ref_(item_ref));
        match self.pagination {
            PaginationStyle::PageNumber => Schema::object()
                .property("count", Schema::integer())
                .property("page", Schema::int32())
                .property("page_size", Schema::int32())
                .property("last_page", Schema::int32())
                .property("results", items)
                .required(["count", "page", "page_size", "last_page", "results"]),
            PaginationStyle::Cursor { .. } => Schema::object()
                .property("page_size", Schema::int32())
                .property("next", Schema::string().nullable())
                .property("results", items)
                .required(["page_size", "results"]),
            PaginationStyle::LimitOffset => Schema::object()
                .property("count", Schema::integer())
                .property("limit", Schema::int32())
                .property("offset", Schema::int32())
                .property("results", items)
                .required(["count", "limit", "offset", "results"]),
        }
    }
}

fn field_type_to_schema(t: FieldType) -> Schema {
    match t {
        FieldType::I16 => {
            // JSON Schema has no `int16`. Render as `int32` and clamp
            // via min/max so the schema still describes the actual
            // bounds Postgres / MySQL enforce.
            let mut s = Schema::int32();
            s.minimum = Some(f64::from(i16::MIN));
            s.maximum = Some(f64::from(i16::MAX));
            s
        }
        FieldType::I32 => Schema::int32(),
        FieldType::I64 => Schema::integer(),
        FieldType::F32 => {
            let mut s = Schema::number();
            s.format = Some("float".into());
            s
        }
        FieldType::F64 => {
            let mut s = Schema::number();
            s.format = Some("double".into());
            s
        }
        FieldType::Bool => Schema::boolean(),
        FieldType::String => Schema::string(),
        FieldType::DateTime => Schema::datetime(),
        FieldType::Date => Schema::date(),
        FieldType::Time => Schema::time(),
        FieldType::Uuid => Schema::uuid(),
        FieldType::Json => Schema::default(), // free-form
        FieldType::Decimal => Schema::decimal(),
        FieldType::Binary => Schema::binary(),
        // #341 — PG array column: `type: array` with element-typed items.
        FieldType::Array(elem) => {
            use crate::core::ArrayElem;
            let items = match elem {
                ArrayElem::Text => Schema::string(),
                ArrayElem::Int => Schema::int32(),
                ArrayElem::BigInt => Schema::integer(),
            };
            Schema::array_of(items)
        }
        // #343 — PG range column: serialized as a range-literal string
        // (`"[1,10)"`), so a `string` schema is the honest shape.
        FieldType::Range(_) => Schema::string(),
        // #342 — PG hstore: a string→string map → `object` with
        // string-typed additionalProperties.
        FieldType::HStore => Schema {
            type_: Some("object".into()),
            additional_properties: Some(Box::new(Schema::string())),
            ..Default::default()
        },
        // #824 — pgvector embedding: a JSON array of numbers.
        FieldType::Vector(_) => Schema::array_of(Schema::number()),
        // #443 — PostGIS Point: a JSON object `{ x, y, srid }`.
        FieldType::Geometry(_) => Schema::object(),
    }
}

/// "PostThing" → "post_thing"; "post" → "post".
fn snake(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_ascii_uppercase() {
            if i != 0 {
                out.push('_');
            }
            out.push(c.to_ascii_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{FieldSchema, FieldType, ModelSchema};

    fn id_field() -> FieldSchema {
        FieldSchema {
            name: "id",
            column: "id",
            ty: FieldType::I64,
            nullable: false,
            primary_key: true,
            relation: None,
            max_length: None,
            min: None,
            max: None,
            default: None,
            auto: true,
            unique: false,
            generated_as: None,
            help_text: None,
            choices: None,
            db_comment: None,
            verbose_name: None,
            editable: true,
            blank: false,
            case_insensitive: false,
            fk_on_delete: None,
            validators: &[],
        }
    }

    fn title_field() -> FieldSchema {
        FieldSchema {
            name: "title",
            column: "title",
            ty: FieldType::String,
            nullable: false,
            primary_key: false,
            relation: None,
            max_length: None,
            min: None,
            max: None,
            default: None,
            auto: false,
            unique: false,
            generated_as: None,
            help_text: None,
            choices: None,
            db_comment: None,
            verbose_name: None,
            editable: true,
            blank: false,
            case_insensitive: false,
            fk_on_delete: None,
            validators: &[],
        }
    }

    fn author_id_field() -> FieldSchema {
        FieldSchema {
            name: "author_id",
            column: "author_id",
            ty: FieldType::I64,
            nullable: false,
            primary_key: false,
            relation: None,
            max_length: None,
            min: None,
            max: None,
            default: None,
            auto: false,
            unique: false,
            generated_as: None,
            help_text: None,
            choices: None,
            db_comment: None,
            verbose_name: None,
            editable: true,
            blank: false,
            case_insensitive: false,
            fk_on_delete: None,
            validators: &[],
        }
    }

    fn schema() -> &'static ModelSchema {
        static FIELDS: &[FieldSchema] = &[
            FieldSchema {
                name: "id",
                column: "id",
                ty: FieldType::I64,
                nullable: false,
                primary_key: true,
                relation: None,
                max_length: None,
                min: None,
                max: None,
                default: None,
                auto: true,
                unique: false,
                generated_as: None,
                help_text: None,
                choices: None,
                db_comment: None,
                verbose_name: None,
                editable: true,
                blank: false,
                case_insensitive: false,
                fk_on_delete: None,
                validators: &[],
            },
            FieldSchema {
                name: "title",
                column: "title",
                ty: FieldType::String,
                nullable: false,
                primary_key: false,
                relation: None,
                max_length: None,
                min: None,
                max: None,
                default: None,
                auto: false,
                unique: false,
                generated_as: None,
                help_text: None,
                choices: None,
                db_comment: None,
                verbose_name: None,
                editable: true,
                blank: false,
                case_insensitive: false,
                fk_on_delete: None,
                validators: &[],
            },
            FieldSchema {
                name: "author_id",
                column: "author_id",
                ty: FieldType::I64,
                nullable: false,
                primary_key: false,
                relation: None,
                max_length: None,
                min: None,
                max: None,
                default: None,
                auto: false,
                unique: false,
                generated_as: None,
                help_text: None,
                choices: None,
                db_comment: None,
                verbose_name: None,
                editable: true,
                blank: false,
                case_insensitive: false,
                fk_on_delete: None,
                validators: &[],
            },
        ];
        // Suppress unused warnings on field helpers if we keep them.
        let _ = (id_field(), title_field(), author_id_field());
        static MS: ModelSchema = ModelSchema {
            name: "Post",
            table: "posts",
            fields: FIELDS,
            display: None,
            app_label: None,
            admin: None,
            soft_delete_column: None,
            audit_track: None,
            permissions: false,
            indexes: &[],
            check_constraints: &[],
            exclusion_constraints: &[],
            default_permissions: &[],
            m2m: &[],
            composite_relations: &[],
            generic_relations: &[],
            scope: crate::core::ModelScope::Tenant,
            default_order: &[],
            is_view: false,
            verbose_name: None,
            verbose_name_plural: None,
            managed: true,
            db_table_comment: None,
            default_related_name: None,
            base_manager_name: None,
            required_db_vendor: None,
            required_db_features: &[],
            order_with_respect_to: None,
            proxy: false,
            get_latest_by: None,
            extra_permissions: &[],
            global_scopes: &[],
        };
        &MS
    }

    fn vs() -> ViewSet {
        ViewSet::for_model(schema())
            .filter_fields(&["author_id"])
            .search_fields(&["title"])
            .ordering(&[("id", true)])
    }

    #[test]
    fn paths_returns_collection_and_item_paths() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let names: Vec<&str> = paths.iter().map(|(p, _)| p.as_str()).collect();
        assert_eq!(names, vec!["/api/posts", "/api/posts/{pk}"]);
    }

    #[test]
    fn collection_has_get_and_post_for_default_viewset() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let item = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        assert!(item.get.is_some(), "list");
        assert!(item.post.is_some(), "create");
    }

    #[test]
    fn read_only_omits_write_methods() {
        let vs = vs().read_only();
        let paths = vs.openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        assert!(coll.get.is_some());
        assert!(coll.post.is_none());
        let item = &paths
            .iter()
            .find(|(p, _)| p == "/api/posts/{pk}")
            .unwrap()
            .1;
        assert!(item.get.is_some());
        assert!(item.put.is_none());
        assert!(item.patch.is_none());
        assert!(item.delete.is_none());
    }

    #[test]
    fn list_response_paginated_shape() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        let v = serde_json::to_value(coll.get.as_ref().unwrap()).unwrap();
        let resp = &v["responses"]["200"]["content"]["application/json"]["schema"];
        assert_eq!(resp["type"], "object");
        assert_eq!(resp["properties"]["count"]["type"], "integer");
        assert_eq!(resp["properties"]["results"]["type"], "array");
        assert_eq!(
            resp["properties"]["results"]["items"]["$ref"],
            "#/components/schemas/Post"
        );
    }

    #[test]
    fn cursor_pagination_changes_list_shape_and_params() {
        let vs = vs().cursor_pagination("id");
        let paths = vs.openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        let v = serde_json::to_value(coll.get.as_ref().unwrap()).unwrap();
        // params should include `cursor`, not `page`
        let param_names: Vec<&str> = v["parameters"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert!(param_names.contains(&"cursor"));
        assert!(!param_names.contains(&"page"));
        // response: { page_size, next, results } — no count
        let resp = &v["responses"]["200"]["content"]["application/json"]["schema"];
        assert!(resp["properties"]["count"].is_null());
        assert_eq!(resp["properties"]["next"]["nullable"], true);
    }

    #[test]
    fn pk_param_uses_primary_key_field_type() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let item = &paths
            .iter()
            .find(|(p, _)| p == "/api/posts/{pk}")
            .unwrap()
            .1;
        let v = serde_json::to_value(item).unwrap();
        let pk = &v["parameters"][0];
        assert_eq!(pk["name"], "pk");
        assert_eq!(pk["in"], "path");
        assert_eq!(pk["required"], true);
        assert_eq!(pk["schema"]["type"], "integer");
        assert_eq!(pk["schema"]["format"], "int64");
    }

    #[test]
    fn create_body_and_response_reference_item_schema() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        let v = serde_json::to_value(coll.post.as_ref().unwrap()).unwrap();
        assert_eq!(
            v["requestBody"]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/Post"
        );
        assert_eq!(
            v["responses"]["201"]["content"]["application/json"]["schema"]["$ref"],
            "#/components/schemas/Post"
        );
    }

    #[test]
    fn filter_fields_emit_query_parameters() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        let v = serde_json::to_value(coll.get.as_ref().unwrap()).unwrap();
        let names: Vec<&str> = v["parameters"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"author_id"));
        assert!(names.contains(&"search"));
        assert!(names.contains(&"ordering"));
    }

    #[test]
    fn operation_ids_are_snake_cased_per_action() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        assert_eq!(
            coll.get.as_ref().unwrap().operation_id.as_deref(),
            Some("list_post")
        );
        assert_eq!(
            coll.post.as_ref().unwrap().operation_id.as_deref(),
            Some("create_post")
        );
    }

    #[test]
    fn snake_lowers_camelcase() {
        assert_eq!(snake("Post"), "post");
        assert_eq!(snake("PostThing"), "post_thing");
        assert_eq!(snake("HTTPRequest"), "h_t_t_p_request");
        assert_eq!(snake("post"), "post");
    }

    /// #1401 — the ViewSet has mounted QUERY since #1112 and the spec
    /// never said so, so no generated client could reach it.
    /// The default must stay 3.1.0-compatible: the QUERY operation is
    /// opt-in because emitting it forces the whole document to 3.2.0,
    /// which a 3.1-pinned generator rejects outright.
    #[cfg(feature = "admin")]
    #[test]
    fn the_query_operation_is_off_by_default() {
        let paths = vs().openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;
        assert!(
            coll.query.is_none(),
            "emitting this by default flips every ViewSet spec to 3.2.0 \
             without the caller asking — `getting_started_blog`'s own \
             openapi test caught exactly that",
        );

        let mut spec = crate::openapi::OpenApiSpec::new("t", "1");
        for (path, item) in vs().openapi_paths("/api/posts", "Post") {
            spec = spec.add_path(path, item);
        }
        assert_eq!(
            spec.openapi, "3.1.0",
            "the default document must stay 3.1.0"
        );
    }

    #[cfg(feature = "admin")]
    #[test]
    fn the_collection_advertises_the_query_operation_it_serves() {
        let paths = vs().openapi_query(true).openapi_paths("/api/posts", "Post");
        let coll = &paths.iter().find(|(p, _)| p == "/api/posts").unwrap().1;

        let q = coll
            .query
            .as_ref()
            .expect("the collection serves QUERY, so the spec must carry it");
        assert_eq!(q.operation_id.as_deref(), Some("query_post"));

        // Both content types the handler accepts, or a generated
        // client picks one and the other 415s.
        let body = q.request_body.as_ref().expect("QUERY takes a body");
        assert!(
            body.content.contains_key("application/json"),
            "{:?}",
            body.content.keys()
        );
        assert!(
            body.content
                .contains_key("application/x-www-form-urlencoded"),
            "{:?}",
            body.content.keys(),
        );

        // The criteria object must carry the same names as the GET
        // querystring — that equivalence is the whole point of the
        // operation, and it is what drifts if a filter is added to
        // one path only.
        let props = &body.content["application/json"].schema.properties;
        for param in vs().list_query_params() {
            assert!(
                props.contains_key(&param.name),
                "`{}` is a GET query param but not a QUERY body criterion: {:?}",
                param.name,
                props.keys().collect::<Vec<_>>(),
            );
        }
        assert!(!props.is_empty(), "criteria schema must not be empty");
    }

    /// The spec version has to follow the operation, or tooling
    /// rejects a 3.1.0 document containing a `query` field.
    #[cfg(feature = "admin")]
    #[test]
    fn a_spec_carrying_the_query_operation_declares_3_2_0() {
        let paths = vs().openapi_query(true).openapi_paths("/api/posts", "Post");
        let mut spec = crate::openapi::OpenApiSpec::new("t", "1");
        for (path, item) in paths {
            spec = spec.add_path(path, item);
        }
        assert_eq!(spec.openapi, "3.2.0");
    }
}