Enum pact_models::HttpStatus
source · pub enum HttpStatus {
Information,
Success,
Redirect,
ClientError,
ServerError,
StatusCodes(Vec<u16>),
NonError,
Error,
}Expand description
Enum that defines the different types of HTTP statuses
Variants§
Information
Informational responses (100–199)
Success
Successful responses (200–299)
Redirect
Redirects (300–399)
ClientError
Client errors (400–499)
ServerError
Server errors (500–599)
StatusCodes(Vec<u16>)
Explicit status codes
NonError
Non-error response(< 400)
Error
Any error response (>= 400)
Implementations§
source§impl HttpStatus
impl HttpStatus
sourcepub fn from_json(value: &Value) -> Result<Self>
pub fn from_json(value: &Value) -> Result<Self>
Parse a JSON structure into a HttpStatus
Examples found in repository?
src/matchingrules/mod.rs (line 434)
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
pub fn create(rule_type: &str, attributes: &Value) -> anyhow::Result<MatchingRule> {
trace!("rule_type: {}, attributes: {}", rule_type, attributes);
let attributes = match attributes {
Value::Object(values) => values.clone(),
Value::Null => Map::default(),
_ => {
error!("Matching rule attributes {} are not valid", attributes);
return Err(anyhow!("Matching rule attributes {} are not valid", attributes));
}
};
match rule_type {
"regex" => match attributes.get(rule_type) {
Some(s) => Ok(MatchingRule::Regex(json_to_string(s))),
None => Err(anyhow!("Regex matcher missing 'regex' field")),
},
"equality" => Ok(MatchingRule::Equality),
"include" => match attributes.get("value") {
Some(s) => Ok(MatchingRule::Include(json_to_string(s))),
None => Err(anyhow!("Include matcher missing 'value' field")),
},
"type" => match (json_to_num(attributes.get("min").cloned()), json_to_num(attributes.get("max").cloned())) {
(Some(min), Some(max)) => Ok(MatchingRule::MinMaxType(min, max)),
(Some(min), None) => Ok(MatchingRule::MinType(min)),
(None, Some(max)) => Ok(MatchingRule::MaxType(max)),
_ => Ok(MatchingRule::Type)
},
"number" => Ok(MatchingRule::Number),
"integer" => Ok(MatchingRule::Integer),
"decimal" => Ok(MatchingRule::Decimal),
"real" => Ok(MatchingRule::Decimal),
"boolean" => Ok(MatchingRule::Boolean),
"min" => match json_to_num(attributes.get(rule_type).cloned()) {
Some(min) => Ok(MatchingRule::MinType(min)),
None => Err(anyhow!("Min matcher missing 'min' field")),
},
"max" => match json_to_num(attributes.get(rule_type).cloned()) {
Some(max) => Ok(MatchingRule::MaxType(max)),
None => Err(anyhow!("Max matcher missing 'max' field")),
},
"timestamp" | "datetime" => match attributes.get("format").or_else(|| attributes.get(rule_type)) {
Some(s) => Ok(MatchingRule::Timestamp(json_to_string(s))),
None => Err(anyhow!("Timestamp matcher missing 'timestamp' or 'format' field")),
},
"date" => match attributes.get("format").or_else(|| attributes.get(rule_type)) {
Some(s) => Ok(MatchingRule::Date(json_to_string(s))),
None => Err(anyhow!("Date matcher missing 'date' or 'format' field")),
},
"time" => match attributes.get("format").or_else(|| attributes.get(rule_type)) {
Some(s) => Ok(MatchingRule::Time(json_to_string(s))),
None => Err(anyhow!("Time matcher missing 'time' or 'format' field")),
},
"null" => Ok(MatchingRule::Null),
"contentType" | "content-type" => match attributes.get("value") {
Some(s) => Ok(MatchingRule::ContentType(json_to_string(s))),
None => Err(anyhow!("ContentType matcher missing 'value' field")),
},
"arrayContains" | "array-contains" => match attributes.get("variants") {
Some(variants) => match variants {
Value::Array(variants) => {
let mut values = Vec::new();
for variant in variants {
let index = json_to_num(variant.get("index").cloned()).unwrap_or_default();
let mut category = MatchingRuleCategory::empty("body");
if let Some(rules) = variant.get("rules") {
category.add_rules_from_json(rules)
.with_context(||
format!("Unable to parse matching rules: {:?}", rules))?;
} else {
category.add_rule(
DocPath::empty(), MatchingRule::Equality, RuleLogic::And);
}
let generators = if let Some(generators_json) = variant.get("generators") {
let mut g = Generators::default();
let cat = GeneratorCategory::BODY;
if let Value::Object(map) = generators_json {
for (k, v) in map {
if let Value::Object(ref map) = v {
let path = DocPath::new(k)?;
g.parse_generator_from_map(&cat, map, Some(path));
}
}
}
g.categories.get(&cat).cloned().unwrap_or_default()
} else {
HashMap::default()
};
values.push((index, category, generators));
}
Ok(MatchingRule::ArrayContains(values))
}
_ => Err(anyhow!("ArrayContains matcher 'variants' field is not an Array")),
}
None => Err(anyhow!("ArrayContains matcher missing 'variants' field")),
}
"values" => Ok(MatchingRule::Values),
"statusCode" | "status-code" => match attributes.get("status") {
Some(s) => {
let status = HttpStatus::from_json(s)
.context("Unable to parse status code for StatusCode matcher")?;
Ok(MatchingRule::StatusCode(status))
},
None => Ok(MatchingRule::StatusCode(HttpStatus::Success))
},
"notEmpty" | "not-empty" => Ok(MatchingRule::NotEmpty),
"semver" => Ok(MatchingRule::Semver),
"eachKey" | "each-key" => {
let generator = generator_from_json(&attributes);
let value = attributes.get("value").cloned().unwrap_or_default();
let rules = rules_from_json(&attributes)?;
let definition = MatchingRuleDefinition {
value: json_to_string(&value),
value_type: ValueType::Unknown,
rules,
generator
};
Ok(MatchingRule::EachKey(definition))
}
"eachValue" | "each-value" => {
let generator = generator_from_json(&attributes);
let value = attributes.get("value").cloned().unwrap_or_default();
let rules = rules_from_json(&attributes)?;
let definition = MatchingRuleDefinition {
value: json_to_string(&value),
value_type: ValueType::Unknown,
rules,
generator
};
Ok(MatchingRule::EachValue(definition))
}
_ => Err(anyhow!("{} is not a valid matching rule type", rule_type)),
}
}sourcepub fn to_json(&self) -> Value
pub fn to_json(&self) -> Value
Generate a JSON structure for this status
Examples found in repository?
src/matchingrules/mod.rs (line 195)
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
pub fn to_json(&self) -> Value {
match self {
MatchingRule::Equality => json!({ "match": "equality" }),
MatchingRule::Regex(ref r) => json!({ "match": "regex",
"regex": r.clone() }),
MatchingRule::Type => json!({ "match": "type" }),
MatchingRule::MinType(min) => json!({ "match": "type",
"min": json!(*min as u64) }),
MatchingRule::MaxType(max) => json!({ "match": "type",
"max": json!(*max as u64) }),
MatchingRule::MinMaxType(min, max) => json!({ "match": "type",
"min": json!(*min as u64), "max": json!(*max as u64) }),
MatchingRule::Timestamp(ref t) => json!({ "match": "datetime",
"format": Value::String(t.clone()) }),
MatchingRule::Time(ref t) => json!({ "match": "time",
"format": Value::String(t.clone()) }),
MatchingRule::Date(ref d) => json!({ "match": "date",
"format": Value::String(d.clone()) }),
MatchingRule::Include(ref s) => json!({ "match": "include",
"value": Value::String(s.clone()) }),
MatchingRule::Number => json!({ "match": "number" }),
MatchingRule::Integer => json!({ "match": "integer" }),
MatchingRule::Decimal => json!({ "match": "decimal" }),
MatchingRule::Boolean => json!({ "match": "boolean" }),
MatchingRule::Null => json!({ "match": "null" }),
MatchingRule::ContentType(ref r) => json!({ "match": "contentType",
"value": Value::String(r.clone()) }),
MatchingRule::ArrayContains(variants) => json!({
"match": "arrayContains",
"variants": variants.iter().map(|(index, rules, generators)| {
let mut json = json!({
"index": index,
"rules": rules.to_v3_json()
});
if !generators.is_empty() {
json["generators"] = Value::Object(generators.iter()
.map(|(k, gen)| {
if let Some(json) = gen.to_json() {
Some((String::from(k), json))
} else {
None
}
})
.filter(|item| item.is_some())
.map(|item| item.unwrap())
.collect())
}
json
}).collect::<Vec<Value>>()
}),
MatchingRule::Values => json!({ "match": "values" }),
MatchingRule::StatusCode(status) => json!({ "match": "statusCode", "status": status.to_json() }),
MatchingRule::NotEmpty => json!({ "match": "notEmpty" }),
MatchingRule::Semver => json!({ "match": "semver" }),
MatchingRule::EachKey(definition) => {
let mut json = json!({
"match": "eachKey",
"rules": definition.rules.iter()
.map(|rule| rule.as_ref().expect_left("Expected a matching rule, found an unresolved reference").to_json())
.collect::<Vec<Value>>()
});
let map = json.as_object_mut().unwrap();
if !definition.value.is_empty() {
map.insert("value".to_string(), Value::String(definition.value.clone()));
}
if let Some(generator) = &definition.generator {
map.insert("generator".to_string(), generator.to_json().unwrap_or_default());
}
Value::Object(map.clone())
}
MatchingRule::EachValue(definition) => {
let mut json = json!({
"match": "eachValue",
"rules": definition.rules.iter()
.map(|rule| rule.as_ref().expect_left("Expected a matching rule, found an unresolved reference").to_json())
.collect::<Vec<Value>>()
});
let map = json.as_object_mut().unwrap();
if !definition.value.is_empty() {
map.insert("value".to_string(), Value::String(definition.value.clone()));
}
if let Some(generator) = &definition.generator {
map.insert("generator".to_string(), generator.to_json().unwrap_or_default());
}
Value::Object(map.clone())
}
}
}
/// If there are any generators associated with this matching rule
pub fn has_generators(&self) -> bool {
match self {
MatchingRule::ArrayContains(variants) => variants.iter()
.any(|(_, _, generators)| !generators.is_empty()),
_ => false
}
}
/// Return the generators for this rule
pub fn generators(&self) -> Vec<Generator> {
match self {
MatchingRule::ArrayContains(variants) => vec![Generator::ArrayContains(variants.clone())],
_ => vec![]
}
}
/// Returns the type name of this matching rule
pub fn name(&self) -> String {
match self {
MatchingRule::Equality => "equality",
MatchingRule::Regex(_) => "regex",
MatchingRule::Type => "type",
MatchingRule::MinType(_) => "min-type",
MatchingRule::MaxType(_) => "max-type",
MatchingRule::MinMaxType(_, _) => "min-max-type",
MatchingRule::Timestamp(_) => "datetime",
MatchingRule::Time(_) => "time",
MatchingRule::Date(_) => "date",
MatchingRule::Include(_) => "include",
MatchingRule::Number => "number",
MatchingRule::Integer => "integer",
MatchingRule::Decimal => "decimal",
MatchingRule::Null => "null",
MatchingRule::ContentType(_) => "content-type",
MatchingRule::ArrayContains(_) => "array-contains",
MatchingRule::Values => "values",
MatchingRule::Boolean => "boolean",
MatchingRule::StatusCode(_) => "status-code",
MatchingRule::NotEmpty => "not-empty",
MatchingRule::Semver => "semver",
MatchingRule::EachKey(_) => "each-key",
MatchingRule::EachValue(_) => "each-value"
}.to_string()
}
/// Returns the type name of this matching rule
pub fn values(&self) -> HashMap<&'static str, Value> {
let empty = hashmap!{};
match self {
MatchingRule::Equality => empty,
MatchingRule::Regex(r) => hashmap!{ "regex" => Value::String(r.clone()) },
MatchingRule::Type => empty,
MatchingRule::MinType(min) => hashmap!{ "min" => json!(min) },
MatchingRule::MaxType(max) => hashmap!{ "max" => json!(max) },
MatchingRule::MinMaxType(min, max) => hashmap!{ "min" => json!(min), "max" => json!(max) },
MatchingRule::Timestamp(f) => hashmap!{ "format" => Value::String(f.clone()) },
MatchingRule::Time(f) => hashmap!{ "format" => Value::String(f.clone()) },
MatchingRule::Date(f) => hashmap!{ "format" => Value::String(f.clone()) },
MatchingRule::Include(s) => hashmap!{ "value" => Value::String(s.clone()) },
MatchingRule::Number => empty,
MatchingRule::Integer => empty,
MatchingRule::Decimal => empty,
MatchingRule::Null => empty,
MatchingRule::ContentType(ct) => hashmap!{ "value" => Value::String(ct.clone()) },
MatchingRule::ArrayContains(variants) => hashmap! { "variants" =>
variants.iter().map(|(variant, rules, gens)| {
Value::Array(vec![json!(variant), rules.to_v3_json(), Value::Object(gens.iter().map(|(key, gen)| {
(key.to_string(), gen.to_json().unwrap())
}).collect())])
}).collect()
},
MatchingRule::Values => empty,
MatchingRule::Boolean => empty,
MatchingRule::StatusCode(sc) => hashmap!{ "status" => sc.to_json() },
MatchingRule::NotEmpty => empty,
MatchingRule::Semver => empty,
MatchingRule::EachKey(definition) | MatchingRule::EachValue(definition) => {
let mut map = hashmap! {
"rules" => Value::Array(definition.rules.iter()
.map(|rule| rule.as_ref().expect_left("Expected a matching rule, found an unresolved reference").to_json())
.collect())
};
if !definition.value.is_empty() {
map.insert("value", Value::String(definition.value.clone()));
}
if let Some(generator) = &definition.generator {
map.insert("generator", generator.to_json().unwrap_or_default());
}
map
}
}
}Trait Implementations§
source§impl Clone for HttpStatus
impl Clone for HttpStatus
source§fn clone(&self) -> HttpStatus
fn clone(&self) -> HttpStatus
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moresource§impl Debug for HttpStatus
impl Debug for HttpStatus
source§impl<'de> Deserialize<'de> for HttpStatus
impl<'de> Deserialize<'de> for HttpStatus
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Display for HttpStatus
impl Display for HttpStatus
source§impl Ord for HttpStatus
impl Ord for HttpStatus
source§fn cmp(&self, other: &HttpStatus) -> Ordering
fn cmp(&self, other: &HttpStatus) -> Ordering
1.21.0 · source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read more
source§impl PartialEq<HttpStatus> for HttpStatus
impl PartialEq<HttpStatus> for HttpStatus
source§fn eq(&self, other: &HttpStatus) -> bool
fn eq(&self, other: &HttpStatus) -> bool
This method tests for
self and other values to be equal, and is used
by ==.source§impl PartialOrd<HttpStatus> for HttpStatus
impl PartialOrd<HttpStatus> for HttpStatus
source§fn partial_cmp(&self, other: &HttpStatus) -> Option<Ordering>
fn partial_cmp(&self, other: &HttpStatus) -> Option<Ordering>
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self and other) and is used by the <=
operator. Read moresource§impl Serialize for HttpStatus
impl Serialize for HttpStatus
impl Eq for HttpStatus
impl StructuralEq for HttpStatus
impl StructuralPartialEq for HttpStatus
Auto Trait Implementations§
impl RefUnwindSafe for HttpStatus
impl Send for HttpStatus
impl Sync for HttpStatus
impl Unpin for HttpStatus
impl UnwindSafe for HttpStatus
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key and return true if they are equal.