canonical / canonical/operator

os.getcwd() is not the charm root in ops[testing]

Open
#2,045 2 comments 1 reaction 1 assignee Claimed by @tonyandrewmeyer View on GitHub
27.04 rainy day roadmap
Dominant language
Python
Stars
267
Forks
136
Avg merge
1d 22h
Merged PRs (30d)
28

Description

When running in Juju, the current directory is the charm root at the start of a hook. When running in Scenario, the current directory is typically the root directory of the repository.

[This hockeypuck-k8s branch](https://github.com/canonical/hockeypuck-k8s-operator/pull/150) has examples of where this fails in a paas-charm.

* test_scenario fails because we [don't support charmcraft extensions in autoload](https://github.com/canonical/operator/issues/1699)
* ~test_scenario_one needs to have the context created as `Context(HockeypuckK8SCharm, meta=METADATA, actions=METADATA['actions'])` because [you can't pass all of charmcraft.yaml in the 'meta' argument](https://github.com/canonical/operator/issues/1424)~
* test_scenario_three needs to have all of the actions provided in the metadata, because otherwise `charm.on` won't have them all.
* test_scenario_two (and test_scenario_one and test_scenario_three once the above issues are fixed) fail because they cannot load the config.

paas_charm [loads the config.yaml file directly](https://github.com/canonical/paas-charm/blob/d101fb07594b9ae4d8740f747c1b9611abb8e074/src/paas_charm/utils.py#L100) rather than using `.config` (or the newer `.load_config`, which would provide the "load a secret as a secret" functionality that they're also implementing). This fails under Scenario because [it looks for config.yaml in the current directory](https://github.com/canonical/paas-charm/blob/d101fb07594b9ae4d8740f747c1b9611abb8e074/src/paas_charm/utils.py#L137), but Scenario carefully creates a temporary directory for executing the tests. For most charms, this would still work (if it fell back to `charmcraft.yaml`), because the YAML is just copied, but in this case the YAML is being explicitly provided because of the lack of extension support.

(I think there is some other issue with the tests, because some of them end up with `UnknownStatus` rather than the expected `BlockedStatus`, but I don't think that's an issue with Scenario).

A simple `os.chdir()` (and restoring the value after the yield) in `_runtime.py` fixed this for me locally, and should probably be a simple and safe fix, I think. It would be nicer if the charms didn't directly access the metadata files but it probably is reasonable that they do. The paas_charm code would be better if it used `Framework`'s `charm_dir` rather than relying on `getcwd()`, but I think it is also reasonable to expect the initial working directory to be the charm dir.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.