Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a function is called within a function with nosetests

I'm trying to set up some automatic unit testing for a project. I have some functions which, as a side effect occasionally call another function. I want to write a unit test which tests that the second function gets called but I'm stumped. Below is pseudocode example:

def a(self):
    data = self.get()
    if len(data) > 3500:
        self.b()

    # Bunch of other magic, which is easy to test.

def b(self):
    serial.write("\x00\x01\x02")

How do I test that b()-gets called?

like image 712
msvalkon Avatar asked Sep 12 '13 10:09

msvalkon


1 Answers

You can mock the function b using mock module and check if it was called. Here's an example:

import unittest
from mock import patch


def a(n):
    if n > 10:
        b()

def b():
    print "test"


class MyTestCase(unittest.TestCase):
    @patch('__main__.b')
    def test_b_called(self, mock):
        a(11)
        self.assertTrue(mock.called)

    @patch('__main__.b')
    def test_b_not_called(self, mock):
        a(10)
        self.assertFalse(mock.called)

if __name__ == "__main__":
    unittest.main()

Also see:

  • Assert that a method was called in a Python unit test
  • Mocking a class: Mock() or patch()?

Hope that helps.

like image 68
alecxe Avatar answered Sep 21 '22 21:09

alecxe