|
3 | 3 |
|
4 | 4 | """ Unit tests for zeroconf._services.browser. """ |
5 | 5 |
|
| 6 | +import asyncio |
6 | 7 | import logging |
7 | 8 | import os |
8 | 9 | import socket |
9 | 10 | import time |
10 | 11 | import unittest |
11 | 12 | from threading import Event |
12 | | -from typing import Iterable, Set |
| 13 | +from typing import Iterable, Set, cast |
13 | 14 | from unittest.mock import patch |
14 | 15 |
|
15 | 16 | import pytest |
@@ -75,6 +76,35 @@ class MyServiceListener(r.ServiceListener): |
75 | 76 | zc.close() |
76 | 77 |
|
77 | 78 |
|
| 79 | +def test_service_browser_cancel_context_manager(): |
| 80 | + """Test we can cancel a ServiceBrowser with it being used as a context manager.""" |
| 81 | + |
| 82 | + # instantiate a zeroconf instance |
| 83 | + zc = Zeroconf(interfaces=['127.0.0.1']) |
| 84 | + # start a browser |
| 85 | + type_ = "_hap._tcp.local." |
| 86 | + |
| 87 | + class MyServiceListener(r.ServiceListener): |
| 88 | + pass |
| 89 | + |
| 90 | + listener = MyServiceListener() |
| 91 | + |
| 92 | + browser = r.ServiceBrowser(zc, type_, None, listener) |
| 93 | + |
| 94 | + assert cast(bool, browser.done) is False |
| 95 | + |
| 96 | + with browser: |
| 97 | + pass |
| 98 | + |
| 99 | + # ensure call_soon_threadsafe in ServiceBrowser.cancel is run |
| 100 | + assert zc.loop is not None |
| 101 | + asyncio.run_coroutine_threadsafe(asyncio.sleep(0), zc.loop).result() |
| 102 | + |
| 103 | + assert cast(bool, browser.done) is True |
| 104 | + |
| 105 | + zc.close() |
| 106 | + |
| 107 | + |
78 | 108 | def test_service_browser_cancel_multiple_times_after_close(): |
79 | 109 | """Test we can cancel a ServiceBrowser multiple times after close.""" |
80 | 110 |
|
|
0 commit comments