gpt4 book ai didi

python - 为 Python REST API 函数编写单元测试

转载 作者:行者123 更新时间:2023-12-02 16:34:31 25 4
gpt4 key购买 nike

我目前正在学习 Python REST API(副项目)。我一直在阅读 RealPython、Python Requests 文档等的大量教程。我发现了这篇关于如何在 Python 中正确编写 try/except 的帖子(Correct way to try/except using Python requests module?)。仍然让我感到困惑的一件事是如何为这样的函数创建单元测试,因为它不返回任何东西。有帮助吗?

def google_do_something(blahblah):
url='http://www.google.com/' + blahblah
try:
r = requests.get(url,timeout=3)
r.raise_for_status()
except requests.exceptions.HTTPError as errh:
print (errh)
except requests.exceptions.ConnectionError as errc:
print (errc)
except requests.exceptions.Timeout as errt:
print (errt)
except requests.exceptions.RequestException as err:
print (err)

我能想到这个,但我不知道用什么来断言。

def test_google_do_something():
g = google_do_something('blahblah')
# assert??

最佳答案

Python 中有多个可用的单元测试框架。 Try/except block 非常适合错误处理,但如果要对其进行单元测试,您仍然需要围绕调用进行单独的单元测试。

您确实有可以测试的东西,您可以将其返回并在单元测试中进行测试。

使用 unittest 的示例单元测试:

import unittest
import requests

class RestCalls():

def google_do_something(blahblah):
url= blahblah
try:
r = requests.get(url,timeout=1)
r.raise_for_status()
return r.status_code
except requests.exceptions.Timeout as errt:
print (errt)
raise
except requests.exceptions.HTTPError as errh:
print (errh)
raise
except requests.exceptions.ConnectionError as errc:
print (errc)
raise
except requests.exceptions.RequestException as err:
print (err)
raise


class TestRESTMethods(unittest.TestCase):

def test_valid_url(self):
self.assertEqual(200,RestCalls.google_do_something('http://www.google.com/search'))

def test_exception(self):
self.assertRaises(requests.exceptions.Timeout,RestCalls.google_do_something,'http://localhost:28989')

if __name__ == '__main__':
unittest.main()

执行应该显示(对这篇文章进行了一些编辑,更新后的输出包含在文章底部):

> python .\Tests.py
.
----------------------------------------------------------------------
Ran 1 test in 0.192s

OK

如果您断言与您的请求不同的响应代码,它将失败(请求只是返回 http 响应代码):

python .\Tests.py
F
======================================================================
FAIL: test_upper (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File ".\Tests.py", line 25, in test_upper
self.assertEqual(404,RestCalls.google_do_something('search'))
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.245s

FAILED (failures=1)

这是预期的。

编辑:包括异常测试。您可以通过在 except block 中包含 raise 来测试这些,这将在运行后显示:

> python .\Tests.py
HTTPConnectionPool(host='localhost', port=28989): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x03688598>, 'Connection to localhost timed out. (connect timeout=1)'))
..
----------------------------------------------------------------------
Ran 2 tests in 2.216s

OK

引用资料:

关于python - 为 Python REST API 函数编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62938765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com