Skip to content

Instantly share code, notes, and snippets.

@rochacon
Last active August 29, 2015 14:06
Show Gist options
  • Save rochacon/fa014de300cfb26ebd6e to your computer and use it in GitHub Desktop.
Save rochacon/fa014de300cfb26ebd6e to your computer and use it in GitHub Desktop.
A different approach to Django view unit testing
from django.db import models
class Twt(models.Model):
txt = models.CharField(max_length=140)
from django.http import HttpRequest
from django.test import TestCase
from .models import Twt
from . import views
class TwtTestCase(TestCase):
def test_list_empty(self):
req = HttpRequest()
resp = views.get(req)
self.assertEquals(resp.status_code, 200)
self.assertEquals(resp['Content-Type'], 'application/json')
self.assertJSONEqual(resp.content, [])
def test_list_with_values(self):
t = Twt.objects.create(txt='140 characters should be enough')
req = HttpRequest()
resp = views.get(req)
self.assertEquals(resp.status_code, 200)
self.assertEquals(resp['Content-Type'], 'application/json')
self.assertJSONEqual(resp.content, [{'txt': t.txt}])
import json
from django.http import HttpResponse
from .models import Twt
def get(request):
twts = [{'txt': t.txt} for t in Twt.objects.all()]
return HttpResponse(json.dumps(twts), content_type='application/json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment