Add mock to TestCase attribute in addition to parameter list

Bug #1629473 reported by Sye van der Veen
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
requests-mock
New
Undecided
Unassigned

Bug Description

Being able to decorate a `TestCase` class and have it apply automatically to all `test*` methods is pretty cool. However, it means modifying every method to accept the new argument. To me, it would make more sense to add the mock to the `TestCase` object itself (i.e. `self`, in the tests).

In my tests I've subclassed `requests_mock.Mocker` to add a new `attr` parameter that sits beside `kw`. I've included the code below. If you agree with this idea, it would be about a 6-line change to add this functionality to `requests_mock.Mocker` itself.

```python
class Mocker(requests_mock.Mocker):
    """A version of requests_mock.Mocker that sets an attribute on `self`. See here for original:
        https://github.com/openstack/requests-mock/blob/master/requests_mock/mocker.py
    """

    def __init__(self, **kwargs):
        self._attr = kwargs.pop('attr', None)
        super(Mocker, self).__init__(**kwargs)

    def copy(self):
        m = Mocker(
            kw=self._kw,
            attr=self._attr,
            real_http=self._real_http
        )
        return m

    def decorate_callable(self, func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            with self as m:
                if self._attr:
                    # The TestCase, i.e. `self` for the `test*` method, is the first arg
                    setattr(args[0], self._attr, m)
                elif self._kw:
                    kwargs[self._kw] = m
                else:
                    args = list(args)
                    args.append(m)

                return func(*args, **kwargs)

        return inner
```

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.