8. Testing Your Extenstions

8.1. Testing Apps

8.1.1. Resolving View Names

Your apps need testing, but in your live site they aren’t in urls.py as they are attached to a CMS page. So if you want to be able to use reverse() in your tests, or test templates that use the url template tag, you need to hook up your app to a special test version of urls.py and tell your tests to use that.

So you could create myapp/tests/test_urls.py with the following code:

  1. from django.contrib import admin
  2. from django.conf.urls import url, patterns, include
  3. urlpatterns = patterns('',
  4. url(r'^admin/', include(admin.site.urls)),
  5. url(r'^myapp/', include('myapp.urls')),
  6. url(r'', include('cms.urls')),
  7. )

And then in your tests you can plug this in with the override_settings() decorator:

  1. from django.test.utils import override_settings
  2. from cms.test_utils.testcases import CMSTestCase
  3. class MyappTests(CMSTestCase):
  4. @override_settings(ROOT_URLCONF='myapp.tests.test_urls')
  5. def test_myapp_page(self):
  6. test_url = reverse('myapp_view_name')
  7. # rest of test as normal

If you want to the test url conf throughout your test class, then you can use apply the decorator to the whole class:

  1. from django.test.utils import override_settings
  2. from cms.test_utils.testcases import CMSTestCase
  3. @override_settings(ROOT_URLCONF='myapp.tests.test_urls')
  4. class MyappTests(CMSTestCase):
  5. def test_myapp_page(self):
  6. test_url = reverse('myapp_view_name')
  7. # rest of test as normal

8.1.2. CMSTestCase

Django CMS includes CMSTestCase which has various utility methods that might be useful for testing your CMS app and manipulating CMS pages.

8.2. Testing Plugins

Plugins can just be created as objects and then have methods called on them. So you could do:

  1. from django.test import TestCase
  2. from myapp.cms_plugins import MyPlugin
  3. from myapp.models import MyappPlugin as MyappPluginModel
  4. class MypluginTests(TestCase):
  5. def setUp(self):
  6. self.plugin = MyPlugin()
  7. def test_plugin(self):
  8. context = {'info': 'value'}
  9. instance = MyappPluginModel(num_items=3)
  10. rendered_html = self.plugin.render(context, instance, None)
  11. self.assertIn('string', rendered_html)

Sometimes you might want to add a placeholder - say to check how the plugin renders when it is in different size placeholders. In that case you can create the placeholder directly and pass it in:

  1. from django.test import TestCase
  2. from cms.api import add_plugin
  3. from myapp.cms_plugins import MyPlugin
  4. from myapp.models import MyappPlugin as MyappPluginModel
  5. class ImageSetTypePluginMixinContainerWidthTests(TestCase):
  6. def setUp(self):
  7. self.placeholder = Placeholder(slot=u"some_slot")
  8. self.placeholder.save()
  9. self.plugin = add_plugin(
  10. self.placeholder,
  11. u"MyPlugin",
  12. u"en",
  13. num_items=3,
  14. )