Skip to content

Commit 5914e8e

Browse files
committed
Fix host string handling in save_key and add tests
Improves host string processing in save_key by correctly removing trailing '/api' and whitespace. Adds unit tests to verify correct host handling and extends HostFormatter test coverage.
1 parent df1ff98 commit 5914e8e

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

swanlab/package.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,9 @@ def save_key(username: str, password: str, host: str = None) -> bool:
195195
"""
196196
if host is None:
197197
host = get_host_api()
198-
host = host.rstrip("/api")
198+
host = host.rstrip()
199+
if host.endswith("/api"):
200+
host = host[:-4]
199201
path = get_nrc_path()
200202
if not os.path.exists(path):
201203
with open(path, "w") as f:

test/unit/test_package.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,18 @@ def test_ok(self):
167167
assert len(nrc.hosts) == 1
168168
assert nrc.authenticators(new_host) is not None
169169

170+
def test_host(self):
171+
"""
172+
测试 host 的正确性
173+
"""
174+
path = os.path.join(get_save_dir(), ".netrc")
175+
password = nanoid.generate()
176+
host = "https://swanlab.ai/api"
177+
P.save_key("user", password, host=host)
178+
nrc = netrc.netrc(path)
179+
assert len(nrc.hosts) == 1
180+
assert nrc.authenticators("https://swanlab.ai") is not None
181+
170182
def test_duplicate(self):
171183
"""
172184
测试重复保存,此时会略过保存,因此不会改变文件的修改时间
@@ -254,6 +266,7 @@ def test_ok(self):
254266
assert formatter.fmt("http://localhost") == "http://localhost"
255267
assert formatter.fmt("http://localhost:8080") == "http://localhost:8080"
256268
assert formatter.fmt("http://127.0.0.1:8080/") == "http://127.0.0.1:8080"
269+
assert formatter.fmt("http://swanlab.zenithal.ai") == "http://swanlab.zenithal.ai"
257270

258271
def test_value_err(self):
259272
formatter = P.HostFormatter()

0 commit comments

Comments
 (0)