Skip to content

Commit 3be8813

Browse files
committed
Clarify unused stub error message
Fixes #125 Improve `check_used` messaging when a stub has been partially consumed. If a stub was never used, keep the existing "Unused stub" message. If some configured answers remain, report that not all answers were used and include an unused/used count summary.
1 parent ac6e6f2 commit 3be8813

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

mockito/invocation.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -715,9 +715,23 @@ def verify(self) -> None:
715715
self.verification.verify(self, self.used)
716716

717717
def check_used(self) -> None:
718-
if not self.allow_zero_invocations and self.used < len(self.answers):
718+
if self.allow_zero_invocations:
719+
return
720+
721+
expected_uses = len(self.answers)
722+
if self.used >= expected_uses:
723+
return
724+
725+
if self.used == 0:
719726
raise verificationModule.VerificationError(
720-
"\nUnused stub: %s" % self)
727+
"\nUnused stub: %s" % self
728+
)
729+
else:
730+
raise verificationModule.VerificationError(
731+
"\nOnly %s of %s answers were used for %s"
732+
% (self.used, expected_uses, self)
733+
)
734+
721735

722736
class StubbedPropertyAccess(StubbedInvocation):
723737
def ensure_mocked_object_has_attribute(self, method_name: str) -> None:

tests/instancemethods_test.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,9 +362,31 @@ def testFailSecondAnswerUnused(self):
362362
when(Dog).bark('Miau').thenReturn('Yep').thenReturn('Nop')
363363
rex = Dog()
364364
rex.bark('Miau')
365-
with pytest.raises(VerificationError):
365+
with pytest.raises(VerificationError) as exc:
366366
verifyStubbedInvocationsAreUsed(Dog)
367367

368+
assert str(exc.value) == (
369+
"\nOnly 1 of 2 answers were used for bark('Miau')"
370+
)
371+
372+
def testFailOnlyTwoOfThreeAnswersUsed(self):
373+
(
374+
when(Dog)
375+
.bark('Miau')
376+
.thenReturn('Yep')
377+
.thenReturn('Nop')
378+
.thenReturn('Nope')
379+
)
380+
rex = Dog()
381+
rex.bark('Miau')
382+
rex.bark('Miau')
383+
with pytest.raises(VerificationError) as exc:
384+
verifyStubbedInvocationsAreUsed(Dog)
385+
386+
assert str(exc.value) == (
387+
"\nOnly 2 of 3 answers were used for bark('Miau')"
388+
)
389+
368390

369391
@pytest.mark.usefixtures('unstub')
370392
class TestImplicitVerificationsUsingExpect:

0 commit comments

Comments
 (0)