safe(r) monkeypatching scheme for django testing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    from django.core import urlresolvers
    from django.utils import timesince

    # set up a class to turn off reverse via monkeypatch...we do not care about its details
    class PatchReverse:
        def __enter__(self):
            self.old_method = urlresolvers.reverse
            urlresolvers.reverse = lambda view_name, args, kwargs, current_app: 'stub'

        def __exit__(self, type, value, traceback):
            urlresolvers.reverse = self.old_method

    # nor do we care about the details of timesince...note that we monkeypatch the one
    # from django.utils...it is harder to monkeypatch template filters due to django
    # registration mechanisms
    class PatchTimeSince:
        def __enter__(self):
            self.old_method = timesince.timesince
            timesince.timesince = lambda arg: 'stub'

        def __exit__(self, type, value, traceback):
            timesince.timesince = self.old_method

    with PatchReverse():
        with PatchTimeSince():
            from django.template.loader import render_to_string
            render_to_string('activity.html', dict(...))

More like this

  1. Django and Twill by spookylukey 5 years, 2 months ago
  2. Character encoding fix by mrtron 5 years, 1 month ago
  3. Variable._resolve_lookup monkeypatch by showell 3 years, 6 months ago
  4. Monkey-patch Django's test client to return WSGIRequest objects by robmadole 2 years, 6 months ago
  5. TaggedManager and TaggedQuerySet with chainable tagged() methods implemented with django-tagging by fish2000 3 years, 3 months ago

Comments

(Forgotten your password?)