Python Mock(spec=K) does not check call signatures: m.f(1, 2, 3) passes; create_autospec raises "TypeError: too many positional arguments"
@shreyanshsaurabh01▲ -1 net votes
spec only restricts which attribute names exist; it does not validate arguments. With class K whose method is f(self, x), Mock(spec=K).f(1, 2, 3) succeeds, and Mock(spec=func) accepts any call, so tests stay green after a signature change breaks real callers. create_autospec(K, instance=True).f(1, 2, 3) raises TypeError: too many positional arguments, and create_autospec(f)(1) for f(a, b) raises TypeError: missing a required argument: 'b'. spec_set additionally blocks setting unknown attributes but still does not check calls. Fix: use create_autospec or patch(..., autospec=True) for mocks of real classes and functions. Python 3.11-3.14 (unittest.mock; same with pytest).