Python code testing

I want to check python code that receives data from another function (e.g. MeasureRadius). MeasureRadius is not ready because it relies on a tool that I have not received yet. What is the best way to test CalculateArea with different values ​​on iRadius and iErrorCode received from MeasureRadius? The automated way will be enjoyable. I was going to use unittest, but I do not know how I would change the iRadius and iErrorCode returned from MeasureRadius.

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,"" 
+4
source share
1 answer

You will need a "Mock fixture" which replaces the Instrument class.

You also need to redesign CalculateArea so that it is validated.

 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. 
+4
source

Source: https://habr.com/ru/post/1337887/


All Articles