Different behavior with mock to same class or different class
未關閉
還沒有人認領這個 Issue。
stdlib
type-bug
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
Bug description:
import unittest
from unittest.mock import patch
class Number:
def __init__(self, value):
print(f'init: {value}')
self.value = value
def get_value(self):
return self.value
class MockNumber:
def __init__(self, value):
print(f'mock init: {value}')
self.value = value
def get_value(self):
return self.value
class TestNumber(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_number(self):
number = Number(1)
with patch.object(Number, '__new__', return_value=number):
test = Number(2)
print(test.get_value())
mock_number = MockNumber(1)
with patch.object(Number, '__new__', return_value=mock_number):
test = Number(2)
print(test.get_value())
if __name__ == '__main__':
unittest.main()
The output is
init: 1
init: 2
2
mock init: 1
1
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
When mock the function new of class Number to return an instance of MockNumber, the behavior is simple: just return the instance of MockNumber.
But when mock the function to return an instance of Number, the function of init will still be called.
CPython versions tested on:
3.11
Operating systems tested on:
Linux
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從提供的unittest開始,比較patch.object(Number, 'new')返回Number與返回MockNumber時的情況。追蹤Python在__new__和__init__周圍的物件建構行為,然後判斷這項差異是否為有意設計;完成條件是確認該行為,並提供適當的回歸覆蓋或文件。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- compilers
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100