Skip to content

support mock.patch.object on HasTraits - #984

Open
minrk wants to merge 1 commit into
ipython:mainfrom
minrk:mock-patch
Open

support mock.patch.object on HasTraits#984
minrk wants to merge 1 commit into
ipython:mainfrom
minrk:mock-patch

Conversation

@minrk

@minrk minrk commented Aug 28, 2026

Copy link
Copy Markdown
Member

mock.patch.object requires allowing delattr(has_traits, "trait") to work and hasattr(has_traits, "trait") to be False afterward.

This fixes mock.patch.object on HasTraits objects, with a previously failing test.

Without this patch, test fails with:

    def __exit__(self, *exc_info):
        """Undo the patch."""
        if not self.is_started:
            return

        if self.is_local and self.temp_original is not DEFAULT:
            setattr(self.target, self.attribute, self.temp_original)
        else:
>           delattr(self.target, self.attribute)
E           AttributeError: __delete__

Initially, I had it just clear the state without the sentinel (could be useful for restoring defaults, for example), but in that case hasattr(obj, 'trait') returns True and mock.patch doesn't restore the before-patch value, it always returns to the default state.

I think the logic in unittest.mock is wrong in how it decides whether to set the original value back, but this is what we need to work with the current standard library.

fixes mock.patch.object on HasTraits objects
@minrk minrk added the bug label Aug 28, 2026
@codecov

codecov Bot commented Aug 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.20%. Comparing base (5b398be) to head (f948af7).

Components Coverage Δ
traitlets 85.62% <100.00%> (+0.01%) ⬆️
tests 99.07% <100.00%> (+<0.01%) ⬆️

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant