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§

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)),
    }
  }

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§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Formats the value using the given formatter. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.
Give this value the specified foreground colour
Give this value the specified background colour

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more