python 测试框架之pytest (三)断⾔
⼀、pytest断⾔
Pytest中断⾔是通过 assert 语句实现的,确定预期值和实际值是否⼀致。
1.1、pytest等值类型断⾔
执⾏结果
1.2、pytest异常信息提⽰
如果想在异常的时候输出⼀些提⽰信息,这样报错后就⽅便查看是什么原因了。import allure class TestAssert : @allure.story("pytest-assert ⽅式") def test_equals (self ): the_biscuit = "Ginger" my_biscuit = "Gingers" assert the_biscuit == my_biscuit
1
2
3
4
5
6
7
8
9def test_equals (self ): the_biscuit = "Ginger" my_biscuit = "Gingerss" assert the_biscuit == my_biscuit , '这条⽤例失败了!'
1
2
3
4
1.3、pytest集合类型断⾔
1.4、pytest其他类型断⾔
⼆、hamcrest断⾔
由于pytest⾃带的断⾔⽅式有限,并不能覆盖我们所有业务测试场景,这时候就需要⽤到hamcrest第三⽅断⾔库。
2.1、hamcrest等值断⾔def test_dict (self ): assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}def t
est_dict2(self ): assert {"a": 0, "b": {"c": 2}} == {"a": 0, "b": {"c": 2}}def test_list (self ): assert [0, 1, 2] == [0, 1, 2]def test_tuple (self ): assert (0, 1, 2) == (0, 1, 2)
1
2
3
4
5
6
equals不等于7
8
9
10
11assert xx # 判断xx 为真assert not xx # 判断xx 不为真assert a > b # 判断a ⼤于b assert a < b # 判断a ⼩于b assert a != b # 判断a 不等于b assert a in b # 判断b 包含a assert a not in b # 判断b 不包含a
1
2
3
4
5
6
7@allure.story("hamcrest ⽅式")def test_equals (self ): the_biscuit = "Ginger" my_biscuit = "Gingerss" assert_that (my_biscuit , equal_to (the_biscuit ), "等值字段校验失败!")
1
2
3
4
5
2.2、hamcrest⽂本类型断⾔
2.3、hamcrest数字类型断⾔
2.4、hamcrest对象类型断⾔
三、jsonschema
实际⼯作中,除了常⽤的字段断⾔外,有时还需要对数据结构进⾏校验。⽐如必填值、null、数据类型、最⼤值、最⼩值等等断⾔,这个时候就可以定义JSON数据结构以及校验JSON数据内容模板来进⾏断⾔。assert_that (actual , equal_to (expected )) # 实际值等于期望值assert_that (actual , equal_to_ignoring_case (expected )) # 忽略⼤⼩写情况下,实际值等于期望值assert_that (actual ,
equal_to_ignoring_whitespace (expected )) # 忽略头尾的任意个空格情况下,实际值等于期望值。注意,字符串中的空格不能忽略assert_that (actual , contains_string (substring )) # actual 包含字符串substring assert_that (actual , starts_with (prefix )) # actual 以⼦字符串开始assert_that (actual , ends_with ("suffix")) # actual 以⼦字符串结尾1
2
3
4
5
6assert_that (actual , greater_than (expected )) # 实际值⼤于期望值assert_that (actual , greater_than_or_equal_to (expected )) # 实际值⼤于等于期望值assert_that (actual , less_than (expected )) # 实际值⼩于于期望值assert_that (actual , less_than_or_equal_to (expected )) # 实际值⼩于等于期望值assert_that (14.7, close_to (15.2, 0.5)) # 匹配接近给定的数字值,在15.2-0.5 ~ 15.2+0.5之间1
2
3
4
5assert_that ({"a": 1, "b": "b"}, equal_to ({"a": 1, "b": "b"})) # 匹配相等对象assert_that ([1, "ab"], has_length (2)) # 长度匹配assert_that ({"a": 1, "b": "b"}, instance_of (dict )) # 匹配对象类型
1
2
3
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论