【发布时间】:2022-01-21 12:59:01
【问题描述】:
为了简单起见,我们在 xsd 中定义了三个元素“a”、“b”和“c”,其中:
- “a”和“b”是“c”的孩子,
- 元素“c”也可以是其自身的子元素,
- 元素“a”和“b”没有子元素。
我编写了一个“扫描”xml 的函数,如果它检测到错误的元素,它会尝试 - 如果可能的话 - 根据 xsd 使它们符合。主要代码:
# conformity.py
from lxml.etree import Element
def conform_element_a(root: Element) -> Element | None:
# If some attributes of the root as element "a"
# are not compliant, apply some transformations
# to these in order to conform root.
# If transformations are possible, return root.
# If transformations are not possible, return None.
def conform_element_b(root: Element) -> Element | None:
# same as before
def conform_element_c(root: Element):
# conform child "a"
a = root.find("a")
if a is not None:
a = conform_element_a(a)
if a is None:
root.remove(a)
# conform child "b"
b = root.find("b")
if b is not None:
b = conform_element_b(b)
if b is None:
root.remove(b)
# conform child "c"
c = root.find("c")
if c is not None:
c = conform_element_c(c)
现在,我想测试这三个功能。为了测试conform_element_a 和conform_element_b,我正在考虑使用工厂作为固定装置,如下conform_element_a:
import pytest
from lxml import etree
from mypackage.utils import tree_equality
from mypackage.conformity import conform_element_a
# Factory
@pytest.fixture
def make_element_a():
def _make_element_a(**kwargs):
# build an element "a"
# according to kwargs
return a
return _make_element_a
class TestConformA:
@pytest.mark.parametrize("attrib_1", [...])
@pytest.mark.parametrize("attrib_2", [...])
def test_none_case(make_element_a, attrib_1, attrib_2):
a = make_element_a(attrib_1, attrib_2)
a = conform_element_a(a)
assert a is None
@pytest.mark.parametrize("attrib_1, exp1", [...])
@pytest.mark.parametrize("attrib_2, exp2", [...])
def test_not_none(make_element, attrib_1, attrib_2, exp1, exp2):
a = make_element_a(attrib_1, attrib_2)
expected = make_element_a(exp1, exp2)
a = conform_element_a(a)
assert tree_equality(a, expected)
两个问题:
-
我想知道这不是测试
conform_element_a和conform_element_b的好方法。这里我放了两个属性作为示例,但实际上还有更多,而且很快就会变得冗长。 -
我看不到如何测试函数
conform_element_c。以前,只有属性作为参数。但是现在有属性和孩子!尤其是“c”可以是它自己的孩子的情况。
【问题讨论】:
标签: python xml unit-testing xsd pytest