Source

django-markitup / tests / tests.py

Full commit
Carl Meyer 771c113 

Carl Meyer e8d64e6 
Carl Meyer eb788c8 
Carl Meyer 640c4f5 


Carl Meyer e8d64e6 

Carl Meyer accdf69 
Carl Meyer 771c113 
Carl Meyer eb788c8 
Carl Meyer fbf20c4 
Carl Meyer eb788c8 

Carl Meyer 640c4f5 
Carl Meyer eb788c8 
Carl Meyer fbf20c4 
Aram Dulyan b8215cc 
Carl Meyer fbf20c4 
Carl Meyer d9ebed4 

Carl Meyer fbf20c4 


Carl Meyer d9ebed4 

Carl Meyer fbf20c4 



Carl Meyer febfc8c 
Edmund von der B… fe49ef1 

Carl Meyer febfc8c 
Carl Meyer fbf20c4 
Carl Meyer d9ebed4 
Carl Meyer fbf20c4 



Edmund von der B… fe49ef1 
Carl Meyer febfc8c 


Edmund von der B… fe49ef1 
Carl Meyer febfc8c 

Carl Meyer d9ebed4 
Carl Meyer fbf20c4 


Carl Meyer d9ebed4 
Carl Meyer fbf20c4 



Carl Meyer d9ebed4 
Carl Meyer fbf20c4 




Carl Meyer d9ebed4 
Carl Meyer fbf20c4 





Carl Meyer d9ebed4 
Carl Meyer fbf20c4 





Carl Meyer d9ebed4 
Carl Meyer fbf20c4 




Carl Meyer d9ebed4 
Carl Meyer accdf69 









Carl Meyer d9ebed4 
Carl Meyer f15f931 













Carl Meyer fbf20c4 







Carl Meyer d9ebed4 
Carl Meyer fbf20c4 





Carl Meyer d9ebed4 
Carl Meyer fbf20c4 






Carl Meyer d9ebed4 
Carl Meyer fbf20c4 





Carl Meyer d9ebed4 
Carl Meyer fbf20c4 




Carl Meyer d9ebed4 
Carl Meyer fbf20c4 



Carl Meyer d9ebed4 
Carl Meyer fbf20c4 

Carl Meyer cf6de85 
Carl Meyer fbf20c4 

Carl Meyer d9ebed4 
Carl Meyer fbf20c4 




Carl Meyer e8d64e6 
Carl Meyer d9ebed4 

Aram Dulyan b8215cc 







Carl Meyer cf6de85 
Aram Dulyan b8215cc 








Carl Meyer e8d64e6 







Carl Meyer d9ebed4 
Carl Meyer e8d64e6 



Mikhail Korobov fdd0099 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 
Carl Meyer e8d64e6 





Carl Meyer d62355a 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 
Carl Meyer b2ce1b6 




Carl Meyer e8d64e6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 








Carl Meyer d62355a 
Carl Meyer d9ebed4 
Carl Meyer ce853ec 




Mikhail Korobov 137b8f6 

Carl Meyer d9ebed4 
Carl Meyer e8d64e6 
Carl Meyer 9f7c4de 
Carl Meyer b2ce1b6 
Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Carl Meyer f5c1a65 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 
Sergey Fursov e8cdd64 


Sergey Fursov 89f2891 
Sergey Fursov e8cdd64 

Carl Meyer 013a955 





Carl Meyer e8d64e6 

Carl Meyer f5c1a65 
Carl Meyer e8d64e6 
Carl Meyer d62355a 
Carl Meyer d9ebed4 
Carl Meyer 013a955 





Carl Meyer b2ce1b6 





Carl Meyer d9ebed4 
Carl Meyer b2ce1b6 










Carl Meyer d9ebed4 
Carl Meyer b2ce1b6 
Carl Meyer f5c1a65 
Carl Meyer b2ce1b6 
Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer f5c1a65 



Carl Meyer d9ebed4 
Carl Meyer f5c1a65 

Carl Meyer 8b7e27b 
Carl Meyer d9ebed4 

Carl Meyer e8d64e6 
Mikhail Korobov fdd0099 
Carl Meyer e8d64e6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 



Carl Meyer 771c113 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 
Carl Meyer e8d64e6 
Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 



Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 


Mikhail Korobov 137b8f6 
Carl Meyer e8d64e6 


Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 


Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Mikhail Korobov fdd0099 

Carl Meyer e8d64e6 


Sergey Fursov abc1f06 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 
Carl Meyer e8d64e6 











Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Carl Meyer d9ebed4 
Carl Meyer e8d64e6 


Carl Meyer 0121d7c 
Carl Meyer f3b0933 
Carl Meyer e8d64e6 

Carl Meyer cf6de85 
Carl Meyer e8d64e6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 




Sergey Fursov abc1f06 


Carl Meyer cf6de85 
Carl Meyer 0a4001d 






Carl Meyer e8d64e6 

Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 










Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 















Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 

Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 


Carl Meyer d9ebed4 
Carl Meyer e8d64e6 





Mikhail Korobov 137b8f6 
Carl Meyer d9ebed4 
Carl Meyer e8d64e6 




Mikhail Korobov 137b8f6 
Sergey Fursov abc1f06 





Sergey Fursov 93d71ed 
Carl Meyer d9ebed4 





Mikhail Korobov 137b8f6 
Carl Meyer 771c113 











  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
from __future__ import with_statement

import re

from django.core import serializers
from django.db.models.fields import FieldDoesNotExist
from django.forms.models import modelform_factory
from django.template import Template, Context, get_library
from django.test import TestCase, Client
from django.utils.safestring import mark_safe
from django.utils.unittest import skipUnless

from django.contrib import admin

from markitup import settings
from markitup.templatetags.markitup_tags import _get_markitup_context
from markitup.widgets import MarkItUpWidget, MarkupTextarea, AdminMarkItUpWidget

from models import Post, AbstractParent, CallableDefault



def test_filter(text, **kwargs):
    return unicode(text) + unicode(kwargs)



class MarkupFieldTests(TestCase):
    def setUp(self):
        self.post = Post.objects.create(title='example post',
                                        body='replace this text')

        self.empty_post = Post.objects.create(title='empty post',
                                        body='')



    def testUnicodeRender(self):
        self.assertEquals(unicode(self.post.body),
                          u'replacement text')

    def testLength(self):
        self.assertEquals(len(self.post.body), 16)
        self.assertEquals(len(self.empty_post.body), 0)

    def testTruth(self):
        self.assertTrue(self.post.body)
        self.assertFalse(self.empty_post.body)

    def testRaw(self):
        self.assertEquals(self.post.body.raw, 'replace this text')


    def testRendered(self):
        self.assertEquals(self.post.body.rendered,
                          u'replacement text')


    def testLoadBack(self):
        post = Post.objects.get(pk=self.post.pk)
        self.assertEquals(post.body.raw, self.post.body.raw)
        self.assertEquals(post.body.rendered, self.post.body.rendered)


    def testAssignToBody(self):
        self.post.body = 'replace this other text'
        self.post.save()
        self.assertEquals(unicode(self.post.body),
                          u'replacement other text')


    def testAssignToRaw(self):
        self.post.body.raw = 'new text, replace this'
        self.post.save()
        self.assertEquals(unicode(self.post.body),
                          u'new text, replacement')


    def testAssignToRendered(self):
        def _invalid_assignment():
            self.post.body.rendered = 'this should fail'
        self.assertRaises(AttributeError, _invalid_assignment)


    def testMarkSafe(self):
        """
        Calling ``mark_safe`` on a ``Markup`` object should have no
        effect, as the ``Markup`` object already handles marking the
        rendered HTML safe on access.

        """
        self.post.body = mark_safe(self.post.body)
        self.assertEquals(self.post.body.raw, 'replace this text')


    def testAbstractInheritance(self):
        """
        Inheriting from an abstract parent class with a MarkupField should not
        cause duplicate _rendered fields to be added.

        """
        class Child(AbstractParent):
            pass

        self.assertEqual(
            [f.name for f in Child._meta.fields],
            ["id", "content", "_content_rendered"])


# TODO
#    def testOverrideFilter(self):
#        self.post.body.save_markup('tests.tests.test_filter',
#                                   some_arg='some_val')
#        self.assertEquals(unicode(self.post.body),
#                          u"**markdown**{'some_arg': 'some_val'}")



class MarkupFieldSerializationTests(TestCase):
    def setUp(self):
        self.post = Post.objects.create(title='example post',
                                        body='replace this thing')
        self.stream = serializers.serialize('json', Post.objects.all())


    def testSerializeJSON(self):
        self.assertEquals(self.stream,
                          '[{"pk": 1, "model": "tests.post", '
                          '"fields": {"body": "replace this thing", '
                          '"_body_rendered": "replacement thing", '
                          '"title": "example post"}}]')


    def testDeserialize(self):
        self.assertEquals(list(serializers.deserialize("json",
                                                       self.stream))[0].object,
                          self.post)



class MarkupFieldFormTests(TestCase):
    def setUp(self):
        self.post = Post(title='example post', body='**markdown**')
        self.form_class = modelform_factory(Post)


    def testWidget(self):
        self.assertEquals(self.form_class().fields['body'].widget.__class__,
                          MarkupTextarea)


    def testFormFieldContents(self):
        form = self.form_class(instance=self.post)
        self.assertHTMLEqual(unicode(form['body']),
                          u'<textarea id="id_body" rows="10" cols="40" name="body">**markdown**</textarea>')


    def testAdminFormField(self):
        ma = admin.ModelAdmin(Post, admin.site)
        self.assertEquals(ma.formfield_for_dbfield(
                Post._meta.get_field('body')).widget.__class__,
                          AdminMarkItUpWidget)



class HiddenFieldFormTests(TestCase):
    def setUp(self):
        self.post = CallableDefault(body='[link](http://example.com) & "text"')
        self.form_class = modelform_factory(CallableDefault)


    def testHiddenFieldContents(self):
        form = self.form_class(instance=self.post)
        self.assertHTMLEqual(unicode(form['body']), (
            u'<textarea id="id_body" rows="10" cols="40" name="body">'
            u'[link](http://example.com) &amp; &quot;text&quot;'
            u'</textarea><input type="hidden" name="initial-body" value="'
            u'[link](http://example.com) &amp; &quot;text&quot;" '
            u'id="initial-id_body" />'
        ))



class PreviewTests(TestCase):
    def test_preview_filter(self):
        c = Client()
        response = c.post('/markitup/preview/',
                          {'data': 'replace this with something else'})
        self.assertContains(response, 'replacement with something else',
                            status_code=200)


    def test_preview_css(self):
        c = Client()
        response = c.post('/markitup/preview/',
                          {'data': 'replace this with something else'})
        self.assertContains(response, '/static/markitup/preview.css',
                            status_code=200)


    def test_preview_template(self):
        c = Client()
        response = c.post('/markitup/preview/',
                          {'data': 'replace this with something else'})
        self.assertTemplateUsed(response, 'markitup/preview.html')



class MIUTestCase(TestCase):
    def assertIn(self, needle, haystack, reverse=False):
        func = reverse and self.failIf or self.failUnless
        descrip = reverse and 'in' or 'not in'
        func(needle in haystack,
             "'%s' %s '%s'" % (needle, descrip, haystack))


    def render(self, template_string, context_dict=None):
        """A shortcut for testing template output."""
        if context_dict is None:
            context_dict = {}

        c = Context(context_dict)
        t = Template(template_string)
        return t.render(c).strip()



class TemplatefilterTests(MIUTestCase):
    def test_render_markup(self):
        tpl_string = "{% load markitup_tags %}{{ content|render_markup }}"
        self.assertEquals('replacement text', self.render(tpl_string,
                                                          {'content': 'replace this text'}))



class RenderTests(MIUTestCase):
    look_for = 'var element = $("#my_id");'
    auto_preview_override = True


    def test_widget_render(self):
        widget = MarkItUpWidget()
        self.assertIn(self.look_for,
                      widget.render('name', 'value', {'id': 'my_id'}))


    def test_widget_render_with_custom_id(self):
        widget = MarkItUpWidget(attrs={'id': 'my_id'})
        self.assertIn(self.look_for,
                      widget.render('name', 'value'))


    def test_widget_render_preview_parser_path(self):
        widget = MarkItUpWidget()
        self.assertIn('mySettings["previewParserPath"] = "/markitup/preview/";',
                      widget.render('name', 'value', {'id': 'my_id'}))


    def test_templatetag_render(self):
        template = """{% load markitup_tags %}{% markitup_editor "my_id" %}"""
        self.assertIn(self.look_for,
                      self.render(template))


    def test_templatetag_render_preview_parser_path(self):
        template = """{% load markitup_tags %}{% markitup_editor "my_id" %}"""
        self.assertIn('mySettings["previewParserPath"] = "/markitup/preview/";',
                      self.render(template))


    def test_per_widget_auto_preview_override(self):
        widget = MarkItUpWidget(auto_preview=self.auto_preview_override)
        self.assertIn(AutoPreviewSettingTests.look_for,
                      widget.render('name', 'value', {'id': 'my_id'}),
                      reverse=not self.auto_preview_override)


    def test_per_ttag_auto_preview_override(self):
        if self.auto_preview_override:
            arg = "auto_preview"
        else:
            arg = "no_auto_preview"
        template = """{%% load markitup_tags %%}{%% markitup_editor "my_id" "%s" %%}""" % (arg,)
        self.assertIn(AutoPreviewSettingTests.look_for,
                      self.render(template),
                      reverse=not self.auto_preview_override)



class AutoPreviewSettingTests(RenderTests):
    look_for = "$('a[title=\"Preview\"]').trigger('mouseup');"
    auto_preview_override = False


    def setUp(self):
        self._old_auto = settings.MARKITUP_AUTO_PREVIEW
        settings.MARKITUP_AUTO_PREVIEW = True


    def tearDown(self):
        settings.MARKITUP_AUTO_PREVIEW = self._old_auto



class TemplatetagMediaUrlTests(MIUTestCase):
    prefix = '/static'


    # helper abstractions so we can reuse same tests for widget and
    # templatetag methods
    def _reset_context(self):
        # monkeypatch a forced recalculation of the template context
        tags = get_library("markitup_tags")
        tags._markitup_context = _get_markitup_context()


    multiple_newlines_re = re.compile('\n+')


    def _compress_newlines(self, s):
        # template includes cause extra newlines in some cases
        # where form.media always outputs only single newlines
        return self.multiple_newlines_re.sub('\n', s)


    def _get_media(self):
        self._reset_context()
        return self._compress_newlines(
            self.render("{% load markitup_tags %}{% markitup_media %}"))


    def _get_css(self):
        self._reset_context()
        return self.render("{% load markitup_tags %}{% markitup_css %}")


    def _get_js(self):
        self._reset_context()
        return self.render("{% load markitup_tags %}{% markitup_js %}")


    # JQUERY_URL settings and resulting link
    jquery_urls = (
        ('jquery.min.js', '/static/jquery.min.js'),
        ('some/path/jquery.min.js', '/static/some/path/jquery.min.js'),
        ('/some/path/jquery.min.js', '/some/path/jquery.min.js'),
        ('http://www.example.com/jquery.min.js', 'http://www.example.com/jquery.min.js'),
        ('https://www.example.com/jquery.min.js', 'https://www.example.com/jquery.min.js'),
        (None, None)
        )


    # MARKITUP_SET settings and resulting CSS link
    set_urls = (
        ('some/path', '%(prefix)s/some/path/%(file)s'),
        ('some/path/', '%(prefix)s/some/path/%(file)s'),
        ('/some/path', '/some/path/%(file)s'),
        ('/some/path/', '/some/path/%(file)s'),
        ('http://www.example.com/path', 'http://www.example.com/path/%(file)s'),
        ('http://www.example.com/path/', 'http://www.example.com/path/%(file)s'),
        ('https://www.example.com/path', 'https://www.example.com/path/%(file)s'),
        ('https://www.example.com/path/', 'https://www.example.com/path/%(file)s'),
        )


    skin_urls = set_urls


    def test_all_media(self):
        out = """<link href="%(prefix)s/markitup/skins/simple/style.css" type="text/css" media="screen" rel="stylesheet" />
<link href="%(prefix)s/markitup/sets/default/style.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="%(prefix)s/markitup/ajax_csrf.js"></script>
<script type="text/javascript" src="%(prefix)s/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="%(prefix)s/markitup/sets/default/set.js"></script>""" % {'prefix': self.prefix}
        self.assertHTMLEqual(self._get_media(), out)


    def test_jquery_url(self):
        _old_jquery_url = settings.JQUERY_URL
        try:
            for url, link in self.jquery_urls:
                settings.JQUERY_URL = url
                if url:
                    self.assertIn(link, self._get_js())
                else:
                    self.assertHTMLEqual(
                        self._get_js(),
                        (
                            '<script type="text/javascript" src="%(prefix)s/markitup/ajax_csrf.js"></script>\n'
                            '<script type="text/javascript" src="%(prefix)s/markitup/jquery.markitup.js"></script>\n'
                            '<script type="text/javascript" src="%(prefix)s/markitup/sets/default/set.js"></script>'
                            % {'prefix': self.prefix}
                            ))
        finally:
            settings.JQUERY_URL = _old_jquery_url


    def test_set_via_settings(self):
        _old_miu_set = settings.MARKITUP_SET
        try:
            for miu_set, link in self.set_urls:
                css_link = link % {'prefix': self.prefix, 'file': 'style.css'}
                js_link = link % {'prefix': self.prefix, 'file': 'set.js'}
                settings.MARKITUP_SET = miu_set
                self.assertIn(css_link, self._get_css())
                self.assertIn(js_link, self._get_js())
        finally:
            settings.MARKITUP_SET = _old_miu_set


    def test_skin_via_settings(self):
        _old_miu_skin = settings.MARKITUP_SKIN
        try:
            for miu_skin, link in self.skin_urls:
                link = link % {'prefix': self.prefix, 'file': 'style.css'}
                settings.MARKITUP_SKIN = miu_skin
                self.assertIn(link, self._get_css())
        finally:
            settings.MARKITUP_SKIN = _old_miu_skin


class WidgetMediaUrlTests(TemplatetagMediaUrlTests):
    def _get_media_obj(self, *args, **kwargs):
        widget = MarkItUpWidget(*args, **kwargs)
        return widget.media


    def _get_media(self, *args, **kwargs):
        return str(self._get_media_obj(*args, **kwargs))


    def _get_css(self, *args, **kwargs):
        return str(self._get_media_obj(*args, **kwargs)['css'])


    def _get_js(self, *args, **kwargs):
        return str(self._get_media_obj(*args, **kwargs)['js'])


    def test_set_via_argument(self):
        for miu_set, link in self.set_urls:
            css_link = link % {'prefix': self.prefix, 'file': 'style.css'}
            js_link = link % {'prefix': self.prefix, 'file': 'set.js'}
            self.assertIn(css_link, self._get_css(markitup_set=miu_set))
            self.assertIn(js_link, self._get_js(markitup_set=miu_set))


    def test_skin_via_argument(self):
        for miu_skin, link in self.skin_urls:
            link = link % {'prefix': self.prefix, 'file': 'style.css'}
            self.assertIn(link, self._get_css(markitup_skin=miu_skin))


    def test_jquery_in_media(self):
        for url, link in self.jquery_urls:
            settings.JQUERY_URL = url
            if url:
                self.assertIn(link, self._get_js())
            else:
                self.assertNotIn('src=""', self._get_js())

try:
    from south.modelsinspector import introspector
except ImportError:
    introspector = None


class SouthFreezingTests(TestCase):
    @skipUnless(introspector, "South not available")
    def test_introspector_adds_no_rendered_field(self):
        mf = Post._meta.get_field('body')
        args, kwargs = introspector(mf)
        self.assertEquals(kwargs['no_rendered_field'], 'True')

    @skipUnless(introspector, "South not available")
    def test_no_rendered_field_works(self):
        from models import NoRendered
        self.assertRaises(FieldDoesNotExist,
                          NoRendered._meta.get_field,
                          '_body_rendered')