syslog2irc.network.parse_port()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 18
nop 1
dl 0
loc 23
rs 8.5666
c 0
b 0
f 0
ccs 17
cts 17
cp 1
crap 6
1
"""
2
syslog2irc.network
3
~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2007-2021 Jochen Kupperschmidt
6
:License: MIT, see LICENSE for details.
7
"""
8
9 1
from dataclasses import dataclass
10 1
from enum import Enum
11
12
13 1
TransportProtocol = Enum('TransportProtocol', ['TCP', 'UDP'])
14
15
16 1
@dataclass(frozen=True, order=True)
17
class Port:
18
    """A network port."""
19
20 1
    number: int
21 1
    transport_protocol: TransportProtocol
22
23
24 1
def format_port(port: Port) -> str:
25
    """Return string representation for port."""
26 1
    return f'{port.number}/{port.transport_protocol.name.lower()}'
27
28
29 1
def parse_port(value: str) -> Port:
30
    """Extract port number and protocol from string representation."""
31 1
    tokens = value.split('/', maxsplit=1)
32 1
    if len(tokens) != 2:
33 1
        raise ValueError(f'Invalid port string "{value}"')
34
35 1
    number_str = tokens[0]
36 1
    try:
37 1
        number = int(number_str)
38 1
    except ValueError:
39 1
        raise ValueError(f'Invalid port number "{number_str}"')
40 1
    if number < 1 or number > 65535:
41 1
        raise ValueError(f'Invalid port number "{number_str}"')
42
43 1
    transport_protocol_str = tokens[1]
44 1
    try:
45 1
        transport_protocol = TransportProtocol[transport_protocol_str.upper()]
46 1
    except KeyError:
47 1
        raise ValueError(
48
            f'Unknown transport protocol "{transport_protocol_str}"'
49
        )
50
51
    return Port(number=number, transport_protocol=transport_protocol)
52