Commits

Jesper Nøhr committed 6c26142

adding test for incoming json/yaml in tests/

Comments (0)

Files changed (5)

tests/buildout.cfg

 [buildout]
-parts = django
+parts = django 
 develop = ..
-eggs = 
-    django-piston
+eggs = django-piston
 
 [django]
 recipe = djangorecipe

tests/test_project/apps/testapp/handlers.py

 from piston.handler import BaseHandler
 from piston.utils import rc, validate
 
-from .models import TestModel
+from models import TestModel, ExpressiveTestModel, Comment
 
 class EntryHandler(BaseHandler):
     model = TestModel
         paginator = Paginator(TestModel.objects.all(), 25)
         return paginator.page(int(request.GET.get('page', 1))).object_list
 
+class ExpressiveHandler(BaseHandler):
+    model = ExpressiveTestModel
+    fields = ('title', 'content', ('comments', ('content',)))
+
+    @classmethod
+    def comments(cls, em):
+        return em.comments.all()
+
+    def read(self, request):
+        inst = ExpressiveTestModel.objects.all()
+        
+        return inst
+        
+    def create(self, request):
+        if request.content_type:
+            data = request.data
+            
+            em = self.model(title=data['title'], content=data['content'])
+            em.save()
+            
+            for comment in data['comments']:
+                Comment(parent=em, content=comment['content']).save()
+                
+            return rc.CREATED
+        else:
+            super(ExpressiveTestModel, self).create(request)
+            

tests/test_project/apps/testapp/models.py

 class TestModel(models.Model):
     test1 = models.CharField(max_length=1, blank=True, null=True)
     test2 = models.CharField(max_length=1, blank=True, null=True)
-    pass
+    
+class ExpressiveTestModel(models.Model):
+    title = models.CharField(max_length=255)
+    content = models.TextField()
+    
+class Comment(models.Model):
+    parent = models.ForeignKey(ExpressiveTestModel, related_name='comments')
+    content = models.TextField()
+    

tests/test_project/apps/testapp/tests.py

 from django.test import TestCase
 from django.contrib.auth.models import User
+from django.utils import simplejson
+
+try:
+    import yaml
+except ImportError:
+    print "Can't run YAML testsuite"
+    yaml = None
+
 import base64
 
-from test_project.apps.testapp.models import TestModel
-
+from test_project.apps.testapp.models import TestModel, ExpressiveTestModel, Comment
 
 class MainTests(TestCase):
     def setUp(self):
         self.user.is_active = True
         self.user.save()
         self.auth_string = 'Basic %s' % base64.encodestring('admin:admin').rstrip()
+
+        if hasattr(self, 'init_delegate'):
+            self.init_delegate()
+        
+    def tearDown(self):
+        self.user.delete()
+ 
+class MultiXMLTests(MainTests):
+    def init_delegate(self):
         self.t1_data = TestModel()
         self.t1_data.save()
         self.t2_data = TestModel()
         self.t2_data.save()
 
-    def tearDown(self):
-        self.user.delete()
- 
     def test_multixml(self):
         expected = '<?xml version="1.0" encoding="utf-8"?>\n<response><resource><test1>None</test1><test2>None</test2></resource><resource><test1>None</test1><test2>None</test2></resource></response>'
         result = self.client.get('/api/entries.xml',
         result = self.client.get('/api/entry-%d.xml' % (obj.pk,),
                 HTTP_AUTHORIZATION=self.auth_string).content
         self.assertEquals(expected, result)
-    def test_single(self):
-        pass
+
+class IncomingExpressiveTests(MainTests):
+    def init_delegate(self):
+        e1 = ExpressiveTestModel(title="foo", content="bar")
+        e1.save()
+        e2 = ExpressiveTestModel(title="foo2", content="bar2")
+        e2.save()
+
+    def test_incoming_json(self):
+        outgoing = simplejson.dumps({ 'title': 'test', 'content': 'test',
+                                      'comments': [ { 'content': 'test1' },
+                                                    { 'content': 'test2' } ] })
+    
+        expected = '[{"content": "bar", "comments": [], "title": "foo"}, {"content": "bar2", "comments": [], "title": "foo2"}]'
+    
+        self.assertEquals(self.client.get('/api/expressive.json', 
+            HTTP_AUTHORIZATION=self.auth_string).content, expected)
+        
+        resp = self.client.post('/api/expressive.json', outgoing, content_type='application/json',
+            HTTP_AUTHORIZATION=self.auth_string)
+            
+        self.assertEquals(resp.status_code, 200)
+        
+        expected = '[{"content": "bar", "comments": [], "title": "foo"}, {"content": "bar2", "comments": [], "title": "foo2"}, {"content": "test", "comments": [{"content": "test1"}, {"content": "test2"}], "title": "test"}]'
+        
+        self.assertEquals(self.client.get('/api/expressive.json', 
+            HTTP_AUTHORIZATION=self.auth_string).content, expected)
+        
+    def test_incoming_yaml(self):
+        if not yaml:
+            return
+            
+        expected = """- comments: []
+  content: bar
+  title: foo
+- comments: []
+  content: bar2
+  title: foo2
+"""
+          
+        self.assertEquals(self.client.get('/api/expressive.yaml',
+            HTTP_AUTHORIZATION=self.auth_string).content, expected)
+
+        outgoing = yaml.dump({ 'title': 'test', 'content': 'test',
+                                      'comments': [ { 'content': 'test1' },
+                                                    { 'content': 'test2' } ] })
+            
+        resp = self.client.post('/api/expressive.json', outgoing, content_type='application/x-yaml',
+            HTTP_AUTHORIZATION=self.auth_string)
+        
+        self.assertEquals(resp.status_code, 200)
+        
+        expected = """- comments: []
+  content: bar
+  title: foo
+- comments: []
+  content: bar2
+  title: foo2
+- comments:
+  - {content: test1}
+  - {content: test2}
+  content: test
+  title: test
+"""
+        self.assertEquals(self.client.get('/api/expressive.yaml', 
+            HTTP_AUTHORIZATION=self.auth_string).content, expected)

tests/test_project/apps/testapp/urls.py

 from piston.resource import Resource
 from piston.authentication import HttpBasicAuthentication
 
-from test_project.apps.testapp.handlers import EntryHandler
+from test_project.apps.testapp.handlers import EntryHandler, ExpressiveHandler
 
 auth = HttpBasicAuthentication(realm='TestApplication')
 
 entries = Resource(handler=EntryHandler, authentication=auth)
+expressive = Resource(handler=ExpressiveHandler, authentication=auth)
 
 urlpatterns = patterns('',
     url(r'^entries/$', entries),
     url(r'^entries/(?P<pk>.+)/$', entries),
     url(r'^entries\.(?P<emitter_format>.+)', entries),
     url(r'^entry-(?P<pk>.+)\.(?P<emitter_format>.+)', entries),
+    
+    url(r'^expressive\.(?P<emitter_format>.+)$', expressive),
 )