我正在从official docs学习pytest,并找到了适合我需要的示例。我键入以下代码,在文件中运行pytest,我没有失败
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return 'C:\\Users\\Admin\\'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == "C:\\Users\\Admin\\.ssh"
但是当我采用上面的代码来处理真正的应用程序代码时,即
import random
def _mkRandom(low_lim, high_lim):
""" generates a random number between given limits
NOTE: sometimes the random number generated is so low
that even after multiplication it remains smaller than
lower limit, this function tries to handle such cases also.
"""
x = random.random()
x = x*high_lim
if x<low_lim:
print("Special case encountered")
x+= low_lim
return x
def test_mkRandom(monkeypatch):
def mockreturn(low, high):
return 0.001
monkeypatch.setattr(random, "random", mockreturn)
x = _mkRandom(1, 2)
assert x == 1.002
return
我收到以下错误:
================================== FAILURES ===================================
________________________________ test_mkRandom ________________________________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x027DB330>
def test_mkRandom(monkeypatch):
def mockreturn(low, high):
return 0.001
monkeypatch.setattr(random, "random", mockreturn)
> x = _mkRandom(1, 2)
monkey.py:22:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
low_lim = 1, high_lim = 2
def _mkRandom(low_lim, high_lim):
""" generates a random number between given limits
NOTE: sometimes the random number generated is so low
that even after multiplication it remains smaller than
lower limit, this function handles such cases also.
"""
> x = random.random()
E TypeError: mockreturn() missing 2 required positional arguments: 'low' and 'high'
monkey.py:11: TypeError
===================== 1 failed, 1 passed in 0.16 seconds ======================
如何正确测试_mkRandom
?