Created
May 24, 2016 17:53
-
-
Save maurobaraldi/14b1f81f9cf52d2760269e7b877a8644 to your computer and use it in GitHub Desktop.
Django unittest view with mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.test import Client, TestCase | |
from mock import patch | |
from .views import index | |
class SimpleTestCase(TestCase): | |
def setUp(self): | |
self.client = Client() | |
@patch('api.views.requests') | |
def test_mocked_test_case_should_succeed(self, mock_request): | |
""" | |
This is a simple testcase using mock feature. | |
1 - Decorate the method with path (app_path.views.module). | |
2 - Reference the mock in test method as param (mock_test). | |
3 - Define a value of the return of method (sub method or property) to mock. | |
4 - Call the mocked method and compare. | |
""" | |
mock_request.get.content.return_value = '{origin: "177.185.2.138"}' | |
response = self.client.get('/api/') | |
self.assertEqual(response.status_code, 200) | |
self.assertEqual(response.content, '{origin: "177.185.2.138"}') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf.urls import url | |
from . import views | |
urlpatterns = [ | |
url(r'^$', views.index, name='index'), | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from json import dumps | |
import requests | |
def index(request): | |
myip = requests.get('https://httpbin.org/ip') | |
return HttpResponse(myip.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment