4

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,""
asked Feb 1, 2011 at 2:01
1
  • 2
    Your indentation is very hard to read. At least 3 spaces. Ideally 4. You have a method function def MeasureRadius with an Upper Case name, which is also a bad idea. Commented Feb 1, 2011 at 2:06

1 Answer 1

4

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.
answered Feb 1, 2011 at 2:17
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.