python unittest测试__init__()需要两个参数?
python unittest测试的时候遇到了个问题, 在测试用例中的setUp()方法中我导入了自定义的Interface类,
然后在运行测试用例的时候遇到了个错误说:
__init__() missing 2 required positional arguments: 'url' and 'method'
req.py
import requestsimport json
class InterFace:
def __init__(self, url, method, data=None):
self.res = self.call_method(url, method, data)
def send_get(self, url, data):
res = requests.get(url).json()
return json.dumps(res, indent=2, sort_keys=True)
def send_post(self, url, data):
res = requests.post(url, data).json()
return json.dumps(res, indent=2, sort_keys=True)
def call_method(self, url, method, data=None):
result = None
if method == 'GET':
result = self.send_get(url, data)
else:
result = self.send_post(url, data)
return result
if __name__ == '__main__':
url = 'xxx'
run = InterFace(url, 'GET')
print(run.res)
test.py
import unittestfrom req import InterFace
class TestMethod(unittest.TestCase):
def setUp(self):
self.run = InterFace()
def test_one(self):
url = 'xxx1111'
data = {
'mobile': '12345678978',
'password': '123456'
}
res = self.run.call_method(url, 'POST', data)
self.assertEqual(res['code'], 1000, '测试通过')
def test_two(self):
url = 'xxx'
res = self.run.call_method(url, 'POST')
self.assertEqual(res['status'], 0, '测试通过')
if __name__ == '__main__':
unittest.main()
回答:
test.py
第7行
self.run = InterFace()
而你的原型是
def __init__(self, url, method, data=None):
所以你缺了两个位置参数url
和method
回答:
注释掉req.py的__init__()
和_if __name__ == '__main__'
方法,
然后执行python test.py
如果返回的res是json类型, 必须用json.loads()
进行转换:
self.assertEqual(json.loads(res)['code], '200', '测试通过')
以上是 python unittest测试__init__()需要两个参数? 的全部内容, 来源链接: utcz.com/a/161622.html