pact_consumer 1.4.3

Pact-Rust module that provides support for writing consumer pact 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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Builder for constructing Asynchronous message interactions

use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap};

use bytes::Bytes;
use maplit::{btreemap, hashmap};
use pact_models::content_types::ContentType;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::MatchingRuleCategory;
use pact_models::generators::Generators;
use pact_models::message::Message;
use pact_models::path_exp::DocPath;
#[cfg(feature = "plugins")] use pact_models::plugins::PluginData;
use pact_models::prelude::{MatchingRules, OptionalBody, ProviderState};
use pact_models::v4::async_message::AsynchronousMessage;
use pact_models::v4::interaction::InteractionMarkup;
use pact_models::v4::message_parts::MessageContents;
#[cfg(feature = "plugins")] use pact_plugin_driver::catalogue_manager::find_content_matcher;
#[cfg(feature = "plugins")] use pact_plugin_driver::content::ContentMatcher;
#[cfg(feature = "plugins")] use pact_plugin_driver::plugin_models::PactPluginManifest;
use serde_json::{json, Map, Value};
use tracing::debug;

use crate::patterns::JsonPattern;
use crate::prelude::Pattern;
#[cfg(feature = "plugins")] use crate::prelude::PluginInteractionBuilder;

#[cfg(not(feature = "plugins"))]
#[derive(Clone, Debug, Default)]
/// Placeholder struct when plugins are disabled
pub struct PactPluginManifest {}

#[derive(Clone, Debug, Default)]
/// Struct to store any config received from plugins
pub struct PluginConfiguration {
  /// Data to persist on the interaction
  pub interaction_configuration: HashMap<String, Value>,
  /// Data to persist in the Pact metadata
  pub pact_configuration: HashMap<String, Value>
}

impl PluginConfiguration {
  /// Create a new struct from a plugin specific one
  #[cfg(feature = "plugins")]
  pub fn from(config: &pact_plugin_driver::content::PluginConfiguration) -> Self {
    PluginConfiguration {
      interaction_configuration: config.interaction_configuration.clone(),
      pact_configuration: config.pact_configuration.clone()
    }
  }
}

#[derive(Clone, Debug, Default)]
/// Struct that stores the interaction contents for the message
pub struct InteractionContents {
  /// Description of what part this interaction belongs to (in the case of there being more than
  /// one, for instance, request/response messages). For async messages, this will not be used.
  #[allow(dead_code)] pub part_name: String,

  /// Body/Contents of the interaction
  pub body: OptionalBody,

  /// Matching rules to apply
  pub rules: Option<MatchingRuleCategory>,

  /// Generators to apply
  pub generators: Option<Generators>,

  /// Message metadata
  pub metadata: Option<HashMap<String, Value>>,

  /// Matching rules to apply to message metadata
  pub metadata_rules: Option<MatchingRuleCategory>,

  /// Plugin configuration data to apply to the interaction
  pub plugin_config: PluginConfiguration,

  /// Markup for the interaction to display in any UI
  pub interaction_markup: String,

  /// The type of the markup (CommonMark or HTML)
  pub interaction_markup_type: String
}

impl InteractionContents {
  #[cfg(feature = "plugins")]
  /// Create a new struct from a plugin specific one
  pub fn from(contents: &pact_plugin_driver::content::InteractionContents) -> Self {
    let metadata = contents.metadata.as_ref()
      .map(|md| {
        md.iter()
          .map(|(k, v)| (k.clone(), v.clone()))
          .collect()
      });
    InteractionContents {
      part_name: contents.part_name.clone(),
      body: contents.body.clone(),
      rules: contents.rules.clone(),
      generators: contents.generators.clone(),
      metadata,
      metadata_rules: contents.metadata_rules.clone(),
      plugin_config: PluginConfiguration::from(&contents.plugin_config),
      interaction_markup: contents.interaction_markup.clone(),
      interaction_markup_type: contents.interaction_markup_type.clone()
    }
  }
}

#[derive(Clone, Debug)]
/// Asynchronous message interaction builder. Normally created via PactBuilder::message_interaction.
pub struct MessageInteractionBuilder {
  description: String,
  provider_states: Vec<ProviderState>,
  comments: Vec<String>,
  test_name: Option<String>,
  key: Option<String>,
  pending: Option<bool>,
  /// Contents of the message. This will include the payload as well as any metadata
  pub message_contents: InteractionContents,
  #[allow(dead_code)] contents_plugin: Option<PactPluginManifest>,
  #[allow(dead_code)] plugin_config: HashMap<String, PluginConfiguration>,
  references: Option<BTreeMap<String, BTreeMap<String, Value>>>
}

impl MessageInteractionBuilder {
  /// Create a new message interaction builder, Description is the interaction description
  /// and interaction_type is the type of message (leave empty for the default type).
  pub fn new<D: Into<String>>(description: D) -> MessageInteractionBuilder {
    MessageInteractionBuilder {
      description: description.into(),
      provider_states: vec![],
      comments: vec![],
      test_name: None,
      key: None,
      pending: None,
      message_contents: Default::default(),
      contents_plugin: None,
      plugin_config: Default::default(),
      references: None
    }
  }

  /// Specify a "provider state" for this interaction. This is normally use to
  /// set up database fixtures when using a pact to test a provider.
  pub fn given<G: Into<String>>(&mut self, given: G) -> &mut Self {
    self.provider_states.push(ProviderState::default(&given.into()));
    self
  }

  /// Specify a "provider state" for this interaction with some defined parameters. This is
  /// normally use to set up database fixtures when using a pact to test a provider.
  ///
  /// The paramaters must be provided as a serde_json::Value Object.
  pub fn given_with_params<G: Into<String>>(&mut self, given: G, params: &Value) -> &mut Self {
    let params = if let Some(params) = params.as_object() {
      params.iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
    } else {
      HashMap::default()
    };

    self.provider_states.push(ProviderState {
      name: given.into(),
      params
    });
    self
  }

  /// Adds a text comment to this interaction. This allows to specify just a bit more information
  /// about the interaction. It has no functional impact, but can be displayed in the broker HTML
  /// page, and potentially in the test output.
  pub fn comment<G: Into<String>>(&mut self, comment: G) -> &mut Self {
    self.comments.push(comment.into());
    self
  }

  /// Sets the test name for this interaction. This allows to specify just a bit more information
  /// about the interaction. It has no functional impact, but can be displayed in the broker HTML
  /// page, and potentially in the test output.
  pub fn test_name<G: Into<String>>(&mut self, name: G) -> &mut Self {
    self.test_name = Some(name.into());
    self
  }

  /// Sets an external reference for the interaction.  The reference will be stored in the Pact
  /// file comments under the group. For instance, you could store the AsyncAPI operation ID that
  /// the interaction corresponds to as an external reference.
  /// ```
  /// # let mut builder = pact_consumer::builders::MessageInteractionBuilder::new("test");
  /// builder.reference("asyncapi", "operationId", "createUser");
  /// ```
  pub fn reference<G: Into<String>, N: Into<String>, J: Into<Value>>(
    &mut self,
    group: G,
    name: N,
    value: J
  ) -> &mut Self {
    if let Some(references) = self.references.as_mut() {
      match references.entry(group.into()) {
        std::collections::btree_map::Entry::Vacant(entry) => {
          entry.insert(btreemap! { name.into() => value.into() });
        }
        std::collections::btree_map::Entry::Occupied(mut entry) => {
          entry.get_mut().insert(name.into(), value.into());
        }
      }
    } else {
      self.references = Some(btreemap!{
        group.into() => btreemap!{
          name.into() => value.into()
        }
      });
    }
    self
  }

  /// Adds a key/value pair to the message metadata. The key can be anything that is convertible
  /// into a string, and the value must be conveyable into a JSON value.
  pub fn metadata<S: Into<String>, J: Into<Value>>(&mut self, key: S, value: J) -> &mut Self {
    let metadata = self.message_contents.metadata
      .get_or_insert_with(|| hashmap!{});
    metadata.insert(key.into(), value.into());
    self
  }

  /// Specify a unique key for this interaction. This key will be used to determine equality of
  /// the interaction, so must be unique.
  pub fn with_key<G: Into<String>>(&mut self, key: G) -> &mut Self {
    self.key = Some(key.into());
    self
  }

  /// Sets this interaction as pending. This will permantly mark the interaction as pending in the
  /// Pact file, and it will not cause a verification failure.
  pub fn pending(&mut self, pending: bool) -> &mut Self {
    self.pending = Some(pending);
    self
  }

  /// The interaction we've built (in V4 format).
  pub fn build(&self) -> AsynchronousMessage {
    debug!("Building V4 AsynchronousMessage interaction: {:?}", self);

    let mut rules = MatchingRules::default();
    rules.add_category("body")
      .add_rules(self.message_contents.rules.as_ref().cloned().unwrap_or_default());

    #[allow(unused_mut, unused_assignments)] let mut plugin_config = hashmap!{};
    #[cfg(feature = "plugins")]
    {
      plugin_config = self.contents_plugin.as_ref().map(|plugin| {
        hashmap! {
          plugin.name.clone() => self.message_contents.plugin_config.interaction_configuration.clone()
        }
      }).unwrap_or_default();
    }

    #[allow(unused_mut, unused_assignments)] let mut interaction_markup = InteractionMarkup::default();
    #[cfg(feature = "plugins")]
    {
      interaction_markup = InteractionMarkup {
        markup: self.message_contents.interaction_markup.clone(),
        markup_type: self.message_contents.interaction_markup_type.clone()
      };
    }

    let metadata = self.message_contents.metadata.as_ref()
      .map(|md| md.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
      .unwrap_or_default();

    let mut comments = hashmap! {
      "text".to_string() => json!(self.comments),
      "testname".to_string() => json!(self.test_name)
    };
    if let Some(references) = &self.references {
      comments.insert("references".to_string(), references.iter()
        .map(|(k, v)| (k.clone(), json!(v)))
        .collect());
    }

    AsynchronousMessage {
      id: None,
      key: self.key.clone(),
      description: self.description.clone(),
      provider_states: self.provider_states.clone(),
      contents: MessageContents {
        contents: self.message_contents.body.clone(),
        metadata,
        matching_rules: rules,
        generators: self.message_contents.generators.as_ref().cloned().unwrap_or_default()
      },
      comments,
      pending: self.pending.unwrap_or(false),
      plugin_config,
      interaction_markup,
      transport: None
    }
  }

  /// The interaction we've built (in V3 format).
  pub fn build_v3(&self) -> Message {
    debug!("Building V3 Message interaction: {:?}", self);

    let mut rules = MatchingRules::default();
    rules.add_category("body")
      .add_rules(self.message_contents.rules.as_ref().cloned().unwrap_or_default());

    let metadata = self.message_contents.metadata.as_ref()
      .map(|md| md.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
      .unwrap_or_default();
    Message {
      id: None,
      description: self.description.clone(),
      provider_states: self.provider_states.clone(),
      contents: self.message_contents.body.clone(),
      metadata,
      matching_rules: rules,
      generators: self.message_contents.generators.as_ref().cloned().unwrap_or_default()
    }
  }

  /// Configure the interaction contents from a map
  pub async fn contents_from(&mut self, contents: Value) -> &mut Self {
    debug!("Configuring interaction from {:?}", contents);

    let contents_map = contents.as_object().cloned().unwrap_or(Map::default());
    let contents_hashmap: HashMap<String, Value> = contents_map.iter()
      .map(|(k, v)| (k.clone(), v.clone()))
      .collect();
    if let Some(content_type) = contents_map.get("pact:content-type") {
      let ct = ContentType::parse(json_to_string(content_type).as_str()).unwrap();

      #[cfg(feature = "plugins")]
      {
        if let Some(content_matcher) = find_content_matcher(&ct) {
          debug!("Found a matcher for '{}': {:?}", ct, content_matcher);
          if content_matcher.is_core() {
            debug!("Content matcher is a core matcher, will use the internal implementation");
            self.setup_core_matcher(&ct, &contents_hashmap, Some(content_matcher));
          } else {
            debug!("Plugin matcher, will get the plugin to provide the interaction contents");
            match content_matcher.configure_interaction(&ct, contents_hashmap).await {
              Ok((contents, plugin_config)) => {
                if let Some(contents) = contents.first() {
                  self.message_contents = InteractionContents::from(contents);
                  if !contents.plugin_config.is_empty() {
                    self.plugin_config.insert(content_matcher.plugin_name(), PluginConfiguration::from(&contents.plugin_config));
                  }
                }
                self.contents_plugin = content_matcher.plugin();

                if let Some(plugin_config) = plugin_config {
                  let plugin_name = content_matcher.plugin_name();
                  if self.plugin_config.contains_key(&*plugin_name) {
                    let entry = self.plugin_config.get_mut(&*plugin_name).unwrap();
                    for (k, v) in plugin_config.pact_configuration {
                      entry.pact_configuration.insert(k.clone(), v.clone());
                    }
                  } else {
                    self.plugin_config.insert(plugin_name.to_string(), PluginConfiguration::from(&plugin_config));
                  }
                }
              }
              Err(err) => panic!("Failed to call out to plugin - {}", err)
            }
          }
        } else {
          debug!("No content matcher found, will use the internal implementation");
          self.setup_core_matcher(&ct, &contents_hashmap, None);
        }
      }

      #[cfg(not(feature = "plugins"))]
      {
        self.message_contents = InteractionContents {
          body: if let Some(contents) = contents_hashmap.get("contents") {
            OptionalBody::Present(
              Bytes::from(contents.to_string()),
              Some(ct.clone()),
              None
            )
          } else {
            OptionalBody::Missing
          },
          .. InteractionContents::default()
        };
      }
    } else {
      self.message_contents = InteractionContents {
        body : OptionalBody::from(Value::Object(contents_map.clone())),
        .. InteractionContents::default()
      };
    }

    self
  }

  /// Configure the interaction contents from a plugin builder
  #[cfg(feature = "plugins")]
  pub async fn contents_for_plugin<B: PluginInteractionBuilder>(&mut self, builder: B) -> &mut Self {
    self.contents_from(builder.build()).await
  }

  #[cfg(feature = "plugins")]
  fn setup_core_matcher(
    &mut self,
    content_type: &ContentType,
    config: &HashMap<String, Value>,
    content_matcher: Option<ContentMatcher>
  ) {
    self.message_contents = InteractionContents {
      body: if let Some(contents) = config.get("contents") {
        OptionalBody::Present(
          Bytes::from(contents.to_string()),
          Some(content_type.clone()),
          None
        )
      } else {
        OptionalBody::Missing
      },
      .. InteractionContents::default()
    };

    if let Some(_content_matcher) = content_matcher {
      // TODO: get the content matcher to apply the matching rules and generators
      //     val (body, rules, generators, _, _) = contentMatcher.setupBodyFromConfig(bodyConfig)
      //     val matchingRules = MatchingRulesImpl()
      //     if (rules != null) {
      //       matchingRules.addCategory(rules)
      //     }
      //     MessageContents(body, mapOf(), matchingRules, generators ?: Generators())
    }
  }

  /// Any global plugin config required to add to the Pact
  #[cfg(feature = "plugins")]
  pub fn plugin_config(&self) -> Option<PluginData> {
    self.contents_plugin.as_ref().map(|plugin| {
      let config = if let Some(config) = self.plugin_config.get(plugin.name.as_str()) {
        config.pact_configuration.clone()
      } else {
        hashmap!{}
      };
      PluginData {
        name: plugin.name.clone(),
        version: plugin.version.clone(),
        configuration: config
      }
    })
  }

  /// Specify the body as `JsonPattern`, possibly including special matching
  /// rules.
  ///
  /// ```
  /// use pact_consumer::prelude::*;
  /// use pact_consumer::*;
  /// use pact_consumer::builders::MessageInteractionBuilder;
  ///
  /// MessageInteractionBuilder::new("hello message").json_body(json_pattern!({
  ///     "message": like!("Hello"),
  /// }));
  /// ```
  pub fn json_body<B: Into<JsonPattern>>(&mut self, body: B) -> &mut Self {
    let body = body.into();
    {
      let message_body = OptionalBody::Present(body.to_example().to_string().into(), Some("application/json".into()), None);
      let mut rules = MatchingRuleCategory::empty("content");
      body.extract_matching_rules(DocPath::root(), &mut rules);
      self.message_contents.body = message_body;
      if rules.is_not_empty() {
        match &mut self.message_contents.rules {
          None => self.message_contents.rules = Some(rules.clone()),
          Some(mr) => mr.add_rules(rules.clone())
        }
      }
    }
    self
  }

  /// Specify the message payload and content type
  pub fn body<B: Into<Bytes>>(&mut self, body: B, content_type: Option<String>) -> &mut Self {
    let message_body = OptionalBody::Present(
      body.into(),
      content_type.as_ref().map(|ct| ct.into()),
      None
    );
    self.message_contents.body = message_body;
    let metadata = self.message_contents.metadata
      .get_or_insert_with(|| hashmap!{});
    if let Some(content_type) = content_type {
      match metadata.entry("contentType".to_string()) {
        Entry::Occupied(_) => {}
        Entry::Vacant(entry) => {
          entry.insert(Value::String(content_type.clone()));
        }
      }
    }
    self
  }
}

#[cfg(test)]
mod tests {
  use expectest::prelude::*;
  use maplit::hashmap;
  use proclaim_it::assert_that;
  use serde_json::{json, Value};

  use crate::builders::MessageInteractionBuilder;

  #[test]
  fn supports_setting_metadata_values() {
    let message = MessageInteractionBuilder::new("test")
      .metadata("a", "a")
      .metadata("b", json!("b"))
      .metadata("c", vec![1, 2, 3])
      .build();
    expect!(message.contents.metadata).to(be_equal_to(hashmap! {
      "a".to_string() => json!("a"),
      "b".to_string() => json!("b"),
      "c".to_string() => json!([1, 2, 3])
    }));
  }

  #[test]
  fn supports_setting_external_references() {
    let message = MessageInteractionBuilder::new("test")
      .reference("asyncapi", "operationId", "test")
      .reference("openapi", "operationId", "test2")
      .build();

    assert_that! {
      message.comments == hashmap! {
        "references".to_string() => json!({
            "asyncapi": {
              "operationId": "test"
            },
            "openapi": {
              "operationId": "test2"
            }
        }),
        "text".to_string() => json!([]),
        "testname".to_string() => Value::Null
      }
    }
  }
}