Skip to content

Commit

Permalink
use urllib to parse apiaddress
Browse files Browse the repository at this point in the history
- test ipv4 and ipv6
  • Loading branch information
barrettj12 committed Nov 8, 2023
1 parent 85946e1 commit d7d7b9f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import controlsocket
import logging
import secrets
import urllib.parse
import yaml
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider
from ops.charm import CharmBase
Expand Down Expand Up @@ -129,7 +130,10 @@ def api_port(self) -> str:
if not isinstance(api_addresses, List):
raise AgentConfException("agent.conf key 'apiaddresses' is not a list")

return api_addresses[0].split(':')[-1]
parsed_url = urllib.parse.urlsplit('//' + api_addresses[0])
if not parsed_url.port:
raise AgentConfException("api address doesn't include port")
return parsed_url.port

def ca_cert(self) -> str:
"""Return the controller's CA certificate."""
Expand Down
28 changes: 28 additions & 0 deletions tests/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@
cacert: fake
'''

agent_conf_ipv4 = '''
apiaddresses:
- "127.0.0.1:17070"
cacert: fake
'''

agent_conf_ipv6 = '''
apiaddresses:
- "[::1]:17070"
cacert: fake
'''


class TestCharm(unittest.TestCase):
def test_relation_joined(self):
Expand Down Expand Up @@ -132,6 +144,22 @@ def test_apiaddresses_missing_status(self, *_):
"can't read controller API port from agent.conf: agent.conf key 'apiaddresses' missing"
))

@patch("builtins.open", new_callable=mock_open, read_data=agent_conf_ipv4)
def test_apiaddresses_ipv4(self, _):
harness = Harness(JujuControllerCharm)
self.addCleanup(harness.cleanup)
harness.begin()

self.assertEqual(harness.charm.api_port(), 17070)

@patch("builtins.open", new_callable=mock_open, read_data=agent_conf_ipv6)
def test_apiaddresses_ipv6(self, _):
harness = Harness(JujuControllerCharm)
self.addCleanup(harness.cleanup)
harness.begin()

self.assertEqual(harness.charm.api_port(), 17070)


class MockBinding:
def __init__(self, address):
Expand Down

0 comments on commit d7d7b9f

Please sign in to comment.