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. Variable._resolve_lookup monkeypatch by showell 4 years, 5 months ago
  2. django-noserun for testing by mjt 5 years, 1 month ago
  3. Fail Faster: unsafe_test Management Command by majgis 1 year, 8 months ago
  4. HttpMethodsMiddleware by hawkeye 7 years ago
  5. testdata tag for templates by showell 4 years, 11 months ago

Comments

(Forgotten your password?)