序列/列表验证器 (Seq)

YAML 中的序列由一系列连字符 ('-') 表示,在 Python 中解析为列表。

可以通过使用 Seq 验证器来验证特定类型的序列,并指定类型。

另请参阅 UniqueSeqFixedSeq,了解其他类型的序列验证。

YAML 片段示例

- 1
- 2
- 3
from strictyaml import Seq, Str, Int, load
from ensure import Ensure

有效解析

Ensure(load(yaml_snippet, Seq(Str()))).equals(["1", "2", "3", ])

是序列

assert load(yaml_snippet, Seq(Str())).is_sequence()

迭代器

assert [x for x in load(yaml_snippet, Seq(Str()))] == ["1", "2", "3"]

列表的列表

-
  - a
  - b
  - c
-
  - d
  - e
  - f
assert load(yaml_snippet, Seq(Seq(Str()))) == [["a", "b", "c"], ["d", "e", "f"]]

.text 是无意义的

- â
- 2
- 3
load(yaml_snippet, Seq(Str())).text
builtins.TypeError:YAML(['â', '2', '3']) is a sequence, has no text value.:

而是无效的映射

a: 1
b: 2
c: 3
load(yaml_snippet, Seq(Str()))
strictyaml.exceptions.YAMLValidationError:
when expecting a sequence
  in "<unicode string>", line 1, column 1:
    a: '1'
     ^ (line: 1)
found a mapping
  in "<unicode string>", line 3, column 1:
    c: '3'
    ^ (line: 3)

而是无效的嵌套结构

- 2
- 3
- a:
  - 1
  - 2
load(yaml_snippet, Seq(Str()))
strictyaml.exceptions.YAMLValidationError:
when expecting a str
  in "<unicode string>", line 3, column 1:
    - a:
    ^ (line: 3)
found a mapping
  in "<unicode string>", line 5, column 1:
      - '2'
    ^ (line: 5)

序列中无效的项目

- 1.1
- 1.2
load(yaml_snippet, Seq(Int()))
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found an arbitrary number
  in "<unicode string>", line 1, column 1:
    - '1.1'
     ^ (line: 1)

序列中一个无效的项目

- 1
- 2
- 3.4
load(yaml_snippet, Seq(Int()))
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found an arbitrary number
  in "<unicode string>", line 3, column 1:
    - '3.4'
    ^ (line: 3)

可执行规范

sequence.story storytests 自动生成的文档。