desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'date_list should be sorted ascending in month view'
| def test_date_list_order(self):
| _make_books(10, base_date=datetime.date(2011, 12, 25))
res = self.client.get('/dates/books/2011/dec/')
self.assertEqual(list(res.context['date_list']), list(sorted(res.context['date_list'])))
|
'Ensure that custom querysets are used when provided to
BaseDateDetailView.get_object()
Refs #16918.'
| def test_get_object_custom_queryset(self):
| res = self.client.get('/dates/books/get_object_custom_queryset/2006/may/01/2/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Book.objects.get(pk=2))
self.assertEqual(res.context['book'], Book.objects.get(pk=2))
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
res = self.client.get('/dates/books/get_object_custom_queryset/2008/oct/01/1/')
self.assertEqual(res.status_code, 404)
|
'Test instance independence of initial data dict (see #16138)'
| def test_initial_data(self):
| initial_1 = FormMixin().get_initial()
initial_1['foo'] = 'bar'
initial_2 = FormMixin().get_initial()
self.assertNotEqual(initial_1, initial_2)
|
'Uploaded file names should be sanitized before ever reaching the view.'
| def test_dangerous_file_names(self):
| scary_file_names = [u'/tmp/hax0rd.txt', u'C:\\Windows\\hax0rd.txt', u'C:/Windows/hax0rd.txt', u'\\tmp\\hax0rd.txt', u'/tmp\\hax0rd.txt', u'subdir/hax0rd.txt', u'subdir\\hax0rd.txt', u'sub/dir\\hax0rd.txt', u'../../hax0rd.txt', u'..\\..\\hax0rd.txt', u'../..\\hax0rd.txt']
payload = client.FakePayload()
for (i, name) in enumerate(scary_file_names):
payload.write(u'\r\n'.join([(u'--' + client.BOUNDARY), (u'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name)), u'Content-Type: application/octet-stream', u'', u'You got pwnd.\r\n']))
payload.write(((u'\r\n--' + client.BOUNDARY) + u'--\r\n'))
r = {u'CONTENT_LENGTH': len(payload), u'CONTENT_TYPE': client.MULTIPART_CONTENT, u'PATH_INFO': u'/file_uploads/echo/', u'REQUEST_METHOD': u'POST', u'wsgi.input': payload}
response = self.client.request(**r)
recieved = json.loads(response.content.decode(u'utf-8'))
for (i, name) in enumerate(scary_file_names):
got = recieved[(u'file%s' % i)]
self.assertEqual(got, u'hax0rd.txt')
|
'File names over 256 characters (dangerous on some platforms) get fixed up.'
| def test_filename_overflow(self):
| name = (u'%s.txt' % (u'f' * 500))
payload = client.FakePayload(u'\r\n'.join([(u'--' + client.BOUNDARY), (u'Content-Disposition: form-data; name="file"; filename="%s"' % name), u'Content-Type: application/octet-stream', u'', ((u'Oops.--' + client.BOUNDARY) + u'--'), u'']))
r = {u'CONTENT_LENGTH': len(payload), u'CONTENT_TYPE': client.MULTIPART_CONTENT, u'PATH_INFO': u'/file_uploads/echo/', u'REQUEST_METHOD': u'POST', u'wsgi.input': payload}
got = json.loads(self.client.request(**r).content.decode(u'utf-8'))
self.assertTrue((len(got[u'file']) < 256), (u'Got a long file name (%s characters).' % len(got[u'file'])))
|
'If passed an incomplete multipart message, MultiPartParser does not
attempt to read beyond the end of the stream, and simply will handle
the part that can be parsed gracefully.'
| def test_truncated_multipart_handled_gracefully(self):
| payload_str = u'\r\n'.join([(u'--' + client.BOUNDARY), u'Content-Disposition: form-data; name="file"; filename="foo.txt"', u'Content-Type: application/octet-stream', u'', ((u'file contents--' + client.BOUNDARY) + u'--'), u''])
payload = client.FakePayload(payload_str[:(-10)])
r = {u'CONTENT_LENGTH': len(payload), u'CONTENT_TYPE': client.MULTIPART_CONTENT, u'PATH_INFO': u'/file_uploads/echo/', u'REQUEST_METHOD': u'POST', u'wsgi.input': payload}
got = json.loads(self.client.request(**r).content.decode(u'utf-8'))
self.assertEqual(got, {})
|
'If passed an empty multipart message, MultiPartParser will return
an empty QueryDict.'
| def test_empty_multipart_handled_gracefully(self):
| r = {u'CONTENT_LENGTH': 0, u'CONTENT_TYPE': client.MULTIPART_CONTENT, u'PATH_INFO': u'/file_uploads/echo/', u'REQUEST_METHOD': u'POST', u'wsgi.input': client.FakePayload('')}
got = json.loads(self.client.request(**r).content.decode(u'utf-8'))
self.assertEqual(got, {})
|
'The server should not block when there are upload errors (bug #8622).
This can happen if something -- i.e. an exception handler -- tries to
access POST while handling an error in parsing POST. This shouldn\'t
cause an infinite loop!'
| def test_file_error_blocking(self):
| class POSTAccessingHandler(client.ClientHandler, ):
u"A handler that'll access POST during an exception."
def handle_uncaught_exception(self, request, resolver, exc_info):
ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
p = request.POST
return ret
try:
client.FakePayload('a').read(2)
except Exception as err:
reference_error = err
self.client.handler = POSTAccessingHandler()
with open(__file__, u'rb') as fp:
post_data = {u'name': u'Ringo', u'file_field': fp}
try:
response = self.client.post(u'/file_uploads/upload_errors/', post_data)
except reference_error.__class__ as err:
self.assertFalse((str(err) == str(reference_error)), u"Caught a repeated exception that'll cause an infinite loop in file uploads.")
except Exception as err:
self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
|
'The storage backend shouldn\'t mess with the case of the filenames
uploaded.'
| def test_filename_case_preservation(self):
| vars = {u'boundary': u'oUrBoUnDaRyStRiNg'}
post_data = [u'--%(boundary)s', u'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"', u'Content-Type: application/octet-stream', u'', u'file contents\n', u'--%(boundary)s--\r\n']
response = self.client.post(u'/file_uploads/filename_case/', (u'\r\n'.join(post_data) % vars), (u'multipart/form-data; boundary=%(boundary)s' % vars))
self.assertEqual(response.status_code, 200)
id = int(response.content)
obj = FileModel.objects.get(pk=id)
self.assertEqual(os.path.basename(obj.testfile.path), u'MiXeD_cAsE.txt')
|
'Permission errors are not swallowed'
| def test_readonly_root(self):
| os.chmod(MEDIA_ROOT, 320)
self.addCleanup(os.chmod, MEDIA_ROOT, 448)
try:
self.obj.testfile.save(u'foo.txt', SimpleUploadedFile(u'foo.txt', 'x'))
except OSError as err:
self.assertEqual(err.errno, errno.EACCES)
except Exception:
self.fail((u'OSError [Errno %s] not raised.' % errno.EACCES))
|
'The correct IOError is raised when the upload directory name exists but isn\'t a directory'
| def test_not_a_directory(self):
| open(UPLOAD_TO, u'wb').close()
self.addCleanup(os.remove, UPLOAD_TO)
with self.assertRaises(IOError) as exc_info:
self.obj.testfile.save(u'foo.txt', SimpleUploadedFile(u'foo.txt', 'x'))
self.assertEqual(exc_info.exception.args[0], (u'%s exists and is not a directory.' % UPLOAD_TO))
|
'Returns the URL for this guitarist.'
| @models.permalink
def url(self):
| return ('guitarist_detail', [self.slug])
|
'Returns the URL for this guitarist and holds an attribute'
| @models.permalink
@set_attr('attribute', 'value')
def url_with_attribute(self):
| return ('guitarist_detail', [self.slug])
|
'Methods using the @permalink decorator retain their docstring.'
| def test_wrapped_docstring(self):
| g = Guitarist(name='Adrien Moignard', slug='adrienmoignard')
self.assertEqual(g.url.__doc__, 'Returns the URL for this guitarist.')
|
'Methods using the @permalink decorator can have attached attributes
from other decorators'
| def test_wrapped_attribute(self):
| g = Guitarist(name='Adrien Moignard', slug='adrienmoignard')
self.assertTrue(hasattr(g.url_with_attribute, 'attribute'))
self.assertEqual(g.url_with_attribute.attribute, 'value')
|
'Ensure that the custom ModelForm\'s `Meta.exclude` is respected when
used in conjunction with `ModelAdmin.readonly_fields` and when no
`ModelAdmin.exclude` is defined.
Refs #14496.'
| def test_custom_form_meta_exclude_with_readonly(self):
| class AdminBandForm(forms.ModelForm, ):
class Meta:
model = Band
exclude = [u'bio']
class BandAdmin(ModelAdmin, ):
readonly_fields = [u'name']
form = AdminBandForm
ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), [u'sign_date'])
class AdminConcertForm(forms.ModelForm, ):
class Meta:
model = Concert
exclude = [u'day']
class ConcertInline(TabularInline, ):
readonly_fields = [u'transport']
form = AdminConcertForm
fk_name = u'main_band'
model = Concert
class BandAdmin(ModelAdmin, ):
inlines = [ConcertInline]
ma = BandAdmin(Band, self.site)
self.assertEqual(list(list(ma.get_formsets(request))[0]().forms[0].fields), [u'main_band', u'opening_band', u'id', u'DELETE'])
|
'Ensure that the custom ModelForm\'s `Meta.exclude` is overridden if
`ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined.
Refs #14496.'
| def test_custom_form_meta_exclude(self):
| class AdminBandForm(forms.ModelForm, ):
class Meta:
model = Band
exclude = [u'bio']
class BandAdmin(ModelAdmin, ):
exclude = [u'name']
form = AdminBandForm
ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), [u'bio', u'sign_date'])
class AdminConcertForm(forms.ModelForm, ):
class Meta:
model = Concert
exclude = [u'day']
class ConcertInline(TabularInline, ):
exclude = [u'transport']
form = AdminConcertForm
fk_name = u'main_band'
model = Concert
class BandAdmin(ModelAdmin, ):
inlines = [ConcertInline]
ma = BandAdmin(Band, self.site)
self.assertEqual(list(list(ma.get_formsets(request))[0]().forms[0].fields), [u'main_band', u'opening_band', u'day', u'id', u'DELETE'])
|
'Ensure that the `exclude` kwarg passed to `ModelAdmin.get_form()`
overrides all other declarations. Refs #8999.'
| def test_form_exclude_kwarg_override(self):
| class AdminBandForm(forms.ModelForm, ):
class Meta:
model = Band
exclude = [u'name']
class BandAdmin(ModelAdmin, ):
exclude = [u'sign_date']
form = AdminBandForm
def get_form(self, request, obj=None, **kwargs):
kwargs[u'exclude'] = [u'bio']
return super(BandAdmin, self).get_form(request, obj, **kwargs)
ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), [u'name', u'sign_date'])
|
'Ensure that the `exclude` kwarg passed to `InlineModelAdmin.get_formset()`
overrides all other declarations. Refs #8999.'
| def test_formset_exclude_kwarg_override(self):
| class AdminConcertForm(forms.ModelForm, ):
class Meta:
model = Concert
exclude = [u'day']
class ConcertInline(TabularInline, ):
exclude = [u'transport']
form = AdminConcertForm
fk_name = u'main_band'
model = Concert
def get_formset(self, request, obj=None, **kwargs):
kwargs[u'exclude'] = [u'opening_band']
return super(ConcertInline, self).get_formset(request, obj, **kwargs)
class BandAdmin(ModelAdmin, ):
inlines = [ConcertInline]
ma = BandAdmin(Band, self.site)
self.assertEqual(list(list(ma.get_formsets(request))[0]().forms[0].fields), [u'main_band', u'day', u'transport', u'id', u'DELETE'])
|
'Ensure that `obj` is passed from `InlineModelAdmin.get_fieldsets()` to
`InlineModelAdmin.get_formset()`.'
| def test_regression_for_ticket_15820(self):
| class CustomConcertForm(forms.ModelForm, ):
class Meta:
model = Concert
fields = [u'day']
class ConcertInline(TabularInline, ):
model = Concert
fk_name = u'main_band'
def get_formset(self, request, obj=None, **kwargs):
if obj:
kwargs[u'form'] = CustomConcertForm
return super(ConcertInline, self).get_formset(request, obj, **kwargs)
class BandAdmin(ModelAdmin, ):
inlines = [ConcertInline]
concert = Concert.objects.create(main_band=self.band, opening_band=self.band, day=1)
ma = BandAdmin(Band, self.site)
inline_instances = ma.get_inline_instances(request)
fieldsets = list(inline_instances[0].get_fieldsets(request))
self.assertEqual(fieldsets[0][1][u'fields'], [u'main_band', u'opening_band', u'day', u'transport'])
fieldsets = list(inline_instances[0].get_fieldsets(request, inline_instances[0].model))
self.assertEqual(fieldsets[0][1][u'fields'], [u'day'])
|
'Deletes on concurrent transactions don\'t collide and lock the database. Regression for #9479'
| @skipUnlessDBFeature('test_db_allows_multiple_connections')
def test_concurrent_delete(self):
| b1 = Book(id=1, pagecount=100)
b2 = Book(id=2, pagecount=200)
b3 = Book(id=3, pagecount=300)
b1.save()
b2.save()
b3.save()
transaction.commit()
self.assertEqual(3, Book.objects.count())
cursor2 = self.conn2.cursor()
cursor2.execute('DELETE from delete_regress_book WHERE id=1')
self.conn2._commit()
Book.objects.filter(pagecount__lt=250).delete()
transaction.commit()
self.assertEqual(1, Book.objects.count())
transaction.commit()
|
'Django cascades deletes through generic-related objects to their
reverse relations.'
| def test_generic_relation_cascade(self):
| person = Person.objects.create(name='Nelson Mandela')
award = Award.objects.create(name='Nobel', content_object=person)
note = AwardNote.objects.create(note='a peace prize', award=award)
self.assertEqual(AwardNote.objects.count(), 1)
person.delete()
self.assertEqual(Award.objects.count(), 0)
self.assertEqual(AwardNote.objects.count(), 0)
|
'If an M2M relationship has an explicitly-specified through model, and
some other model has an FK to that through model, deletion is cascaded
from one of the participants in the M2M, to the through model, to its
related model.'
| def test_fk_to_m2m_through(self):
| juan = Child.objects.create(name='Juan')
paints = Toy.objects.create(name='Paints')
played = PlayedWith.objects.create(child=juan, toy=paints, date=datetime.date.today())
note = PlayedWithNote.objects.create(played=played, note='the next Jackson Pollock')
self.assertEqual(PlayedWithNote.objects.count(), 1)
paints.delete()
self.assertEqual(PlayedWith.objects.count(), 0)
self.assertEqual(PlayedWithNote.objects.count(), 0)
|
'Auto-created many-to-many through tables referencing a parent model are
correctly found by the delete cascade when a child of that parent is
deleted.
Refs #14896.'
| def test_inheritance(self):
| r = Researcher.objects.create()
email = Email.objects.create(label='office-email', email_address='[email protected]')
r.contacts.add(email)
email.delete()
|
'Cascade deletion works with ForeignKey.to_field set to non-PK.'
| def test_to_field(self):
| apple = Food.objects.create(name='apple')
eaten = Eaten.objects.create(food=apple, meal='lunch')
apple.delete()
self.assertFalse(Food.objects.exists())
self.assertFalse(Eaten.objects.exists())
|
'Regression for #13309 -- if the number of objects > chunk size, deletion still occurs'
| def test_large_deletes(self):
| for x in range(300):
track = Book.objects.create(pagecount=(x + 100))
def noop(*args, **kwargs):
pass
models.signals.post_delete.connect(noop, sender=Book)
Book.objects.all().delete()
models.signals.post_delete.disconnect(noop, sender=Book)
self.assertEqual(Book.objects.count(), 0)
|
'Return an Image referenced by both a FooImage and a FooFile.'
| def create_image(self):
| test_image = Image()
test_image.save()
foo_image = FooImage(my_image=test_image)
foo_image.save()
test_file = File.objects.get(pk=test_image.pk)
foo_file = FooFile(my_file=test_file)
foo_file.save()
return test_image
|
'Deleting the *proxy* instance bubbles through to its non-proxy and
*all* referring objects are deleted.'
| def test_delete_proxy(self):
| self.create_image()
Image.objects.all().delete()
self.assertEqual(len(Image.objects.all()), 0)
self.assertEqual(len(File.objects.all()), 0)
self.assertEqual(len(FooImage.objects.all()), 0)
self.assertEqual(len(FooFile.objects.all()), 0)
|
'Deleting a proxy-of-proxy instance should bubble through to its proxy
and non-proxy parents, deleting *all* referring objects.'
| def test_delete_proxy_of_proxy(self):
| test_image = self.create_image()
test_photo = Photo.objects.get(pk=test_image.pk)
foo_photo = FooPhoto(my_photo=test_photo)
foo_photo.save()
Photo.objects.all().delete()
self.assertEqual(len(Photo.objects.all()), 0)
self.assertEqual(len(Image.objects.all()), 0)
self.assertEqual(len(File.objects.all()), 0)
self.assertEqual(len(FooPhoto.objects.all()), 0)
self.assertEqual(len(FooFile.objects.all()), 0)
self.assertEqual(len(FooImage.objects.all()), 0)
|
'Deleting an instance of a concrete model should also delete objects
referencing its proxy subclass.'
| def test_delete_concrete_parent(self):
| self.create_image()
File.objects.all().delete()
self.assertEqual(len(File.objects.all()), 0)
self.assertEqual(len(Image.objects.all()), 0)
self.assertEqual(len(FooFile.objects.all()), 0)
self.assertEqual(len(FooImage.objects.all()), 0)
|
'If a pair of proxy models are linked by an FK from one concrete parent
to the other, deleting one proxy model cascade-deletes the other, and
the deletion happens in the right order (not triggering an
IntegrityError on databases unable to defer integrity checks).
Refs #17918.'
| def test_delete_proxy_pair(self):
| image = Image.objects.create()
as_file = File.objects.get(pk=image.pk)
FooFileProxy.objects.create(my_file=as_file)
Image.objects.all().delete()
self.assertEqual(len(FooFileProxy.objects.all()), 0)
|
'Models module can be loaded from an app in an egg'
| def test_egg1(self):
| egg_name = ('%s/modelapp.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('app_with_models')
self.assertFalse((models is None))
|
'Loading an app from an egg that has no models returns no models (and no error)'
| def test_egg2(self):
| egg_name = ('%s/nomodelapp.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('app_no_models')
self.assertTrue((models is None))
|
'Models module can be loaded from an app located under an egg\'s top-level package'
| def test_egg3(self):
| egg_name = ('%s/omelet.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('omelet.app_with_models')
self.assertFalse((models is None))
|
'Loading an app with no models from under the top-level egg package generates no error'
| def test_egg4(self):
| egg_name = ('%s/omelet.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('omelet.app_no_models')
self.assertTrue((models is None))
|
'Loading an app from an egg that has an import error in its models module raises that error'
| def test_egg5(self):
| egg_name = ('%s/brokenapp.egg' % self.egg_dir)
sys.path.append(egg_name)
self.assertRaises(ImportError, load_app, 'broken_app')
try:
load_app('broken_app')
except ImportError as e:
self.assertTrue(('modelz' in e.args[0]))
|
'The default ordering should be by name, as specified in the inner Meta
class.'
| def test_default_ordering(self):
| ma = ModelAdmin(Band, None)
names = [b.name for b in ma.queryset(request)]
self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names)
|
'Let\'s use a custom ModelAdmin that changes the ordering, and make sure
it actually changes.'
| def test_specified_ordering(self):
| class BandAdmin(ModelAdmin, ):
ordering = (u'rank',)
ma = BandAdmin(Band, None)
names = [b.name for b in ma.queryset(request)]
self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names)
|
'Let\'s use a custom ModelAdmin that changes the ordering dinamically.'
| def test_dynamic_ordering(self):
| super_user = User.objects.create(username=u'admin', is_superuser=True)
other_user = User.objects.create(username=u'other')
request = self.request_factory.get(u'/')
request.user = super_user
ma = DynOrderingBandAdmin(Band, None)
names = [b.name for b in ma.queryset(request)]
self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names)
request.user = other_user
names = [b.name for b in ma.queryset(request)]
self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names)
|
'The default ordering should be by name, as specified in the inner Meta
class.'
| def test_default_ordering(self):
| inline = SongInlineDefaultOrdering(self.b, None)
names = [s.name for s in inline.queryset(request)]
self.assertEqual([u'Dude (Looks Like a Lady)', u'Jaded', u'Pink'], names)
|
'Let\'s check with ordering set to something different than the default.'
| def test_specified_ordering(self):
| inline = SongInlineNewOrdering(self.b, None)
names = [s.name for s in inline.queryset(request)]
self.assertEqual([u'Jaded', u'Pink', u'Dude (Looks Like a Lady)'], names)
|
'Regression test for #6755'
| def test_issue_6755(self):
| r = Restaurant(serves_pizza=False)
r.save()
self.assertEqual(r.id, r.place_ptr_id)
orig_id = r.id
r = Restaurant(place_ptr_id=orig_id, serves_pizza=True)
r.save()
self.assertEqual(r.id, orig_id)
self.assertEqual(r.id, r.place_ptr_id)
|
'Regression test for #11764'
| def test_issue_11764(self):
| wholesalers = list(Wholesaler.objects.all().select_related())
self.assertEqual(wholesalers, [])
|
'Regression test for #7853
If the parent class has a self-referential link, make sure that any
updates to that link via the child update the right table.'
| def test_issue_7853(self):
| obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
obj.delete()
|
'Regression tests for #8076
get_(next/previous)_by_date should work'
| def test_get_next_previous_by_date(self):
| c1 = ArticleWithAuthor(headline=u'ArticleWithAuthor 1', author=u'Person 1', pub_date=datetime.datetime(2005, 8, 1, 3, 0))
c1.save()
c2 = ArticleWithAuthor(headline=u'ArticleWithAuthor 2', author=u'Person 2', pub_date=datetime.datetime(2005, 8, 1, 10, 0))
c2.save()
c3 = ArticleWithAuthor(headline=u'ArticleWithAuthor 3', author=u'Person 3', pub_date=datetime.datetime(2005, 8, 2))
c3.save()
self.assertEqual(c1.get_next_by_pub_date(), c2)
self.assertEqual(c2.get_next_by_pub_date(), c3)
self.assertRaises(ArticleWithAuthor.DoesNotExist, c3.get_next_by_pub_date)
self.assertEqual(c3.get_previous_by_pub_date(), c2)
self.assertEqual(c2.get_previous_by_pub_date(), c1)
self.assertRaises(ArticleWithAuthor.DoesNotExist, c1.get_previous_by_pub_date)
|
'Regression test for #8825 and #9390
Make sure all inherited fields (esp. m2m fields, in this case) appear
on the child class.'
| def test_inherited_fields(self):
| m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
self.assertEqual(m2mchildren, [])
qs = ArticleWithAuthor.objects.order_by(u'pub_date', u'pk')
sql = qs.query.get_compiler(qs.db).as_sql()[0]
fragment = sql[sql.find(u'ORDER BY'):]
pos = fragment.find(u'pub_date')
self.assertEqual(fragment.find(u'pub_date', (pos + 1)), (-1))
|
'Regression test for #10362
It is possible to call update() and only change a field in
an ancestor model.'
| def test_queryset_update_on_parent_model(self):
| article = ArticleWithAuthor.objects.create(author=u'fred', headline=u'Hey there!', pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0))
update = ArticleWithAuthor.objects.filter(author=u'fred').update(headline=u'Oh, no!')
self.assertEqual(update, 1)
update = ArticleWithAuthor.objects.filter(pk=article.pk).update(headline=u'Oh, no!')
self.assertEqual(update, 1)
derivedm1 = DerivedM.objects.create(customPK=44, base_name=u'b1', derived_name=u'd1')
self.assertEqual(derivedm1.customPK, 44)
self.assertEqual(derivedm1.base_name, u'b1')
self.assertEqual(derivedm1.derived_name, u'd1')
derivedms = list(DerivedM.objects.all())
self.assertEqual(derivedms, [derivedm1])
|
'Regression tests for #10406
If there\'s a one-to-one link between a child model and the parent and
no explicit pk declared, we can use the one-to-one link as the pk on
the child.'
| def test_use_explicit_o2o_to_parent_as_pk(self):
| self.assertEqual(ParkingLot2._meta.pk.name, u'parent')
self.assertEqual(ParkingLot3._meta.pk.name, u'primary_key')
self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, u'parent')
|
'Regression tests for #7588'
| def test_all_fields_from_abstract_base_class(self):
| QualityControl.objects.create(headline=u'Problems in Django', pub_date=datetime.datetime.now(), quality=10, assignee=u'adrian')
|
'verbose_name_plural correctly inherited from ABC if inheritance chain
includes an abstract model.'
| def test_abstract_verbose_name_plural_inheritance(self):
| self.assertEqual(InternalCertificationAudit._meta.verbose_name_plural, u'Audits')
|
'Primary key set correctly with concrete->abstract->concrete inheritance.'
| def test_concrete_abstract_concrete_pk(self):
| self.assertEqual(len([field for field in BusStation._meta.local_fields if field.primary_key]), 1)
self.assertEqual(len([field for field in TrainStation._meta.local_fields if field.primary_key]), 1)
self.assertIs(BusStation._meta.pk.model, BusStation)
self.assertIs(TrainStation._meta.pk.model, TrainStation)
|
'Test that a model which has different primary key for the parent model
passes unique field checking correctly. Refs #17615.'
| def test_inherited_unique_field_with_form(self):
| class ProfileForm(forms.ModelForm, ):
class Meta:
model = Profile
User.objects.create(username=u'user_only')
p = Profile.objects.create(username=u'user_with_profile')
form = ProfileForm({u'username': u'user_with_profile', u'extra': u'hello'}, instance=p)
self.assertTrue(form.is_valid())
|
'We can fill a value in all objects with an other value of the
same object.'
| def test_fill_with_value_from_same_object(self):
| self.assertQuerysetEqual(Number.objects.all(), ['<Number: -1, -1.000>', '<Number: 42, 42.000>', '<Number: 1337, 1337.000>'])
|
'We can increment a value of all objects in a query set.'
| def test_increment_value(self):
| self.assertEqual(Number.objects.filter(integer__gt=0).update(integer=(F('integer') + 1)), 2)
self.assertQuerysetEqual(Number.objects.all(), ['<Number: -1, -1.000>', '<Number: 43, 42.000>', '<Number: 1338, 1337.000>'])
|
'We can filter for objects, where a value is not equals the value
of an other field.'
| def test_filter_not_equals_other_field(self):
| self.assertEqual(Number.objects.filter(integer__gt=0).update(integer=(F('integer') + 1)), 2)
self.assertQuerysetEqual(Number.objects.exclude(float=F('integer')), ['<Number: 43, 42.000>', '<Number: 1338, 1337.000>'])
|
'Complex expressions of different connection types are possible.'
| def test_complex_expressions(self):
| n = Number.objects.create(integer=10, float=123.45)
self.assertEqual(Number.objects.filter(pk=n.pk).update(float=(F('integer') + (F('float') * 2))), 1)
self.assertEqual(Number.objects.get(pk=n.pk).integer, 10)
self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.9, places=3))
|
'\'manage.py help test\' works after r16352.'
| def test_ticket_17477(self):
| args = [u'help', u'test']
(out, err) = self.run_manage(args)
self.assertNoOutput(err)
|
'Check that the get_tests helper function can find tests in a directory'
| def test_get_tests(self):
| module = import_module(TEST_APP_OK)
tests = get_tests(module)
self.assertIsInstance(tests, type(module))
|
'Test for #12658 - Tests with ImportError\'s shouldn\'t fail silently'
| def test_import_error(self):
| module = import_module(TEST_APP_ERROR)
self.assertRaises(ImportError, get_tests, module)
|
'Ticket #16329: sqlite3 in-memory test databases'
| @unittest.skipUnless(all(((db.connections[conn].vendor == u'sqlite') for conn in db.connections)), u'This is a sqlite-specific issue')
def test_transaction_support(self):
| old_db_connections = db.connections
for option in (u'NAME', u'TEST_NAME'):
try:
db.connections = db.ConnectionHandler({u'default': {u'ENGINE': u'django.db.backends.sqlite3', option: u':memory:'}, u'other': {u'ENGINE': u'django.db.backends.sqlite3', option: u':memory:'}})
other = db.connections[u'other']
DjangoTestSuiteRunner(verbosity=0).setup_databases()
msg = (u"DATABASES setting '%s' option set to sqlite3's ':memory:' value shouldn't interfere with transaction support detection." % option)
self.assertTrue(other.features.supports_transactions, msg)
self.assertTrue(connections_support_transactions(), msg)
finally:
db.connections = old_db_connections
|
'Test that setup_databases() doesn\'t fail with dummy database backend.'
| def test_setup_databases(self):
| runner = DjangoTestSuiteRunner(verbosity=0)
old_db_connections = db.connections
try:
db.connections = db.ConnectionHandler({})
old_config = runner.setup_databases()
runner.teardown_databases(old_config)
except Exception as e:
self.fail((u'setup_databases/teardown_databases unexpectedly raised an error: %s' % e))
finally:
db.connections = old_db_connections
|
'Can view a shortcut for an Author object that has a get_absolute_url method'
| def test_shortcut_with_absolute_url(self):
| for obj in Author.objects.all():
short_url = (u'/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Author).id, obj.pk))
response = self.client.get(short_url)
self.assertRedirects(response, (u'http://testserver%s' % obj.get_absolute_url()), status_code=302, target_status_code=404)
|
'Shortcuts for an object that has no get_absolute_url method raises 404'
| def test_shortcut_no_absolute_url(self):
| for obj in Article.objects.all():
short_url = (u'/views/shortcut/%s/%s/' % (ContentType.objects.get_for_model(Article).id, obj.pk))
response = self.client.get(short_url)
self.assertEqual(response.status_code, 404)
|
'A 404 status is returned by the page_not_found view'
| def test_page_not_found(self):
| for url in self.non_existing_urls:
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
|
'The 404 page should have the csrf_token available in the context'
| def test_csrf_token_in_404(self):
| for url in self.non_existing_urls:
response = self.client.get(url)
csrf_token = response.context[u'csrf_token']
self.assertNotEqual(str(csrf_token), u'NOTPROVIDED')
self.assertNotEqual(str(csrf_token), u'')
|
'The server_error view raises a 500 status'
| def test_server_error(self):
| response = self.client.get(u'/views/server_error/')
self.assertEqual(response.status_code, 500)
|
'Test that 404.html and 500.html templates are picked by their respective
handler.'
| def test_custom_templates(self):
| setup_test_template_loader({u'404.html': u'This is a test template for a 404 error.', u'500.html': u'This is a test template for a 500 error.'})
try:
for (code, url) in ((404, u'/views/non_existing_url/'), (500, u'/views/server_error/')):
response = self.client.get(url)
self.assertContains(response, (u'test template for a %d error' % code), status_code=code)
finally:
restore_template_loaders()
|
'A model can set attributes on the get_absolute_url method'
| def test_get_absolute_url_attributes(self):
| self.assertTrue(getattr(UrlArticle.get_absolute_url, u'purge', False), u'The attributes of the original get_absolute_url must be added.')
article = UrlArticle.objects.get(pk=1)
self.assertTrue(getattr(article.get_absolute_url, u'purge', False), u'The attributes of the original get_absolute_url must be added.')
|
'The set_language view can be used to change the session language.
The user is redirected to the \'next\' argument if provided.'
| def test_setlang(self):
| for (lang_code, lang_name) in settings.LANGUAGES:
post_data = dict(language=lang_code, next='/views/')
response = self.client.post('/views/i18n/setlang/', data=post_data)
self.assertRedirects(response, 'http://testserver/views/')
self.assertEqual(self.client.session['django_language'], lang_code)
|
'The set_language view only redirects to the \'next\' argument if it is
"safe".'
| def test_setlang_unsafe_next(self):
| (lang_code, lang_name) = settings.LANGUAGES[0]
post_data = dict(language=lang_code, next='//unsafe/redirection/')
response = self.client.post('/views/i18n/setlang/', data=post_data)
self.assertEqual(response['Location'], 'http://testserver/')
self.assertEqual(self.client.session['django_language'], lang_code)
|
'The javascript_catalog can be deployed with language settings'
| def test_jsi18n(self):
| for lang_code in ['es', 'fr', 'ru']:
with override(lang_code):
catalog = gettext.translation('djangojs', locale_dir, [lang_code])
if six.PY3:
trans_txt = catalog.gettext('this is to be translated')
else:
trans_txt = catalog.ugettext('this is to be translated')
response = self.client.get('/views/jsi18n/')
self.assertContains(response, javascript_quote(trans_txt), 1)
if (lang_code == 'fr'):
self.assertContains(response, "['month name\x04May'] = 'mai';", 1)
|
'The javascript_catalog shouldn\'t load the fallback language in the
case that the current selected language is actually the one translated
from, and hence missing translation files completely.
This happens easily when you\'re translating from English to other
languages and you\'ve set settings.LANGUAGE_CODE to some other language
than English.'
| def test_jsi18n_with_missing_en_files(self):
| with self.settings(LANGUAGE_CODE='es'):
with override('en-us'):
response = self.client.get('/views/jsi18n/')
self.assertNotContains(response, 'esto tiene que ser traducido')
|
'Let\'s make sure that the fallback language is still working properly
in cases where the selected language cannot be found.'
| def test_jsi18n_fallback_language(self):
| with self.settings(LANGUAGE_CODE='fr'):
with override('fi'):
response = self.client.get('/views/jsi18n/')
self.assertContains(response, 'il faut le traduire')
|
'Check if the Javascript i18n view returns an empty language catalog
if the default language is non-English, the selected language
is English and there is not \'en\' translation available. See #13388,
#3594 and #13726 for more details.'
| def testI18NLanguageNonEnglishDefault(self):
| with self.settings(LANGUAGE_CODE='fr'):
with override('en-us'):
response = self.client.get('/views/jsi18n/')
self.assertNotContains(response, 'Choisir une heure')
|
'Same as above with the difference that there IS an \'en\' translation
available. The Javascript i18n view must return a NON empty language catalog
with the proper English translations. See #13726 for more details.'
| def test_nonenglish_default_english_userpref(self):
| extended_apps = (list(settings.INSTALLED_APPS) + ['regressiontests.views.app0'])
with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
with override('en-us'):
response = self.client.get('/views/jsi18n_english_translation/')
self.assertContains(response, javascript_quote('this app0 string is to be translated'))
|
'Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.'
| def testI18NLanguageNonEnglishFallback(self):
| with self.settings(LANGUAGE_CODE='fr'):
with override('none'):
response = self.client.get('/views/jsi18n/')
self.assertContains(response, 'Choisir une heure')
|
'Check if the JavaScript i18n view returns a complete language catalog
if the default language is en-us, the selected language has a
translation available and a catalog composed by djangojs domain
translations of multiple Python packages is requested. See #13388,
#3594 and #13514 for more details.'
| def testI18NLanguageEnglishDefault(self):
| extended_apps = (list(settings.INSTALLED_APPS) + ['regressiontests.views.app1', 'regressiontests.views.app2'])
with self.settings(LANGUAGE_CODE='en-us', INSTALLED_APPS=extended_apps):
with override('fr'):
response = self.client.get('/views/jsi18n_multi_packages1/')
self.assertContains(response, javascript_quote('il faut traduire cette cha\xc3\xaene de caract\xc3\xa8res de app1'))
|
'Similar to above but with neither default or requested language being
English.'
| def testI18NDifferentNonEnLangs(self):
| extended_apps = (list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4'])
with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
with override('es-ar'):
response = self.client.get('/views/jsi18n_multi_packages2/')
self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
|
'The static view can serve static media'
| def test_serve(self):
| media_files = ['file.txt', 'file.txt.gz']
for filename in media_files:
response = self.client.get(('/views/%s/%s' % (self.prefix, filename)))
response_content = ''.join(response)
response.close()
file_path = path.join(media_dir, filename)
with open(file_path, 'rb') as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response['Content-Length']))
self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None))
|
'Handle bogus If-Modified-Since values gracefully
Assume that a file is modified since an invalid timestamp as per RFC
2616, section 14.25.'
| def test_invalid_if_modified_since(self):
| file_name = 'file.txt'
invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT'
response = self.client.get(('/views/%s/%s' % (self.prefix, file_name)), HTTP_IF_MODIFIED_SINCE=invalid_date)
response_content = ''.join(response)
response.close()
with open(path.join(media_dir, file_name), 'rb') as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response['Content-Length']))
|
'Handle even more bogus If-Modified-Since values gracefully
Assume that a file is modified since an invalid timestamp as per RFC
2616, section 14.25.'
| def test_invalid_if_modified_since2(self):
| file_name = 'file.txt'
invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT'
response = self.client.get(('/views/%s/%s' % (self.prefix, file_name)), HTTP_IF_MODIFIED_SINCE=invalid_date)
response_content = ''.join(response)
response.close()
with open(path.join(media_dir, file_name), 'rb') as fp:
self.assertEqual(fp.read(), response_content)
self.assertEqual(len(response_content), int(response['Content-Length']))
|
'Test that a floating point mtime does not disturb was_modified_since.
(#18675)'
| def test_was_modified_since_fp(self):
| mtime = 1343416141.107817
header = http_date(mtime)
self.assertFalse(was_modified_since(header, mtime))
|
'Tests that redirecting to an IRI, requiring encoding before we use it
in an HTTP response, is handled correctly. In this case the arg to
HttpRedirect is ASCII but the current request path contains non-ASCII
characters so this test ensures the creation of the full path with a
base non-ASCII part is handled correctly.'
| def test_combining_redirect(self):
| response = self.client.get(u'/\u4e2d\u6587/')
self.assertRedirects(response, self.redirect_target)
|
'Tests that a non-ASCII argument to HttpRedirect is handled properly.'
| def test_nonascii_redirect(self):
| response = self.client.get(u'/nonascii_redirect/')
self.assertRedirects(response, self.redirect_target)
|
'Tests that a non-ASCII argument to HttpPermanentRedirect is handled
properly.'
| def test_permanent_nonascii_redirect(self):
| response = self.client.get(u'/permanent_nonascii_redirect/')
self.assertRedirects(response, self.redirect_target, status_code=301)
|
'A simple exception report can be generated'
| def test_request_and_exception(self):
| try:
request = self.rf.get(u'/test_view/')
raise ValueError(u"Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn(u'<h1>ValueError at /test_view/</h1>', html)
self.assertIn(u'<pre class="exception_value">Can't find my keys</pre>', html)
self.assertIn(u'<th>Request Method:</th>', html)
self.assertIn(u'<th>Request URL:</th>', html)
self.assertIn(u'<th>Exception Type:</th>', html)
self.assertIn(u'<th>Exception Value:</th>', html)
self.assertIn(u'<h2>Traceback ', html)
self.assertIn(u'<h2>Request information</h2>', html)
self.assertNotIn(u'<p>Request data not supplied</p>', html)
|
'An exception report can be generated without request'
| def test_no_request(self):
| try:
raise ValueError(u"Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn(u'<h1>ValueError</h1>', html)
self.assertIn(u'<pre class="exception_value">Can't find my keys</pre>', html)
self.assertNotIn(u'<th>Request Method:</th>', html)
self.assertNotIn(u'<th>Request URL:</th>', html)
self.assertIn(u'<th>Exception Type:</th>', html)
self.assertIn(u'<th>Exception Value:</th>', html)
self.assertIn(u'<h2>Traceback ', html)
self.assertIn(u'<h2>Request information</h2>', html)
self.assertIn(u'<p>Request data not supplied</p>', html)
|
'An exception report can be generated for just a request'
| def test_no_exception(self):
| request = self.rf.get(u'/test_view/')
reporter = ExceptionReporter(request, None, None, None)
html = reporter.get_traceback_html()
self.assertIn(u'<h1>Report at /test_view/</h1>', html)
self.assertIn(u'<pre class="exception_value">No exception supplied</pre>', html)
self.assertIn(u'<th>Request Method:</th>', html)
self.assertIn(u'<th>Request URL:</th>', html)
self.assertNotIn(u'<th>Exception Type:</th>', html)
self.assertNotIn(u'<th>Exception Value:</th>', html)
self.assertNotIn(u'<h2>Traceback ', html)
self.assertIn(u'<h2>Request information</h2>', html)
self.assertNotIn(u'<p>Request data not supplied</p>', html)
|
'A message can be provided in addition to a request'
| def test_request_and_message(self):
| request = self.rf.get(u'/test_view/')
reporter = ExceptionReporter(request, None, u"I'm a little teapot", None)
html = reporter.get_traceback_html()
self.assertIn(u'<h1>Report at /test_view/</h1>', html)
self.assertIn(u'<pre class="exception_value">I'm a little teapot</pre>', html)
self.assertIn(u'<th>Request Method:</th>', html)
self.assertIn(u'<th>Request URL:</th>', html)
self.assertNotIn(u'<th>Exception Type:</th>', html)
self.assertNotIn(u'<th>Exception Value:</th>', html)
self.assertNotIn(u'<h2>Traceback ', html)
self.assertIn(u'<h2>Request information</h2>', html)
self.assertNotIn(u'<p>Request data not supplied</p>', html)
|
'A simple exception report can be generated'
| def test_request_and_exception(self):
| try:
request = self.rf.get(u'/test_view/')
raise ValueError(u"Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
text = reporter.get_traceback_text()
self.assertIn(u'ValueError at /test_view/', text)
self.assertIn(u"Can't find my keys", text)
self.assertIn(u'Request Method:', text)
self.assertIn(u'Request URL:', text)
self.assertIn(u'Exception Type:', text)
self.assertIn(u'Exception Value:', text)
self.assertIn(u'Traceback:', text)
self.assertIn(u'Request information:', text)
self.assertNotIn(u'Request data not supplied', text)
|
'An exception report can be generated without request'
| def test_no_request(self):
| try:
raise ValueError(u"Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
text = reporter.get_traceback_text()
self.assertIn(u'ValueError', text)
self.assertIn(u"Can't find my keys", text)
self.assertNotIn(u'Request Method:', text)
self.assertNotIn(u'Request URL:', text)
self.assertIn(u'Exception Type:', text)
self.assertIn(u'Exception Value:', text)
self.assertIn(u'Traceback:', text)
self.assertIn(u'Request data not supplied', text)
|
'An exception report can be generated for just a request'
| def test_no_exception(self):
| request = self.rf.get(u'/test_view/')
reporter = ExceptionReporter(request, None, None, None)
text = reporter.get_traceback_text()
|
'A message can be provided in addition to a request'
| def test_request_and_message(self):
| request = self.rf.get(u'/test_view/')
reporter = ExceptionReporter(request, None, u"I'm a little teapot", None)
text = reporter.get_traceback_text()
|
'Asserts that potentially sensitive info are displayed in the response.'
| def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, u'cooked_eggs', status_code=500)
self.assertContains(response, u'scrambled', status_code=500)
self.assertContains(response, u'sauce', status_code=500)
self.assertContains(response, u'worcestershire', status_code=500)
if check_for_POST_params:
for (k, v) in self.breakfast_data.items():
self.assertContains(response, k, status_code=500)
self.assertContains(response, v, status_code=500)
|
'Asserts that certain sensitive info are not displayed in the response.'
| def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, u'cooked_eggs', status_code=500)
self.assertContains(response, u'scrambled', status_code=500)
self.assertContains(response, u'sauce', status_code=500)
self.assertNotContains(response, u'worcestershire', status_code=500)
if check_for_POST_params:
for (k, v) in self.breakfast_data.items():
self.assertContains(response, k, status_code=500)
self.assertContains(response, u'baked-beans-value', status_code=500)
self.assertContains(response, u'hash-brown-value', status_code=500)
self.assertNotContains(response, u'sausage-value', status_code=500)
self.assertNotContains(response, u'bacon-value', status_code=500)
|
'Asserts that no variables or POST parameters are displayed in the response.'
| def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, u'cooked_eggs', status_code=500)
self.assertNotContains(response, u'scrambled', status_code=500)
self.assertContains(response, u'sauce', status_code=500)
self.assertNotContains(response, u'worcestershire', status_code=500)
if check_for_POST_params:
for (k, v) in self.breakfast_data.items():
self.assertContains(response, k, status_code=500)
self.assertNotContains(response, v, status_code=500)
|
'Asserts that potentially sensitive info are displayed in the email report.'
| def verify_unsafe_email(self, view, check_for_POST_params=True):
| with self.settings(ADMINS=((u'Admin', u'[email protected]'),)):
mail.outbox = []
request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
body_plain = force_text(email.body)
self.assertNotIn(u'cooked_eggs', body_plain)
self.assertNotIn(u'scrambled', body_plain)
self.assertNotIn(u'sauce', body_plain)
self.assertNotIn(u'worcestershire', body_plain)
body_html = force_text(email.alternatives[0][0])
self.assertIn(u'cooked_eggs', body_html)
self.assertIn(u'scrambled', body_html)
self.assertIn(u'sauce', body_html)
self.assertIn(u'worcestershire', body_html)
if check_for_POST_params:
for (k, v) in self.breakfast_data.items():
self.assertIn(k, body_plain)
self.assertIn(v, body_plain)
self.assertIn(k, body_html)
self.assertIn(v, body_html)
|
'Asserts that certain sensitive info are not displayed in the email report.'
| def verify_safe_email(self, view, check_for_POST_params=True):
| with self.settings(ADMINS=((u'Admin', u'[email protected]'),)):
mail.outbox = []
request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
body_plain = force_text(email.body)
self.assertNotIn(u'cooked_eggs', body_plain)
self.assertNotIn(u'scrambled', body_plain)
self.assertNotIn(u'sauce', body_plain)
self.assertNotIn(u'worcestershire', body_plain)
body_html = force_text(email.alternatives[0][0])
self.assertIn(u'cooked_eggs', body_html)
self.assertIn(u'scrambled', body_html)
self.assertIn(u'sauce', body_html)
self.assertNotIn(u'worcestershire', body_html)
if check_for_POST_params:
for (k, v) in self.breakfast_data.items():
self.assertIn(k, body_plain)
self.assertIn(u'baked-beans-value', body_plain)
self.assertIn(u'hash-brown-value', body_plain)
self.assertIn(u'baked-beans-value', body_html)
self.assertIn(u'hash-brown-value', body_html)
self.assertNotIn(u'sausage-value', body_plain)
self.assertNotIn(u'bacon-value', body_plain)
self.assertNotIn(u'sausage-value', body_html)
self.assertNotIn(u'bacon-value', body_html)
|
'Asserts that no variables or POST parameters are displayed in the email report.'
| def verify_paranoid_email(self, view):
| with self.settings(ADMINS=((u'Admin', u'[email protected]'),)):
mail.outbox = []
request = self.rf.post(u'/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
body = force_text(email.body)
self.assertNotIn(u'cooked_eggs', body)
self.assertNotIn(u'scrambled', body)
self.assertNotIn(u'sauce', body)
self.assertNotIn(u'worcestershire', body)
for (k, v) in self.breakfast_data.items():
self.assertIn(k, body)
self.assertNotIn(v, body)
|
'Ensure that everything (request info and frame variables) can bee seen
in the default error reports for non-sensitive requests.'
| def test_non_sensitive_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(non_sensitive_view)
self.verify_unsafe_email(non_sensitive_view)
with self.settings(DEBUG=False):
self.verify_unsafe_response(non_sensitive_view)
self.verify_unsafe_email(non_sensitive_view)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.