89 lines
2.2 KiB
Go
89 lines
2.2 KiB
Go
package tea
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func writeConfig(t *testing.T, content string) string {
|
|
t.Helper()
|
|
path := filepath.Join(t.TempDir(), "config.yml")
|
|
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
|
t.Fatalf("写 tea config 失败: %v", err)
|
|
}
|
|
return path
|
|
}
|
|
|
|
const sampleConfig = `logins:
|
|
- name: local
|
|
url: http://localhost:3000
|
|
token: tok-local
|
|
default: true
|
|
- name: work
|
|
url: https://Gitea.Example.com/
|
|
token: tok-work
|
|
`
|
|
|
|
func TestLoginForHostMatchesByHostname(t *testing.T) {
|
|
path := writeConfig(t, sampleConfig)
|
|
cases := map[string]string{
|
|
"gitea.example.com": "tok-work",
|
|
"GITEA.example.com": "tok-work",
|
|
"localhost": "tok-local",
|
|
}
|
|
for host, wantToken := range cases {
|
|
l, err := LoginForHost(path, host)
|
|
if err != nil {
|
|
t.Fatalf("LoginForHost(%s) 出错: %v", host, err)
|
|
}
|
|
if l == nil || l.Token != wantToken {
|
|
t.Fatalf("LoginForHost(%s) = %+v, want token %s", host, l, wantToken)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLoginForHostIgnoresDefaultLoginOfOtherHost(t *testing.T) {
|
|
path := writeConfig(t, sampleConfig)
|
|
l, err := LoginForHost(path, "git.other.org")
|
|
if err != nil {
|
|
t.Fatalf("没匹配上不应报错: %v", err)
|
|
}
|
|
if l != nil {
|
|
t.Fatalf("host 不匹配时不应回退到默认 login,得到 %+v", l)
|
|
}
|
|
}
|
|
|
|
func TestLoginForHostMissingConfigIsNotAnError(t *testing.T) {
|
|
l, err := LoginForHost(filepath.Join(t.TempDir(), "absent.yml"), "gitea.example.com")
|
|
if err != nil || l != nil {
|
|
t.Fatalf("没有 tea config 时应返回 (nil, nil),得到 (%+v, %v)", l, err)
|
|
}
|
|
}
|
|
|
|
func TestLoginForHostBadYAMLIsAnError(t *testing.T) {
|
|
path := writeConfig(t, "logins: [this is: not valid")
|
|
if _, err := LoginForHost(path, "gitea.example.com"); err == nil {
|
|
t.Fatal("tea config 解析失败应当报错")
|
|
}
|
|
}
|
|
|
|
func TestLoginForHostPrefersDefaultAmongSameHost(t *testing.T) {
|
|
path := writeConfig(t, `logins:
|
|
- name: bot
|
|
url: https://gitea.example.com
|
|
token: tok-bot
|
|
- name: me
|
|
url: https://gitea.example.com/
|
|
token: tok-me
|
|
default: true
|
|
`)
|
|
l, err := LoginForHost(path, "gitea.example.com")
|
|
if err != nil {
|
|
t.Fatalf("LoginForHost 出错: %v", err)
|
|
}
|
|
if l == nil || l.Name != "me" {
|
|
t.Fatalf("同一 host 有多条 login 时应取 default 那条,得到 %+v", l)
|
|
}
|
|
}
|