系列: Go
go
83 行
· 更新于 2026-04-18
hashmap_test.go
Go/part2-dsa/ds/hashmap/hashmap_test.go
package hashmap
import (
"fmt"
"testing"
)
func TestPutGet(t *testing.T) {
m := New[string, int]()
if _, ok := m.Get("missing"); ok {
t.Fatal("expected !ok")
}
if _, existed := m.Put("a", 1); existed {
t.Fatal("did not expect existed=true")
}
if _, existed := m.Put("b", 2); existed {
t.Fatal("did not expect existed=true")
}
if old, existed := m.Put("a", 10); !existed || old != 1 {
t.Fatalf("Put existing key: old=%d existed=%v", old, existed)
}
if v, ok := m.Get("a"); !ok || v != 10 {
t.Errorf("Get a = %d %v", v, ok)
}
if v, ok := m.Get("b"); !ok || v != 2 {
t.Errorf("Get b = %d %v", v, ok)
}
if m.Len() != 2 {
t.Errorf("Len = %d", m.Len())
}
}
func TestDelete(t *testing.T) {
m := New[string, int]()
m.Put("a", 1)
m.Put("b", 2)
if old, ok := m.Delete("a"); !ok || old != 1 {
t.Fatalf("delete a: %d %v", old, ok)
}
if _, ok := m.Get("a"); ok {
t.Error("expected a to be gone")
}
if _, ok := m.Delete("nope"); ok {
t.Error("expected delete missing -> !ok")
}
if m.Len() != 1 {
t.Errorf("Len = %d", m.Len())
}
}
func TestResize(t *testing.T) {
m := New[int, int]()
const n = 1000
for i := 0; i < n; i++ {
m.Put(i, i*i)
}
if m.Len() != n {
t.Fatalf("Len = %d", m.Len())
}
for i := 0; i < n; i++ {
v, ok := m.Get(i)
if !ok || v != i*i {
t.Fatalf("Get(%d) = %d %v", i, v, ok)
}
}
}
func TestRange(t *testing.T) {
m := New[string, int]()
for i := 0; i < 5; i++ {
m.Put(fmt.Sprintf("k%d", i), i)
}
count := 0
m.Range(func(_ string, _ int) bool {
count++
return true
})
if count != 5 {
t.Errorf("Range visited %d, want 5", count)
}
}
相关文章
Go
go
更新于 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
阅读文章 →
Go
go
更新于 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
阅读文章 →
Go
go
更新于 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
阅读文章 →
Go
go
更新于 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
阅读文章 →
Go
go
更新于 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
阅读文章 →
Go
go
更新于 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
阅读文章 →