def test_delete(self): p1 = Post.delete(id=1).commit() self.assertEqual(p1.rowcount, 1) p2 = Post.delete(id=1).commit() self.assertEqual(p2.rowcount, 0) p3 = Post.delete('id < 3').commit() self.assertEqual(p3.rowcount, 1)
def test_update(self): p1 = Post.update(id=5).set(title="new title 5").commit() self.assertEqual(p1.rowcount, 1) p2 = Post.get(id=5) self.assertEqual(p2.title, 'new title 5') p3 = Post.update(id=-1).set(title="unexisted id").commit() self.assertEqual(p3.rowcount, 0)
def test_max(self): c1 = Post.select('id').max() self.assertEqual(c1, 5) c2 = Post.select('id').where('id < 3').max() self.assertEqual(c2, 2) c3 = Post.select('id').where('id > 10').max() self.assertEqual(c3, None)
def test_get_object_id_from_related_object(self): """get_object_id() should return the value of a field specified by GRAPH_ID_FIELD. If the field isn't found on the instance, it's searched on a related object specified by RELATED_OBJECT_FIELD. """ post = Post(graph_id='111111111_22222222') post.save() post_insights = PostInsightsWithoutGraphID(post=post) self.assertEqual(post_insights.RELATED_OBJECT_FIELD, 'post') self.assertEqual(post_insights.get_graph_id(), '111111111_22222222')
def test_save_and_insert(self): author = Author(name='test author 6') author.save() post = Post(title='test title 6', content='test content 6', pub_date=datetime.now(), author_id='6') post.save() c = db.execute('select * from author where id=6;') self.assertEqual(len(c.fetchall()), 1) c = db.execute('select * from my_post where id=6;') self.assertEqual(len(c.fetchall()), 1)
def test_foreign_key_field(): post = Post() assert isinstance(post.category, Related) assert post.category_id is None assert isinstance(post.author, Related) assert post.author_id is None
def test_select(self): p1 = Post.select('*').where(id=2).all() self.assertEqual(len(p1), 1) self.assertEqual(p1[0].id, 2) p2 = Post.select('id', 'content').where(id=2).all() self.assertEqual(len(p1), 1) self.assertEqual(p2[0].id, 2) self.assertEqual(p2[0].content, 'test content 2') p3 = Post.select().where("id < 5").all() self.assertEqual(len(p3), 4) self.assertEqual([1, 2, 3, 4], [i.id for i in p3]) p4 = Post.select().first() self.assertEqual(p4.id, 1)
def setUp(self): """Creates three ``Post`` objects with different field settings.""" # Post with Markdown field self.mp = Post(title="example Markdown post", body="**markdown**", body_markup_type='markdown') self.mp.save() # default data attribute values for textareas: self.mm_settings = mm_settings.MARKUPMIRROR_CODEMIRROR_SETTINGS.copy() default = mm_settings.MARKUPMIRROR_DEFAULT_MARKUP_TYPE self.mm_settings.update({ 'preview_url': reverse('markupmirror:preview'), 'base_url': reverse('markupmirror:base'), 'mode': markup_pool[default].codemirror_mode, 'markup_type': default, })
def test_m2m_add(self): p = Post.get(id=1) t1 = Tag.get(id=1) t2 = Tag.get(id=2) p.tags.add(t1) p.tags.add(t2) self.assertEqual([p.id for p in p.tags.all()], [t1.id, t2.id]) self.assertEqual([p.id for p in t1.posts.all()], [p.id]) self.assertEqual([p.id for p in t2.posts.all()], [p.id])
def test_m2m_remove(self): p = Post.get(id=5) self.assertEqual(p.tags.all(), []) t = Tag.get(id=5) p.tags.add(t) self.assertEqual([t.id for t in p.tags.all()], [t.id]) self.assertEqual([p.id for p in t.posts.all()], [p.id]) p.tags.remove(t) self.assertEqual(p.tags.all(), []) self.assertEqual(t.posts.all(), [])
def test_like(self): posts = Post.select().where('content').like("test%").all() self.assertEqual([p.id for p in Post.select().all()], [i.id for i in posts]) posts = Post.select().where('id').like("1").all() self.assertEqual([Post.get(id=1).id], [p.id for p in posts]) posts = Post.select().where('content').like('%est%').all() self.assertEqual([p.id for p in Post.select().all()], [i.id for i in posts])
def setUp(self): """Creates three ``Post`` objects with different field settings.""" # Post with Markdown field self.mp = Post(title="example Markdown post", body="**markdown**", body_markup_type='markdown') self.mp.save() # Post with reStructuredText field self.rp = Post(title="example reStructuredText post", body="*reST*", body_markup_type='restructuredtext') self.rp.save() # Post being attacked self.xss_str = "<script>alert('xss');</script>" self.xss_post = Post(title="example XSS post", body=self.xss_str, body_markup_type='markdown', comment=self.xss_str) self.xss_post.save()
def test_avg(self): c1 = Post.select('id').avg() self.assertEqual(c1, 3)
def test_get(self): p1 = Post.get(id=1) self.assertEqual(p1.title, 'test title 1') self.assertEqual(p1.content, 'test content 1') self.assertEqual(p1.id, 1)
def test_sum(self): c1 = Post.select('id').sum() self.assertEqual(c1, 15)
def test_min(self): c1 = Post.select('id').min() self.assertEqual(c1, 1)
def test_count(self): c1 = Post.select().count() self.assertEqual(c1, 5) c2 = Post.select().where('id>3').count() self.assertEqual(c2, 2)
def test_orderby(self): posts = Post.select().orderby('id', 'asc').all() self.assertEqual([p.id for p in posts], [1, 2, 3, 4, 5]) posts = Post.select().orderby('id', 'desc').all() self.assertEqual([p.id for p in posts], [5, 4, 3, 2, 1])
def test_m2m_count(self): p = Post.get(id=3) self.assertEqual(p.tags.count(), 0) p.tags.add(Tag.get(id=3)) p.tags.add(Tag.get(id=4)) self.assertEqual(p.tags.count(), 2)
class MarkupMirrorWidgetTests(TestCase): """Tests the ``markupmirror.widget.MarkupMirrorTextarea`` and ``..AdminMarkupMirrorTextareaWidget`` implementations. """ def setUp(self): """Creates three ``Post`` objects with different field settings.""" # Post with Markdown field self.mp = Post(title="example Markdown post", body="**markdown**", body_markup_type='markdown') self.mp.save() # default data attribute values for textareas: self.mm_settings = mm_settings.MARKUPMIRROR_CODEMIRROR_SETTINGS.copy() default = mm_settings.MARKUPMIRROR_DEFAULT_MARKUP_TYPE self.mm_settings.update({ 'preview_url': reverse('markupmirror:preview'), 'base_url': reverse('markupmirror:base'), 'mode': markup_pool[default].codemirror_mode, 'markup_type': default, }) def test_widget_media(self): """Tests that the CSS and JS files required by the ``MarkupMirrorTextarea`` and the corresponding admin widget are used by forms correctly. """ pass def test_widget_default_attributes(self): """Tests the rendered HTML of the ``MarkupMirrorTextarea`` to make sure the default attributes are ok. """ form = PostForm(instance=self.mp) comment = form.fields['comment'] self.assertHTMLEqual( comment.widget.render('comment', self.mp.comment), textwrap.dedent("""\ <textarea rows="10" cols="40" name="comment" class="markupmirror-editor" data-mm-settings='{0}'></textarea>""").format( json.dumps(self.mm_settings, sort_keys=True)) ) def test_widget_additional_attributes(self): """Tests that additional attributes passed to the widget's ``render`` method are not lost. """ form = PostForm(instance=self.mp) comment = form.fields['comment'] self.assertHTMLEqual( comment.widget.render('comment', self.mp.comment, attrs={ 'data-something': "else", }), textwrap.dedent("""\ <textarea rows="10" cols="40" name="comment" class="markupmirror-editor" data-mm-settings='{0}' data-something="else"></textarea>""").format( json.dumps(self.mm_settings, sort_keys=True)) ) def test_widget_default_mode_and_markuptype(self): """Widgets initialized without data (create model forms) should have a default markup_type and mode. """ form = PostForm(instance=self.mp) comment = form.fields['comment'] default = settings.MARKUPMIRROR_DEFAULT_MARKUP_TYPE attrs = self.mm_settings.copy() attrs.update({ 'mode': markup_pool[default].codemirror_mode, 'markup_type': default, }) self.assertHTMLEqual( comment.widget.render('comment', u""), textwrap.dedent("""\ <textarea rows="10" cols="40" name="comment" class="markupmirror-editor" data-mm-settings='{0}'></textarea>""").format( json.dumps(attrs, sort_keys=True)) ) def test_admin_widget_render(self): """Tests that the ``AdminMarkupMirrorTextareaWidget`` renders properly. """ admin_widget = AdminMarkupMirrorTextareaWidget() attrs = self.mm_settings.copy() attrs.update({ 'mode': 'text/x-markdown', 'markup_type': 'markdown', }) self.assertHTMLEqual( admin_widget.render('comment', self.mp.comment), textwrap.dedent("""\ <textarea rows="10" cols="40" name="comment" class="vLargeTextField markupmirror-editor" data-mm-settings='{0}' />""").format( json.dumps(attrs, sort_keys=True)) )
class MarkupMirrorFieldTests(TestCase): """Tests the ``markupmirror.fields.MarkupMirrorField`` implementation.""" def setUp(self): """Creates three ``Post`` objects with different field settings.""" # Post with Markdown field self.mp = Post(title="example Markdown post", body="**markdown**", body_markup_type='markdown') self.mp.save() # Post with reStructuredText field self.rp = Post(title="example reStructuredText post", body="*reST*", body_markup_type='restructuredtext') self.rp.save() # Post being attacked self.xss_str = "<script>alert('xss');</script>" self.xss_post = Post(title="example XSS post", body=self.xss_str, body_markup_type='markdown', comment=self.xss_str) self.xss_post.save() def test_verbose_name(self): """Tests that the standard field property ``verbose_name`` works.""" self.assertEqual(self.mp._meta.get_field('body').verbose_name, "post body") def test_markup_type_exclusive(self): """``MarkupMirrorField`` fields in models may only define one of ``markup_type`` or ``default_markup_type`` parameters. """ self.assertRaises(ImproperlyConfigured, MarkupMirrorField, verbose_name='broken', markup_type='markdown', default_markup_type='markdown') def test_markup_body(self): """Tests the three accessors ``raw``, ``rendered`` and ``markup_type`` of the ``Markup`` content wrapper class. """ self.assertEquals(self.mp.body.raw, "**markdown**") self.assertEquals(self.mp.body.rendered, "<p><strong>markdown</strong></p>") self.assertEquals(self.mp.body.markup_type, "markdown") def test_markup_unicode(self): """Converting ``Markup`` to unicode uses the ``Markup.rendered`` accessor internally. """ self.assertEqual( str(self.rp.body.rendered), textwrap.dedent(u"""\ <div class="document"> <p><em>reST</em></p> </div> """)) def test_from_database(self): """Test that data loads back from the database correctly and 'post' has the right type. """ post1 = Post.objects.get(pk=self.mp.pk) self.assertIsInstance(post1.body, Markup) self.assertEqual(str(post1.body.rendered), "<p><strong>markdown</strong></p>") def test_pre_save(self): """Test that saving markup values for markup_types which are not registered fails. """ post1 = Post.objects.get(pk=self.mp.pk) self.assertEqual(post1.body.markup_type, 'markdown') # unregister markdown del markup_pool['markdown'] self.assertFalse('markdown' in markup_pool) # trying to save the Post now should fail self.assertRaises(ValueError, post1.save) # restore markup pool from markupmirror.markup import markdown_ markup_pool.register_markup(markdown_.MarkdownMarkup) self.assertTrue('markdown' in markup_pool) def test_prepare_for_database(self): """Tests that ``Markup`` can be used to compare with ``MarkupMirrorField`` values at query time. """ post1 = Post.objects.get(pk=self.mp.pk) body = post1.body self.assertIsInstance(body, Markup) self.assertEqual(post1, Post.objects.get(body=body)) def test_accessor_classmethod(self): """``MarkupMirrorField`` attributes on model classes can only be accessed via an instance. """ def access_body(): return Post.body self.assertRaises(AttributeError, access_body) def test_accessor_none(self): """If the field is ``None`` that's what should be returned.""" self.assertIsInstance(self.mp.body, Markup) self.mp.body = None self.assertEqual(self.mp.body, None) def test_body_assignment(self): """Setting the field's value works through the descriptor's setter (``MarkupMirrorFieldDescriptor.__set__``) and accepts both strings and ``Markup`` instances. """ self.rp.body = "**reST**" self.rp.save() self.assertEquals( str(self.rp.body.rendered), textwrap.dedent( u"""\ <div class="document"> <p><strong>reST</strong></p> </div> """ ) ) rest_markup = Markup( self.rp, 'body', 'body_rendered', 'body_markup_type' ) rest_markup.raw = "*reST*" self.rp.body = rest_markup self.rp.save() self.assertEquals( str(self.rp.body.rendered), textwrap.dedent( u"""\ <div class="document"> <p><em>reST</em></p> </div> """ ) ) def test_raw_assignment(self): """Setting the ``Markup.raw`` property modifies the field's value.""" self.rp.body.raw = '*more reST*' self.rp.save() self.assertEquals( str(self.rp.body.rendered), textwrap.dedent("""\ <div class="document"> <p><em>more reST</em></p> </div> """) ) def test_rendered_assignment(self): """The ``Markup.rendered`` property dos not have a setter.""" def set_rendered(text): self.rp.body.rendered = text self.assertRaises(AttributeError, set_rendered, "fail!") def test_body_type_assignment(self): """The markup type can be changed using the ``Markup.markup_type`` property. """ self.rp.body.markup_type = 'markdown' self.rp.save() self.assertEquals(self.rp.body.markup_type, 'markdown') self.assertEquals(str(self.rp.body.rendered), "<p><em>reST</em></p>") def test_serialize_to_json(self): """Serializing a ``Post`` with a ``MarkupMirrorField`` works.""" stream = serializers.serialize('json', Post.objects.all()) json_data = json.loads(stream) self.assertEqual(json_data, [ { 'fields': { 'body': '**markdown**', 'body_markup_type': 'markdown', 'body_rendered': '<p><strong>markdown</strong></p>', 'comment': '', 'comment_markup_type': 'markdown', 'comment_rendered': '', 'markdown_field': '', 'markdown_field_markup_type': 'markdown', 'markdown_field_rendered': '', 'title': 'example Markdown post', }, 'model': 'tests.post', 'pk': 1, }, { 'fields': { 'body': '*reST*', 'body_markup_type': 'restructuredtext', 'body_rendered': ( '<div class="document">' '\n<p><em>reST</em></p>\n</div>\n'), 'comment': '', 'comment_markup_type': 'markdown', 'comment_rendered': '', 'markdown_field': '', 'markdown_field_markup_type': 'markdown', 'markdown_field_rendered': '', 'title': 'example reStructuredText post', }, 'model': 'tests.post', 'pk': 2, }, { 'fields': { 'body': u"<script>alert('xss');</script>", 'body_markup_type': 'markdown', 'body_rendered': u"<script>alert('xss');</script>", 'comment': u"<script>alert('xss');</script>", 'comment_markup_type': 'markdown', 'comment_rendered': ( '<p><script>' 'alert('xss');</script></p>'), 'markdown_field': '', 'markdown_field_markup_type': 'markdown', 'markdown_field_rendered': '', 'title': 'example XSS post', }, 'model': 'tests.post', 'pk': 3, }, ]) def test_deserialize_json(self): """Tests that objects with ``MarkupMirrorFields`` can be deserialized correctly. """ stream = serializers.serialize('json', Post.objects.all()) obj = list(serializers.deserialize('json', stream))[0] self.assertEquals(obj.object, self.mp) def test_escape_html(self): """Rendered content should be escaped to prevent XSS attacks.""" self.assertEquals(self.xss_post.comment.raw, self.xss_str) self.assertEquals( str(self.xss_post.comment.rendered), '<p><script>alert('xss');</script></p>') def test_escape_html_false(self): """The ``MarkupMirrorField.escape_html`` prevents this escaping.""" self.assertEquals(self.xss_post.body.raw, self.xss_str) self.assertEquals(str(self.xss_post.body.rendered), self.xss_str) def test_inheritance(self): """Abstract base models inherit the ``MarkupMirrorField`` to the concrete subclasses. """ concrete_fields = [f.name for f in Concrete._meta.fields] self.assertEquals( concrete_fields, ['id', 'content', 'content_markup_type', 'content_rendered']) def test_markup_type_validation(self): """Invalid markup types are rejected.""" self.assertRaises( ImproperlyConfigured, MarkupMirrorField, 'verbose name', 'markup_field', 'bad_markup_type') def test_default_markup_types(self): """Per default the markup types plaintext, html are available. Depending on available third-party products, markdown, restructuredtext and textile are also in the markup pool. """ markups = markup_pool.markups for markup_type, markup in markups.items(): rendered = markup(u"test") self.assertTrue(hasattr(rendered, '__str__')) def test_formfield(self): """Form fields for ``MarkupMirrorFields`` always have two additional attributes: * ``class=markupmirror-editor``. * ``data-mm-settings``: a JSON dictionary containing the init settings for CodeMirror and the URLs and parameters required for the preview view. """ form = PostForm() comment = form.fields['comment'] self.assertEqual( sorted(comment.widget.attrs.keys()), ['class', 'cols', 'data-mm-settings', 'rows']) self.assertTrue('markupmirror-editor' in comment.widget.attrs['class']) self.assertEqual( comment.widget.attrs['data-mm-settings'], '{{"markup_type": "{0}", "mode": "{1}"}}'.format( self.mp.comment.markup_type, markup_pool[self.mp.comment.markup_type].codemirror_mode) )