Merge ~axino/charm-canonical-is-reviewbot/+git/charm-canonical-is-reviewbot:axino into charm-canonical-is-reviewbot:main

Proposed by Junien F
Status: Merged
Approved by: Junien F
Approved revision: 971bbcf68ce690076c434f1c292c6d71ddd11148
Merged at revision: 9763831c66fb1ba544d4b657de58f8bac49ee979
Proposed branch: ~axino/charm-canonical-is-reviewbot/+git/charm-canonical-is-reviewbot:axino
Merge into: charm-canonical-is-reviewbot:main
Diff against target: 735 lines (+663/-0)
12 files modified
.gitignore (+9/-0)
CONTRIBUTING.md (+33/-0)
LICENSE (+202/-0)
README.md (+7/-0)
charmcraft.yaml (+11/-0)
config.yaml (+30/-0)
metadata.yaml (+18/-0)
pyproject.toml (+39/-0)
requirements.txt (+1/-0)
src/charm.py (+121/-0)
tests/unit/test_charm.py (+108/-0)
tox.ini (+84/-0)
Reviewer Review Type Date Requested Status
Barry Price Approve
Review via email: mp+436216@code.launchpad.net

Commit message

initial commit

To post a comment you must log in.
Revision history for this message
Barry Price (barryprice) wrote :

Tiny nitpick inline, LGTM otherwise

review: Approve
Revision history for this message
Junien F (axino) wrote :

Fixed, thanks !

Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

This merge proposal is being monitored by mergebot. Change the status to Approved to merge.

Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

Change has no commit message, setting status to needs review.

Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

Change successfully merged at revision 9763831c66fb1ba544d4b657de58f8bac49ee979

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
diff --git a/.gitignore b/.gitignore
0new file mode 1006440new file mode 100644
index 0000000..a26d707
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
1venv/
2build/
3*.charm
4.tox/
5.coverage
6__pycache__/
7*.py[cod]
8.idea
9.vscode/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
0new file mode 10064410new file mode 100644
index 0000000..2969183
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,33 @@
1# Contributing
2
3To make contributions to this charm, you'll need a working [development setup](https://juju.is/docs/sdk/dev-setup).
4
5You can use the environments created by `tox` for development:
6
7```shell
8tox --notest -e unit
9source .tox/unit/bin/activate
10```
11
12## Testing
13
14This project uses `tox` for managing test environments. There are some pre-configured environments
15that can be used for linting and formatting code when you're preparing contributions to the charm:
16
17```shell
18tox -e fmt # update your code according to linting rules
19tox -e lint # code style
20tox -e unit # unit tests
21tox -e integration # integration tests
22tox # runs 'lint' and 'unit' environments
23```
24
25## Build the charm
26
27Build the charm in this git repository using:
28
29```shell
30charmcraft pack
31```
32
33<!-- You may want to include any contribution/style guidelines in this document>
diff --git a/LICENSE b/LICENSE
0new file mode 10064434new file mode 100644
index 0000000..ecbda55
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
1
2 Apache License
3 Version 2.0, January 2004
4 http://www.apache.org/licenses/
5
6 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
8 1. Definitions.
9
10 "License" shall mean the terms and conditions for use, reproduction,
11 and distribution as defined by Sections 1 through 9 of this document.
12
13 "Licensor" shall mean the copyright owner or entity authorized by
14 the copyright owner that is granting the License.
15
16 "Legal Entity" shall mean the union of the acting entity and all
17 other entities that control, are controlled by, or are under common
18 control with that entity. For the purposes of this definition,
19 "control" means (i) the power, direct or indirect, to cause the
20 direction or management of such entity, whether by contract or
21 otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 outstanding shares, or (iii) beneficial ownership of such entity.
23
24 "You" (or "Your") shall mean an individual or Legal Entity
25 exercising permissions granted by this License.
26
27 "Source" form shall mean the preferred form for making modifications,
28 including but not limited to software source code, documentation
29 source, and configuration files.
30
31 "Object" form shall mean any form resulting from mechanical
32 transformation or translation of a Source form, including but
33 not limited to compiled object code, generated documentation,
34 and conversions to other media types.
35
36 "Work" shall mean the work of authorship, whether in Source or
37 Object form, made available under the License, as indicated by a
38 copyright notice that is included in or attached to the work
39 (an example is provided in the Appendix below).
40
41 "Derivative Works" shall mean any work, whether in Source or Object
42 form, that is based on (or derived from) the Work and for which the
43 editorial revisions, annotations, elaborations, or other modifications
44 represent, as a whole, an original work of authorship. For the purposes
45 of this License, Derivative Works shall not include works that remain
46 separable from, or merely link (or bind by name) to the interfaces of,
47 the Work and Derivative Works thereof.
48
49 "Contribution" shall mean any work of authorship, including
50 the original version of the Work and any modifications or additions
51 to that Work or Derivative Works thereof, that is intentionally
52 submitted to Licensor for inclusion in the Work by the copyright owner
53 or by an individual or Legal Entity authorized to submit on behalf of
54 the copyright owner. For the purposes of this definition, "submitted"
55 means any form of electronic, verbal, or written communication sent
56 to the Licensor or its representatives, including but not limited to
57 communication on electronic mailing lists, source code control systems,
58 and issue tracking systems that are managed by, or on behalf of, the
59 Licensor for the purpose of discussing and improving the Work, but
60 excluding communication that is conspicuously marked or otherwise
61 designated in writing by the copyright owner as "Not a Contribution."
62
63 "Contributor" shall mean Licensor and any individual or Legal Entity
64 on behalf of whom a Contribution has been received by Licensor and
65 subsequently incorporated within the Work.
66
67 2. Grant of Copyright License. Subject to the terms and conditions of
68 this License, each Contributor hereby grants to You a perpetual,
69 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 copyright license to reproduce, prepare Derivative Works of,
71 publicly display, publicly perform, sublicense, and distribute the
72 Work and such Derivative Works in Source or Object form.
73
74 3. Grant of Patent License. Subject to the terms and conditions of
75 this License, each Contributor hereby grants to You a perpetual,
76 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 (except as stated in this section) patent license to make, have made,
78 use, offer to sell, sell, import, and otherwise transfer the Work,
79 where such license applies only to those patent claims licensable
80 by such Contributor that are necessarily infringed by their
81 Contribution(s) alone or by combination of their Contribution(s)
82 with the Work to which such Contribution(s) was submitted. If You
83 institute patent litigation against any entity (including a
84 cross-claim or counterclaim in a lawsuit) alleging that the Work
85 or a Contribution incorporated within the Work constitutes direct
86 or contributory patent infringement, then any patent licenses
87 granted to You under this License for that Work shall terminate
88 as of the date such litigation is filed.
89
90 4. Redistribution. You may reproduce and distribute copies of the
91 Work or Derivative Works thereof in any medium, with or without
92 modifications, and in Source or Object form, provided that You
93 meet the following conditions:
94
95 (a) You must give any other recipients of the Work or
96 Derivative Works a copy of this License; and
97
98 (b) You must cause any modified files to carry prominent notices
99 stating that You changed the files; and
100
101 (c) You must retain, in the Source form of any Derivative Works
102 that You distribute, all copyright, patent, trademark, and
103 attribution notices from the Source form of the Work,
104 excluding those notices that do not pertain to any part of
105 the Derivative Works; and
106
107 (d) If the Work includes a "NOTICE" text file as part of its
108 distribution, then any Derivative Works that You distribute must
109 include a readable copy of the attribution notices contained
110 within such NOTICE file, excluding those notices that do not
111 pertain to any part of the Derivative Works, in at least one
112 of the following places: within a NOTICE text file distributed
113 as part of the Derivative Works; within the Source form or
114 documentation, if provided along with the Derivative Works; or,
115 within a display generated by the Derivative Works, if and
116 wherever such third-party notices normally appear. The contents
117 of the NOTICE file are for informational purposes only and
118 do not modify the License. You may add Your own attribution
119 notices within Derivative Works that You distribute, alongside
120 or as an addendum to the NOTICE text from the Work, provided
121 that such additional attribution notices cannot be construed
122 as modifying the License.
123
124 You may add Your own copyright statement to Your modifications and
125 may provide additional or different license terms and conditions
126 for use, reproduction, or distribution of Your modifications, or
127 for any such Derivative Works as a whole, provided Your use,
128 reproduction, and distribution of the Work otherwise complies with
129 the conditions stated in this License.
130
131 5. Submission of Contributions. Unless You explicitly state otherwise,
132 any Contribution intentionally submitted for inclusion in the Work
133 by You to the Licensor shall be under the terms and conditions of
134 this License, without any additional terms or conditions.
135 Notwithstanding the above, nothing herein shall supersede or modify
136 the terms of any separate license agreement you may have executed
137 with Licensor regarding such Contributions.
138
139 6. Trademarks. This License does not grant permission to use the trade
140 names, trademarks, service marks, or product names of the Licensor,
141 except as required for reasonable and customary use in describing the
142 origin of the Work and reproducing the content of the NOTICE file.
143
144 7. Disclaimer of Warranty. Unless required by applicable law or
145 agreed to in writing, Licensor provides the Work (and each
146 Contributor provides its Contributions) on an "AS IS" BASIS,
147 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 implied, including, without limitation, any warranties or conditions
149 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 PARTICULAR PURPOSE. You are solely responsible for determining the
151 appropriateness of using or redistributing the Work and assume any
152 risks associated with Your exercise of permissions under this License.
153
154 8. Limitation of Liability. In no event and under no legal theory,
155 whether in tort (including negligence), contract, or otherwise,
156 unless required by applicable law (such as deliberate and grossly
157 negligent acts) or agreed to in writing, shall any Contributor be
158 liable to You for damages, including any direct, indirect, special,
159 incidental, or consequential damages of any character arising as a
160 result of this License or out of the use or inability to use the
161 Work (including but not limited to damages for loss of goodwill,
162 work stoppage, computer failure or malfunction, or any and all
163 other commercial damages or losses), even if such Contributor
164 has been advised of the possibility of such damages.
165
166 9. Accepting Warranty or Additional Liability. While redistributing
167 the Work or Derivative Works thereof, You may choose to offer,
168 and charge a fee for, acceptance of support, warranty, indemnity,
169 or other liability obligations and/or rights consistent with this
170 License. However, in accepting such obligations, You may act only
171 on Your own behalf and on Your sole responsibility, not on behalf
172 of any other Contributor, and only if You agree to indemnify,
173 defend, and hold each Contributor harmless for any liability
174 incurred by, or claims asserted against, such Contributor by reason
175 of your accepting any such warranty or additional liability.
176
177 END OF TERMS AND CONDITIONS
178
179 APPENDIX: How to apply the Apache License to your work.
180
181 To apply the Apache License to your work, attach the following
182 boilerplate notice, with the fields enclosed by brackets "[]"
183 replaced with your own identifying information. (Don't include
184 the brackets!) The text should be enclosed in the appropriate
185 comment syntax for the file format. We also recommend that a
186 file or class name and description of purpose be included on the
187 same "printed page" as the copyright notice for easier
188 identification within third-party archives.
189
190 Copyright 2022 Ubuntu
191
192 Licensed under the Apache License, Version 2.0 (the "License");
193 you may not use this file except in compliance with the License.
194 You may obtain a copy of the License at
195
196 http://www.apache.org/licenses/LICENSE-2.0
197
198 Unless required by applicable law or agreed to in writing, software
199 distributed under the License is distributed on an "AS IS" BASIS,
200 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 See the License for the specific language governing permissions and
202 limitations under the License.
diff --git a/README.md b/README.md
0new file mode 100644203new file mode 100644
index 0000000..6cca19d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,7 @@
1# charm-canonical-is-reviewbot
2
3Charmhub package name: mm-reviewbot-charmers-canonical-is-reviewbot
4More information: https://charmhub.io/mm-reviewbot-charmers-canonical-is-reviewbot
5
6This charm deploys the Canonical IS reviewbot, which helps doing reviews of
7Launchpad merge proposals for the IS team.
diff --git a/charmcraft.yaml b/charmcraft.yaml
0new file mode 1006448new file mode 100644
index 0000000..900d34a
--- /dev/null
+++ b/charmcraft.yaml
@@ -0,0 +1,11 @@
1# This file configures Charmcraft.
2# See https://juju.is/docs/sdk/charmcraft-config for guidance.
3
4type: charm
5bases:
6 - build-on:
7 - name: ubuntu
8 channel: "22.04"
9 run-on:
10 - name: ubuntu
11 channel: "22.04"
diff --git a/config.yaml b/config.yaml
0new file mode 10064412new file mode 100644
index 0000000..79e1a0d
--- /dev/null
+++ b/config.yaml
@@ -0,0 +1,30 @@
1# This file defines charm config options, and populates the Configure tab on Charmhub.
2# If your charm does not require configuration options, delete this file entirely.
3#
4# See https://juju.is/docs/config for guidance.
5
6options:
7 launchpad_secret:
8 description: "Launchpad credential secret"
9 default: ""
10 type: string
11 launchpad_token:
12 description: "Launchpad credential token"
13 default: ""
14 type: string
15 mattermost_token:
16 description: "Mattermost API token"
17 default: ""
18 type: string
19 mattermost_channel:
20 description: "Mattermost channel in which to expect review requests"
21 default: ""
22 type: string
23 mattermost_url:
24 description: "Mattermost URL"
25 default: ""
26 type: string
27 mattermost_team:
28 description: "Mattermost team"
29 default: ""
30 type: string
diff --git a/metadata.yaml b/metadata.yaml
0new file mode 10064431new file mode 100644
index 0000000..83d6842
--- /dev/null
+++ b/metadata.yaml
@@ -0,0 +1,18 @@
1name: canonical-is-reviewbot
2display-name: Mattermost Review Bot
3summary: MatterMost Review Bot charm
4maintainers:
5 - https://launchpad.net/~mm-reviewbot-charmers
6description: |
7 A charm which deploys Mattermost Review Bot on kubernetes.
8 Mattermost is a flexible, open source messaging platform that enables
9 secure team collaboration.
10 This bot allows reviewing Launchpad merge proposals on Mattermost
11containers:
12 reviewbot:
13 resource: reviewbot-image
14resources:
15 reviewbot-image:
16 type: oci-image
17 description: Reviewbot docker image
18 auto-fetch: true
diff --git a/pyproject.toml b/pyproject.toml
0new file mode 10064419new file mode 100644
index 0000000..3f51442
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,39 @@
1# Testing tools configuration
2[tool.coverage.run]
3branch = true
4
5[tool.coverage.report]
6show_missing = true
7
8[tool.pytest.ini_options]
9minversion = "6.0"
10log_cli_level = "INFO"
11
12# Formatting tools configuration
13[tool.black]
14line-length = 99
15target-version = ["py38"]
16
17# Linting tools configuration
18[tool.ruff]
19line-length = 99
20select = ["E", "W", "F", "C", "N", "D", "I001"]
21extend-ignore = [
22 "D203",
23 "D204",
24 "D213",
25 "D215",
26 "D400",
27 "D404",
28 "D406",
29 "D407",
30 "D408",
31 "D409",
32 "D413",
33]
34ignore = ["E501", "D107"]
35extend-exclude = ["__pycache__", "*.egg_info"]
36per-file-ignores = {"tests/*" = ["D100","D101","D102","D103","D104"]}
37
38[tool.ruff.mccabe]
39max-complexity = 10
diff --git a/requirements.txt b/requirements.txt
0new file mode 10064440new file mode 100644
index 0000000..56f5f64
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1 @@
1ops >= 1.5.0
diff --git a/src/charm.py b/src/charm.py
0new file mode 1007552new file mode 100755
index 0000000..e2bf66d
--- /dev/null
+++ b/src/charm.py
@@ -0,0 +1,121 @@
1#!/usr/bin/env python3
2# Copyright 2022 Ubuntu
3# See LICENSE file for licensing details.
4#
5# Learn more at: https://juju.is/docs/sdk
6
7"""Charm the service.
8
9Refer to the following post for a quick-start guide that will help you
10develop a new k8s charm using the Operator Framework:
11
12https://discourse.charmhub.io/t/4208
13"""
14
15import logging
16
17from ops.charm import CharmBase
18from ops.main import main
19from ops.model import ActiveStatus, BlockedStatus, WaitingStatus
20
21# Log messages can be retrieved using juju debug-log
22logger = logging.getLogger(__name__)
23
24VALID_LOG_LEVELS = ["info", "debug", "warning", "error", "critical"]
25
26
27class CharmReviewbotCharm(CharmBase):
28 """Charm the service."""
29
30 def __init__(self, *args):
31 super().__init__(*args)
32 self.framework.observe(self.on.reviewbot_pebble_ready, self._on_reviewbot_pebble_ready)
33 self.framework.observe(self.on.config_changed, self._on_config_changed)
34
35 def _missing_config(self):
36 # All config options must be set
37 missing_config = []
38 for k, v in self.model.config.items():
39 if not v:
40 missing_config.append(k)
41 return missing_config
42
43 def _on_reviewbot_pebble_ready(self, event):
44 """Define and start a workload using the Pebble API.
45
46 Change this example to suit your needs. You'll need to specify the right entrypoint and
47 environment configuration for your specific workload.
48
49 Learn more about interacting with Pebble at at https://juju.is/docs/sdk/pebble.
50 """
51 missing_config = self._missing_config()
52 if missing_config:
53 self.unit.status = BlockedStatus(f"required config not set: '{missing_config}'")
54 return
55 # Get a reference the container attribute on the PebbleReadyEvent
56 container = event.workload
57 # Add initial Pebble config layer using the Pebble API
58 container.add_layer("reviewbot", self._pebble_layer, combine=True)
59 # Make Pebble reevaluate its plan, ensuring any services are started if enabled.
60 container.replan()
61 # Learn more about statuses in the SDK docs:
62 # https://juju.is/docs/sdk/constructs#heading--statuses
63 self.unit.status = ActiveStatus()
64
65 def _get_reviewbot_env_config(self) -> dict:
66 """Return an envConfig with configuration."""
67 env_config = {
68 "REVIEWBOT_LP_SECRET": self.config["launchpad_secret"],
69 "REVIEWBOT_LP_TOKEN": self.config["launchpad_token"],
70 "REVIEWBOT_MM_CHANNEL": self.config["mattermost_channel"],
71 "REVIEWBOT_MM_TEAM": self.config["mattermost_team"],
72 "REVIEWBOT_MM_TOKEN": self.config["mattermost_token"],
73 "REVIEWBOT_MM_URL": self.config["mattermost_url"],
74 "HOME": "/home/reviewbot", # work around https://github.com/canonical/pebble/issues/183
75 }
76
77 return env_config
78
79 def _on_config_changed(self, event):
80 """Handle changed configuration."""
81 missing_config = self._missing_config()
82 if missing_config:
83 self.unit.status = BlockedStatus(f"required config not set: '{missing_config}'")
84 return
85
86 # The config is good, so update the configuration of the workload
87 container = self.unit.get_container("reviewbot")
88 # Verify that we can connect to the Pebble API in the workload container
89 if container.can_connect():
90 # Push an updated layer with the new config
91 container.add_layer("reviewbot", self._pebble_layer, combine=True)
92 container.replan()
93
94 self.unit.status = ActiveStatus()
95 else:
96 # We were unable to connect to the Pebble API, so we defer this event
97 event.defer()
98 self.unit.status = WaitingStatus("waiting for Pebble API")
99
100 @property
101 def _pebble_layer(self):
102 """Return a dictionary representing a Pebble layer."""
103 return {
104 "summary": "reviewbot layer",
105 "description": "pebble config layer for reviewbot",
106 "services": {
107 "reviewbot": {
108 "override": "replace",
109 "summary": "reviewbot",
110 "user": "reviewbot",
111 "group": "reviewbot",
112 "command": "/app/bot.py",
113 "startup": "enabled",
114 "environment": self._get_reviewbot_env_config(),
115 },
116 },
117 }
118
119
120if __name__ == "__main__": # pragma: nocover
121 main(CharmReviewbotCharm)
diff --git a/tests/unit/test_charm.py b/tests/unit/test_charm.py
0new file mode 100644122new file mode 100644
index 0000000..3399c04
--- /dev/null
+++ b/tests/unit/test_charm.py
@@ -0,0 +1,108 @@
1# Copyright 2022 Ubuntu
2# See LICENSE file for licensing details.
3#
4# Learn more about testing at: https://juju.is/docs/sdk/testing
5
6import unittest
7
8import ops.testing
9from charm import CharmReviewbotCharm
10from ops.model import ActiveStatus, BlockedStatus, WaitingStatus
11from ops.testing import Harness
12
13
14class TestCharm(unittest.TestCase):
15 base_config = {
16 "launchpad_secret": "lps",
17 "launchpad_token": "lpt",
18 "mattermost_token": "mmtok",
19 "mattermost_channel": "mmc",
20 "mattermost_url": "mmu",
21 "mattermost_team": "mmt",
22 }
23
24 def setUp(self):
25 # Enable more accurate simulation of container networking.
26 # For more information, see https://juju.is/docs/sdk/testing#heading--simulate-can-connect
27 ops.testing.SIMULATE_CAN_CONNECT = True
28 self.addCleanup(setattr, ops.testing, "SIMULATE_CAN_CONNECT", False)
29
30 self.harness = Harness(CharmReviewbotCharm)
31 self.addCleanup(self.harness.cleanup)
32 self.harness.begin()
33
34 def test_reviewbot_pebble_ready(self):
35 # Expected plan after Pebble ready with default config
36 expected_plan = {
37 "services": {
38 "reviewbot": {
39 "override": "replace",
40 "summary": "reviewbot",
41 "command": "/app/bot.py",
42 "startup": "enabled",
43 "environment": {
44 "REVIEWBOT_LP_SECRET": "lps",
45 "REVIEWBOT_LP_TOKEN": "lpt",
46 "REVIEWBOT_MM_CHANNEL": "mmc",
47 "REVIEWBOT_MM_TEAM": "mmt",
48 "REVIEWBOT_MM_TOKEN": "mmtok",
49 "REVIEWBOT_MM_URL": "mmu",
50 "HOME": "/home/reviewbot",
51 },
52 "user": "reviewbot",
53 "group": "reviewbot",
54 }
55 },
56 }
57 # Simulate the container coming up and emission of pebble-ready event
58 self.harness.update_config(self.base_config)
59 self.harness.container_pebble_ready("reviewbot")
60 # Get the plan now we've run PebbleReady
61 updated_plan = self.harness.get_container_pebble_plan("reviewbot").to_dict()
62 # Check we've got the plan we expected
63 self.assertEqual(expected_plan, updated_plan)
64 # Check the service was started
65 service = self.harness.model.unit.get_container("reviewbot").get_service("reviewbot")
66 self.assertTrue(service.is_running())
67 # Ensure we set an ActiveStatus with no message
68 self.assertEqual(self.harness.model.unit.status, ActiveStatus())
69
70 def test_reviewbot_pebble_ready_no_config(self):
71 # Expect an empty plan when a config item is missing
72 expected_plan = {}
73 # Simulate the container coming up and emission of pebble-ready event
74 self.harness.container_pebble_ready("reviewbot")
75 # Get the plan now we've run PebbleReady
76 updated_plan = self.harness.get_container_pebble_plan("reviewbot").to_dict()
77 # Check we've got the plan we expected
78 self.assertEqual(expected_plan, updated_plan)
79 # Ensure we got a BlockedStatus
80 self.assertIsInstance(self.harness.model.unit.status, BlockedStatus)
81
82 def test_config_changed_valid_can_connect(self):
83 # Ensure the simulated Pebble API is reachable
84 self.harness.set_can_connect("reviewbot", True)
85 # Trigger a config-changed event with an updated value
86 changed_config = self.base_config.copy()
87 changed_config["launchpad_secret"] = "CHANGED"
88 self.harness.update_config(changed_config)
89 # Get the plan now we've run PebbleReady
90 updated_plan = self.harness.get_container_pebble_plan("reviewbot").to_dict()
91 updated_env = updated_plan["services"]["reviewbot"]["environment"]
92 # Check the config change was effective
93 self.assertEqual(updated_env["REVIEWBOT_LP_SECRET"], "CHANGED")
94 self.assertEqual(self.harness.model.unit.status, ActiveStatus())
95
96 def test_config_changed_valid_cannot_connect(self):
97 # Trigger a config-changed event with an updated value
98 self.harness.update_config(self.base_config)
99 # Check the charm is in WaitingStatus
100 self.assertIsInstance(self.harness.model.unit.status, WaitingStatus)
101
102 def test_config_changed_invalid(self):
103 # Ensure the simulated Pebble API is reachable
104 self.harness.set_can_connect("reviewbot", True)
105 # Trigger a config-changed event with an updated value
106 self.harness.update_config({})
107 # Check the charm is in BlockedStatus
108 self.assertIsInstance(self.harness.model.unit.status, BlockedStatus)
diff --git a/tox.ini b/tox.ini
0new file mode 100644109new file mode 100644
index 0000000..d4284f8
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,84 @@
1# Copyright 2022 Ubuntu
2# See LICENSE file for licensing details.
3
4[tox]
5skipsdist=True
6skip_missing_interpreters = True
7envlist = fmt, lint, unit
8
9[vars]
10src_path = {toxinidir}/src/
11tst_path = {toxinidir}/tests/
12;lib_path = {toxinidir}/lib/charms/operator_name_with_underscores
13all_path = {[vars]src_path} {[vars]tst_path}
14
15[testenv]
16setenv =
17 PYTHONPATH = {toxinidir}:{toxinidir}/lib:{[vars]src_path}
18 PYTHONBREAKPOINT=pdb.set_trace
19 PY_COLORS=1
20passenv =
21 PYTHONPATH
22 CHARM_BUILD_DIR
23 MODEL_SETTINGS
24
25[testenv:fmt]
26description = Apply coding style standards to code
27deps =
28 black
29 ruff
30commands =
31 black {[vars]all_path}
32 ruff --fix {[vars]all_path}
33
34[testenv:lint]
35description = Check code against coding style standards
36deps =
37 black
38 ruff
39 codespell
40commands =
41 # uncomment the following line if this charm owns a lib
42 # codespell {[vars]lib_path}
43 codespell {toxinidir} \
44 --skip {toxinidir}/.git \
45 --skip {toxinidir}/.tox \
46 --skip {toxinidir}/build \
47 --skip {toxinidir}/lib \
48 --skip {toxinidir}/venv \
49 --skip {toxinidir}/.mypy_cache \
50 --skip {toxinidir}/icon.svg
51
52 ruff {[vars]all_path}
53 black --check --diff {[vars]all_path}
54
55[testenv:unit]
56description = Run unit tests
57deps =
58 pytest
59 coverage[toml]
60 -r{toxinidir}/requirements.txt
61commands =
62 coverage run --source={[vars]src_path} \
63 -m pytest \
64 --ignore={[vars]tst_path}integration \
65 --tb native \
66 -v \
67 -s \
68 {posargs}
69 coverage report
70
71[testenv:integration]
72description = Run integration tests
73deps =
74 pytest
75 juju
76 pytest-operator
77 -r{toxinidir}/requirements.txt
78commands =
79 pytest -v \
80 -s \
81 --tb native \
82 --ignore={[vars]tst_path}unit \
83 --log-cli-level=INFO \
84 {posargs}

Subscribers

People subscribed via source and target branches