gpt4 book ai didi

python - 测试 python 代码

转载 作者:太空狗 更新时间:2023-10-30 03:07:22 26 4
gpt4 key购买 nike

我想测试从不同函数(例如 MeasureRadius)获取输入的 python 代码。 MeasureRadius 尚未准备好,因为它依赖于我尚未收到的仪器。在 iRadius 上测试具有不同值的 CalculateArea 和从 MeasureRadius 输出的 iErrorCode 的最佳方法是什么?自动化的方式会很好。我打算使用 unittest,但我不知道如何更改从 MeasureRadius 返回的 iRadius 和 iErrorCode。

class Instrument():
def MeasureRadius(self):
iErrorCode = 0
sErrorMsg = ""
iRadius = 0
try:
#tell the instrument to measure param A, the measurement goes into iRadius param
#iRadius = Measure()

except:
sErrorMsg = "MeasureRadius caught an exception."
iErrorCode = 1
return iRadius, iErrorCode, sErrorMsg

def CalculateArea():

"""calculate area from the measured radius. Returns area, error code, error message"""

iRadius, iErrorCode, sErrorMsg = Instrument.MeasureRadius()
if iErrorCode != 0:
return 0.0,iErrorCode, sErrorMsg
if iRadius <1 :
return 0.0,1, "Radius too small."
fArea = 3.14*iRadius*iRadius
return fArea,0,""

最佳答案

您需要一个“Mock fixture”来替换 Instrument 类。

您还需要重新设计 CalculateArea 以使其可测试。

def CalculateArea( someInstrument ):
iRadius, iErrorCode, sErrorMsg = someInstrument.measureRadius()
# rest of this is the same.

class MockInstrument( object ):
def __init__( self, iRadius, iErrorCode, sErrorMsg ):
self.iRadius= iRadius
self.iErrorCode= iErrorCode
self.sErrorMsg= sErrorMsg
def measureRadius( self ):
return self.iRadius, self.iErrorCode, self.sErrorMsg
class TestThisCondition( unittest.TestCase ):
def setUp( self ):
x = MockInstrument( some set of values )
def test_should_do_something( self ):
area, a, b = CalculateArea( x )
assert equality for the various values.

关于python - 测试 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4858152/

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