Scenario Snapshot: unittest semi-auto generation, juju unit state insight, and more!

Scenario, the state-transition unit-testing framework for charms, comes with a cli tool called snapshot. Assuming you’ve pip-installed ops-scenario>=2.1.3, you should be able to reach the entry point by typing scenario snapshot in a shell.

Depending on your environment, you might need to tweak the PATH for scenario to be found. If you’re using multipass for example, you can run scenario by doing: /home/ubuntu/.local/bin/scenario.

Snapshot’s purpose is to gather the State data structure from a real, live charm running in some cloud your local juju client has access to. This is handy in case:

  • you want to write a test about the state the charm you’re developing is currently in
  • your charm is bork or in some inconsistent state, and you want to write a test to check the charm will handle it correctly the next time around (aka regression testing)
  • you are new to Scenario and want to quickly get started with a real-life example.

Example: gathering state from prometheus-k8s

Suppose you have a Juju model with a prometheus-k8s unit deployed as prometheus-k8s/0. If you type scenario snapshot prometheus-k8s/0, you will get a printout of the State object.

image

Copy-paste that in some file, import all you need from scenario, and you have a working State that you can .trigger() events from.

You can also pass a --format json | pytest flag to obtain respectively:

  • a jsonified State data structure (a plain dataclasses.asdict preprocessing step in fact), for portability

image

  • a full-fledged pytest test case (with imports and all), where you only have to fill in the charm type and the event that you wish to trigger.

image

[…]

image

Pipe that out to a file, and you have your unit-test!

Snapshot is fairly complete, only secrets still need to be implemented, but expect, out of the box:

  • config
  • networks
  • relations (and relation data)
  • containers for k8s charms
  • deferred events
  • stored state
  • status
  • model metadata
  • leadership

With some setup, you can also fetch files from kubernetes workload containers (think: application config files, etc…) and see them assigned automatically to the container mounts they’re at!

3 Likes