I have a view here which adds a new List
to the database and redirects to the List
page. I have get_absolute_url
configured in the model class. It seems to works perfectly.
def new_list(request):form = ItemForm(request.POST)if form.is_valid():list_ = List()list_.owner = request.userlist_.save()form.save(for_list=list_)return redirect(list_)else:return render(request, 'home.html', {'form': form})
But the problem happens when I try to mock the model class and the form class with patch
from unitest.mock
class TestMyLists(TestCase):@patch('lists.views.List')@patch('lists.views.ItemForm')def test_list_owner_is_saved_if_user_is_authenticated(self, mockItemFormClass, mockListClass):user = User.objects.create(email='[email protected]')self.client.force_login(user)self.client.post('/lists/new', data={'text': 'new item'})mock_list = mockListClass.return_valueself.assertEqual(mock_list.owner, user)
When I run the test, I get error like this:
Traceback (most recent call last):
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in innerresponse = get_response(request)
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_responseresponse = self.process_exception_by_middleware(e, request)
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_responseresponse = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/BAC4BB93C4BB4FFD/codes/tdd/superlists/lists/views.py", line 36, in new_listreturn redirect(list_)
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/shortcuts.py", line 58, in redirectreturn redirect_class(resolve_url(to, *args, **kwargs))
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/http/response.py", line 407, in __init__self['Location'] = iri_to_uri(redirect_to)
File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/utils/encoding.py", line 151, in iri_to_urireturn quote(iri, safe="/#%[]=:;$&()+,!?*@'~")
File "/usr/local/lib/python3.6/urllib/parse.py", line 787, in quotereturn quote_from_bytes(string, safe)
File "/usr/local/lib/python3.6/urllib/parse.py", line 812, in quote_from_bytesraise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
It seems like the redirect function will not work with a mock object. How can I fix this? I'm using Django 2.0.1