按条件跳过
有时,若满足某个条件,您会希望跳过测试。例如,除非今天是星期六,否则都要运行测试。此时,您可以使用 datetime 库获取当前星期几,并用 pytest 的标记按条件跳过测试函数。要将条件传给按条件跳过的 pytest 标记,可使用 @pytest.mark.skipif(condition)。
pytest 库已为您导入。
本练习是课程的一部分
Python 测试入门
练习说明
- 添加"按条件跳过"的装饰器使其生效。
- 将
condition_string加入装饰器调用。 - 完成断言测试。
交互式实操练习
通过完成这段示例代码来试试这个练习。
day_of_week = datetime.now().isoweekday()
def get_unique_values(lst):
return list(set(lst))
condition_string = 'day_of_week == 6'
# Add the conditional skip marker and the string here
____.____.____(____)
def test_function():
# Complete the assertion tests here
____ ____([1,2,3]) == [1,2,3]
____ ____([1,2,3,1]) == [1,2,3]