LKa
LKa

Reputation: 71

Testing python code

I want to test a python code that gets inputs from a different function (eg MeasureRadius). MeasureRadius is not ready because it relies on an instrument that I haven't receive yet. What's the best way to test CalculateArea with different values on iRadius, and iErrorCode outputted from MeasureRadius? An automated way will be nice. I was going to use unittest, but I don't know how I would change 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,""

Upvotes: 4

Views: 666

Answers (1)

S.Lott
S.Lott

Reputation: 392070

You need a "Mock fixture" that replaces the Instrument class.

You also need to redesign CalculateArea so it's testable.

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.

Upvotes: 4

Related Questions