rsoap 0.2.0

A SOAP client library for Rust with compile-time code generation from WSDL files
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
//! Integration tests for rsoap — SOAP client, envelope parsing, and code generation from WSDL.

use rsoap::{SoapClient, SoapOperation, SoapVersion};

// ---------------------------------------------------------------------------
// Unit / smoke tests
// ---------------------------------------------------------------------------

/// Test that SoapClient creation works with valid URLs.
#[test]
fn creates_client_with_valid_url() {
    let client = SoapClient::new("https://example.com/soap").unwrap();
    assert_eq!(client.endpoint(), "https://example.com/soap");
}

/// Test that invalid URLs are rejected.
#[test]
fn rejects_invalid_url() {
    SoapClient::new("not-a-url").unwrap_err();
}

/// Test SOAP fault detection and parsing.
#[test]
fn parses_soap_fault() {
    let fault_xml = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <soap:Fault xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                         <faultcode>Server</faultcode>
                        <faultstring>Invalid credentials</faultstring>
                     </soap:Fault>
                 </soap:Body>
             </soap:Envelope>"#;

    let (code, message) = rsoap::envelope::parse_soap_fault(fault_xml).unwrap();
    assert_eq!(code, "Server");
    assert_eq!(message, "Invalid credentials");
}

/// Test that response bodies are correctly extracted from SOAP envelopes.
#[test]
fn extracts_body_from_envelope() {
    let xml = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
           <soap:Body>
             <GetWeatherResponse>
               <temperature>72</temperature>
             </GetWeatherResponse>
            </soap:Body>
          </soap:Envelope>"#;

    let body = rsoap::envelope::extract_body(xml).unwrap();
    assert!(body.contains("GetWeatherResponse"));
    assert!(body.contains("72"));
}

/// Test that SOAP fault strings with no code produce defaults.
#[test]
fn empty_soap_fault_defaults() {
    let fault_xml = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <soap:Fault xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                         <faultstring>Generic error</faultstring>
                     </soap:Fault>
                 </soap:Body>
             </soap:Envelope>"#;

    let (code, message) = rsoap::envelope::parse_soap_fault(fault_xml).unwrap();
    assert_eq!(code, "unknown");
    assert_eq!(message, "Generic error");
}

/// Test that SOAP clients can be constructed with headers.
#[test]
fn client_with_headers() {
    let client = SoapClient::new("https://example.com")
        .unwrap()
        .with_header("X-Auth", "token123")
        .with_header("X-Tenant", "acme");

    let debug = format!("{client:?}");
    assert!(debug.contains("SoapClient"));
    assert!(debug.contains("X-Auth"));
    assert!(debug.contains("X-Tenant"));
    assert!(debug.contains("token123"));
    assert!(debug.contains("acme"));
}

/// Test end-to-end request serialization and response deserialization.
#[test]
fn full_serialize_deserialize_round_trip() {
    #[derive(Debug, serde::Serialize)]
    struct WeatherReq {
        zip: String,
    }

    #[derive(Debug, serde::Deserialize)]
    struct WeatherRsp {
        temp: Option<f64>,
    }

    let req = WeatherReq {
        zip: "90210".into(),
    };
    let xml = rsoap::quick_xml::se::to_string_with_root("GetWeather", &req).unwrap();
    assert!(xml.contains("90210"));

    let resp_xml = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
               <soap:Body>
                   <GetWeather><temp>72.5</temp>
                </GetWeather></soap:Body>
            </soap:Envelope>"#;

    let rsp: WeatherRsp = rsoap::envelope::deserialize_response(resp_xml).unwrap();
    assert_eq!(rsp.temp, Some(72.5));
}

/// Test that SoapOperation trait is correctly exported and usable.
#[test]
fn soap_operation_trait_exists() {
    // Verify the SoapOperation trait methods exist by constructing a dummy impl
    use rsoap::SoapOperation;

    struct DummyOp;

    impl SoapOperation for DummyOp {
        type Request = ();
        type Response = ();

        const ACTION: &'static str = "http://example.com/DummyOp";
        const ENDPOINT: &'static str = "http://localhost:8080/dummy";
        const BODY_ELEMENT: &'static str = "DummyRequest";

        fn build_request_body(
            &self,
            _request: &Self::Request,
        ) -> Result<(String, String), quick_xml::se::SeError> {
            Ok((Self::ACTION.into(), Self::BODY_ELEMENT.into()))
        }

        fn parse_response(&self, _response_xml: &str) -> Result<Self::Response, rsoap::SoapError>
        where
            Self::Response: serde::de::DeserializeOwned,
        {
            Ok(())
        }
    }

    let _op = DummyOp;
    assert_eq!(
        <DummyOp as SoapOperation>::ACTION,
        "http://example.com/DummyOp"
    );
    // (no ENDPOINT assertion needed - const access confirmed above)
}

// ---------------------------------------------------------------------------
// End-to-end tests with a wiremock SOAP server
// ---------------------------------------------------------------------------

/// A minimal dummy operation that produces a well-known SOAP envelope payload.
#[derive(Debug)]
struct TestOp;

impl SoapOperation for TestOp {
    type Request = WeatherReqE2e;
    type Response = WeatherRspE2e;

    const ACTION: &'static str = "http://example.com/GetWeather";
    const ENDPOINT: &'static str = "http://127.0.0.1:0/mock-soap"; // port set by mock server at runtime
    const BODY_ELEMENT: &'static str = "GetWeather";
}

#[derive(Debug, serde::Serialize)]
struct WeatherReqE2e {
    zip_code: String,
}

#[derive(Debug, PartialEq, serde::Deserialize)]
struct WeatherRspE2e {
    temperature: f64,
}

/// End-to-end: successful SOAP call through mock server.
#[tokio::test]
async fn e2e_successful_call() {
    let mock_server = wiremock::MockServer::start().await;

    // Arrange a response body matching what the macro-generated op would expect
    let soap_response = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            <soap:Body>
                <GetWeatherResponse>
                    <temperature>72.5</temperature>
                </GetWeatherResponse>
            </soap:Body>
        </soap:Envelope>"#;

    // Mount the mock expectation
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_response))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp,
            &WeatherReqE2e {
                zip_code: "90210".into(),
            },
        )
        .await;

    assert!(
        result.is_ok(),
        "expected successful call, got error: {:?}",
        result.err()
    );
    let rsp = result.unwrap();
    assert_eq!(rsp.temperature, 72.5);
}

/// End-to-end: soap fault returned by server produces SoapError::SoapFault.
#[tokio::test]
async fn e2e_soap_fault() {
    let mock_server = wiremock::MockServer::start().await;

    let soap_fault = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            <soap:Body>
                <soap:Fault xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                    <faultcode>Client</faultcode>
                    <faultstring>Invalid API key</faultstring>
                </soap:Fault>
            </soap:Body>
        </soap:Envelope>"#;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_fault))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp,
            &WeatherReqE2e {
                zip_code: "10001".into(),
            },
        )
        .await;

    assert!(result.is_err(), "expected SoapFault error");
    match result.unwrap_err() {
        rsoap::SoapError::SoapFault { code, message } => {
            assert_eq!(code, "Client");
            assert_eq!(message, "Invalid API key");
        }
        other => panic!("expected SoapFault, got {:?}", other),
    }
}

/// End-to-end: server returns non-200 HTTP status → SoapError::Http.
#[tokio::test]
async fn e2e_http_error() {
    let mock_server = wiremock::MockServer::start().await;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp,
            &WeatherReqE2e {
                zip_code: "0".into(),
            },
        )
        .await;

    assert!(result.is_err(), "expected HTTP error");
    match result.unwrap_err() {
        rsoap::SoapError::HttpStatus { code, .. } => assert_eq!(code, 500),
        other => panic!("expected SoapError::HttpStatus, got {:?}", other),
    }
}

/// End-to-end: mock server validates that the request body contains expected XML.
#[tokio::test]
async fn e2e_request_body_check() {
    let mock_server = wiremock::MockServer::start().await;

    let soap_response = r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
              <soap:Body>
                  <GetWeatherResponse><temperature>68.0</temperature></GetWeatherResponse>
              </soap:Body>
          </soap:Envelope>"#;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::header(
            "Content-Type",
            "text/xml; charset=utf-8",
        ))
        .and(|req: &wiremock::Request| {
            String::from_utf8(req.body.clone())
                .unwrap_or_default()
                .contains("90210")
        })
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_response))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp,
            &WeatherReqE2e {
                zip_code: "90210".into(),
            },
        )
        .await;

    assert!(
        result.is_ok(),
        "expected successful call with body check, got error: {:?}",
        result.err()
    );
    assert_eq!(result.unwrap().temperature, 68.0);
}

/// End-to-end: custom headers are included in HTTP requests made through the client.
#[tokio::test]
async fn e2e_custom_headers_sent() {
    let mock_server = wiremock::MockServer::start().await;

    // Verify the Authorization header was sent with the correct value
    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::header("Authorization", "Bearer mytoken123"))
        .respond_with(wiremock::ResponseTemplate::new(200)
            .set_body_string(r#"<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body><GetWeatherResponse><temperature>80.0</temperature></GetWeatherResponse></soap:Body>
            </soap:Envelope>"#))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri())
        .unwrap()
        .with_header("Authorization", "Bearer mytoken123");

    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp,
            &WeatherReqE2e {
                zip_code: "30301".into(),
            },
        )
        .await;

    assert!(
        result.is_ok(),
        "expected successful call with auth header, got error: {:?}",
        result.err()
    );
}

// ---------------------------------------------------------------------------
// SOAP 1.2 tests
// ---------------------------------------------------------------------------

/// A 1.2 version of the dummy operation for end-to-end SOAP 1.2 testing.
#[derive(Debug)]
struct TestOp12;

impl SoapOperation for TestOp12 {
    type Request = WeatherReqE2e;
    type Response = WeatherRspE2e;

    const ACTION: &'static str = "http://example.com/GetWeather12";
    const ENDPOINT: &'static str = "http://127.0.0.1:0/mock-soap12";
    const BODY_ELEMENT: &'static str = "GetWeather";
    const VERSION: SoapVersion = SoapVersion::V12;
}

/// End-to-end: SOAP 1.2 request — verify Content-Type includes the action
/// parameter and no `SOAPAction` HTTP header is sent.
#[tokio::test]
async fn e2e_soap12_content_type_carries_action() {
    let mock_server = wiremock::MockServer::start().await;

    let soap_response = r#"<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
            <env:Body>
                <GetWeatherResponse>
                    <temperature>65.0</temperature>
                </GetWeatherResponse>
            </env:Body>
        </env:Envelope>"#;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(wiremock::matchers::header_regex(
            "Content-Type",
            r#"^application/soap\+xml; charset=utf-8; action="http://example.com/GetWeather12""#,
        ))
        .and(|req: &wiremock::Request| {
            !req.headers
                .iter()
                .any(|(k, _)| k.as_str().eq_ignore_ascii_case("SOAPAction"))
        })
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_response))
        .expect(1)
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp12,
            &WeatherReqE2e {
                zip_code: "20001".into(),
            },
        )
        .await;

    assert!(
        result.is_ok(),
        "expected successful 1.2 call, got error: {:?}",
        result.err()
    );
    assert_eq!(result.unwrap().temperature, 65.0);
}

/// End-to-end: SOAP 1.2 request — verify envelope uses env: prefix and 1.2 namespace.
#[tokio::test]
async fn e2e_soap12_envelope_uses_env_namespace() {
    let mock_server = wiremock::MockServer::start().await;

    let soap_response = r#"<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
            <env:Body>
                <GetWeatherResponse>
                    <temperature>70.0</temperature>
                </GetWeatherResponse>
            </env:Body>
        </env:Envelope>"#;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .and(|req: &wiremock::Request| {
            String::from_utf8(req.body.clone())
                .unwrap_or_default()
                .contains("<env:Envelope")
                && String::from_utf8(req.body.clone())
                    .unwrap_or_default()
                    .contains("http://www.w3.org/2003/05/soap-envelope")
        })
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_response))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp12,
            &WeatherReqE2e {
                zip_code: "94101".into(),
            },
        )
        .await;

    assert!(
        result.is_ok(),
        "expected successful 1.2 envelope call, got error: {:?}",
        result.err()
    );
}

/// End-to-end: SOAP 1.2 fault — server returns a 1.2 fault, client detects it.
#[tokio::test]
async fn e2e_soap12_fault_detected() {
    let mock_server = wiremock::MockServer::start().await;

    let soap_fault = r#"<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
            <env:Body>
                <env:Fault>
                    <Code><Value>env:Sender</Value></Code>
                    <Reason><Text xml:lang="en">Invalid zip code</Text></Reason>
                </env:Fault>
            </env:Body>
        </env:Envelope>"#;

    wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(soap_fault))
        .mount(&mock_server)
        .await;

    let client = SoapClient::new(mock_server.uri()).unwrap();
    let result: Result<WeatherRspE2e, _> = client
        .call(
            &TestOp12,
            &WeatherReqE2e {
                zip_code: "00000".into(),
            },
        )
        .await;

    assert!(result.is_err(), "expected SoapFault error for 1.2");
    match result.unwrap_err() {
        rsoap::SoapError::SoapFault { code, message } => {
            assert_eq!(code, "env:Sender");
            assert_eq!(message, "Invalid zip code");
        }
        other => panic!("expected SoapFault, got {:?}", other),
    }
}