Skip to content

Commit 9dc472b

Browse files
authored
Add SSDPResponse::sendto method and tests (#96)
1 parent 04d3ce2 commit 9dc472b

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

ssdp/messages.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __str__(self):
5353

5454
def __bytes__(self):
5555
"""Return full HTTP message as bytes."""
56-
return self.__str__().encode().replace(b"\n", b"\r\n") + b"\r\n\r\n"
56+
return self.__str__().encode() + b"\r\n\r\n"
5757

5858

5959
class SSDPResponse(SSDPMessage):
@@ -74,6 +74,20 @@ def parse(cls, msg: str):
7474
version=version, status_code=status_code, reason=reason, headers=headers
7575
)
7676

77+
def sendto(self, transport, addr):
78+
"""
79+
Send response to a given address via given transport.
80+
81+
Args:
82+
transport (asyncio.DatagramTransport):
83+
Write transport to send the message on.
84+
addr (Tuple[str, int]):
85+
IP address and port pair to send the message to.
86+
87+
"""
88+
logger.debug("%s:%s - - %s", *(addr + (self,)))
89+
transport.sendto(bytes(self), addr)
90+
7791
def __str__(self):
7892
"""Return complete SSDP response."""
7993
lines = list()

tests/test_messages.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def test_str(self):
3939
def test_bytes(self):
4040
class MyMessage(SSDPMessage):
4141
def __str__(self):
42-
return "NOTIFY * HTTP/1.1\n" "Cache-Control: max-age=3600"
42+
return "NOTIFY * HTTP/1.1\r\n" "Cache-Control: max-age=3600"
4343

4444
msg = MyMessage()
4545
assert bytes(msg) == (
@@ -61,6 +61,16 @@ def test_str(self):
6161
"HTTP/1.1 200 OK\r\nLocation: http://192.168.1.239:55443"
6262
)
6363

64+
def test_sendto(self):
65+
transport = Mock()
66+
addr = network.MULTICAST_ADDRESS_IPV4, network.PORT
67+
SSDPResponse(
68+
200, "OK", headers=[("Location", "http://192.168.1.239:55443")]
69+
).sendto(transport, addr)
70+
transport.sendto.assert_called_once_with(
71+
b"HTTP/1.1 200 OK\r\nLocation: http://192.168.1.239:55443\r\n\r\n", addr
72+
)
73+
6474

6575
class TestSSDPRequest:
6676
def test_parse(self):

0 commit comments

Comments
 (0)