1

For the test coverage I want to test also the exception block of this function that is in the file 'signalC':

 class SignalC:
    def readSignal(self, a):
    try:
        with open(os.path.join(self.newSubFolder, "my file" + '.csv'), 'a') as csvfile:
            writer = csv.writer(csvfile, delimiter=',', quotechar='|',
                                quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
            print 'Reading'
            z = random.uniform(-0.1, 0.1)
            readValue = z + setP[element]

            writer.writerow([self.element + '-' + str(element+1),)
    except IOError as message:
        logging.error('Error in writing the csv file ' + str(message))
        print(message.strerror)
        raise IOError

So far I tried with this approach, but still cant go inside the exception block:

def testReadSignal(self):
    sc = signalC.SignalC()
    a = [1, 1, 1]
    with mock.patch("signalC.SignalC.readSignal", side_effect=IOError("IOError")):
        self.assertRaises(IOError, sc.readSignal, a)

Or I should instead raise the exception with a wrong input? Can anyone give any example? Thanks in advance

1 Answer 1

1

It appears you want to create an instance of SignalC and then call that readSignal method. So you shouldn't patch that method itself ("signalC.SignalC.readSignal") because that means it'll be mocked and you won't be calling the real implementation of that method.

You could raise the IOError when calling open for example:

def testReadSignal(self):
    sc = signalC.SignalC()
    a = [1, 1, 1]
    with mock.patch("signalC.open", side_effect=IOError("IOError")):
        self.assertRaises(IOError, sc.readSignal, a)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks lot! I dont know why I didnt think about open to raise the error

Your Answer

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.