X Tutup
The Wayback Machine - https://web.archive.org/web/20230815191715/https://github.com/python/cpython/issues/96485
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Magic Mock does not support fixed point notation in strings #96485

Closed
3 tasks done
carvajalluis opened this issue Sep 1, 2022 · 2 comments
Closed
3 tasks done

Magic Mock does not support fixed point notation in strings #96485

carvajalluis opened this issue Sep 1, 2022 · 2 comments
Labels
type-bug An unexpected behavior, bug, or error

Comments

@carvajalluis
Copy link

Bug report

  • a detailed description of the bug or problem you are having
  • output of pip list from the virtual environment you are using
  • python and operating system versions

Description and Example

Adding a decorator for timing sync/async functions in my python projects , when running pytest a error arises
time_it.py

def time_it(func):
    async def process(f, *args, **params):
        if asyncio.iscoroutinefunction(f):
            return await f(*args, **params)
        else:
            return f(*args, **params)

    @wraps(func)
    async def helper(*args, **params):
        try:
            start = time.time()
            return await process(func, *args, **params)
        finally:
            logging.debug(f'Function `{func.__name__}` took {time.time() - start:.2f} seconds')

    return helper

and adding some unit tests with pytest for it
test_time_it_.py

import asyncio
from unittest.mock import patch

from utils.time_it import time_it


async def coro(*args, **params):
    await asyncio.sleep(0)
    return 'foobar'


@patch('time.time')
def test_sync_time_it(mock_time, loop):
    async def do_test():
        mock_time.time.side_effect = [2, 10]
        expectation = 'foobar'
        func = lambda *args, **params: 'foobar'
        ti = time_it(func)
        result = await ti({}, {})
        assert result == expectation

    loop.run_until_complete(do_test())


@patch('time.time')
def test_async_time_it(mock_time, loop):
    async def do_test():
        mock_time.time.side_effect = [2, 10]
        expectation = 'foobar'
        ti = time_it(coro)
        result = await ti({}, {})
        assert result == expectation

    loop.run_until_complete(do_test())

running pytest i get this result

(venv) PS C:\git\serverless> coverage  run -m pytest

C:\Program Files\Python39\lib\asyncio\base_events.py:647: in run_until_complete
    return future.result()
tests\utils\test_time_it.py:31: in do_test
    result = await ti({}, {})
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

args = ({}, {}), params = {}, start = <MagicMock name='time()' id='2187073136000'>

    @wraps(func)
    async def helper(*args, **params):
        try:
            start = time.time()
            return await process(func, *args, **params)
        finally:
>           logging.debug(f'Function `{func.__name__}` took {time.time() - start:.2f} seconds')
E           TypeError: unsupported format string passed to MagicMock.__format__

utils\time_it.py:20: TypeError

Dependencies

(venv) PS C:\git\serverless> pip list
Package           Version
----------------- ---------
anyio             3.6.1
astroid           2.12.5
atomicwrites      1.4.1
attrs             22.1.0
boto3             1.24.64
botocore          1.27.64
certifi           2022.6.15
colorama          0.4.5
coverage          6.4.4
dill              0.3.5.1
dnspython         2.2.1
event-utils       4.0.10 // private package
h11               0.12.0
httpcore          0.15.0
httpx             0.23.0
idna              3.3
iniconfig         1.1.1
isort             5.10.1
jmespath          1.0.1
lazy-object-proxy 1.7.1
mccabe            0.7.0
motor             3.0.0
packaging         21.3
pip               21.3.1
platformdirs      2.5.2
pluggy            1.0.0
py                1.11.0
pydantic          1.10.1
pylint            2.15.0
pymongo           4.2.0
pyparsing         3.0.9
pytest            7.1.2
pytest-asyncio    0.19.0
pytest-mock       3.8.2
python-dateutil   2.8.2
pytz              2022.2.1
rfc3986           1.5.0
s3transfer        0.6.0
setuptools        60.2.0
six               1.16.0
sniffio           1.2.0
tomli             2.0.1
tomlkit           0.11.4
typing_extensions 4.3.0
urllib3           1.26.12
wheel             0.37.1
wrapt             1.14.1

OS version running pytest

(venv) PS C:\git\serverless> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
10     0      22000  0


(venv) PS C:\git\serverless> systeminfo /fo csv | ConvertFrom-Csv | select OS*, System*, Hotfix* | Format-List
                                                                              

OS Name             : Microsoft Windows 11 Pro
OS Version          : 10.0.22000 N/A Build 22000
OS Manufacturer     : Microsoft Corporation
OS Configuration    : Standalone Workstation
OS Build Type       : Multiprocessor Free
System Boot Time    : 9/1/2022, 9:45:04 AM
System Manufacturer : Dell Inc.
System Model        : Precision 5550
System Type         : x64-based PC
System Directory    : C:\WINDOWS\system32
System Locale       : en-us;English (United States)
Hotfix(s)           : 5 Hotfix(s) Installed.,[01]: KB5016594,[02]: KB5007575,[03]: KB5012170,[04]: KB5016629,[05]: KB5015898

(venv) PS C:\git\serverless> python --version 
Python 3.9.12
@carvajalluis carvajalluis added the type-bug An unexpected behavior, bug, or error label Sep 1, 2022
@tirkarthi
Copy link
Member

It's documented as not setup by default. You can try adding your implementation like below sample for __format__

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.NonCallableMagicMock

Magic methods that are supported but not setup by default in MagicMock are:
    __subclasses__
    __dir__
    __format__
    __get__, __set__ and __delete__
    __reversed__ and __missing__
    __reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__
    __getformat__ and __setformat__
python
Python 3.11.0a6 (main, Mar  8 2022, 17:42:42) [GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> f"{m:.2f}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to MagicMock.__format__
>>> m.__format__ = lambda obj, format_spec: repr(obj)
>>> f"{m:.2f}"
"<MagicMock id='140674518595792'>"

@carvajalluis
Copy link
Author

today I should be able to invest a couple of minutes with this, thankyou you for the prompt response!

@sobolevn sobolevn closed this as not planned Won't fix, can't repro, duplicate, stale Nov 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

3 participants
X Tutup