我可以在python3 的单元测试中使用一些非常需要的指导
我所有的文件都在同一个目录中。没有子文件夹。
Params是一个在脚本中初始化的类。文件1在连接到API时运行良好。
#文件1资产Sensu.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资产Sensu_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单元测试资产Sensu_tests.py
我们将不胜感激。
您正在测试GetAssets
方法,所以不应该模拟它。相反,您应该模拟requests.request
方法及其返回值。我们使用requests.Response()
类来创建一个模拟响应。
例如(Python 3.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%