pact_verifier 1.3.5

Pact-Rust support library that implements provider verification functions
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
use std::collections::HashMap;
use std::panic::RefUnwindSafe;

use ansi_term::{ANSIGenericString, Style};
use ansi_term::Colour::*;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use bytes::Bytes;
use maplit::*;
use pact_models::bodies::OptionalBody;
use pact_models::http_parts::HttpPart;
use pact_models::interaction::Interaction;
use pact_models::message::Message;
use pact_models::prelude::Pact;
use pact_models::v4::async_message::AsynchronousMessage;
use pact_models::v4::http_parts::{HttpRequest, HttpResponse};
use pact_models::v4::message_parts::MessageContents;
use pact_models::v4::sync_message::SynchronousMessage;
use serde_json::{json, Value};
use tracing::{debug, trace, warn};

use pact_matching::{match_message, match_sync_message_response, Mismatch};

use crate::{MismatchResult, ProviderInfo, ProviderTransport, VerificationOptions};
use crate::callback_executors::RequestFilterExecutor;
use crate::provider_client::make_provider_request;
use crate::utils::as_safe_ref;

pub(crate) async fn verify_message_from_provider<'a, F: RequestFilterExecutor>(
  provider: &ProviderInfo,
  pact: &Box<dyn Pact + Send + Sync + RefUnwindSafe + 'a>,
  interaction: &Box<dyn Interaction + Send + Sync + RefUnwindSafe>,
  options: &VerificationOptions<F>,
  client: &reqwest::Client,
  _: &HashMap<&str, Value>
) -> Result<Option<String>, MismatchResult> {
  let mut request_body = json!({
    "description": interaction.description()
  });

  if !interaction.provider_states().is_empty() {
    if let Some(map) = request_body.as_object_mut() {
      map.insert("providerStates".into(), Value::Array(interaction.provider_states().iter()
        .map(|ps| ps.to_json()).collect()));
    }
  }

  let message_request = HttpRequest {
    method: "POST".into(),
    body: OptionalBody::Present(Bytes::from(request_body.to_string()), Some("application/json".into()), None),
    headers: Some(hashmap! {
        "Content-Type".to_string() => vec!["application/json".to_string()]
    }),
    .. HttpRequest::default()
  };

  let transport = if interaction.is_v4() {
    if let Some(v4) = interaction.as_v4() {
      v4.transport().clone()
    } else {
      None
    }
  } else {
    None
  };
  let transport = if let Some(transport) = transport {
    provider.transports
      .iter()
      .find(|t| t.transport == transport)
      .cloned()
  } else {
    provider.transports
      .iter()
      .find(|t| t.transport == "message" || t.transport == "async-message")
      .cloned()
  }.map(|t| {
    if t.scheme.is_none() {
      ProviderTransport {
        scheme: Some("http".to_string()),
        .. t
      }
    } else {
      t
    }
  });

  match make_provider_request(provider, &message_request, options, client, transport).await {
    Ok(ref actual_response) => {
      let metadata = extract_metadata(actual_response);
      let actual = AsynchronousMessage {
        contents: MessageContents {
          metadata,
          contents: actual_response.body.clone(),
          .. MessageContents::default()
        },
        .. AsynchronousMessage::default()
      };

      debug!("actual message = {:?}", actual);

      let mismatches = match_message(interaction, &actual.boxed(), pact).await;
      if mismatches.is_empty() {
        Ok(interaction.id().clone())
      } else {
        Err(MismatchResult::Mismatches {
          mismatches,
          expected: as_safe_ref(interaction.as_ref()),
          actual: as_safe_ref(&actual),
          interaction_id: interaction.id().clone()
        })
      }
    },
    Err(err) => {
      Err(MismatchResult::Error(err.to_string(), interaction.id().clone()))
    }
  }
}

pub fn process_message_result(
  interaction: &Message,
  match_result: &Result<Option<String>, MismatchResult>,
  output: &mut Vec<String>,
  coloured: bool) {
  let plain = Style::new();
  match match_result {
    Ok(_) => {
      let metadata_result = interaction.metadata.iter()
        .map(|(k, v)| (
          k.clone(),
          serde_json::to_string(&v.clone()).unwrap_or_default(),
          if coloured { Green.paint("OK") } else { plain.paint("OK") }
        )).collect();
      generate_display_for_result(if coloured { Green.paint("OK") } else { plain.paint("OK") },
        metadata_result, output, coloured);
    },
    Err(err) => match err {
      MismatchResult::Error(err_des, _) => {
        if coloured {
          output.push(format!("      {}", Red.paint(format!("Request Failed - {}", err_des))));
        } else {
          output.push(format!("      {}", format!("Request Failed - {}", err_des)));
        }
      },
      MismatchResult::Mismatches { mismatches, .. } => {
        let metadata_results = interaction.metadata.iter().map(|(k, v)| {
          (k.clone(), serde_json::to_string(&v.clone()).unwrap_or_default(), if mismatches.iter().any(|m| {
            match *m {
              Mismatch::MetadataMismatch { ref key, .. } => k == key,
              _ => false
            }
          }) {
            if coloured { Red.paint("FAILED") } else { plain.paint("FAILED") }
          } else {
            if coloured { Green.paint("OK") } else { plain.paint("OK") }
          })
        }).collect();
        let body_result = if mismatches.iter().any(|m| m.mismatch_type() == "BodyMismatch" ||
          m.mismatch_type() == "BodyTypeMismatch") {
          if coloured { Red.paint("FAILED") } else { plain.paint("FAILED") }
        } else {
          if coloured { Green.paint("OK") } else { plain.paint("OK") }
        };

        generate_display_for_result(body_result, metadata_results, output, coloured);
      }
    }
  }
}

pub fn process_sync_message_result(
  interaction: &SynchronousMessage,
  match_result: &Result<Option<String>, MismatchResult>,
  output: &mut Vec<String>,
  coloured: bool
) {
  let plain = Style::new();
  match match_result {
    Ok(_) => {
      for response in &interaction.response {
        let metadata_result = response.metadata.iter()
          .map(|(k, v)| (
            k.clone(),
            serde_json::to_string(&v.clone()).unwrap_or_default(),
            if coloured { Green.paint("OK") } else { plain.paint("OK") }
          )).collect();
        generate_display_for_result(if coloured { Green.paint("OK") } else { plain.paint("OK") },
                                    metadata_result, output, coloured);
      }
    },
    Err(err) => match err {
      MismatchResult::Error(err_des, _) => {
        if coloured {
          output.push(format!("      {}", Red.paint(format!("Request Failed - {}", err_des))));
        } else {
          output.push(format!("      {}", format!("Request Failed - {}", err_des)));
        }
      },
      MismatchResult::Mismatches { mismatches, .. } => {
        // TODO: need to be able to map the errors to the different responses (if there are multiple)
        // Currently, just using the first one as there is no way to know which one it is for
        let response = interaction.response.first().cloned().unwrap_or_default();
        let metadata_results = response.metadata.iter().map(|(k, v)| {
          (k.clone(), serde_json::to_string(&v.clone()).unwrap_or_default(), if mismatches.iter().any(|m| {
            match *m {
              Mismatch::MetadataMismatch { ref key, .. } => k == key,
              _ => false
            }
          }) {
            if coloured { Red.paint("FAILED") } else { plain.paint("FAILED") }
          } else {
            if coloured { Green.paint("OK") } else { plain.paint("OK") }
          })
        }).collect();
        let body_result = if mismatches.iter().any(|m| m.mismatch_type() == "BodyMismatch" ||
          m.mismatch_type() == "BodyTypeMismatch") {
          if coloured { Red.paint("FAILED") } else { plain.paint("FAILED") }
        } else {
          if coloured { Green.paint("OK") } else { plain.paint("OK") }
        };

        generate_display_for_result(body_result, metadata_results, output, coloured);
      }
    }
  }
}

fn generate_display_for_result(
  body_result: ANSIGenericString<str>,
  metadata_result: Vec<(String, String, ANSIGenericString<str>)>,
  output: &mut Vec<String>,
  coloured: bool
) {
  output.push("    generates a message which".to_string());
  if !metadata_result.is_empty() {
    output.push("      includes metadata".to_string());
    let style = if coloured { Style::new().bold() } else { Style::new() };
    for (key, value, result) in metadata_result {
      output.push(format!("        \"{}\" with value {} ({})", style.paint(key),
        style.paint(value), result));
    }
  }
  output.push(format!("      has a matching body ({})", body_result));
}

fn extract_metadata(actual_response: &HttpResponse) -> HashMap<String, Value> {
  let content_type = "contentType".to_string();

  let mut default = hashmap!{
    content_type => Value::String(actual_response.lookup_content_type().unwrap_or_default()),
  };

  actual_response.headers.clone().unwrap_or_default().iter().for_each(|(k,v)| {
    if k.to_lowercase() == "pact-message-metadata" {
      let json: String = v.first().unwrap_or(&"".to_string()).to_string();
      trace!("found raw metadata from headers: {:?}", json);

      let decoded = STANDARD.decode(json.as_str()).unwrap_or(Vec::default());
      trace!("have base64 decoded headers: {:?}", decoded);

      let metadata: HashMap<String, Value> = serde_json::from_slice(&decoded).unwrap_or_default();
      trace!("have JSON metadata from headers: {:?}", metadata);

      for (k, v) in metadata {
        default.insert(k, v);
      }
    }
  });

  default
}

pub(crate) async fn verify_sync_message_from_provider<'a, F: RequestFilterExecutor>(
  provider: &ProviderInfo,
  pact: &Box<dyn Pact + Send + Sync + RefUnwindSafe + 'a>,
  message: SynchronousMessage,
  options: &VerificationOptions<F>,
  client: &reqwest::Client,
  _: &HashMap<&str, Value>
) -> Result<Option<String>, MismatchResult> {
  if message.response.len() > 1 {
    warn!("Matching synchronous messages with more than one response is not currently supported, will only use the first response");
  }

  let mut request_body = json!({
    "description": message.description(),
    "request": message.request.to_json()
  });

  if !message.provider_states().is_empty() {
    if let Some(map) = request_body.as_object_mut() {
      map.insert("providerStates".into(), Value::Array(message.provider_states().iter()
        .map(|ps| ps.to_json()).collect()));
    }
  }

  let message_request = HttpRequest {
    method: "POST".into(),
    body: OptionalBody::Present(Bytes::from(request_body.to_string()), Some("application/json".into()), None),
    headers: Some(hashmap! {
        "Content-Type".to_string() => vec!["application/json".to_string()]
    }),
    .. HttpRequest::default()
  };

  let transport = if let Some(transport) = &message.transport {
    provider.transports
      .iter()
      .find(|t| &t.transport == transport)
      .cloned()
  } else {
    provider.transports
      .iter()
      .find(|t| t.transport == "message" || t.transport == "sync-message")
      .cloned()
  }.map(|t| {
    if t.scheme.is_none() {
      ProviderTransport {
        scheme: Some("http".to_string()),
        .. t
      }
    } else {
      t
    }
  });

  match make_provider_request(provider, &message_request, options, client, transport).await {
    Ok(ref actual_response) => {
      if actual_response.is_success() {
        let metadata = extract_metadata(actual_response);
        let actual_contents = MessageContents {
          metadata,
          contents: actual_response.body.clone(),
          ..MessageContents::default()
        };
        let actual = SynchronousMessage {
          response: vec![actual_contents],
          .. SynchronousMessage::default()
        };

        debug!("actual synchronous message = {:?}", actual);

        let mismatches = match_sync_message_response(&message, &message.response, &actual.response, pact).await;
        if mismatches.is_empty() {
          Ok(message.id().clone())
        } else {
          Err(MismatchResult::Mismatches {
            mismatches,
            expected: as_safe_ref(&message),
            actual: as_safe_ref(&actual),
            interaction_id: message.id().clone()
          })
        }
      } else {
        Err(MismatchResult::Error(format!("Request to fetch message from provider failed: status {}", actual_response.status), message.id().clone()))
      }
    },
    Err(err) => {
      Err(MismatchResult::Error(err.to_string(), message.id().clone()))
    }
  }
}

#[cfg(test)]
mod tests {
  use expectest::prelude::*;
  use pact_models::generators::Generators;
  use pact_models::matchingrules::MatchingRules;

  use super::*;

  #[test]
    fn extract_metadata_default() {
      let response = HttpResponse {
        status: 200,
        headers: Some(hashmap! {
          "content-type".into() => vec!["application/json".into()],
        }),
        body: OptionalBody::default(),
        generators: Generators{
          categories: hashmap!()
        },
        matching_rules: MatchingRules {
          rules: hashmap!()
        }
      };
      let expected = hashmap! {
        "contentType".to_string() => Value::String("application/json".to_string())
      };

      expect(extract_metadata(&response)).to(be_eq(expected));
    }

    #[test]
    fn extract_metadata_from_base64_header() {
      let response = HttpResponse {
        status: 200,
        headers: Some(hashmap! {
          "content-type".into() => vec!["application/json".into()],
          // must convert lowercase here, because the http framework actually lowercases this for us
          "Pact-Message-Metadata".to_lowercase().into() => vec!["ewogICJDb250ZW50LVR5cGUiOiAiYXBwbGljYXRpb24vanNvbiIsCiAgInRvcGljIjogImJheiIsCiAgIm51bWJlciI6IDI3LAogICJjb21wbGV4IjogewogICAgImZvbyI6ICJiYXIiCiAgfQp9Cg==".into()],
        }),
        body: OptionalBody::default(),
        generators: Generators{
          categories: hashmap!()
        },
        matching_rules: MatchingRules {
          rules: hashmap!()
        }
      };
      let expected = hashmap! {
        "contentType".to_string() => Value::String("application/json".to_string()), // From actual HTTP response header
        "Content-Type".to_string() => Value::String("application/json".to_string()), // From metadata header
        "complex".to_string() => json!({"foo": "bar"}),
        "topic".to_string() => Value::String("baz".into()),
        "number".to_string() => json!(27),
      };

      expect(extract_metadata(&response)).to(be_eq(expected));
    }
}