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
//! # Chapter 7: Test Integration
//!
//! This chapter covers using [`TestClient`][crate::test_client::TestClient] for
//! end-to-end testing with automatic server lifecycle management.
//!
//! ## Why TestClient?
//!
//! While [`ApiClient`][crate::ApiClient] works against any HTTP server,
//! [`TestClient`][crate::test_client::TestClient] provides:
//!
//! - **Automatic server startup** on a random port
//! - **Health checking** with exponential backoff
//! - **Automatic cleanup** when tests complete
//! - **Direct access** to all `ApiClient` methods
//!
//! ## Implementing TestServer
//!
//! First, implement the [`TestServer`][crate::test_client::TestServer] trait for your server:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::{TestServer, TestServerConfig, HealthStatus};
//! use clawspec_core::ApiClient;
//! use std::net::TcpListener;
//!
//! #[derive(Debug)]
//! struct MyAppServer;
//!
//! impl TestServer for MyAppServer {
//! type Error = std::io::Error;
//!
//! async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! // Convert to async listener
//! listener.set_nonblocking(true)?;
//! let listener = tokio::net::TcpListener::from_std(listener)?;
//!
//! // Start your server (Axum, Actix, Warp, etc.)
//! // my_app::run(listener).await?;
//!
//! Ok(())
//! }
//! }
//! ```
//!
//! ## Custom Health Checks
//!
//! Override `is_healthy` for custom health checking:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::{TestServer, HealthStatus};
//! use clawspec_core::ApiClient;
//! use std::net::TcpListener;
//!
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! impl TestServer for MyAppServer {
//! type Error = std::io::Error;
//!
//! async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! listener.set_nonblocking(true)?;
//! let _ = tokio::net::TcpListener::from_std(listener)?;
//! Ok(())
//! }
//!
//! async fn is_healthy(&self, client: &mut ApiClient) -> Result<HealthStatus, Self::Error> {
//! // Check your actual health endpoint
//! match client.get("/health")
//! .expect("valid path")
//! .without_collection() // Don't include in OpenAPI
//! .await
//! {
//! Ok(_) => Ok(HealthStatus::Healthy),
//! Err(_) => Ok(HealthStatus::Unhealthy),
//! }
//! }
//! }
//! ```
//!
//! ## Configuring the Test Server
//!
//! Use [`TestServerConfig`][crate::test_client::TestServerConfig] for customization:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::{TestServer, TestServerConfig};
//! use clawspec_core::ApiClient;
//! use utoipa::openapi::{InfoBuilder, ServerBuilder};
//! use std::net::TcpListener;
//! use std::time::Duration;
//!
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! impl TestServer for MyAppServer {
//! type Error = std::io::Error;
//!
//! async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! listener.set_nonblocking(true)?;
//! let _ = tokio::net::TcpListener::from_std(listener)?;
//! Ok(())
//! }
//!
//! fn config(&self) -> TestServerConfig {
//! // Configure the API client with metadata
//! let client_builder = ApiClient::builder()
//! .with_base_path("/api/v1").expect("valid path")
//! .with_info(
//! InfoBuilder::new()
//! .title("My API")
//! .version("1.0.0")
//! .build()
//! )
//! .add_server(
//! ServerBuilder::new()
//! .url("https://api.example.com")
//! .description(Some("Production"))
//! .build()
//! );
//!
//! TestServerConfig {
//! api_client: Some(client_builder),
//! min_backoff_delay: Duration::from_millis(10),
//! max_backoff_delay: Duration::from_secs(5),
//! backoff_jitter: true,
//! max_retry_attempts: 20,
//! }
//! }
//! }
//! ```
//!
//! ## Writing Tests
//!
//! Use [`TestClient::start`][crate::test_client::TestClient::start] in your tests:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::TestClient;
//! # use clawspec_core::test_client::TestServer;
//! # use std::net::TcpListener;
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! # impl TestServer for MyAppServer {
//! # type Error = std::io::Error;
//! # async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! # listener.set_nonblocking(true)?;
//! # let _ = tokio::net::TcpListener::from_std(listener)?;
//! # Ok(())
//! # }
//! # }
//! use serde::{Deserialize, Serialize};
//! use utoipa::ToSchema;
//!
//! #[derive(Serialize, ToSchema)]
//! struct CreateUser { name: String }
//!
//! #[derive(Deserialize, ToSchema)]
//! struct User { id: u64, name: String }
//!
//! #[tokio::test]
//! async fn test_user_crud() -> Result<(), Box<dyn std::error::Error>> {
//! // Start server and get client
//! let mut client = TestClient::start(MyAppServer).await?;
//!
//! // Create user
//! let user: User = client.post("/users")?
//! .json(&CreateUser { name: "Alice".to_string() })?
//! .with_tag("users")
//! .await?
//! .as_json()
//! .await?;
//!
//! assert_eq!(user.name, "Alice");
//!
//! // Get user
//! let fetched: User = client.get(format!("/users/{}", user.id))?
//! .with_tag("users")
//! .await?
//! .as_json()
//! .await?;
//!
//! assert_eq!(fetched.id, user.id);
//!
//! Ok(())
//! } // Server automatically stops when client is dropped
//! ```
//!
//! ## Generating OpenAPI
//!
//! Use [`write_openapi`][crate::test_client::TestClient::write_openapi] to save the spec:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::TestClient;
//! # use clawspec_core::test_client::TestServer;
//! # use std::net::TcpListener;
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! # impl TestServer for MyAppServer {
//! # type Error = std::io::Error;
//! # async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! # listener.set_nonblocking(true)?;
//! # let _ = tokio::net::TcpListener::from_std(listener)?;
//! # Ok(())
//! # }
//! # }
//!
//! #[tokio::test]
//! async fn generate_openapi() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = TestClient::start(MyAppServer).await?;
//!
//! // Exercise all your API endpoints...
//! client.get("/users")?.with_tag("users").await?;
//! client.post("/users")?.with_tag("users").await?;
//! client.get("/users/1")?.with_tag("users").await?;
//! client.delete("/users/1")?.with_tag("users").await?;
//!
//! // Generate OpenAPI spec (format detected by extension)
//! client.write_openapi("docs/openapi.yml").await?;
//! // Or JSON: client.write_openapi("docs/openapi.json").await?;
//!
//! Ok(())
//! }
//! ```
//!
//! ## Test Organization Pattern
//!
//! A common pattern is to have a dedicated test for OpenAPI generation:
//!
//! ```rust,no_run
//! // tests/generate_openapi.rs
//! use clawspec_core::test_client::TestClient;
//! # use clawspec_core::test_client::TestServer;
//! # use std::net::TcpListener;
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! # impl TestServer for MyAppServer {
//! # type Error = std::io::Error;
//! # async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! # listener.set_nonblocking(true)?;
//! # let _ = tokio::net::TcpListener::from_std(listener)?;
//! # Ok(())
//! # }
//! # }
//!
//! #[tokio::test]
//! async fn generate_openapi() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = TestClient::start(MyAppServer).await?;
//!
//! // Call helper functions that exercise different parts of the API
//! test_users_endpoints(&mut client).await?;
//! test_posts_endpoints(&mut client).await?;
//! test_error_cases(&mut client).await?;
//!
//! // Generate the spec
//! client.write_openapi("docs/openapi.yml").await?;
//!
//! Ok(())
//! }
//!
//! async fn test_users_endpoints(client: &mut TestClient<MyAppServer>) -> Result<(), Box<dyn std::error::Error>> {
//! client.get("/users")?
//! .with_tag("users")
//! .with_description("List all users")
//! .await?;
//! // ... more user endpoints
//! Ok(())
//! }
//! # async fn test_posts_endpoints(client: &mut TestClient<MyAppServer>) -> Result<(), Box<dyn std::error::Error>> { Ok(()) }
//! # async fn test_error_cases(client: &mut TestClient<MyAppServer>) -> Result<(), Box<dyn std::error::Error>> { Ok(()) }
//! ```
//!
//! ## Accessing the Underlying Client
//!
//! `TestClient` derefs to `ApiClient`, so all methods are available:
//!
//! ```rust,no_run
//! use clawspec_core::test_client::TestClient;
//! # use clawspec_core::test_client::TestServer;
//! # use std::net::TcpListener;
//! # #[derive(Debug)]
//! # struct MyAppServer;
//! # impl TestServer for MyAppServer {
//! # type Error = std::io::Error;
//! # async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
//! # listener.set_nonblocking(true)?;
//! # let _ = tokio::net::TcpListener::from_std(listener)?;
//! # Ok(())
//! # }
//! # }
//! # use serde::{Serialize, Deserialize};
//! # use utoipa::ToSchema;
//! # #[derive(Serialize, Deserialize, ToSchema)]
//! # struct MySchema { field: String }
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = TestClient::start(MyAppServer).await?;
//!
//! // All ApiClient methods work directly
//! client.register_schema::<MySchema>().await;
//! let spec = client.collected_openapi().await;
//! # Ok(())
//! # }
//! ```
//!
//! ## Key Points
//!
//! - Implement [`TestServer`][crate::test_client::TestServer] for your web framework
//! - Override `is_healthy()` for custom health checking
//! - Override `config()` for API metadata and timing settings
//! - Use `TestClient::start()` in tests for automatic lifecycle management
//! - Use `write_openapi()` to generate specs in YAML or JSON format
//! - Server stops automatically when `TestClient` is dropped
//!
//! ## Complete Example
//!
//! For a full working example with Axum, see the
//! [axum-example](https://github.com/ilaborie/clawspec/tree/main/examples/axum-example)
//! in the Clawspec repository.
//!
//! ---
//!
//! Congratulations! You've completed the Clawspec tutorial. You now know how to:
//!
//! - Create and configure API clients
//! - Make requests with various parameters
//! - Handle different response types
//! - Customize OpenAPI output
//! - Use redaction for stable examples
//! - Integrate with test frameworks
//!
//! For more details, explore the [API documentation][crate] or check out the
//! [GitHub repository](https://github.com/ilaborie/clawspec).