close
Skip to content

fix!: ensure that the testing context manager is exited when an exception occurs#2117

Merged
tonyandrewmeyer merged 2 commits intocanonical:mainfrom
tonyandrewmeyer:record-run-calls
Oct 19, 2025
Merged

fix!: ensure that the testing context manager is exited when an exception occurs#2117
tonyandrewmeyer merged 2 commits intocanonical:mainfrom
tonyandrewmeyer:record-run-calls

Conversation

@tonyandrewmeyer
Copy link
Copy Markdown
Collaborator

@tonyandrewmeyer tonyandrewmeyer commented Oct 17, 2025

Currently, if testing.Context is used as a context manager, and an exception occurs during the event, proper cleanup is not done. This is noticeable in two ways in particular:

  • Exceptions aren't wrapped in UncaughtCharmError.
  • The environment is not cleaned up. This can manifest in a cascading failure of tests if OPERATOR_DISPATCH is left set.

We currently manually call the __exit__ function of one of the context managers when wrapping up. However, if an exception occurs, we never reach that point, and the context manager is left un-exited (you'll also often see errors when exiting Python, because it doesn't like being left in that state). The PR fixes this by also calling __exit__ if exiting the Context context manager, and it's handling an exception.

Many thanks to @james-garner-canonical for helping figure out where things were wrong wrong and a good way to fix this.

Fixes #1926

Copy link
Copy Markdown
Contributor

@james-garner-canonical james-garner-canonical left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM -- quite a mission to figure out that +2/-3 though, wasn't it!

Do you think it's worth adding the 'environment gets cleaned up' tests for non-crashy charms too?

@tonyandrewmeyer
Copy link
Copy Markdown
Collaborator Author

Do you think it's worth adding the 'environment gets cleaned up' tests for non-crashy charms too?

I thought there was already one for this, but can't find it, so yes I've added two more.

Copy link
Copy Markdown
Collaborator

@benhoyt benhoyt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks guys for the analysis and fix!

@tonyandrewmeyer tonyandrewmeyer merged commit 3ac3706 into canonical:main Oct 19, 2025
53 checks passed
@tonyandrewmeyer tonyandrewmeyer deleted the record-run-calls branch October 19, 2025 19:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OPERATOR_DISPATCH should be reset after every Context.run

3 participants