New submission from Barry McLarnon <bmclar...@hotmail.co.uk>:

The error handling in mock.decorate_callable (3.5-3.7) and 
mock.decoration_helper (3.8-3.9) is incorrectly implemented. If the error 
handler is triggered in the loop, the `patching` variable is out of scope and 
raises an unhandled `UnboundLocalError` instead.

This happened as a result of a 3rd-party library that attempts to clear the 
`patchings` list of a decorated function. The below code shows a recreation of 
the incorrect error handling:

import functools
from unittest import mock


def is_valid():
    return True


def mock_is_valid():
    return False


def decorate(f):
    @functools.wraps(f)
    def decorate_wrapper(*args, **kwargs):
        # This happens in a 3rd-party library
        f.patchings = []
        return f(*args, **kwargs)

    return decorate_wrapper


@decorate
@mock.patch('test.is_valid', new=mock_is_valid)
def test_patch():
    raise Exception()

----------
components: Tests
messages: 365395
nosy: bmclarnon
priority: normal
severity: normal
status: open
title: Incorrect error handling in unittest.mock
type: behavior
versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue40126>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to