Skip to content

Commit 35e25fd

Browse files
authored
Reduce branching in DNSOutgoing.add_answer_at_time (#592)
1 parent 72032d6 commit 35e25fd

2 files changed

Lines changed: 45 additions & 4 deletions

File tree

tests/test_dns.py

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from typing import Dict, cast # noqa # used in type hints
1515

1616
import zeroconf as r
17-
from zeroconf import const
17+
from zeroconf import const, current_time_millis
1818
from zeroconf import (
1919
DNSHinfo,
2020
DNSText,
@@ -175,6 +175,48 @@ def test_parse_own_packet_response(self):
175175
assert len(generated.answers) == 1
176176
assert len(generated.answers) == len(parsed.answers)
177177

178+
def test_adding_empty_answer(self):
179+
generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE)
180+
generated.add_answer_at_time(
181+
None,
182+
0,
183+
)
184+
generated.add_answer_at_time(
185+
r.DNSService(
186+
"æøå.local.",
187+
const._TYPE_SRV,
188+
const._CLASS_IN | const._CLASS_UNIQUE,
189+
const._DNS_HOST_TTL,
190+
0,
191+
0,
192+
80,
193+
"foo.local.",
194+
),
195+
0,
196+
)
197+
parsed = r.DNSIncoming(generated.packets()[0])
198+
assert len(generated.answers) == 1
199+
assert len(generated.answers) == len(parsed.answers)
200+
201+
def test_adding_expired_answer(self):
202+
generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE)
203+
generated.add_answer_at_time(
204+
r.DNSService(
205+
"æøå.local.",
206+
const._TYPE_SRV,
207+
const._CLASS_IN | const._CLASS_UNIQUE,
208+
const._DNS_HOST_TTL,
209+
0,
210+
0,
211+
80,
212+
"foo.local.",
213+
),
214+
current_time_millis() + 1000000,
215+
)
216+
parsed = r.DNSIncoming(generated.packets()[0])
217+
assert len(generated.answers) == 0
218+
assert len(generated.answers) == len(parsed.answers)
219+
178220
def test_match_question(self):
179221
generated = r.DNSOutgoing(const._FLAGS_QR_QUERY)
180222
question = r.DNSQuestion("testname.local.", const._TYPE_SRV, const._CLASS_IN)

zeroconf/_dns.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -579,9 +579,8 @@ def add_answer(self, inp: DNSIncoming, record: DNSRecord) -> None:
579579

580580
def add_answer_at_time(self, record: Optional[DNSRecord], now: Union[float, int]) -> None:
581581
"""Adds an answer if it does not expire by a certain time"""
582-
if record is not None:
583-
if now == 0 or not record.is_expired(now):
584-
self.answers.append((record, now))
582+
if record is not None and (now == 0 or not record.is_expired(now)):
583+
self.answers.append((record, now))
585584

586585
def add_authorative_answer(self, record: DNSPointer) -> None:
587586
"""Adds an authoritative answer"""

0 commit comments

Comments
 (0)