coapum 0.2.0

A modern, ergonomic CoAP (Constrained Application Protocol) library for Rust with support for DTLS, observers, and asynchronous handlers
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
//! Error path coverage tests
//!
//! These tests specifically target error handling paths that were identified
//! as having low coverage in the serve.rs and other modules.

use std::sync::Arc;

use coapum::{
    ContentFormat,
    extract::{Cbor, Json, StatusCode},
    observer::memory::MemObserver,
    router::RouterBuilder,
};
use serde::{Deserialize, Serialize};
use tower::Service;

#[derive(Debug, Clone)]
struct ErrorTestState {
    should_error: Arc<std::sync::Mutex<bool>>,
}

impl AsRef<ErrorTestState> for ErrorTestState {
    fn as_ref(&self) -> &ErrorTestState {
        self
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct ErrorTestData {
    id: u32,
    force_error: bool,
}

// Handler that can simulate state access errors
async fn handler_with_state_error(
    coapum::extract::State(state): coapum::extract::State<ErrorTestState>,
) -> StatusCode {
    let should_error = state.should_error.lock().unwrap();
    if *should_error {
        // Simulate a scenario where state access fails
        drop(should_error);
        // Force an error condition by returning server error
        StatusCode::InternalServerError
    } else {
        StatusCode::Content
    }
}

// Handler that can fail response serialization
async fn handler_response_serialization_test(
    Json(data): Json<ErrorTestData>,
) -> Result<Json<ErrorTestData>, StatusCode> {
    if data.force_error {
        Err(StatusCode::InternalServerError)
    } else {
        Ok(Json(data))
    }
}

// Handler that tests CBOR serialization errors
async fn handler_cbor_serialization_test(
    Cbor(data): Cbor<ErrorTestData>,
) -> Result<Cbor<ErrorTestData>, StatusCode> {
    if data.force_error {
        Err(StatusCode::BadRequest)
    } else {
        Ok(Cbor(data))
    }
}

// Handler with complex error conditions
async fn handler_complex_error_scenarios(
    Json(data): Json<ErrorTestData>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    // Simulate various error conditions
    match data.id {
        0 => Err(StatusCode::BadRequest),
        1 => Err(StatusCode::Unauthorized),
        2 => Err(StatusCode::Forbidden),
        3 => Err(StatusCode::NotFound),
        4 => Err(StatusCode::MethodNotAllowed),
        5 => Err(StatusCode::NotAcceptable),
        6 => Err(StatusCode::PreconditionFailed),
        7 => Err(StatusCode::RequestEntityTooLarge),
        8 => Err(StatusCode::UnsupportedContentFormat),
        9 => Err(StatusCode::InternalServerError),
        10 => Err(StatusCode::NotImplemented),
        11 => Err(StatusCode::BadGateway),
        12 => Err(StatusCode::ServiceUnavailable),
        13 => Err(StatusCode::GatewayTimeout),
        _ => Ok(Json(serde_json::json!({
            "id": data.id,
            "status": "success"
        }))),
    }
}

mod error_handling_tests {
    use super::*;

    #[tokio::test]
    async fn test_state_access_error_handling() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(true)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .get("/state_error", handler_with_state_error)
            .build();

        let request = coapum::test_utils::create_test_request("/state_error");
        let response = router.call(request).await.unwrap();

        assert_eq!(
            *response.get_status(),
            coapum::ResponseType::InternalServerError
        );
    }

    #[tokio::test]
    async fn test_json_extraction_error_paths() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/json_test", handler_response_serialization_test)
            .build();

        // Test with completely invalid JSON
        let invalid_json = b"}{invalid json{";
        let request = coapum::test_utils::create_test_request_with_content(
            "/json_test",
            invalid_json.to_vec(),
            ContentFormat::ApplicationJSON,
        );

        let response = router.call(request).await.unwrap();
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }

    #[tokio::test]
    async fn test_cbor_extraction_error_paths() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/cbor_test", handler_cbor_serialization_test)
            .build();

        // Test with invalid CBOR data
        let invalid_cbor = vec![0xFF, 0xFF, 0xFF, 0xFF];
        let request = coapum::test_utils::create_test_request_with_content(
            "/cbor_test",
            invalid_cbor,
            ContentFormat::ApplicationCBOR,
        );

        let response = router.call(request).await.unwrap();
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }

    #[tokio::test]
    async fn test_response_serialization_error() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/serialize_error", handler_response_serialization_test)
            .build();

        let error_data = ErrorTestData {
            id: 123,
            force_error: true,
        };
        let json_data = serde_json::to_vec(&error_data).unwrap();

        let request = coapum::test_utils::create_test_request_with_content(
            "/serialize_error",
            json_data,
            ContentFormat::ApplicationJSON,
        );

        let response = router.call(request).await.unwrap();
        assert_eq!(
            *response.get_status(),
            coapum::ResponseType::InternalServerError
        );
    }

    #[tokio::test]
    async fn test_all_error_status_codes() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/error_codes", handler_complex_error_scenarios)
            .build();

        let error_codes_to_test = vec![
            (0, coapum::ResponseType::BadRequest),
            (1, coapum::ResponseType::Unauthorized),
            (2, coapum::ResponseType::Forbidden),
            (3, coapum::ResponseType::NotFound),
            (4, coapum::ResponseType::MethodNotAllowed),
            (5, coapum::ResponseType::NotAcceptable),
            (6, coapum::ResponseType::PreconditionFailed),
            (7, coapum::ResponseType::RequestEntityTooLarge),
            (8, coapum::ResponseType::UnsupportedContentFormat),
            (9, coapum::ResponseType::InternalServerError),
            (10, coapum::ResponseType::NotImplemented),
            (11, coapum::ResponseType::BadGateway),
            (12, coapum::ResponseType::ServiceUnavailable),
            (13, coapum::ResponseType::GatewayTimeout),
        ];

        for (error_id, expected_status) in error_codes_to_test {
            let error_data = ErrorTestData {
                id: error_id,
                force_error: false,
            };
            let json_data = serde_json::to_vec(&error_data).unwrap();

            let request = coapum::test_utils::create_test_request_with_content(
                "/error_codes",
                json_data,
                ContentFormat::ApplicationJSON,
            );

            let response = router.call(request).await.unwrap();
            assert_eq!(
                *response.get_status(),
                expected_status,
                "Failed for error ID: {}",
                error_id
            );
        }
    }

    #[tokio::test]
    async fn test_successful_response_after_errors() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/error_codes", handler_complex_error_scenarios)
            .build();

        // Test successful case
        let success_data = ErrorTestData {
            id: 999, // Will return success
            force_error: false,
        };
        let json_data = serde_json::to_vec(&success_data).unwrap();

        let request = coapum::test_utils::create_test_request_with_content(
            "/error_codes",
            json_data,
            ContentFormat::ApplicationJSON,
        );

        let response = router.call(request).await.unwrap();
        assert_eq!(*response.get_status(), coapum::ResponseType::Content);

        let response_data: serde_json::Value =
            serde_json::from_slice(&response.message.payload).unwrap();
        assert_eq!(response_data["id"], 999);
        assert_eq!(response_data["status"], "success");
    }
}

mod content_format_error_tests {
    use super::*;

    #[tokio::test]
    async fn test_wrong_content_format_error() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/format_test", handler_response_serialization_test)
            .build();

        let valid_json_data = serde_json::json!({
            "id": 42,
            "force_error": false
        });
        let json_bytes = serde_json::to_vec(&valid_json_data).unwrap();

        // Send JSON data but claim it's CBOR
        let request = coapum::test_utils::create_test_request_with_content(
            "/format_test",
            json_bytes,
            ContentFormat::ApplicationCBOR, // Wrong format!
        );

        let response = router.call(request).await.unwrap();
        // Should fail due to content format mismatch
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }

    #[tokio::test]
    async fn test_missing_content_format() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/no_format", handler_response_serialization_test)
            .build();

        let valid_json_data = serde_json::json!({
            "id": 42,
            "force_error": false
        });
        let json_bytes = serde_json::to_vec(&valid_json_data).unwrap();

        // Create request without explicit content format
        let mut request = coapum::test_utils::create_test_request("/no_format");
        request.message.payload = json_bytes;
        // Don't set content format - this may cause extraction issues

        let _response = router.call(request).await.unwrap();
        // Handler should handle missing content format gracefully
        // Just verify we get some response (success or error)
        // This test validates that the code path exists - assertion removed to fix clippy warning
    }

    #[tokio::test]
    async fn test_empty_payload_with_content_format() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .post("/empty_payload", handler_response_serialization_test)
            .build();

        // Create request with content format but empty payload
        let request = coapum::test_utils::create_test_request_with_content(
            "/empty_payload",
            vec![], // Empty payload
            ContentFormat::ApplicationJSON,
        );

        let response = router.call(request).await.unwrap();
        // Should handle empty payload error
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }
}

mod router_error_path_tests {
    use super::*;

    #[tokio::test]
    async fn test_route_not_found_error() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .get("/existing", handler_with_state_error)
            .build();

        // Request non-existent route
        let request = coapum::test_utils::create_test_request("/nonexistent");
        let response = router.call(request).await.unwrap();

        // Should return appropriate error for missing route
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }

    #[tokio::test]
    async fn test_method_not_allowed_error() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .get("/get_only", handler_with_state_error) // Only GET is registered
            .build();

        // Try to POST to a GET-only route
        let request =
            coapum::test_utils::create_test_request_with_payload("/get_only", vec![1, 2, 3]);

        let response = router.call(request).await.unwrap();
        // Should handle method not allowed
        assert_ne!(*response.get_status(), coapum::ResponseType::Content);
    }

    #[tokio::test]
    async fn test_malformed_path_parameters() {
        let state = ErrorTestState {
            should_error: Arc::new(std::sync::Mutex::new(false)),
        };

        let observer = MemObserver::new();
        let mut router = RouterBuilder::new(state, observer)
            .get("/test/:id", handler_with_state_error)
            .build();

        // Test with various potentially problematic paths
        let problematic_paths = vec![
            "/test/",  // Empty parameter
            "/test//", // Double slash
            "/test/id%with%encoded%chars",
            "/test/very_long_parameter_that_might_cause_issues_with_parsing_or_memory",
        ];

        for path in problematic_paths {
            let request = coapum::test_utils::create_test_request(path);
            let response = router.call(request).await;

            // Should handle malformed paths gracefully
            assert!(response.is_ok(), "Failed to handle path: {}", path);
        }
    }
}