Note that there are some explanatory texts on larger screens.

plurals
  1. POMocking object gets in Django unittests
    primarykey
    data
    text
    <p><strong>Edit:</strong> This didn't work initially as the imports used differing imports into the view, and into the mock. I used <code>project.app.views.Model</code> in the test mock, whereas in the import in the <code>views.py</code> was actually <code>app.views.Model</code>.</p> <p>Thereby this question is actually solved, but the problem might be useful to others, as it highlights the need for consistency of imports in mocking. (Something Michael Foord (Mock creator) mentions in his <a href="https://www.youtube.com/watch?v=yFA-FFaEZPo" rel="nofollow">talk</a>).</p> <p>This question revolves around mocking out the methods of Django model managers to return factory_boy objects, thereby avoiding the database. I have an 'Destination' model:</p> <pre><code>class Destination(models.Model): name = models.CharField(max_length=50) country = models.CharField(max_length=50) </code></pre> <p>And a DestinationView class based view. Within that, I try to retrieve a database object using a url-provided name for a destination:</p> <pre><code>from app.models import Destination class DestinationView(View): def get(self, request, **kwargs): [snip - gets the name from the URL request] try: destination = Destination.objects.get(name=name) except: return HttpResponse('No such destination', status=400) </code></pre> <p>I now want to mock out the above for a unittest. I use <a href="https://github.com/dnerdy/factory_boy" rel="nofollow">factory_boy</a> instances for my unittests to take them out of the database, and was trying to hand one of them back as the <a href="http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.return_value" rel="nofollow">return_value</a> when <code>get</code> is called:</p> <pre><code>def test_mocked_destination(self): with patch('app.views.Destination') as mock_destination: rf = RequestFactory() mock_destination.objects.get.return_value = DestinationFactory.build() request = rf.get('/destination/', {'destination': 'London'}) response = DestinationView.as_view()(request) </code></pre> <p>However, this doesn't work as planned, as the fake mock never appears to get called. How do I correctly override the <code>Destination</code> object's <code>get()</code> return_value in order to mock out the whole view from the database?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload