【问题标题】:pytest.raises passes when should fails (ValueError: The truth value of a DataFrame is ambiguous.)pytest.raises 在应该失败时通过(ValueError:DataFrame 的真值不明确。)
【发布时间】:2020-11-14 12:31:48
【问题描述】:

我正在使用 pytest 测试我的代码。

如果我这样做:

response = clients(5)
print(response)

我得到一个数据框作为输出(在客户端函数中定义)

 client_id    name           country    currency  
 5            John Doe       Spain      EUR  

客户是这样定义的:

def clients(id):

    endpoint = f"myendpoint/{id}"
    response = requests.get(endpoint)
    j_response = json.loads(response.text)

    df = pd.DataFrame(pd.json_normalize(j_response))

    return df

然后在我的tests.py中我做

import pytest  

test_clients_exceptions():

    with pytest.raises(Exception):
        assert clients(5)

我通过了,当我应该失败时,因为不应该引发异常。 例如,如果我将“ValueError”更改为“Exception”,则它会通过,但如果我更改为“TypeError”则不会。在这种情况下,我得到:

 ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这是为什么呢?


另一方面,如果我想一次测试多个加注,正确的语法是什么?如果我这样做可以吗:

test_clients_exceptions():

    with pytest.raises(TypeError):
        assert clients("this_is_str_and_should_be_int")

    key_dict="Hi"
    value = 4
    with pytest.raises(Exception) as e:
        assert clients(**{key_dict: value})
        assert str(e.value) == f"\'{key_dict}\' is not supported"

【问题讨论】:

    标签: dataframe unit-testing pytest valueerror raise


    【解决方案1】:

    我从来没有用过 pytest.raises,另一种做你想做的事情是这样的:

    try:
        clients(5)
    except:
        pytest.fail("My test failed \n", False)
    

    注意:如果您不想在终端中显示所有失败的内容,则使用 False。但是,如果您想查看所有内容,可以将其更改为 True。 来源:https://docs.pytest.org/en/stable/reference.html#pytest-fail

    *我不明白客户的方法是做什么的。这似乎不是一个测试。

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2021-01-19
      • 2017-11-22
      • 1970-01-01
      • 2021-11-28
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多