canonical / operator

Pure Python framework for writing Juju charms
Apache License 2.0
244 stars 119 forks source link

event context is unset when it probably should be #1378

Open PietroPasotti opened 2 weeks ago

PietroPasotti commented 2 weeks ago

the Framework._event_context var is used by the framework to determine whether it should be validating relation data access and for example raise if a nonleader unit is trying to read data only a leader can access. _event_context is only set during _reemit, that is, when an event is actually being processed by the charm. This causes the following confusing situation during testing:

(supposing we don't have leadership)

class MyCharm:
    def __init__():
        relation.data[self.app]  # no problem: false positive
        ...
    def _on_foo_event(self, _):
        relation.data[self.app]  # problem

Note that this issue also (very probably) causes inconsistent tracebacks in production.

class MyCharm:
    def __init__():
        relation.data[self.app]  # ModelError
        ...
    def _on_foo_event(self, _):
        relation.data[self.app]  # RelationDataAccessError

A possible solution could be to enter the event context before the charm is initialized if we are testing (and set it to some "not-a-real-event" string as, at the point in time when we initialize the charm, we don't yet necessarily know what event we'll be emitting on it)

benhoyt commented 2 weeks ago

Yes, seems best to have RelationDataAccessError in both cases (init and otherwise). We'll look at this at some point.