8000 Use pytest-socket to ensure no tests are performing io by sdb9696 · Pull Request #1133 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

Use pytest-socket to ensure no tests are performing io #1133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions kasa/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import sys
import warnings
from unittest.mock import MagicMock, patch

Expand Down Expand Up @@ -87,6 +88,11 @@ def pytest_addoption(parser):
def pytest_collection_modifyitems(config, items):
if not config.getoption("--ip"):
print("Testing against fixtures.")
# pytest_socket doesn't work properly in windows with asyncio
# fine to disable as other platforms will pickup any issues.
if sys.platform == "win32":
for item in items:
item.add_marker(pytest.mark.enable_socket)
else:
print("Running against ip %s" % config.getoption("--ip"))
requires_dummy = pytest.mark.skip(
Expand All @@ -95,18 +101,45 @@ def pytest_collection_modifyitems(config, items):
for item in items:
if "requires_dummy" in item.keywords:
item.add_marker(requires_dummy)
else:
item.add_marker(pytest.mark.enable_socket)


@pytest.fixture(autouse=True, scope="session")
def asyncio_sleep_fixture(): # noqa: PT004
def asyncio_sleep_fixture(request): # noqa: PT004
"""Patch sleep to prevent tests actually waiting."""
orig_asyncio_sleep = asyncio.sleep

async def _asyncio_sleep(*_, **__):
await orig_asyncio_sleep(0)

with patch("asyncio.sleep", side_effect=_asyncio_sleep):
if request.config.getoption("--ip"):
yield
else:
with patch("asyncio.sleep", side_effect=_asyncio_sleep):
yield


@pytest.fixture(autouse=True, scope="session")
def mock_datagram_endpoint(request): # noqa: PT004
"""Mock create_datagram_endpoint so it doesn't perform io."""

async def _create_datagram_endpoint(protocol_factory, *_, **__):
protocol = protocol_factory()
transport = MagicMock()
try:
return transport, protocol
finally:
protocol.connection_made(transport)

if request.config.getoption("--ip"):
yield
else:
with patch(
"asyncio.BaseEventLoop.create_datagram_endpoint",
side_effect=_create_datagram_endpoint,
):
yield


# allow mocks to be awaited
Expand Down
14 changes: 8 additions & 6 deletions kasa/tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,13 @@ async def test_discover_single_hostname(discovery_mock, mocker):
async def test_discover_credentials(mocker):
"""Make sure that discover gives credentials precedence over un and pw."""
host = "127.0.0.1"
mocker.patch("kasa.discover._DiscoverProtocol.wait_for_discovery_to_complete")

def mock_discover(self, *_, **__):
async def mock_discover(self, *_, **__):
self.discovered_devices = {host: MagicMock()}
self.seen_hosts.add(host)
self._handle_discovered_event()

mocker.patch.object(_DiscoverProtocol, "do_discover", mock_discover)
mocker.patch.object(_DiscoverProtocol, "do_discover", new=mock_discover)
dp = mocker.spy(_DiscoverProtocol, "__init__")

# Only credentials passed
Expand All @@ -197,12 +198,13 @@ def mock_discover(self, *_, **__):
async def test_discover_single_credentials(mocker):
"""Make sure that discover_single gives credentials precedence over un and pw."""
host = "127.0.0.1"
mocker.patch("kasa.discover._DiscoverProtocol.wait_for_discovery_to_complete")

def mock_discover(self, *_, **__):
async def mock_discover(self, *_, **__):
self.discovered_devices = {host: MagicMock()}
self.seen_hosts.add(host)
self._handle_discovered_event()

mocker.patch.object(_DiscoverProtocol, "do_discover", mock_discover)
mocker.patch.object(_DiscoverProtocol, "do_discover", new=mock_discover)
dp = mocker.spy(_DiscoverProtocol, "__init__")

# Only credentials passed
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dev-dependencies = [
"pytest-freezer~=0.4",
"mypy~=1.0",
"pytest-xdist>=3.6.1",
"pytest-socket>=0.7.0",
]


Expand Down Expand Up @@ -108,6 +109,7 @@ markers = [
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
timeout = 10
addopts = "--disable-socket --allow-unix-socket"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--allow-unix-socket required for asyncio


[tool.doc8]
paths = ["docs"]
Expand Down
14 changes: 14 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
0