|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | + |
| 5 | +""" Unit tests for zeroconf.core """ |
| 6 | + |
| 7 | +import itertools |
| 8 | +import logging |
| 9 | +import threading |
| 10 | +import time |
| 11 | +import unittest |
| 12 | +import unittest.mock |
| 13 | + |
| 14 | + |
| 15 | +import pytest |
| 16 | +import zeroconf as r |
| 17 | +from zeroconf import core |
| 18 | + |
| 19 | +log = logging.getLogger('zeroconf') |
| 20 | +original_logging_level = logging.NOTSET |
| 21 | + |
| 22 | + |
| 23 | +@pytest.fixture(autouse=True) |
| 24 | +def verify_threads_ended(): |
| 25 | + """Verify that the threads are not running after the test.""" |
| 26 | + threads_before = frozenset(threading.enumerate()) |
| 27 | + yield |
| 28 | + threads = frozenset(threading.enumerate()) - threads_before |
| 29 | + assert not threads |
| 30 | + |
| 31 | + |
| 32 | +def setup_module(): |
| 33 | + global original_logging_level |
| 34 | + original_logging_level = log.level |
| 35 | + log.setLevel(logging.DEBUG) |
| 36 | + |
| 37 | + |
| 38 | +def teardown_module(): |
| 39 | + if original_logging_level != logging.NOTSET: |
| 40 | + log.setLevel(original_logging_level) |
| 41 | + |
| 42 | + |
| 43 | +class TestReaper(unittest.TestCase): |
| 44 | + @unittest.mock.patch.object(core, "_CACHE_CLEANUP_INTERVAL", 10) |
| 45 | + def test_reaper(self): |
| 46 | + zeroconf = core.Zeroconf(interfaces=['127.0.0.1']) |
| 47 | + cache = zeroconf.cache |
| 48 | + original_entries = list(itertools.chain(*[cache.entries_with_name(name) for name in cache.names()])) |
| 49 | + record_with_10s_ttl = r.DNSAddress('a', r._TYPE_SOA, r._CLASS_IN, 10, b'a') |
| 50 | + record_with_1s_ttl = r.DNSAddress('a', r._TYPE_SOA, r._CLASS_IN, 1, b'b') |
| 51 | + zeroconf.cache.add(record_with_10s_ttl) |
| 52 | + zeroconf.cache.add(record_with_1s_ttl) |
| 53 | + entries_with_cache = list(itertools.chain(*[cache.entries_with_name(name) for name in cache.names()])) |
| 54 | + time.sleep(1) |
| 55 | + with zeroconf.engine.condition: |
| 56 | + zeroconf.engine._notify() |
| 57 | + time.sleep(0.1) |
| 58 | + entries = list(itertools.chain(*[cache.entries_with_name(name) for name in cache.names()])) |
| 59 | + zeroconf.close() |
| 60 | + assert entries != original_entries |
| 61 | + assert entries_with_cache != original_entries |
| 62 | + assert record_with_10s_ttl in entries |
| 63 | + assert record_with_1s_ttl not in entries |
0 commit comments