Skip to content

unittest mock with __new__ function lead to TypeErrorΒ #123723

@Fryguest

Description

@Fryguest

Bug report

Bug description:

import unittest
from unittest.mock import patch

class Summary(object):

    def __init__(self, path):
        print("Summary init")

    def __del__(self):
        print("Summary del")

    def get_summary(self):
        print("get_summary")

class MockSummary:
    def __init__(self, path):
        print("Mock start")

    def __del__(self):
        print("Mock end")

    def get_summary(self):
        print("mock_get_summary")

class TestSummary(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_summary(self):
        # 1 success case
        summary1 = Summary('path')
        summary1.get_summary()

        # 2 mock case
        mock = patch.object(Summary, '__new__', return_value=MockSummary('path'))
        mock.start()
        summary2 = Summary('path')
        summary2.get_summary()
        mock.stop()

        # 3 fail case
        summary3 = Summary('path')
        summary3.get_summary()

if __name__ == '__main__':
    unittest.main()

When run this python unittest file, it turns out with error:

Summary init
get_summary
Mock start
mock_get_summary
ESummary del

======================================================================
ERROR: test_summary (__main__.TestSummary.test_summary)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/admin/workspace/python/testSummaryAll.py", line 46, in test_summary
    summary3 = Summary('path')
               ^^^^^^^^^^^^^^^
TypeError: object.__new__() takes exactly one argument (the type to instantiate)

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
Mock end

All the instance init after the mock stop will be failed.

CPython versions tested on:

3.11

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions