【发布时间】: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