代码之家  ›  专栏  ›  技术社区  ›  Alex

如何为py.test创建扩展的xfail标记?

  •  0
  • Alex  · 技术社区  · 5 年前

    py.test (版本4.6.2)您有一个mark decorator,用于测试将其标记为失败,例如。

    @pytest.mark.xfail
    def test1():
        return 1/0
    

    也可以验证异常本身

    @pytest.mark.xfail(raises=ZeroDivisionError)
    

    但是,是否可以通过某种方式验证错误消息本身?

    当你有一个 HTTPError 因为有很多原因。当您比较错误消息本身时,您可以更具体地了解测试失败的时间(例如,区分 Client Error 从A Server Error )

    到目前为止,我正在使用以下构造:

    def test_fail_request(self):      
        with pytest.raises(requests.exceptions.HTTPError) as excinfo:
            response = requests.something
        assert '403 Client Error: Not Found' in str(excinfo.value)
    

    但是,像下面这样的测试当然更具可读性、简洁性和正确的处理方式 P.试验 :

     @pytest.mark.xfail(expected_error = "403 Client Error: Not Found"):
     def test_fail_request(self):      
        response = requests.something
    

    有没有办法实现这种行为/特性?

    为了澄清,最后一个代码示例预计会失败,但仅当错误消息包含特定消息时(示例: 400 Client Error: Bad Request )。在这种情况下,测试将报告为 XFAIL .

    但如果测试失败并创建 不同的 错误消息(即使是相同的异常,但是 500 Server Error 相反,在错误消息中,必须将测试报告为意外通过( XPASS )

    0 回复  |  直到 5 年前
        1
  •  2
  •   MultiSkill    5 年前

    如果失败是正常行为,您可以创建自己的装饰器,例如:

    import functools
    def expect_http_error(func=None, *, expected_error):
      def wrapper(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
          with pytest.raises(requests.exceptions.HTTPError) as excinfo:
            func(*args, **kwargs)
          assert expected_error in str(excinfo.value)
    
        return inner
    
      return wrapper if func is None else wrapper(func)
    

    然后你就这样使用它:

    @expect_http_error(expected_error = "403 Client Error: Not Found")
    def test_fail_request(self):      
      response = requests.something