对于python3的单元测试,我可以使用一些急需的指导。
我所有的文件都在同一个目录里。没有子文件夹。
Params是在脚本中初始化的类。文件1可以很好地连接到API。
#文件1 AssetsSensu.py
import requests
import json
from Params import params
class Assets():
def GetAssets():
response = requests.request(
"GET", params.url+"assets", headers=params.headers, verify=params.verify)
return response
#文件2 AssetsSensu_tests.py
from Params import params
from AssetsSensu import Assets
from unittest import TestCase, mock
class TestAPI(TestCase):
@mock.patch('AssetsSensu.Assets.GetAssets', return_val=200)
def test_GetAssets(self, getassets):
self.result = Assets.GetAssets().status_code
self.assertEquals(self.result, 200)
我得到了这个结果,运行Assets.GetAssets().status_code将在任何一个文件中返回200。
AssertionError: <MagicMock name='GetAssets().status_code' id='140685448294016'> != 200
在文件2中,"getassets“没有突出显示,这对我来说意味着它没有被使用。如果删除它,将得到以下错误
TypeError: test_GetAssets() takes 1 positional argument but 2 were given
命令是python3 -m unittest AssetsSensu_tests.py。
我们将非常感谢您的帮助。
发布于 2022-04-08 02:42:33
您正在测试GetAssets
方法,因此不应该模拟它。相反,您应该模拟requests.request
方法及其返回值。我们使用requests.Response()
类创建一个模拟的响应。
例如(Python3.9.6,requests==2.26.0)
AssetsSensu.py
import requests
from Params import params
class Assets():
def GetAssets():
response = requests.request(
"GET", params.url+"assets", headers=params.headers, verify=params.verify)
return response
Params.py
from collections import namedtuple
requestOptions = namedtuple("RequestOptions", ["url", "headers", "verify"])
params = requestOptions('http://localhost:8080/api/', {}, False)
AssetsSensu_tests.py
import unittest
from AssetsSensu import Assets
from unittest import TestCase, mock
import requests
class TestAPI(TestCase):
@mock.patch('AssetsSensu.requests')
def test_GetAssets(self, mock_requests):
resp = requests.Response()
resp.status_code = 200
mock_requests.request.return_value = resp
result = Assets.GetAssets()
self.assertEqual(result.status_code, 200)
mock_requests.request.assert_called_once_with("GET", "http://localhost:8080/api/assets", headers={}, verify=False)
if __name__ == '__main__':
unittest.main()
测试结果:
coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/71782055/AssetsSensu_tests.py && coverage report -m
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
-------------------------------------------------------------------------------
src/stackoverflow/71782055/AssetsSensu.py 6 0 100%
src/stackoverflow/71782055/AssetsSensu_tests.py 15 0 100%
src/stackoverflow/71782055/Params.py 3 0 100%
-------------------------------------------------------------------------------
TOTAL 24 0 100%
https://stackoverflow.com/questions/71782055
复制相似问题