Skip to content

Commit

Permalink
Give Port.protocol a default value, as per review.
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyandrewmeyer committed Jun 6, 2024
1 parent c7c1277 commit 37df763
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
6 changes: 2 additions & 4 deletions scenario/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -865,22 +865,20 @@ def handle_path(self):
class Port:
"""Represents a port on the charm host."""

protocol: _RawPortProtocolLiteral
protocol: _RawPortProtocolLiteral = "tcp"
port: Optional[int] = None
"""The port to open. Required for TCP and UDP; not allowed for ICMP."""

# NOTE: This can be replaced with dataclass(kw_only=True) in Python 3.10+
def __init__(
self,
*,
protocol: _RawPortProtocolLiteral,
protocol: _RawPortProtocolLiteral = "tcp",
port: Optional[int] = None,
):
object.__setattr__(self, "protocol", protocol)
object.__setattr__(self, "port", port)

def __post_init__(self):
port = self.port
is_icmp = self.protocol == "icmp"
if port:
if is_icmp:
Expand Down
24 changes: 23 additions & 1 deletion tests/test_e2e/test_ports.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from ops import CharmBase, Framework, StartEvent, StopEvent

from scenario import Context, State
from scenario.state import Port
from scenario.state import Port, StateValidationError


class MyCharm(CharmBase):
Expand Down Expand Up @@ -37,3 +37,25 @@ def test_open_port(ctx):
def test_close_port(ctx):
out = ctx.run(ctx.on.stop(), State(opened_ports=[Port(protocol="tcp", port=42)]))
assert not out.opened_ports


def test_port_no_arguments():
with pytest.raises(StateValidationError):
Port()


def test_port_default_protocol():
port = Port(port=42)
assert port.protocol == "tcp"
assert port.port == 42


def test_port_port():
with pytest.raises(StateValidationError):
Port(protocol="icmp", port=42)
with pytest.raises(StateValidationError):
Port(protocol="tcp", port=0)
with pytest.raises(StateValidationError):
Port(protocol="udp", port=65536)
with pytest.raises(StateValidationError):
Port(protocol="tcp")

0 comments on commit 37df763

Please sign in to comment.