Djangoists:
I often want to assert that a given method call (possibly a
client.post() call) creates one or a given number of records. This
assertion samples the high-water-mark in the primary keys of a given
QuerySet, calls your block, and then asserts that it could find your
records:
new_entry = self.assert_latest( my_blog.entries.all(),
lambda: client.post(uri,
entry_data) )
self.assert_contains('yack yack yack', new_entry.content)
Note, because the method takes a QuerySet, not a Model, it would fail
if client.post(), for example, were to create new Entry models but
neglect to attach them to my_blog.
Here's it's source, which is a stellar example of absolutely pristine
Python mastery. Really:
def assert_latest(self, query_set, lamb):
pks = list(query_set.values_list('pk', flat=True).order_by('-
pk'))
high_water_mark = (pks+[0])[0]
lamb()
# NOTE we ass-ume the database generates primary keys in monotonic
order.
# Don't use these techniques in production,
# or in the presence of a pro DBA
nu_records =
list(query_set.filter(pk__gt=high_water_mark).order_by('pk'))
if len(nu_records) == 1: return nu_records[0]
if nu_records: return nu_records # treating the returned
value as a scalar or list
# implicitly asserts it is
a scalar or list
source = open(lamb.func_code.co_filename, 'r').readlines()
[lamb.func_code.co_firstlineno - 1]
source = source.replace('lambda:', '').strip()
model_name = str(query_set.model)
self.assertFalse(True, 'The called block, `' + source +
'` should produce new ' + model_name +
' records')
Note:
- we return records sorted by pk - ostensibly their creation order
- if we have one record we return it as a scalar. This saves an
excess assert, afterwards, to detect there's only one
- we sample the lambda source, to make the error message as
clear as possible; this works best if the lambda's on its own
line
- every assert needs a deny; I will write deny_latest as soon as
a need appears.
--
Phlip
http://zeekland.zeroplayer.com/Pigleg_Too/1
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.