使用mock测试python中的函数

时间:2017-08-04 06:10:58

标签: python unit-testing exception mocking

对于测试覆盖,我想测试文件'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

到目前为止,我尝试了这种方法,但仍然无法进入异常块:

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)

或者我应该用错误的输入引发异常?谁能举一个例子?提前致谢

1 个答案:

答案 0 :(得分:1)

您似乎想要创建SignalC的实例,然后调用readSignal方法。所以你不应该修补那个方法本身("signalC.SignalC.readSignal"),因为这意味着它将被嘲笑,你不会调用该方法的真正实现。

例如,您可以在调用IOError时提升open

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)