On Mar 31, 7:39 pm, belred <bel...@gmail.com> wrote:
> i have a questions about mock objects.  i currently have a django view
> function that calls a 2nd function.  this second function calls
> urllib2.urlopen.   i was thinking about adding in a mock object so i
> can get some better code coverage in the 2nd function when calling
> manage.py test.   my first thought was to create a mock
> urllib2.urlopen function, but how do i inject it into the code from a
> django unit test?  is there a best practice way to do this?
>
> def foo_view(request):
>      ...
>      foo_func(...):
>      ...
>      return HttpResponse('response')
>
> def foo_func(...):
>     ...
>     response =  urllib2.urlopen(url)
>     tree = etree.parse(response)
>     try:
>         if tree.xpath('/exception'):
>             raise FooError()
>         else:
>             result_attribute = tree.xpath('/success/@n-success')[0] ==
> '1'
>     except IndexError:
>         result_attribute = False
>     return result_attribute
>
> import unittest
> import os
> from django.test.client import Client
>
> class TestFoo(unittest.TestCase):
>     def setUp(self):
>         self.client = Client()
>
>     def test_foo(self):
>        # how do i inject a mock urllib2.urlopen into foo_func?
>
> thanks,
>
> bryan

The easiest way is to define a wrapper in your views.py that simply
passes its arguments to urlopen:

def urlopen(url):
    return urllib2.urlopen(url)

and throughout your views code, call that function rather than the
urllib2 one.
Then in your test setup you can do:

def mock_urlopen(url):
    return whatever
from myapp import views
views.urlopen = mock_urlopen

--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to