Skip to content

Commit

Permalink
Add ipv6 testing support
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Jun 16, 2021
1 parent 7814f08 commit 563bab8
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
2 changes: 1 addition & 1 deletion sanic_testing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sanic_testing.manager import TestManager

__version__ = "0.5.0"
__version__ = "0.6.0"
__all__ = ("TestManager",)
25 changes: 19 additions & 6 deletions sanic_testing/testing.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import typing
from functools import partial
from ipaddress import IPv6Address, ip_address
from json import JSONDecodeError
from socket import socket
from socket import AF_INET6, SOCK_STREAM, socket
from types import SimpleNamespace

import httpx
import websockets
from sanic import Sanic # type: ignore
from sanic.asgi import ASGIApp # type: ignore
from sanic.exceptions import MethodNotSupported # type: ignore
from sanic.log import logger # type: ignore
from sanic.request import Request # type: ignore
from sanic.response import text # type: ignore
from websockets import connect

ASGI_HOST = "mockserver"
ASGI_PORT = 1234
Expand Down Expand Up @@ -76,7 +77,7 @@ async def _local_request(self, method: str, url: str, *args, **kwargs):

if method == "websocket":
ws_proxy = SimpleNamespace()
async with websockets.connect(url, *args, **kwargs) as websocket:
async with connect(url, *args, **kwargs) as websocket:
ws_proxy.ws = websocket
ws_proxy.opened = True
return ws_proxy
Expand Down Expand Up @@ -185,10 +186,22 @@ def _sanic_endpoint_test(
)
host, port = host or self.host, self.port
else:
sock = socket()
sock.bind((host or self.host, 0))
bind = host or self.host
ip = ip_address(bind)
if isinstance(ip, IPv6Address):
sock = socket(AF_INET6, SOCK_STREAM)
port = ASGI_PORT
else:
sock = socket()
port = 0
sock.bind((bind, port))
server_kwargs = dict(sock=sock, **server_kwargs)
host, port = sock.getsockname()

if isinstance(ip, IPv6Address):
host, port, _, _ = sock.getsockname()
host = f"[{host}]"
else:
host, port = sock.getsockname()
self.port = port

if uri.startswith(
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def open_local(paths, mode="r", encoding="utf8"):
}
requirements = [
"httpx==0.18.*",
"websockets>=8.1",
"websockets>=9.0",
]

tests_require = ["pytest", "sanic==21.3", "pytest-asyncio"]
Expand Down

0 comments on commit 563bab8

Please sign in to comment.