[Answered ]-Using Pytest and Mock to test view that queries database

2👍

You’ve missed one key component of using mock to override methods. You need to use mock as a method decorator to basically monkey match your method to be able to do what you would like.

You’ll want to write something that looks like this. (Note: Haven’t tested this at all, but should lead you in the right direction).

@pytest.mark.django_db
class TestDataReduction(TestCase):

    @mock.patch(your_module.xyz.DataSource)
    @mock.patch(your_module.xyz.Datapoint)
    @mock.patch(your_module.xyz.Decision)
    def test_calibrator_data(self, mock_source, mock_points,
                             mock_people):

        mock_source.objects.filter.return_value.values.return_value.order_by.return_value = [array([random.randint(0,10)]), datetime.now()]

        mock_points.objects.filter.return_value = []

        mock_people.objects.filter.values_list.return_value.distinct.return_value = []

        calid = 22
        code = 'corot2b'

        self.output = calibrator_data(calid,code)

        assert type(self.output[0])==type([])

You are also going to need to mock out whatever you want the return values to be your multiple calls to points.filter. One way to do this would be by using side effects. There is a pretty good example here: https://stackoverflow.com/a/7665754/2022511

In addition to my post that you’ve already looked at (https://www.chicagodjango.com/blog/quick-introduction-mock/), there is more information about using mock.patch in this blog post: http://fgimian.github.io/blog/2014/04/10/using-the-python-mock-library-to-fake-regular-functions-during-tests/

Leave a comment