patch does not correctly restore state on objects without __dict__
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 77.2k
- フォーク
- 35.9k
- PR マージ指標
- PR 指標を取得中
説明
Bug report
Bug description:
from unittest.mock import patch
class Proxy(object):
config = {}
def __getattr__(self, name):
return self.config[name]
def __setattr__(self, name, value):
if name == 'config':
object.__setattr__(self, name, value)
return
self.config[name] = value
def __delattr__(self, name):
self.config[name] = 'DEFAULT'
p = Proxy()
p.a = True
print(p.a)
with patch('__main__.p.a', False):
print(p.a)
print(p.a)
Expected
True
False
True
Actual
True
False
DEFAULT
Note that this is a relatively niche issue, but for example in a config system (i.e. https://github.com/pytorch/pytorch/pull/140779), if you don't want to have a delete work, (i.e. have it set it back to a default value), the code in https://github.com/python/cpython/blob/94a7a4e22fb8f567090514785c69e65298acca42/Lib/unittest/mock.py#L1637 will call delattr, and then not call setattr, because it still has the attr.
Possible fixes:
If delattr throws (maybe NotImplementederror), call setattr instead (this is nice and explicit + removes the hacky workaround I have to do).
If the value after it's been deleted doesn't equal the original value, reassign it? (this might require objects to be comparable, not sure if that is already an issue here).
Either way I wanted to see if there was any interest in fixing this, and if anyone saw a solution that seemed reasonable enough.
CPython versions tested on:
3.12
Operating systems tested on:
Linux
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
issue の再現から始め、Lib/unittest/mock.py の 1637 行付近にある復元ロジックを調べてください。削除によって観測される値が変わる場合に、patch が dict を持たないオブジェクトの属性をどのように処理するかを比較してください。完了条件は、例で p.a が True に復元され、通常のオブジェクトに対する既存の動作が維持され、関連する unittest.mock テストに回帰テストのカバレッジが追加されていることです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- testing-qa
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100