How to test 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.urls import re_path, include
  3. urlpatterns = [
  4. re_path(r'^admin/', admin.site.urls),
  5. re_path(r'^myapp/', include('myapp.urls')),
  6. re_path(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 django.test.client import RequestFactory
  3. from cms.api import add_plugin
  4. from cms.models import Placeholder
  5. from cms.plugin_rendering import ContentRenderer
  6. from myapp.cms_plugins import MyPlugin
  7. from myapp.models import MyappPlugin
  8. class MypluginTests(TestCase):
  9. def test_plugin_context(self):
  10. placeholder = Placeholder.objects.create(slot='test')
  11. model_instance = add_plugin(
  12. placeholder,
  13. MyPlugin,
  14. 'en',
  15. )
  16. plugin_instance = model_instance.get_plugin_class_instance()
  17. context = plugin_instance.render({}, model_instance, None)
  18. self.assertIn('key', context)
  19. self.assertEqual(context['key'], 'value')
  20. def test_plugin_html(self):
  21. placeholder = Placeholder.objects.create(slot='test')
  22. model_instance = add_plugin(
  23. placeholder,
  24. MyPlugin,
  25. 'en',
  26. )
  27. renderer = ContentRenderer(request=RequestFactory())
  28. html = renderer.render_plugin(model_instance, {})
  29. self.assertEqual(html, '<strong>Test</strong>')