Skip to content

Commit

Permalink
Moved translation-related code to separate plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
Almad committed Jun 1, 2009
1 parent 7ce717b commit ae2df8a
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 27 deletions.
44 changes: 31 additions & 13 deletions djangosanetesting/noseplugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from django.core.handlers.wsgi import WSGIHandler
from django.core.servers.basehttp import WSGIRequestHandler, AdminMediaHandler, WSGIServerException
from django.utils import translation

import nose
from nose import SkipTest
Expand Down Expand Up @@ -290,14 +289,6 @@ def startTest(self, test):
mail.outbox = []
enable_test(test_case, 'django_plugin_started')

# set translation, if allowed
if getattr(test_case, "make_translations", None):
lang = getattr(test_case, "translation_language_code", None)
if not lang:
lang = getattr(settings, "LANGUAGE_CODE", 'en-us')
translation.activate(lang)


# clear URLs if needed
if hasattr(test_case, 'urls'):
test_case._old_root_urlconf = settings.ROOT_URLCONF
Expand All @@ -316,7 +307,7 @@ def startTest(self, test):
# make self.transaction available
test_case.transaction = transaction
self.commits_could_be_used = False

if getattr(test_case, "database_flush", True):
call_command('flush', verbosity=0, interactive=False)
# it's possible that some garbage will be left after us, flush next time
Expand Down Expand Up @@ -347,7 +338,7 @@ def startTest(self, test):
commit = False
call_command('loaddata', *test_case.fixtures, **{'verbosity': 0, 'commit' : commit})


def stopTest(self, test):
"""
After test is run, clear urlconf and caches
Expand All @@ -365,7 +356,34 @@ def stopTest(self, test):
from django.contrib.contenttypes.models import ContentType
ContentType.objects.clear_cache()

# if getattr(test_case, "make_translations", None):
class DjangoTranslationPlugin(Plugin):
"""
For testcases with selenium_start set to True, connect to Selenium RC.
"""
activation_parameter = '--with-djangotranslations'
name = 'djangotranslations'

score = 70

def options(self, parser, env=os.environ):
Plugin.options(self, parser, env)

def configure(self, options, config):
Plugin.configure(self, options, config)

def startTest(self, test):
# set translation, if allowed
test_case = get_test_case_class(test)
if getattr(test_case, "make_translations", None):
from django.conf import settings
from django.utils import translation
lang = getattr(test_case, "translation_language_code", None)
if not lang:
lang = getattr(settings, "LANGUAGE_CODE", 'en-us')
translation.activate(lang)

def stopTest(self, test):
from django.utils import translation
translation.deactivate()

class SeleniumPlugin(Plugin):
Expand Down Expand Up @@ -417,7 +435,7 @@ def startTest(self, test):
test.test.test.im_self.selenium = sel
else:
raise SkipTest("I can only assign selenium to TestCase instance; argument passing will be implemented later")

def stopTest(self, test):
test_case = get_test_case_class(test)
if getattr(test_case, "selenium_start", False):
Expand Down
9 changes: 7 additions & 2 deletions djangosanetesting/testrunner.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import sys

from djangosanetesting.noseplugins import DjangoLiveServerPlugin, DjangoPlugin, SeleniumPlugin, CherryPyLiveServerPlugin
from djangosanetesting.noseplugins import (
DjangoPlugin,
DjangoLiveServerPlugin, SeleniumPlugin, CherryPyLiveServerPlugin,
DjangoTranslationPlugin,
)

import nose
from nose.config import Config, all_config_files
Expand All @@ -16,7 +20,7 @@ def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
""" Run tests with nose instead of defualt test runner """
from django.conf import settings

plugins = [DjangoPlugin(), SeleniumPlugin()]
plugins = [DjangoPlugin(), SeleniumPlugin(), DjangoTranslationPlugin()]

if getattr(settings, 'CHERRYPY_TEST_SERVER', False):
plugins.append(CherryPyLiveServerPlugin())
Expand All @@ -32,6 +36,7 @@ def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
# activate all required plugins
activate_plugin(DjangoPlugin)
activate_plugin(SeleniumPlugin)
activate_plugin(DjangoTranslationPlugin)

if getattr(settings, 'CHERRYPY_TEST_SERVER', False):
activate_plugin(CherryPyLiveServerPlugin)
Expand Down
21 changes: 16 additions & 5 deletions doc/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Provided plugins:
* :ref:`cherrypy-live-server-plugin`
* :ref:`selenium-plugin`
* :ref:`sane-test-selection-plugin`
* :ref:`django-translation-plugin`

.. _django-plugin:

Expand All @@ -92,11 +93,6 @@ Provided plugins:
* If :attr:`no_database_interaction` attribute is True, then whole database handling is skipped (this is to speed thing up for :class:`UnitTestCase`)
* If :attr:`database_single_transaction` is True (:class:`DatabaseTestCase`), manual transaction handling is enabled and things are rolled back after every case.
* If :attr:`database_flush` is True, then database if flushed before every case (and on the beginning of next one, if needed)
* If :attr:`make_translation` is True, django.utils.translation.activate() is called before every test. If :attr:`translation_language_code` is set, it's passed to activate(); otherwise settings.LANGUAGE_CODE or 'en-us' is used.

.. Warning::

It looks like Django is not switching back to "null" translations once any translation has been selected. make_translations=False will thus return lastly-activated translation.

.. _django-live-server-plugin:

Expand Down Expand Up @@ -186,8 +182,23 @@ Only selected test types will be run. Test type is determined from class attribu
.. Note::
You're still responsible for loading required plugins for respective test cases. Unlike test selection with usual plugins, selection plugin enables you to run slower tests without faster (i.e. HTTP tests without unittests), and also skipping is faster (Selection plugin is run before others, thus skip is done without any unneccessary database handling, which may not be true for usual skips).

.. _django-translation-plugin:

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:class:`DjangoTranslationPlugin`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If :attr:`make_translation` is True (default for every test), django.utils.translation.activate() is called before every test. If :attr:`translation_language_code` is set, it's passed to activate(); otherwise settings.LANGUAGE_CODE or 'en-us' is used.

This allows you to use translatable string taking usage of ugettest_lazy in tests.

.. Warning::

It looks like Django is not switching back to "null" translations once any translation has been selected. make_translations=False will thus return lastly-activated translation.


.. _django-sane-testing: http://devel.almad.net/trac/django-sane-testing/
.. _Selenium: http://seleniumhq.org/
.. _Selenium RC: http://seleniumhq.org/projects/remote-control/
.. _CherryPy: http://www.cherrypy.org/

1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
'django = %s.noseplugins:DjangoPlugin' % name,
'selenium = %s.noseplugins:SeleniumPlugin' % name,
'sanetestselection = %s.noseplugins:SaneTestSelectionPlugin' % name,
'djangotranslations = %s.noseplugins:DjangoTranslationPlugin' % name,
]
}
)
14 changes: 7 additions & 7 deletions testproject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@

# AUTHENTICATION_BACKENDS = ('keykeeper.libopenid.OpenidBackend',)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.http.SetRemoteAddrFromForwardedFor',
)
#MIDDLEWARE_CLASSES = (
# 'django.middleware.common.CommonMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.middleware.transaction.TransactionMiddleware',
# 'django.middleware.http.SetRemoteAddrFromForwardedFor',
#)

ROOT_URLCONF = 'testproject.urls'

Expand Down
11 changes: 11 additions & 0 deletions testproject/test/test_liveserver.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
import urllib2
from djangosanetesting.cases import HttpTestCase, SeleniumTestCase

from testapp.models import ExampleModel

class TestLiveServerRunning(HttpTestCase):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
Expand Down Expand Up @@ -47,6 +50,14 @@ def test_not_authorized_not_resetable(self):
assert False, "401 expected"

class TestSeleniumWorks(SeleniumTestCase):
def setUp(self):
super(TestSeleniumWorks, self).setUp()
# from django.utils import translation
# translation.activate("cs")

def test_ok(self):
self.selenium.open("/testtwohundred/")
self.selenium.is_text_present("200 OK")

def test_czech_string_acquired_even_with_selenium(self):
self.assert_equals(u"Přeložitelný řetězec", unicode(ExampleModel.get_translated_string()))

0 comments on commit ae2df8a

Please sign in to comment.