0
votes

I'm having trouble understanding how to write a Python 3 unit test that uses mock objects to mock an instance method for a Django model. Here are my models and the test:

# models.py
class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name='books')

    def retrieve_isbn(self):
        return 'abc123'

# tests.py
class TestModel(unittest.TestCase):
    @mock.patch('run.models.Book', autospec=True)
    @mock.patch('run.models.Author', autospec=True)
    def test_book_isbn(self, mock_author, mock_book):
        mock_author.name = 'Henry Miller'
        mock_book.title = 'Time of the Assassins'
        mock_book.author = mock_author
        mock_book.retrieve_isbn = MagicMock(return_value='foo123')
        # the next line doesn't work either
        #mock_book.retrieve_isbn.return_value = 'foo123'
        isbn = Book().retrieve_isbn()
        self.assertEqual(isbn, 'foo123')

My test fails with this error:

AssertionError: 'abc123' != 'foo123'

As I understand it, when I create the mock_book object, any calls to instances of the Book class will be intercepted and replaced with the values I assign to the mock object's attributes. Isn't the line "mock_book.retrieve_isbn = MagicMock(return_value='foo123')" going to cause any calls to the Book class's retrieve_isbn method to return 'foo123' or have I not set up my test correctly?

1
But at the last line, you call the real Book(), with Book().retrieve_isbn(). - Willem Van Onsem
I could have also written book = Book() and then called book.retrieve_isbn(), but it doesn't make a difference. - Jim

1 Answers

0
votes

This is how to do it (leaving out all the extraneous stuff):

@mock.patch('run.models.Book.retrieve_isbn')
def test_book_isbn(self, mock_method):
    mock_method.return_value = 'foo123'
    isbn = Book().retrieve_isbn()
    self.assertEqual(isbn, 'foo123')