desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Backs up the AUTH_PROFILE_MODULE'
def setUp(self):
self.old_AUTH_PROFILE_MODULE = getattr(settings, 'AUTH_PROFILE_MODULE', None)
'Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted, otherwise the old value is restored'
def tearDown(self):
if ((self.old_AUTH_PROFILE_MODULE is None) and hasattr(settings, 'AUTH_PROFILE_MODULE')): del settings.AUTH_PROFILE_MODULE if (self.old_AUTH_PROFILE_MODULE is not None): settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE
'Test that the order of registered permissions doesn\'t break'
def test_permission_register_order(self):
auth_models.Permission.objects.all().delete() contenttypes_models.ContentType.objects.all().delete() create_permissions(auth_models, [], verbosity=0) create_permissions(contenttypes_models, [], verbosity=0) stderr = StringIO() call_command('loaddata', 'test_permissions.json', verbosity=0, commit...
'Check that login_required is assignable to callable objects.'
def testCallable(self):
class CallableView(object, ): def __call__(self, *args, **kwargs): pass login_required(CallableView())
'Check that login_required is assignable to normal views.'
def testView(self):
def normal_view(request): pass login_required(normal_view)
'Check that login_required works on a simple view wrapped in a login_required decorator.'
def testLoginRequired(self, view_url='/login_required/', login_url=settings.LOGIN_URL):
response = self.client.get(view_url) self.assertEqual(response.status_code, 302) self.assertTrue((login_url in response['Location'])) self.login() response = self.client.get(view_url) self.assertEqual(response.status_code, 200)
'Check that login_required works on a simple view wrapped in a login_required decorator with a login_url set.'
def testLoginRequiredNextUrl(self):
self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/')
'creates a user and returns a tuple (user_object, username, email)'
def create_dummy_user(self):
username = 'jsmith' email = 'jsmith@example.com' user = User.objects.create_user(username, email, 'test123') return (user, username, email)
'Tests requests where no remote user is specified and insures that no users get created.'
def test_no_remote_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/') self.assertTrue(response.context['user'].is_anonymous()) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', REMOTE_USER=None) self.assertTrue(response.context['user'].is_anonym...
'Tests the case where the username passed in the header does not exist as a User.'
def test_unknown_user(self):
num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER='newuser') self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(User.objects.count(), (num_users + 1)) User.objects.get(username='newuser') response = self.client.get('/remote_user...
'Tests the case where the username passed in the header is a valid User.'
def test_known_user(self):
User.objects.create(username='knownuser') User.objects.create(username='knownuser2') num_users = User.objects.count() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) self.assertEqual(response.context['user'].username, 'knownuser') self.assertEqual(User.objects.count(), n...
'Tests that a user\'s last_login is set the first time they make a request but not updated in subsequent requests with the same session.'
def test_last_login(self):
user = User.objects.create(username='knownuser') default_login = datetime(2000, 1, 1) user.last_login = default_login user.save() response = self.client.get('/remote_user/', REMOTE_USER=self.known_user) self.assertNotEqual(default_login, response.context['user'].last_login) user = User.objec...
'Restores settings to avoid breaking other tests.'
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.curr_middleware settings.AUTHENTICATION_BACKENDS = self.curr_auth
'Grabs username before the @ character.'
def clean_username(self, username):
return username.split('@')[0]
'Sets user\'s email address.'
def configure_user(self, user):
user.email = 'user@example.com' user.save() return user
'The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address.'
def test_known_user(self):
super(RemoteUserCustomTest, self).test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '')
'The unknown user created should be configured with an email address.'
def test_unknown_user(self):
super(RemoteUserCustomTest, self).test_unknown_user() newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, 'user@example.com')
'Ensure that we can make a token and that it is valid'
def test_make_token(self):
user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertTrue(p0.check_token(user, tk1))
'Ensure that the token generated for a user created in the same request will work correctly.'
def test_10265(self):
user = User.objects.create_user('comebackkid', 'test3@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) reload = User.objects.get(username='comebackkid') tk2 = p0.make_token(reload) self.assertEqual(tk1, tk2)
'Ensure we can use the token after n days, but no greater.'
def test_timeout(self):
class Mocked(PasswordResetTokenGenerator, ): def __init__(self, today): self._today_val = today def _today(self): return self._today_val user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.mak...
'Ensure we can use the hashes generated by Django 1.2'
def test_django12_hash(self):
def _make_token(user): from django.utils.hashcompat import sha_constructor from django.utils.http import int_to_base36 timestamp = (date.today() - date(2001, 1, 1)).days ts_b36 = int_to_base36(timestamp) hash = sha_constructor(((((settings.SECRET_KEY + unicode(user.id)) + use...
'Make sure we don\'t allow overly long dates, causing a potential DoS.'
def test_date_length(self):
user = User.objects.create_user('ima1337h4x0r', 'test4@example.com', 'p4ssw0rd') p0 = PasswordResetTokenGenerator() tk1 = p0._make_token_with_timestamp(user, 175455491841851871349L) self.assertFalse(p0.check_token(user, tk1))
'Error is raised if the provided email address isn\'t currently registered'
def test_email_not_found(self):
response = self.client.get('/password_reset/') self.assertEqual(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) self.assertContains(response, 'That e-mail address doesn't have an associated user account') ...
'Email is sent if a valid email address is provided for password reset'
def test_email_found(self):
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertTrue(('http://' in mail.outbox[0].body)) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
'Email is sent if a valid email address is provided for password reset when a custom from_email is provided.'
def test_email_found_custom_from(self):
response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual('staffmember@example.com', mail.outbox[0].from_email)
'Logout without next_page option renders the default template'
def test_logout_default(self):
self.login() response = self.client.get('/logout/') self.assertEqual(200, response.status_code) self.assertTrue(('Logged out' in response.content)) self.confirm_logged_out()
'Logout with next_page option given redirects to specified resource'
def test_logout_with_next_page_specified(self):
self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Logout with query string redirects to specified resource'
def test_logout_with_redirect_argument(self):
self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/login/')) self.confirm_logged_out()
'Logout with custom query string redirects to specified resource'
def test_logout_with_custom_redirect_argument(self):
self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith('/somewhere/')) self.confirm_logged_out()
'Set up the listeners and reset the logged in/logged out counters'
def setUp(self):
self.logged_in = [] self.logged_out = [] signals.user_logged_in.connect(self.listener_login) signals.user_logged_out.connect(self.listener_logout)
'Disconnect the listeners'
def tearDown(self):
signals.user_logged_in.disconnect(self.listener_login) signals.user_logged_out.disconnect(self.listener_logout)
'Check that users can be created and can set their password'
def test_user(self):
u = User.objects.create_user('testuser', 'test@example.com', 'testpw') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('testpw')) u.set_unusable_password() u.save() self.assertFalse(u.check_password('testpw')) self.asser...
'Check the properties of the anonymous user'
def test_anonymous_user(self):
a = AnonymousUser() self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) self.assertFalse(a.is_superuser) self.assertEqual(a.groups.all().count(), 0) self.assertEqual(a.user_permissions.all().count(), 0)
'Check the creation and properties of a superuser'
def test_superuser(self):
super = User.objects.create_superuser('super', 'super@example.com', 'super') self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff)
'Check the operation of the createsuperuser management command'
def test_createsuperuser_management_command(self):
new_io = StringIO() call_command('createsuperuser', interactive=False, username='joe', email='joe@somewhere.org', stdout=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = User.objects.get(username='joe') self.assertEq...
'Creates and saves a User with the given username, e-mail and password.'
def create_user(self, username, email, password=None):
now = datetime.datetime.now() try: (email_name, domain_part) = email.strip().split('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, l...
'Generates a random password with the given length and given allowed_chars'
def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
from random import choice return ''.join([choice(allowed_chars) for i in range(length)])
'Always returns False. This is a way of comparing User objects to anonymous users.'
def is_anonymous(self):
return False
'Always return True. This is a way to tell if the user has been authenticated in templates.'
def is_authenticated(self):
return True
'Returns the first_name plus the last_name, with a space in between.'
def get_full_name(self):
full_name = (u'%s %s' % (self.first_name, self.last_name)) return full_name.strip()
'Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes.'
def check_password(self, raw_password):
if ('$' not in self.password): is_correct = (self.password == get_hexdigest('md5', '', raw_password)) if is_correct: self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password)
'Returns a list of permission strings that this user has through his/her groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned.'
def get_group_permissions(self, obj=None):
permissions = set() for backend in auth.get_backends(): if hasattr(backend, 'get_group_permissions'): if (obj is not None): if backend.supports_object_permissions: permissions.update(backend.get_group_permissions(self, obj)) else: ...
'Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific objec...
def has_perm(self, perm, obj=None):
if (self.is_active and self.is_superuser): return True return _user_has_perm(self, perm, obj)
'Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object.'
def has_perms(self, perm_list, obj=None):
for perm in perm_list: if (not self.has_perm(perm, obj)): return False return True
'Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above.'
def has_module_perms(self, app_label):
if (self.is_active and self.is_superuser): return True return _user_has_module_perms(self, app_label)
'Sends an e-mail to this User.'
def email_user(self, subject, message, from_email=None):
from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email])
'Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles.'
def get_profile(self):
if (not hasattr(self, '_profile_cache')): from django.conf import settings if (not getattr(settings, 'AUTH_PROFILE_MODULE', False)): raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MODULE in your project settings') try: (app_label, ...
'Returns a set of permission strings that this user has through his/her groups.'
def get_group_permissions(self, user_obj):
if (not hasattr(user_obj, '_group_perm_cache')): if user_obj.is_superuser: perms = Permission.objects.all() else: perms = Permission.objects.filter(group__user=user_obj) perms = perms.values_list('content_type__app_label', 'codename').order_by() user_obj._grou...
'Returns True if user_obj has any permissions in the given app_label.'
def has_module_perms(self, user_obj, app_label):
if (not user_obj.is_active): return False for perm in self.get_all_permissions(user_obj): if (perm[:perm.index('.')] == app_label): return True return False
'The username passed as ``remote_user`` is considered trusted. This method simply returns the ``User`` object with the given username, creating a new ``User`` object if ``create_unknown_user`` is ``True``. Returns None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given username is not found i...
def authenticate(self, remote_user):
if (not remote_user): return user = None username = self.clean_username(remote_user) if self.create_unknown_user: (user, created) = User.objects.get_or_create(username=username) if created: user = self.configure_user(user) else: try: user = Use...
'Performs any cleaning on the "username" prior to using it to get or create the user object. Returns the cleaned username. By default, returns the username unchanged.'
def clean_username(self, username):
return username
'Configures a user after creation and returns the updated user. By default, returns the user unmodified.'
def configure_user(self, user):
return user
'Use special form during user creation'
def get_form(self, request, obj=None, **kwargs):
defaults = {} if (obj is None): defaults.update({'form': self.add_form, 'fields': admin.util.flatten_fieldsets(self.add_fieldsets)}) defaults.update(kwargs) return super(UserAdmin, self).get_form(request, obj, **defaults)
'Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.'
def response_add(self, request, obj, post_url_continue='../%s/'):
if (('_addanother' not in request.POST) and ('_popup' not in request.POST)): request.POST['_continue'] = 1 return super(UserAdmin, self).response_add(request, obj, post_url_continue)
'If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation.'
def __init__(self, request=None, *args, **kwargs):
self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs)
'Validates that an active user exists with the given e-mail address.'
def clean_email(self):
email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email, is_active=True) if (len(self.users_cache) == 0): raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've regis...
'Generates a one-use only link for resetting password and sends to the user'
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None):
from django.core.mail import send_mail for user in self.users_cache: if (not domain_override): current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override t ...
'Validates that the old_password field is correct.'
def clean_old_password(self):
old_password = self.cleaned_data['old_password'] if (not self.user.check_password(old_password)): raise forms.ValidationError(_('Your old password was entered incorrectly. Please enter it again.')) return old_password
'Saves the new password.'
def save(self, commit=True):
self.user.set_password(self.cleaned_data['password1']) if commit: self.user.save() return self.user
'Returns a token that can be used once to do a password reset for the given user.'
def make_token(self, user):
return self._make_token_with_timestamp(user, self._num_days(self._today()))
'Check that a password reset token is correct for a given user.'
def check_token(self, user, token):
try: (ts_b36, hash) = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False if (not constant_time_compare(self._make_token_with_timestamp(user, ts), token)): if (not constant_time_compare(self._make_to...
'Allows the backend to clean the username, if the backend defines a clean_username method.'
def clean_username(self, username, request):
backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: username = backend.clean_username(username) except AttributeError: pass return username
'Start a new wizard with a list of forms. form_list should be a list of Form classes (not instances).'
def __init__(self, form_list, initial=None):
self.form_list = form_list[:] self.initial = (initial or {}) self.extra_context = {} self.step = 0
'Helper method that returns the Form instance for the given step.'
def get_form(self, step, data=None):
return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None))
'Helper method that returns the number of steps.'
def num_steps(self):
return len(self.form_list)
'Main method that does all the hard work, conforming to the Django view interface.'
@method_decorator(csrf_protect) def __call__(self, request, *args, **kwargs):
if ('extra_context' in kwargs): self.extra_context.update(kwargs['extra_context']) current_step = self.determine_step(request, *args, **kwargs) self.parse_params(request, *args, **kwargs) if (current_step >= self.num_steps()): raise Http404(('Step %s does not exist' % current...
'Renders the given Form object, returning an HttpResponse.'
def render(self, form, request, step, context=None):
old_data = request.POST prev_fields = [] if old_data: hidden = forms.HiddenInput() for i in range(step): old_form = self.get_form(i, old_data) hash_name = ('hash_%s' % i) prev_fields.extend([bf.as_hidden() for bf in old_form]) prev_fields.appen...
'Given the step, returns a Form prefix to use.'
def prefix_for_step(self, step):
return str(step)
'Hook for rendering a template if a hash check failed. step is the step that failed. Any previous step is guaranteed to be valid. This default implementation simply renders the form for the given step, but subclasses may want to display an error message, etc.'
def render_hash_failure(self, request, step):
return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')})
'Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation.'
def render_revalidation_failure(self, request, step, form):
return self.render(form, request, step)
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return form_hmac(form)
'Given the request object and whatever *args and **kwargs were passed to __call__(), returns the current step (which is zero-based). Note that the result should not be trusted. It may even be a completely invalid number. It\'s not the job of this method to validate it.'
def determine_step(self, request, *args, **kwargs):
if (not request.POST): return 0 try: step = int(request.POST.get(self.step_field_name, 0)) except ValueError: return 0 return step
'Hook for setting some state, given the request object and whatever *args and **kwargs were passed to __call__(), sets some state. This is called at the beginning of __call__().'
def parse_params(self, request, *args, **kwargs):
pass
'Hook for specifying the name of the template to use for a given step. Note that this can return a tuple of template names if you\'d like to use the template system\'s select_template() hook.'
def get_template(self, step):
return 'forms/wizard.html'
'Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead. The template will be rendered with the following context: step_field -- The...
def render_template(self, request, form, previous_fields, step, context=None):
context = (context or {}) context.update(self.extra_context) return render_to_response(self.get_template(step), dict(context, step_field=self.step_field_name, step0=step, step=(step + 1), step_count=self.num_steps(), form=form, previous_fields=previous_fields), context_instance=RequestContext(request))
'Hook for modifying the FormWizard\'s internal state, given a fully validated Form object. The Form is guaranteed to have clean, valid data. This method should *not* modify any of that data. Rather, it might want to set self.extra_context or dynamically alter self.form_list, based on previously submitted forms. Note th...
def process_step(self, request, form, step):
pass
'Hook for doing something with the validated data. This is responsible for the final processing. form_list is a list of Form instances, each containing clean, valid data.'
def done(self, request, form_list):
raise NotImplementedError(('Your %s class has not defined a done() method, which is required.' % self.__class__.__name__))
'Given a first-choice name, adds an underscore to the name until it reaches a name that isn\'t claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form.'
def unused_name(self, name):
while 1: try: f = self.form.base_fields[name] except KeyError: break name += '_' return name
'Displays the form'
def preview_get(self, request):
f = self.form(auto_id=self.get_auto_id(), initial=self.get_initial(request)) return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request))
'Validates the POST data. If valid, displays the preview page. Else, redisplays form.'
def preview_post(self, request):
f = self.form(request.POST, auto_id=self.get_auto_id()) context = self.get_context(request, f) if f.is_valid(): self.process_preview(request, f, context) context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_r...
'Validates the POST data. If valid, calls done(). Else, redisplays form.'
def post_post(self, request):
f = self.form(request.POST, auto_id=self.get_auto_id()) if f.is_valid(): if (not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f)): return self.failed_hash(request) return self.done(request, f.cleaned_data) else: return render_to_respo...
'Hook to override the ``auto_id`` kwarg for the form. Needed when rendering two form previews in the same template.'
def get_auto_id(self):
return AUTO_ID
'Takes a request argument and returns a dictionary to pass to the form\'s ``initial`` kwarg when the form is being created from an HTTP get.'
def get_initial(self, request):
return {}
'Context for template rendering.'
def get_context(self, request, form):
return {'form': form, 'stage_field': self.unused_name('stage'), 'state': self.state}
'Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r\'^contact/(?P<user_id>\d{1,6})/$\', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {\'user_id\': 32} for a req...
def parse_params(self, *args, **kwargs):
pass
'Given a validated form, performs any extra processing before displaying the preview page, and saves any extra data in context.'
def process_preview(self, request, form, context):
pass
'Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address.'
def security_hash(self, request, form):
return security_hash(request, form)
'Returns an HttpResponse in the case of an invalid security hash.'
def failed_hash(self, request):
return self.preview_post(request)
'Does something with the cleaned_data and returns an HttpResponseRedirect.'
def done(self, request, cleaned_data):
raise NotImplementedError(('You must define a done() method on your %s subclass.' % self.__class__.__name__))
'Verifies name mangling to get uniue field name.'
def test_unused_name(self):
self.assertEqual(self.preview.unused_name('field1'), 'field1__')
'Test contrib.formtools.preview form retrieval. Use the client library to see if we can sucessfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage.'
def test_form_get(self):
response = self.client.get('/test1/') stage = (self.input % 1) self.assertContains(response, stage, 1) self.assertEqual(response.context['custom_context'], True) self.assertEqual(response.context['form'].initial, {'field1': 'Works!'})
'Test contrib.formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form.'
def test_form_preview(self):
self.test_data.update({'stage': 1}) response = self.client.post('/test1/', self.test_data) stage = (self.input % 2) self.assertContains(response, stage, 1)
'Test contrib.formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify sucess.'
def test_form_submit(self):
self.test_data.update({'stage': 2}) response = self.client.post('/test1/', self.test_data) self.assertNotEqual(response.content, success_string) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test1/', self.tes...
'Test contrib.formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form\'s hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rend...
def test_bool_submit(self):
self.test_data.update({'stage': 2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash, 'bool1': u'False'}) response = self.client.post('/test1/', self.test_data) self.assertEqual(response.content, success_string)
'Test contrib.formtools.preview form submittal, using the hash function used in Django 1.2'
def test_form_submit_django12_hash(self):
self.test_data.update({'stage': 2}) response = self.client.post('/test1/', self.test_data) self.assertNotEqual(response.content, success_string) hash = utils.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test1/', self.test_data)...
'Test contrib.formtools.preview form submittal, using the hash function used in Django 1.2 and a custom security_hash method.'
def test_form_submit_django12_hash_custom_hash(self):
self.test_data.update({'stage': 2}) response = self.client.post('/test2/', self.test_data) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, success_string) hash = utils.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) respon...
'Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).'
def test_textfield_hash(self):
f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.'
def test_empty_permitted(self):
f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2)
'Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).'
def test_textfield_hash(self):
f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2)
'Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.'
def test_empty_permitted(self):
f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2)