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
//! The `pact_models` crate provides all the structs and traits required to model a Pact.

use std::fmt::{Display, Formatter};
use std::fmt;

use anyhow::anyhow;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::verify_json::{json_type_of, PactFileVerificationResult, PactJsonVerifier, ResultLevel};

pub mod content_types;
pub mod bodies;
pub mod v4;
pub mod provider_states;
pub mod verify_json;
pub mod json_utils;
pub mod expression_parser;
pub mod time_utils;
mod timezone_db;
#[cfg(not(target_family = "wasm"))] pub mod file_utils;
pub mod xml_utils;
pub mod matchingrules;
pub mod generators;
pub mod path_exp;
pub mod query_strings;
#[cfg(not(target_family = "wasm"))] pub mod http_utils;
pub mod http_parts;
pub mod request;
pub mod response;
pub mod headers;
pub mod interaction;
pub mod sync_interaction;
pub mod message;
pub mod pact;
pub mod sync_pact;
pub mod message_pact;
mod iterator_utils;
pub mod plugins;

/// A "prelude" or a default list of import types to include.
pub mod prelude {
  pub use crate::{Consumer, Provider};
  pub use crate::bodies::OptionalBody;
  pub use crate::content_types::ContentType;
  pub use crate::expression_parser::DataType;
  pub use crate::generators::{Generator, GeneratorCategory, Generators};
  pub use crate::interaction::Interaction;
  pub use crate::matchingrules::{Category, MatchingRuleCategory, MatchingRules, RuleLogic};
  pub use crate::message_pact::MessagePact;
  pub use crate::pact::Pact;
  pub use crate::PactSpecification;
  pub use crate::provider_states::ProviderState;
  pub use crate::request::Request;
  pub use crate::response::Response;
  pub use crate::sync_interaction::RequestResponseInteraction;
  pub use crate::sync_pact::RequestResponsePact;
  #[cfg(not(target_family = "wasm"))] pub use crate::http_utils::HttpAuth;

  pub mod v4 {
    pub use crate::v4::pact::V4Pact;
    pub use crate::v4::synch_http::SynchronousHttp;
  }
}

/// Version of the library
pub const PACT_RUST_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");

/// Enum defining the pact specification versions supported by the library
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Deserialize, Serialize)]
#[allow(non_camel_case_types)]
pub enum PactSpecification {
  /// Unknown or unsupported specification version
  Unknown,
  /// First version of the pact specification (`https://github.com/pact-foundation/pact-specification/tree/version-1`)
  V1,
  /// Second version of the pact specification (`https://github.com/pact-foundation/pact-specification/tree/version-1.1`)
  V1_1,
  /// Version two of the pact specification (`https://github.com/pact-foundation/pact-specification/tree/version-2`)
  V2,
  /// Version three of the pact specification (`https://github.com/pact-foundation/pact-specification/tree/version-3`)
  V3,
  /// Version four of the pact specification (`https://github.com/pact-foundation/pact-specification/tree/version-4`)
  V4
}

impl Default for PactSpecification {
  fn default() -> Self {
        PactSpecification::Unknown
    }
}

impl PactSpecification {
  /// Returns the semantic version string of the specification version.
  pub fn version_str(&self) -> String {
    match *self {
        PactSpecification::V1 => "1.0.0",
        PactSpecification::V1_1 => "1.1.0",
        PactSpecification::V2 => "2.0.0",
        PactSpecification::V3 => "3.0.0",
        PactSpecification::V4 => "4.0",
        _ => "unknown"
    }.into()
  }

  /// Parse a version string into a PactSpecification
  pub fn parse_version<S: Into<String>>(input: S) -> anyhow::Result<PactSpecification> {
    let str_version = input.into();
    let version = lenient_semver::parse(str_version.as_str())
      .map_err(|_| anyhow!("Invalid specification version '{}'", str_version))?;
    match version.major {
      1 => match version.minor {
        0 => Ok(PactSpecification::V1),
        1 => Ok(PactSpecification::V1_1),
        _ => Err(anyhow!("Unsupported specification version '{}'", str_version))
      },
      2 => match version.minor {
        0 => Ok(PactSpecification::V2),
        _ => Err(anyhow!("Unsupported specification version '{}'", str_version))
      },
      3 => match version.minor {
        0 => Ok(PactSpecification::V3),
        _ => Err(anyhow!("Unsupported specification version '{}'", str_version))
      },
      4 => match version.minor {
        0 => Ok(PactSpecification::V4),
        _ => Err(anyhow!("Unsupported specification version '{}'", str_version))
      },
      _ => Err(anyhow!("Invalid specification version '{}'", str_version))
    }
  }
}

impl From<&str> for PactSpecification {
  fn from(s: &str) -> Self {
    match s.to_uppercase().as_str() {
      "V1" => PactSpecification::V1,
      "V1.1" => PactSpecification::V1_1,
      "V2" => PactSpecification::V2,
      "V3" => PactSpecification::V3,
      "V4" => PactSpecification::V4,
      _ => PactSpecification::Unknown
    }
  }
}

impl From<String> for PactSpecification {
  fn from(s: String) -> Self {
    PactSpecification::from(s.as_str())
  }
}

impl From<&String> for PactSpecification {
  fn from(s: &String) -> Self {
    PactSpecification::from(s.as_str())
  }
}

// impl ToString for PactSpecification {
//   fn to_string(&self) -> String {
//     match *self {
//       PactSpecification::V1 => "V1",
//       PactSpecification::V1_1 => "V1.1",
//       PactSpecification::V2 => "V2",
//       PactSpecification::V3 => "V3",
//       PactSpecification::V4 => "V4",
//       _ => "unknown"
//     }.into()
//   }
// }

impl Display for PactSpecification {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    match *self {
      PactSpecification::V1 => write!(f, "V1"),
      PactSpecification::V1_1 => write!(f, "V1.1"),
      PactSpecification::V2 => write!(f, "V2"),
      PactSpecification::V3 => write!(f, "V3"),
      PactSpecification::V4 => write!(f, "V4"),
      _ => write!(f, "unknown")
    }
  }
}

/// Struct that defines the consumer of the pact.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
pub struct Consumer {
  /// Each consumer should have a unique name to identify it.
  pub name: String
}

impl Consumer {
  /// Builds a `Consumer` from the `Json` struct.
  pub fn from_json(pact_json: &Value) -> Consumer {
    let val = match pact_json.get("name") {
      Some(v) => match v.clone() {
        Value::String(s) => s,
        _ => v.to_string()
      },
      None => "consumer".to_string()
    };
    Consumer { name: val.clone() }
  }

  /// Converts this `Consumer` to a `Value` struct.
  pub fn to_json(&self) -> Value {
    json!({ "name" : self.name })
  }

  /// Generate the JSON schema properties for the given Pact specification
  pub fn schema(_spec_version: PactSpecification) -> Value {
    json!({
      "properties": {
        "name": {
          "type": "string"
        }
      },
      "required": ["name"],
      "type": "object"
    })
  }
}

impl PactJsonVerifier for Consumer {
  fn verify_json(path: &str, pact_json: &Value, strict: bool, _spec_version: PactSpecification) -> Vec<PactFileVerificationResult> {
    let mut results = vec![];

    match pact_json {
      Value::Object(values) => {
        if let Some(name) = values.get("name") {
          if !name.is_string() {
            results.push(PactFileVerificationResult::new(path.to_owned() + "/name", ResultLevel::ERROR,
              format!("Must be a String, got {}", json_type_of(pact_json))))
          }
        } else {
          results.push(PactFileVerificationResult::new(path.to_owned() + "/name",
            if strict { ResultLevel::ERROR } else { ResultLevel::WARNING }, "Missing name"))
        }

        for key in values.keys() {
          if key != "name" {
            results.push(PactFileVerificationResult::new(path.to_owned(),
              if strict { ResultLevel::ERROR } else { ResultLevel::WARNING }, format!("Unknown attribute '{}'", key)))
          }
        }
      }
      _ => results.push(PactFileVerificationResult::new(path, ResultLevel::ERROR,
        format!("Must be an Object, got {}", json_type_of(pact_json))))
    }

    results
  }
}

/// Struct that defines a provider of a pact.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
pub struct Provider {
  /// Each provider should have a unique name to identify it.
  pub name: String
}

impl Provider {
  /// Builds a `Provider` from a `Value` struct.
  pub fn from_json(pact_json: &Value) -> Provider {
    let val = match pact_json.get("name") {
      Some(v) => match v.clone() {
        Value::String(s) => s,
        _ => v.to_string()
      },
      None => "provider".to_string()
    };
    Provider { name: val.clone() }
  }

  /// Converts this `Provider` to a `Value` struct.
  pub fn to_json(&self) -> Value {
    json!({ "name" : self.name })
  }

  /// Generate the JSON schema properties for the given Pact specification
  pub fn schema(_spec_version: PactSpecification) -> Value {
    json!({
      "properties": {
        "name": {
          "type": "string"
        }
      },
      "required": ["name"],
      "type": "object"
    })
  }
}

impl PactJsonVerifier for Provider {
  fn verify_json(path: &str, pact_json: &Value, strict: bool, _spec_version: PactSpecification) -> Vec<PactFileVerificationResult> {
    let mut results = vec![];

    match pact_json {
      Value::Object(values) => {
        if let Some(name) = values.get("name") {
          if !name.is_string() {
            results.push(PactFileVerificationResult::new(path.to_owned() + "/name", ResultLevel::ERROR,
                                                         format!("Must be a String, got {}", json_type_of(pact_json))))
          }
        } else {
          results.push(PactFileVerificationResult::new(path.to_owned() + "/name",
            if strict { ResultLevel::ERROR } else { ResultLevel::WARNING }, "Missing name"))
        }

        for key in values.keys() {
          if key != "name" {
            results.push(PactFileVerificationResult::new(path.to_owned(),
              if strict { ResultLevel::ERROR } else { ResultLevel::WARNING }, format!("Unknown attribute '{}'", key)))
          }
        }
      }
      _ => results.push(PactFileVerificationResult::new(path, ResultLevel::ERROR,
                                                        format!("Must be an Object, got {}", json_type_of(pact_json))))
    }

    results
  }
}


/// Enumeration of the types of differences between requests and responses
#[derive(PartialEq, Debug, Clone, Eq)]
pub enum DifferenceType {
  /// Methods differ
  Method,
  /// Paths differ
  Path,
  /// Headers differ
  Headers,
  /// Query parameters differ
  QueryParameters,
  /// Bodies differ
  Body,
  /// Matching Rules differ
  MatchingRules,
  /// Response status differ
  Status
}

/// Enum that defines the different types of HTTP statuses
#[derive(Debug, Clone, Deserialize, Serialize, Ord, PartialOrd, Eq, PartialEq)]
pub enum HttpStatus {
  /// Informational responses (100–199)
  Information,
  /// Successful responses (200–299)
  Success,
  /// Redirects (300–399)
  Redirect,
  /// Client errors (400–499)
  ClientError,
  /// Server errors (500–599)
  ServerError,
  /// Explicit status codes
  StatusCodes(Vec<u16>),
  /// Non-error response(< 400)
  NonError,
  /// Any error response (>= 400)
  Error
}

impl HttpStatus {
  /// Parse a JSON structure into a HttpStatus
  pub fn from_json(value: &Value) -> anyhow::Result<Self> {
    match value {
      Value::String(s) => match s.as_str() {
        "info" => Ok(HttpStatus::Information),
        "success" => Ok(HttpStatus::Success),
        "redirect" => Ok(HttpStatus::Redirect),
        "clientError" => Ok(HttpStatus::ClientError),
        "serverError" => Ok(HttpStatus::ServerError),
        "nonError" => Ok(HttpStatus::NonError),
        "error" => Ok(HttpStatus::Error),
        _ => Err(anyhow!("'{}' is not a valid value for an HTTP Status", s))
      },
      Value::Array(a) => {
        let status_codes = a.iter().map(|status| match status {
          Value::Number(n) => if n.is_u64() {
            Ok(n.as_u64().unwrap() as u16)
          } else if n.is_i64() {
            Ok(n.as_i64().unwrap() as u16)
          } else {
            Ok(n.as_f64().unwrap() as u16)
          },
          Value::String(s) => s.parse::<u16>().map_err(|err| anyhow!(err)),
          _ => Err(anyhow!("'{}' is not a valid JSON value for an HTTP Status", status))
        }).collect::<Vec<anyhow::Result<u16>>>();
        if status_codes.iter().any(|it| it.is_err()) {
          Err(anyhow!("'{}' is not a valid JSON value for an HTTP Status", value))
        } else {
          Ok(HttpStatus::StatusCodes(status_codes.iter().map(|code| *code.as_ref().unwrap()).collect()))
        }
      }
      _ => Err(anyhow!("'{}' is not a valid JSON value for an HTTP Status", value))
    }
  }

  /// Generate a JSON structure for this status
  pub fn to_json(&self) -> Value {
    match self {
      HttpStatus::StatusCodes(codes) => json!(codes),
      HttpStatus::Information => json!("info"),
      HttpStatus::Success => json!("success"),
      HttpStatus::Redirect => json!("redirect"),
      HttpStatus::ClientError => json!("clientError"),
      HttpStatus::ServerError => json!("serverError"),
      HttpStatus::NonError => json!("nonError"),
      HttpStatus::Error => json!("error")
    }
  }
}

impl Display for HttpStatus {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    match self {
      HttpStatus::Information => write!(f, "Informational response (100–199)"),
      HttpStatus::Success => write!(f, "Successful response (200–299)"),
      HttpStatus::Redirect => write!(f, "Redirect (300–399)"),
      HttpStatus::ClientError => write!(f, "Client error (400–499)"),
      HttpStatus::ServerError => write!(f, "Server error (500–599)"),
      HttpStatus::StatusCodes(status) =>
        write!(f, "{}", status.iter().map(|s| s.to_string()).join(", ")),
      HttpStatus::NonError => write!(f, "Non-error response (< 400)"),
      HttpStatus::Error => write!(f, "Error response (>= 400)")
    }
  }
}

#[cfg(test)]
mod tests;