clawspec-core 0.4.4

Core library for generating OpenAPI specifications from tests
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
use headers::ContentType;
use http::{Method, StatusCode};
use indexmap::IndexMap;
use tracing::warn;
use utoipa::openapi::{Content, PathItem, RefOr, Response, ResponseBuilder, Schema};

use super::operation::{CalledOperation, merge_operation};
use super::schema::Schemas;

/// Builds an OpenAPI response with optional schema and example.
///
/// This helper is used by both `get_output()` and `register_response_with_example()`
/// to avoid code duplication.
pub(in crate::client) fn build_response(
    description: String,
    content_type: Option<&ContentType>,
    schema: Option<RefOr<Schema>>,
    example: Option<serde_json::Value>,
) -> Response {
    if let Some(content_type) = content_type {
        let content = Content::builder().schema(schema).example(example).build();
        ResponseBuilder::new()
            .description(description)
            .content(content_type.to_string(), content)
            .build()
    } else {
        ResponseBuilder::new().description(description).build()
    }
}

/// Normalizes content types for OpenAPI specification by removing parameters
/// that are implementation details (like multipart boundaries, charset, etc.).
pub(super) fn normalize_content_type(content_type: &ContentType) -> String {
    let content_type_str = content_type.to_string();

    // Strip all parameters by truncating at the first semicolon
    if let Some(semicolon_pos) = content_type_str.find(';') {
        content_type_str[..semicolon_pos].to_string()
    } else {
        content_type_str
    }
}

/// Collects and merges OpenAPI operations and schemas from API test executions.
///
/// # Schema Merge Behavior
///
/// The `Collectors` struct implements intelligent merging behavior for OpenAPI operations
/// and schemas to handle multiple test calls to the same endpoint with different parameters,
/// headers, or request bodies.
///
/// ## Operation Merging
///
/// When multiple tests call the same endpoint (same HTTP method and path), the operations
/// are merged using the following rules:
///
/// - **Parameters**: New parameters are added; existing parameters are preserved by name
/// - **Request Bodies**: Content types are merged; same content type overwrites previous
/// - **Responses**: New response status codes are added; existing status codes are preserved
/// - **Tags**: Tags from all operations are combined, sorted, and deduplicated
/// - **Description**: First non-empty description is used
///
/// ## Schema Merging
///
/// Schemas are merged by TypeId to ensure type safety:
///
/// - **Type Identity**: Same Rust type (TypeId) maps to same schema entry
/// - **Examples**: Examples from all usages are collected and deduplicated
/// - **Primitive Types**: Inlined directly (String, i32, etc.)
/// - **Complex Types**: Referenced in components/schemas section
///
/// ## Performance Optimizations
///
/// The merge operations have been optimized to reduce memory allocations:
///
/// - **Request Body Merging**: Uses `extend()` instead of `clone()` for content maps
/// - **Parameter Merging**: Uses `entry().or_insert()` to avoid duplicate lookups
/// - **Schema Merging**: Direct insertion by TypeId for O(1) lookup
///
/// ## Example Usage
///
/// ```rust,ignore
/// // Internal usage - not exposed in public API
/// let mut collectors = Collectors::default();
///
/// // Schemas from different test calls are merged
/// collectors.collect_schemas(schemas_from_test_1);
/// collectors.collect_schemas(schemas_from_test_2);
///
/// // Operations with same endpoint are merged
/// collectors.collect_operation(get_users_operation);
/// collectors.collect_operation(get_users_with_params_operation);
/// ```
#[derive(Debug, Clone, Default)]
pub(in crate::client) struct Collectors {
    pub(super) operations: IndexMap<String, Vec<CalledOperation>>,
    pub(in crate::client) schemas: Schemas,
}

impl Collectors {
    pub(in crate::client) fn collect_schemas(&mut self, schemas: Schemas) {
        self.schemas.merge(schemas);
    }

    pub(in crate::client) fn collect_schema_entry(&mut self, entry: super::schema::SchemaEntry) {
        self.schemas.add_entry(entry);
    }

    pub(in crate::client) fn collect_operation(
        &mut self,
        operation: CalledOperation,
    ) -> Option<&mut CalledOperation> {
        let operation_id = operation.operation_id.clone();
        let operations = self.operations.entry(operation_id).or_default();

        operations.push(operation);
        operations.last_mut()
    }

    pub(in crate::client) fn schemas(&self) -> Vec<(String, RefOr<Schema>)> {
        self.schemas.schema_vec()
    }

    /// Returns an iterator over collected operations.
    ///
    /// This method provides access to all operations that have been collected
    /// during API calls, which is useful for tag computation and analysis.
    pub(in crate::client) fn operations(&self) -> impl Iterator<Item = &CalledOperation> {
        self.operations.values().flatten()
    }

    /// Registers a response for an operation (used by channel-based collection).
    ///
    /// This method records a response with an optional schema and description.
    pub(in crate::client) fn register_response(
        &mut self,
        operation_id: &str,
        status: StatusCode,
        content_type: Option<&ContentType>,
        schema: Option<RefOr<Schema>>,
        description: String,
    ) {
        let Some(operations) = self.operations.get_mut(operation_id) else {
            tracing::warn!(%operation_id, "Operation not found for response registration");
            return;
        };
        let Some(operation) = operations.last_mut() else {
            return;
        };

        let response = build_response(description, content_type, schema, None);

        operation
            .operation
            .responses
            .responses
            .insert(status.as_u16().to_string(), RefOr::T(response));
    }

    /// Registers a response with an example in the operation.
    ///
    /// This method is used by the redaction feature to add a response with the redacted
    /// example after all redactions have been applied.
    #[cfg(feature = "redaction")]
    pub(in crate::client) fn register_response_with_example(
        &mut self,
        operation_id: &str,
        status: StatusCode,
        content_type: Option<&ContentType>,
        schema: RefOr<Schema>,
        example: serde_json::Value,
    ) {
        let Some(operations) = self.operations.get_mut(operation_id) else {
            return;
        };
        let Some(operation) = operations.last_mut() else {
            return;
        };

        let description = operation
            .response_description
            .clone()
            .unwrap_or_else(|| format!("Status code {}", status.as_u16()));

        let response = build_response(description, content_type, Some(schema), Some(example));

        operation
            .operation
            .responses
            .responses
            .insert(status.as_u16().to_string(), RefOr::T(response));
    }

    pub(in crate::client) fn as_map(&mut self, base_path: &str) -> IndexMap<String, PathItem> {
        /// Merges an operation into the appropriate field of a PathItem based on HTTP method.
        macro_rules! merge_into {
            ($item:expr, $field:ident, $operation_id:expr, $operation:expr) => {{ $item.$field = merge_operation($operation_id, $item.$field.clone(), $operation) }};
        }

        let mut result = IndexMap::<String, PathItem>::new();
        for (operation_id, calls) in &self.operations {
            debug_assert!(!calls.is_empty(), "having at least a call");
            let path = format!("{base_path}/{}", calls[0].path.trim_start_matches('/'));
            let item = result.entry(path.clone()).or_default();
            for call in calls {
                match &call.method {
                    &Method::GET => merge_into!(item, get, operation_id, call.operation.clone()),
                    &Method::PUT => merge_into!(item, put, operation_id, call.operation.clone()),
                    &Method::POST => merge_into!(item, post, operation_id, call.operation.clone()),
                    &Method::DELETE => {
                        merge_into!(item, delete, operation_id, call.operation.clone())
                    }
                    &Method::OPTIONS => {
                        merge_into!(item, options, operation_id, call.operation.clone())
                    }
                    &Method::HEAD => merge_into!(item, head, operation_id, call.operation.clone()),
                    &Method::PATCH => {
                        merge_into!(item, patch, operation_id, call.operation.clone())
                    }
                    &Method::TRACE => {
                        merge_into!(item, trace, operation_id, call.operation.clone())
                    }
                    method => warn!(%method, "unsupported method"),
                }
            }
        }
        result
    }
}

#[cfg(test)]
mod operation_metadata_tests {
    use super::super::operation::{generate_description, generate_tags, singularize};
    use super::*;
    use http::Method;

    #[test]
    fn test_generate_description_simple_paths() {
        assert_eq!(
            generate_description(&Method::GET, "/users"),
            Some("Retrieve users".to_string())
        );
        assert_eq!(
            generate_description(&Method::POST, "/users"),
            Some("Create user".to_string())
        );
        assert_eq!(
            generate_description(&Method::PUT, "/users"),
            Some("Update users".to_string())
        );
        assert_eq!(
            generate_description(&Method::DELETE, "/users"),
            Some("Delete users".to_string())
        );
        assert_eq!(
            generate_description(&Method::PATCH, "/users"),
            Some("Partially update users".to_string())
        );
    }

    #[test]
    fn test_generate_description_with_id_parameter() {
        assert_eq!(
            generate_description(&Method::GET, "/users/{id}"),
            Some("Retrieve user by ID".to_string())
        );
        assert_eq!(
            generate_description(&Method::PUT, "/users/{id}"),
            Some("Update user by ID".to_string())
        );
        assert_eq!(
            generate_description(&Method::DELETE, "/users/{id}"),
            Some("Delete user by ID".to_string())
        );
        assert_eq!(
            generate_description(&Method::PATCH, "/users/{id}"),
            Some("Partially update user by ID".to_string())
        );
    }

    #[test]
    fn test_generate_description_special_actions() {
        assert_eq!(
            generate_description(&Method::POST, "/observations/import"),
            Some("Import observations".to_string())
        );
        assert_eq!(
            generate_description(&Method::POST, "/observations/upload"),
            Some("Upload observations".to_string())
        );
        assert_eq!(
            generate_description(&Method::POST, "/users/export"),
            Some("Export users".to_string())
        );
        assert_eq!(
            generate_description(&Method::GET, "/users/search"),
            Some("Search users".to_string())
        );
    }

    #[test]
    fn test_generate_description_api_prefix() {
        assert_eq!(
            generate_description(&Method::GET, "/api/observations"),
            Some("Retrieve observations".to_string())
        );
        assert_eq!(
            generate_description(&Method::POST, "/api/observations/import"),
            Some("Import observations".to_string())
        );
        // Test multiple prefixes
        assert_eq!(
            generate_description(&Method::GET, "/api/v1/users"),
            Some("Retrieve users".to_string())
        );
        assert_eq!(
            generate_description(&Method::POST, "/rest/service/items"),
            Some("Create item".to_string())
        );
    }

    #[test]
    fn test_generate_tags_simple_paths() {
        assert_eq!(generate_tags("/users"), Some(vec!["users".to_string()]));
        assert_eq!(
            generate_tags("/observations"),
            Some(vec!["observations".to_string()])
        );
    }

    #[test]
    fn test_generate_tags_with_api_prefix() {
        assert_eq!(generate_tags("/api/users"), Some(vec!["users".to_string()]));
        assert_eq!(
            generate_tags("/api/observations"),
            Some(vec!["observations".to_string()])
        );
        // Test multiple prefixes
        assert_eq!(
            generate_tags("/api/v1/users"),
            Some(vec!["users".to_string()])
        );
        assert_eq!(
            generate_tags("/rest/service/items"),
            Some(vec!["items".to_string()])
        );
    }

    #[test]
    fn test_generate_tags_with_special_actions() {
        assert_eq!(
            generate_tags("/api/observations/import"),
            Some(vec!["observations".to_string(), "import".to_string()])
        );
        assert_eq!(
            generate_tags("/api/observations/upload"),
            Some(vec!["observations".to_string(), "upload".to_string()])
        );
        assert_eq!(
            generate_tags("/users/export"),
            Some(vec!["users".to_string(), "export".to_string()])
        );
    }

    #[test]
    fn test_generate_tags_with_id_parameter() {
        assert_eq!(
            generate_tags("/api/observations/{id}"),
            Some(vec!["observations".to_string()])
        );
        assert_eq!(
            generate_tags("/users/{user_id}"),
            Some(vec!["users".to_string()])
        );
    }

    #[test]
    fn test_singularize() {
        // Regular plurals that cruet handles well
        assert_eq!(singularize("users"), "user");
        assert_eq!(singularize("observations"), "observation");
        assert_eq!(singularize("items"), "item");

        // Irregular plurals - handled by manual overrides + cruet
        assert_eq!(singularize("mice"), "mouse"); // cruet handles this
        assert_eq!(singularize("children"), "child"); // manual override
        assert_eq!(singularize("people"), "person"); // manual override
        assert_eq!(singularize("feet"), "foot"); // manual override
        assert_eq!(singularize("teeth"), "tooth"); // manual override
        assert_eq!(singularize("geese"), "goose"); // manual override
        assert_eq!(singularize("men"), "man"); // manual override
        assert_eq!(singularize("women"), "woman"); // manual override
        assert_eq!(singularize("data"), "datum"); // manual override

        // Words ending in 'es'
        assert_eq!(singularize("boxes"), "box");
        assert_eq!(singularize("watches"), "watch");

        // Already singular - cruet handles these gracefully
        assert_eq!(singularize("user"), "user");
        assert_eq!(singularize("child"), "child");

        // Edge cases - with fallback protection
        assert_eq!(singularize("s"), "s"); // Falls back to original when cruet returns empty
        assert_eq!(singularize(""), ""); // Empty string stays empty

        // Complex cases that cruet handles well
        assert_eq!(singularize("categories"), "category");
        assert_eq!(singularize("companies"), "company");
        assert_eq!(singularize("libraries"), "library");

        // Additional cases cruet handles
        assert_eq!(singularize("stories"), "story");
        assert_eq!(singularize("cities"), "city");
    }

    #[test]
    fn test_normalize_json_content_type() {
        let content_type = ContentType::json();
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "application/json");
    }

    #[test]
    fn test_normalize_multipart_content_type() {
        // Create a multipart content type with boundary
        let content_type_str = "multipart/form-data; boundary=----formdata-clawspec-12345";
        let content_type = ContentType::from(
            content_type_str
                .parse::<mime::Mime>()
                .expect("MIME type is valid"),
        );
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "multipart/form-data");
    }

    #[test]
    fn test_normalize_form_urlencoded_content_type() {
        let content_type = ContentType::form_url_encoded();
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "application/x-www-form-urlencoded");
    }

    #[test]
    fn test_normalize_content_type_with_charset() {
        // Test content type with charset parameter
        let content_type_str = "application/json; charset=utf-8";
        let content_type = ContentType::from(
            content_type_str
                .parse::<mime::Mime>()
                .expect("MIME type is valid"),
        );
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "application/json");
    }

    #[test]
    fn test_normalize_content_type_with_multiple_parameters() {
        // Test content type with multiple parameters
        let content_type_str = "text/html; charset=utf-8; boundary=something";
        let content_type = ContentType::from(
            content_type_str
                .parse::<mime::Mime>()
                .expect("MIME type is valid"),
        );
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "text/html");
    }

    #[test]
    fn test_normalize_content_type_without_parameters() {
        // Test content type without parameters (should remain unchanged)
        let content_type_str = "application/xml";
        let content_type = ContentType::from(
            content_type_str
                .parse::<mime::Mime>()
                .expect("MIME type is valid"),
        );
        let normalized = normalize_content_type(&content_type);
        assert_eq!(normalized, "application/xml");
    }
}