david / django-modelviews

Backup of an old repository with useful ideas. Initial goal: integrating REST to django admin (class-based views).

Clone this repository (size: 85.7 KB): HTTPS / SSH
$ hg clone http://code.welldev.org/django-modelviews
r44:add8532b04a8 252 loc 11.0 KB embed / history / annotate / raw /
from django.test import TestCase
from models import Article, Comment
from django.utils import simplejson
from django.contrib.auth.models import User
from xml.dom.minidom import parseString
        

class ArticleTest(TestCase):
    def test_model(self):
        a = Article.objects.create(name="An article",
                                   slug="an-article",
                                   body="some text")
        self.assertEqual(a.name, "An article")
        self.assertEqual(a.slug, "an-article")
        self.assertEqual(a.body, "some text")


class ModelViewTest(TestCase):
    def setUp(self):
        Article.objects.create(name="My Story",
                               slug="my-story",
                               body="My thrilling story!")
        david = User.objects.create_user('david', 'foo@example.com', 'baz')
        will = User.objects.create_user('will', 'bar@example.com', 'baz')
        Comment.objects.create(content="David comment", user=david)
        Comment.objects.create(content="Will comment", user=will)

    def test_restricting_exposed_methods(self):
        """
        The service exposed at /article/ should only
        allow the 'GET' method, and should reject
        all other http methods.
        """
        a = Article.objects.all()[0]
        response = self.client.post('/articles/', {})
        self.assertEqual(response.status_code, 405)
        # no explicit way to send DELETE or PUT methods, so get
        # a bit sneaky here.
        response = self.client.get('/articles/%s/' % a.slug, 
                                   REQUEST_METHOD='DELETE')
        self.assertEqual(response.status_code, 405)
        response = self.client.get('/articles/%s/' % a.slug,
                                   REQUEST_METHOD='PUT')
        self.assertEqual(response.status_code, 405)


    def test_restricting_authentication(self):
        a = Article.objects.all()[0]
        david = User.objects.all()[0]
        david.is_superuser = True
        david.save()
        will = User.objects.all()[1]
        will.is_staff = True
        will.save()
        response = self.client.get('/auth-articles/')
        self.assertEqual(response.status_code, 405)
        response = self.client.post('/auth-articles/', {})
        self.assertEqual(response.status_code, 405)
        response = self.client.login(username='david', password='baz')
        response = self.client.get('/auth-articles/')
        self.assertEqual(response.status_code, 200)
        response = self.client.post('/auth-articles/', {'name': "Another article",
                                                        'slug': "another-article",
                                                        'body': "some other text"})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Article.objects.count(), 2)
        response = self.client.login(username='will', password='baz')
        response = self.client.get('/auth-articles/')
        self.assertEqual(response.status_code, 200)
        response = self.client.post('/auth-articles/', {'name': "Another article",
                                                        'slug': "another-article",
                                                        'body': "some other text"})
        self.assertEqual(response.status_code, 405)
        self.assertEqual(Article.objects.count(), 2)
        a2 = Article.objects.all()[1]
        response = self.client.login(username='david', password='baz')
        response = self.client.post('/auth-articles/%s/' % a2.slug, {'name': "Yet another article",
                                                                     'slug': "yet-another-article",
                                                                     'body': "some other text"},
                                                                     REQUEST_METHOD='PUT')
        self.assertEqual(response.status_code, 405)
        a2 = Article.objects.all()[1]
        self.assertEqual(a2.name, u'Another article')
        response = self.client.login(username='will', password='baz')
        response = self.client.post('/auth-articles/%s/' % a2.slug, {'name': "Yet another article again",
                                                                     'slug': "yet-another-article-again",
                                                                     'body': "some other text"},
                                                                     REQUEST_METHOD='PUT')
        self.assertEqual(response.status_code, 302)
        a2 = Article.objects.all()[1]
        self.assertEqual(a2.name, u'Yet another article again')
        

    def test_default_responder(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/' % a.slug)
        self.assertEqual(response.status_code, 200)


    def test_html_responder_read_detail(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/html/' % a.slug)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'test_modelview/article_detail.html')
        self.assertNotEqual(response.content.find(a.name), -1)


    def test_html_responder_read_list(self):
        response = self.client.get('/articles/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'test_modelview/article_list.html')
        for article in Article.objects.all():
            self.assertNotEqual(response.content.find(article.name),-1)


    def test_html_responder_create(self):
        response = self.client.post('/rw-articles/', {'name': "Another article",
                                                      'slug': "another-article",
                                                      'body': "some other text"})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Article.objects.count(), 2)


    def test_html_responder_update(self):
        a = Article.objects.all()[0]
        response = self.client.post('/rw-articles/%s/' % a.slug,
                                    {'name': "An updated article",
                                     'slug': "an-article",
                                     'body': "some text"},
                                     REQUEST_METHOD='PUT')
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Article.objects.count(), 1)
        self.assertEqual(Article.objects.all()[0].name, u'An updated article')


    def test_html_responder_delete(self):
        a = Article.objects.all()[0]
        response = self.client.post('/rw-articles/%s/' % a.slug,
                                     REQUEST_METHOD='DELETE')
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Article.objects.count(), 0)


    def test_atom_responder_read_detail(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/atom/' % a.slug)
        self.assertEqual(response.status_code, 200)
        feed_content = '</updated><entry><title>%s</title>' % a.name
        self.assertEqual(response.content.find(feed_content), -1)


    def test_atom_responder_read_list(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/atom/')
        self.assertEqual(response.status_code, 200)
        feed_content = '</updated><entry><title>%s</title>' % a.name
        self.assertEqual(response.content.find(feed_content), -1)


    def test_rss_responder_read_detail(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/rss/' % a.slug)
        self.assertEqual(response.status_code, 200)
        feed_content = '</updated><entry><title>%s</title>' % a.name
        self.assertEqual(response.content.find(feed_content), -1)


    def test_rss_responder_read_list(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/rss/')
        self.assertEqual(response.status_code, 200)
        feed_content = '</updated><entry><title>%s</title>' % a.name
        self.assertEqual(response.content.find(feed_content), -1)


    def test_json_responder_detail(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/json/' % a.slug)
        self.assertEqual(response.status_code, 200)
        data = simplejson.loads(response.content)
        self.assertEqual(data[0]['fields']['slug'], a.slug)
        self.assertEqual(data[0]['pk'], a.pk)
        self.assertEqual(data[0]['fields']['body'], a.body)


    def test_json_responder_list(self):
        response = self.client.get('/articles/json/')
        self.assertEqual(response.status_code, 200)
        data = simplejson.loads(response.content)
        self.assertEqual(Article.objects.count(), len(data))


    def test_xml_responder_detail(self):
        a = Article.objects.all()[0]
        response = self.client.get('/articles/%s/xml/' % a.slug)
        self.assertEqual(response.status_code, 200)
        dom = parseString(response.content)
        obj = dom.childNodes[0].childNodes[0]
        self.assertEqual(obj.attributes['pk'].value, str(a.pk))
        for node in obj.childNodes:
            field = node.attributes['name'].value
            value = node.childNodes[0].nodeValue
            """
            Ignoring date, because checking it was failing on
            'correct' but different results like:
            AssertionError: '2008-06-19 02:54:12.951959' != u'2008-06-19 02:54:12'
            """
            if field != 'date':
                self.assertEqual(str(getattr(a,field)),value)


    def test_xml_responder_list(self):
        response = self.client.get('/articles/xml/')
        self.assertEqual(response.status_code, 200)
        dom = parseString(response.content)
        self.assertEqual(Article.objects.count(), len(dom.childNodes[0].childNodes))


    def test_yaml_responder_detail(self):
        try:
            import yaml
            a = Article.objects.all()[0]
            response = self.client.get(u'/articles/%s/yaml/' % a.slug)
            self.assertEqual(response.status_code, 200)
            data = yaml.load(response.content)[0]
            self.assertEqual(a.slug, data['fields']['slug'])
            self.assertEqual(a.body, data['fields']['body'])
        except ImportError:
            pass


    def test_yaml_responder_list(self):
        try:
            import yaml
            response = self.client.get(u'/articles/yaml/')
            self.assertEqual(response.status_code, 200)
            data = yaml.load(response.content)
            self.assertEqual(len(data), Article.objects.count())
        except ImportError:
            pass


    def test_nested_resource(self):
        david = User.objects.all()[0]
        david_comment = Comment.objects.all()[0]
        will_comment = Comment.objects.all()[1]
        response = self.client.get('/users/%s/comments/' % david.username)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'test_modelview/comment_list.html')
        self.assertNotEqual(response.content.find(david_comment.content), -1)
        self.assertEqual(response.content.find(will_comment.content), -1)