python / python/cpython

unittest mock with __new__ function lead to TypeError

未关闭
#123,723 3 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从提供的 unittest 复现开始,检查对 Summary.new 进行 patch 时 unittest.mock.patch.object 的行为。在 mock.stop() 后复现该失败,然后跟踪原始构造函数行为是如何恢复的。完成的标准是停止 patch 后可以创建实例,并且该回归由测试覆盖。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
testing-qa
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
38/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。