Testing Your Extensions

Testing Apps

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/urls.py with the following code:

  1. from django.contrib import admin
  2. from django.conf.urls import url, include
  3. urlpatterns = [
  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.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.urls')
  4. class MyappTests(CMSTestCase):
  5. def test_myapp_page(self):
  6. test_url = reverse('myapp_view_name')
  7. # rest of test as normal

CMSTestCase

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

Testing Plugins

To test plugins, you need to assign them to a placeholder. Depending on at what level you want to test your plugin, you can either check the HTML generated by it or the context provided to its template:

  1. from django.test import TestCase
  2. from cms.api import add_plugin
  3. from cms.models import Placeholder
  4. from myapp.cms_plugins import MyPlugin
  5. from myapp.models import MyappPlugin
  6. class MypluginTests(TestCase):
  7. def test_plugin_context(self):
  8. placeholder = Placeholder.objects.create(slot='test')
  9. model_instance = add_plugin(
  10. placeholder,
  11. MyPlugin,
  12. 'en',
  13. )
  14. plugin_instance = model_instance.get_plugin_class_instance()
  15. context = plugin_instance.render({}, model_instance, None)
  16. self.assertIn('key', context)
  17. self.assertEqual(context['key'], 'value')
  18. def test_plugin_html(self):
  19. placeholder = Placeholder.objects.create(slot='test')
  20. model_instance = add_plugin(
  21. placeholder,
  22. MyPlugin,
  23. 'en',
  24. )
  25. html = model_instance.render_plugin({})
  26. self.assertEqual(html, '<strong>Test</strong>')