lundi 4 avril 2016

How mock/patch Model.objects.get() for Django testing?

I'm trying to test this get_context_data() in one of my views:

def get_context_data(self, **kwargs):
    context = super(MyView, self).get_context_data(**kwargs)
    context["obj"] = MyModel.objects.get(pk=kwargs["my_key"])
    return context

The test shows a keyError: "my_key", which is understandable. So I wan't to mock the MyModel.objects.get(), but have no success so far: The test still errors out on the same keyError.

This is my test code so far (simplified to get the point across):

@patch("app.views.MyModel.objects.get", return_value={"obj": "lol"})
def test_get_context_data(self, mock_get):
    self.assertIn("obj", self.view.get_context_data())

However, MyModel.objects.get(pk=kwargs["my_key"]) keeps being ran which resulted in the keyError.

How can I mock/patch the get() query?

Aucun commentaire:

Enregistrer un commentaire