TurboGears / tg2

Python web framework with full-stack layer implemented on top of a microframework core with support for SQL DBMS, MongoDB and Pluggable Applications
http://www.turbogears.org/
Other
806 stars 78 forks source link

Error with objectproxy globals and current versions of mock #136

Closed brondsem closed 1 year ago

brondsem commented 1 year ago

When using mock library version 4+, or unittest.mock on newer versions of Python, patching a TG global like tg.request etc will error out if you don't have any global context objects set up. This is unexpected since the goal of patching an object is so that it isn't used at all.

import unittest
import mock

class TestURLs(unittest.TestCase):
    @mock.patch('tg.request')
    def test_it(self, mock_req):
        print("TEST!")

causes this error:

Traceback (most recent call last):
  File "/tmp-venv/lib/python3.7/site-packages/mock/mock.py", line 1422, in patched
    keywargs) as (newargs, newkeywargs):
  File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "/tmp-venv/lib/python3.7/site-packages/mock/mock.py", line 1402, in decoration_helper
    arg = exit_stack.enter_context(patching)
  File "/usr/local/lib/python3.7/contextlib.py", line 427, in enter_context
    result = _cm_type.__enter__(cm)
  File "/tmp-venv/lib/python3.7/site-packages/mock/mock.py", line 1514, in __enter__
    if spec is None and _is_async_obj(original):
  File "/tmp-venv/lib/python3.7/site-packages/mock/mock.py", line 61, in _is_async_obj
    return iscoroutinefunction(obj) or inspect.isawaitable(obj)
  File "/tmp-venv/lib/python3.7/site-packages/mock/backports.py", line 34, in iscoroutinefunction
    getattr(obj, '_is_coroutine', None) is _is_coroutine
  File "/tmp-venv/lib/python3.7/site-packages/tg/support/objectproxy.py", line 26, in __getattr__
    return getattr(self._current_obj(), attr)
  File "/tmp-venv/lib/python3.7/site-packages/tg/request_local.py", line 235, in _current_obj
    return getattr(context, self.name)
  File "/tmp-venv/lib/python3.7/site-packages/tg/support/objectproxy.py", line 26, in __getattr__
    return getattr(self._current_obj(), attr)
  File "/tmp-venv/lib/python3.7/site-packages/tg/support/registry.py", line 72, in _current_obj
    'thread' % self.____name__)
TypeError: No object (name: context) has been registered for this thread

I'll submit a merge request with a potential fix.