TTT
TTT

Reputation: 4434

Python Unit Testing a loop function

This is a followup question from 1

I need to test the function with two given cases in a loop. However, based on the printed results, it seems like only the first iteration is checked? Is this related to runner.run(unittest.makeSuite(MyTestCase))?

import unittest
from StringIO import StringIO
import rice_output

class MyTestCase(unittest.TestCase):
    def setUp(self):
        #####Pre-defined inputs########
        self.dsed_in=[1,2]
        self.a_in=[2,3]
        self.pb_in=[3,4]

        #####Pre-defined outputs########
        self.msed_out=[6,24]

        #####TestCase run variables########
        self.tot_iter=len(self.a_in)

def testMsed(self):
    for i in range(self.tot_iter):
        print i
        fun = rice_output.msed(self.dsed_in[i],self.a_in[i],self.pb_in[i])
        value = self.msed_out[i]
        testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("msed",i,value,fun)
        return self.assertEqual(round(fun,3),round(self.msed_out[i],3),testFailureMessage)

from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream)
result = runner.run(unittest.makeSuite(MyTestCase))
print 'Tests run ', result.testsRun
print 'Errors ', result.errors

Here is he output:

0
Tests run  1
Errors  []
[]
Test output
testMsed (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Any suggestions? Thanks!

Upvotes: 0

Views: 3615

Answers (1)

Nix
Nix

Reputation: 58602

Remove the return statement

def testMsed(self):
  for i in range(self.tot_iter):
    print i
    fun = rice_output.msed(self.dsed_in[i],self.a_in[i],self.pb_in[i])
    value = self.msed_out[i]
    testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("msed",i,value,fun)
    self.assertEqual(round(fun,3),round(self.msed_out[i],3),testFailureMessage)

Upvotes: 3

Related Questions