Skip to content

Commit

Permalink
fix: Have httpstan use an unused port
Browse files Browse the repository at this point in the history
Closes #94
  • Loading branch information
riddell-stan committed Dec 16, 2019
1 parent 59e59cd commit 9bd2b33
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
11 changes: 10 additions & 1 deletion stan/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Common routines"""
import asyncio
import contextlib
import socket
import threading
import time
import typing
Expand All @@ -19,7 +20,15 @@ class ServerAddress(typing.NamedTuple):
@contextlib.contextmanager
def httpstan_server():
"""Manage starting and stopping an httpstan web gateway."""
host, port = "127.0.0.1", 8080

def unused_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port

host, port = "127.0.0.1", unused_port()
runner = aiohttp.web.AppRunner(httpstan.app.make_app())
loop = asyncio.get_event_loop()

Expand Down
12 changes: 5 additions & 7 deletions tests/test_httpstan_unused_port.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import socket

import requests
import pytest

import stan

Expand All @@ -10,11 +9,10 @@ def test_httpstan_port_conflict():
s = socket.socket()
try:
s.bind(("", 8080))
with pytest.raises(OSError) as excinfo:
with stan.common.httpstan_server() as server:
host, port = server.host, server.port
response = requests.get(f"http://{host}:{port}/v1/health")
assert response.status_code == 200
assert "address already in use" in str(excinfo.value)
with stan.common.httpstan_server() as server:
host, port = server.host, server.port
response = requests.get(f"http://{host}:{port}/v1/health")
assert response.status_code == 200
assert port != 8080
finally:
s.close()

0 comments on commit 9bd2b33

Please sign in to comment.