Skip to content

Commit

Permalink
Add support for honoring the host and port arguments in consul.Consul()
Browse files Browse the repository at this point in the history
  • Loading branch information
Emma May committed Nov 15, 2024
1 parent 7d93521 commit 5671705
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 4 deletions.
11 changes: 8 additions & 3 deletions consul/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ def close(self):
class Consul:
def __init__(
self,
host: str = "127.0.0.1",
port: int = 8500,
host: str | None = None,
port: int | None = None,
token: str | None = None,
scheme: str = "http",
consistency: str = "default",
Expand Down Expand Up @@ -106,13 +106,18 @@ def __init__(

# TODO: Status

if os.getenv("CONSUL_HTTP_ADDR"):
if os.getenv("CONSUL_HTTP_ADDR") and not (host or port):
try:
host, port = os.getenv("CONSUL_HTTP_ADDR").split(":") # type: ignore
except ValueError as err:
raise ConsulException(
f"CONSUL_HTTP_ADDR ({os.getenv('CONSUL_HTTP_ADDR')}) invalid, does not match <host>:<port>"
) from err
if not host:
host = "127.0.0.1"
if not port:
port = 8500

use_ssl = os.getenv("CONSUL_HTTP_SSL")
if use_ssl is not None:
scheme = "https" if use_ssl == "true" else "http"
Expand Down
81 changes: 80 additions & 1 deletion tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class HTTPClient:
def __init__(
self, host: Optional[str] = None, port: Optional[int] = None, scheme=None, verify: bool = True, cert=None
) -> None:
pass
self.host = host
self.port = int(port)

def get(self, callback, path, params=None, headers=None): # pylint: disable=unused-argument
return Request("get", path, params, headers, None)
Expand Down Expand Up @@ -70,6 +71,84 @@ def _should_support_meta(c: Consul) -> tuple[Callable[..., Any], ...]:
)


class TestBaseInit:
"""
Tests that connection arguments are handled
"""

@pytest.mark.parametrize(
("env", "host", "port", "want"),
[
(
None,
None,
None,
{
"host": "127.0.0.1",
"port": 8500,
},
),
(
"127.0.0.1:443",
None,
None,
{
"host": "127.0.0.1",
"port": 443,
},
),
(
None,
"consul.domain.tld",
None,
{
"host": "consul.domain.tld",
"port": 8500,
},
),
(
"consul.domain.tld:443",
"127.0.0.1",
None,
{
"host": "127.0.0.1",
"port": 8500,
},
),
(
"consul.domain.tld:443",
"127.0.0.1",
8080,
{
"host": "127.0.0.1",
"port": 8080,
},
),
(
"bad",
"127.0.0.1",
8080,
{
"host": "127.0.0.1",
"port": 8080,
},
),
],
)
def test_base_init(self, monkeypatch, env, host, port, want) -> None:
if env:
monkeypatch.setenv("CONSUL_HTTP_ADDR", env)
else:
try:
monkeypatch.delenv("CONSUL_HTTP_ADDR")
except KeyError:
pass

c = Consul(host=host, port=port)
assert c.http.host == want["host"]
assert c.http.port == want["port"]


class TestIndex:
"""
Tests read requests that should support blocking on an index
Expand Down

0 comments on commit 5671705

Please sign in to comment.