| 1 |
Validating strings with regexes (Regex): |
| 2 |
docs: scalar/regular-expressions |
| 3 |
based on: strictyaml |
| 4 |
description: | |
| 5 |
StrictYAML can validate regular expressions and return a |
| 6 |
string. If the regular expression does not match, an |
| 7 |
exception is raised. |
| 8 |
given: |
| 9 |
setup: | |
| 10 |
from strictyaml import Regex, Map, load, as_document |
| 11 |
from collections import OrderedDict |
| 12 |
from ensure import Ensure |
| 13 |
|
| 14 |
schema = Map({"a": Regex(u"[1-4]"), "b": Regex(u"[5-9]")}) |
| 15 |
variations: |
| 16 |
Parsed correctly: |
| 17 |
given: |
| 18 |
yaml_snippet: | |
| 19 |
a: 1 |
| 20 |
b: 5 |
| 21 |
steps: |
| 22 |
- Run: |
| 23 |
code: | |
| 24 |
Ensure(load(yaml_snippet, schema)).equals({"a": "1", "b": "5"}) |
| 25 |
|
| 26 |
Non-matching: |
| 27 |
given: |
| 28 |
yaml_snippet: | |
| 29 |
a: 5 |
| 30 |
b: 5 |
| 31 |
steps: |
| 32 |
- Run: |
| 33 |
code: load(yaml_snippet, schema) |
| 34 |
raises: |
| 35 |
type: strictyaml.exceptions.YAMLValidationError |
| 36 |
message: |- |
| 37 |
when expecting string matching [1-4] |
| 38 |
found non-matching string |
| 39 |
in "<unicode string>", line 1, column 1: |
| 40 |
a: '5' |
| 41 |
^ (line: 1) |
| 42 |
|
| 43 |
Non-matching suffix: |
| 44 |
given: |
| 45 |
yaml_snippet: | |
| 46 |
a: 1 Hello |
| 47 |
b: 5 |
| 48 |
steps: |
| 49 |
- Run: |
| 50 |
code: load(yaml_snippet, schema) |
| 51 |
raises: |
| 52 |
type: strictyaml.exceptions.YAMLValidationError |
| 53 |
message: |- |
| 54 |
when expecting string matching [1-4] |
| 55 |
found non-matching string |
| 56 |
in "<unicode string>", line 1, column 1: |
| 57 |
a: 1 Hello |
| 58 |
^ (line: 1) |
| 59 |
|
| 60 |
Serialized successfully: |
| 61 |
steps: |
| 62 |
- Run: |
| 63 |
code: | |
| 64 |
print(as_document(OrderedDict([("a", "1"), ("b", "5")]), schema).as_yaml()) |
| 65 |
will output: |- |
| 66 |
a: 1 |
| 67 |
b: 5 |
| 68 |
|
| 69 |
Serialization failure non matching regex: |
| 70 |
steps: |
| 71 |
- Run: |
| 72 |
code: | |
| 73 |
as_document(OrderedDict([("a", "x"), ("b", "5")]), schema) |
| 74 |
raises: |
| 75 |
type: strictyaml.exceptions.YAMLSerializationError |
| 76 |
message: when expecting string matching [1-4] found 'x' |
| 77 |
|
| 78 |
Serialization failure not a string: |
| 79 |
steps: |
| 80 |
- Run: |
| 81 |
code: | |
| 82 |
as_document(OrderedDict([("a", 1), ("b", "5")]), schema) |
| 83 |
raises: |
| 84 |
type: strictyaml.exceptions.YAMLSerializationError |
| 85 |
message: when expecting string matching [1-4] got '1' of type int. |