Django: Define a form differently when in testing mode
I have a customized captcha field. I want to remove that field from a form when displaying it during tests.
My initial thought was to have a TESTING
variable in a separate settings file that will be supplied as an argument to the test runner command. Then, I could to something like:
class CaptchaForm(forms.Form):
notify_email = forms.EmailField(required=False)
if not settings.TESTING:
recaptcha = CaptchaField()
I believe this should work.
There might be an even better approach. Any ideas?
Update
After playing around with the suggestions below, I added this to the test folder's __init__.py
:
from project.app.forms import CaptchaField
CaptchaField.clean = lambda x, y: y
This worked---witho开发者_如何学编程ut creating a shared TESTING
setting. Does this look acceptable? Is there a reason that I should not do this?
You can disable captcha in constructor of unit-testing class. Like this:
class MyTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(MyTest, self).__init__(*args, **kwargs)
settings.TESTING = True
Or you can disable captcha field validation in this constructor, for example.
I assume CaptchaField
is your own class. Then you could change the validation method:
from django.core.exceptions import ValidationError
class CaptchaField(Field):
# ...
def validate(self, value, model_instance):
if settings.TESTING:
return
else:
# Do CAPTCHA checking, leading to either
# raise ValidationError or
# return
As werehuman already mentioned, you don't really need a separate settings file but can change the setting inside the unit test class.
精彩评论