Login

Fuzzy testing with assertNumQueries

Author:
spookylukey
Posted:
January 12, 2011
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

Django 1.3 has an assertNumQueries method which will allows you to simply specify the number of queries you expect. Sometimes, however, specifying the exact number of queries is overkill, and makes the test too brittle. This code provides a way to make more forgiving tests.

See http://lukeplant.me.uk/blog/posts/fuzzy-testing-with-assertnumqueries/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Django 1.3 adds 'assertNumQueries'. Here is how to do fuzzy testing 
# with this function, using a clever subclass of int.

class FuzzyInt(int):
    def __new__(cls, lowest, highest):
        obj = super(FuzzyInt, cls).__new__(cls, highest)
        obj.lowest = lowest
        obj.highest = highest
        return obj

    def __eq__(self, other):
        return other >= self.lowest and other <= self.highest

    def __repr__(self):
        return "[%d..%d]" % (self.lowest, self.highest)

class MyFuncTests(TestCase):
    def test_1(self):
        # This will fail if the number of queries is outside the range 5 to 8 inclusive
        with self.assertNumQueries(FuzzyInt(5,8)):
            my_func(some_args)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

dudus (on January 20, 2011):

standard unittest already has assertAlmostEqual that seems to perform the same thing with a different approach.

#

Please login first before commenting.