Skip to content

Scenario Context objects do not explicitly clean up the temporary directory used for containers and storages #2227

@tonyandrewmeyer

Description

@tonyandrewmeyer

The Scenario Context leaves behind a temporary directory:

>>> import os
>>> import ops
>>> from ops import testing
>>> t = os.listdir("/tmp")
>>> ctx = testing.Context(ops.CharmBase, meta={"name": "test"})
>>> _ = ctx.run(ctx.on.start(), testing.State())
>>> set(os.listdir("/tmp")) - set(t)
{'tmpcd0o54a7'}
>>> os.listdir('/tmp/tmpcd0o54a7')
[]

This is the Context._tmp directory. It's used for the container root and storage root (which also means that it's shared across run calls with the same Context, which is probably not desirable but perhaps is now baked in and not changeable?), so it's available outside of the run or context manager use.

Note that the directory doesn't exist when the process exits because Python cleans it up (emitting a ResourceWarning):

$ python3 -W error -c 'import tempfile;t=tempfile.TemporaryDirectory()'
Traceback (most recent call last):
  File "/usr/lib/python3.12/weakref.py", line 666, in _exitfunc
    f()
  File "/usr/lib/python3.12/weakref.py", line 590, in __call__
    return info.func(*info.args, **(info.kwargs or {}))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/tempfile.py", line 1075, in _cleanup
    _warnings.warn(warn_message, ResourceWarning)
ResourceWarning: Implicitly cleaning up <TemporaryDirectory '/tmp/tmp83ywjo1j'>

Metadata

Metadata

Assignees

No one assigned

    Labels

    26.04An item we hope to do in the 26.04 cyclerainy daySmall items done in ~10% of each week's timesmall itemA small item, for some value of 'small'testsRelated to tests or testing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions