github.com/sunvim/utils@v0.1.0/stringsbank/stringsbank_test.go (about) 1 package stringbank 2 3 import ( 4 "fmt" 5 "runtime" 6 "strconv" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestStringbank(t *testing.T) { 14 sb := Stringbank{} 15 16 s1 := sb.Save("hello") 17 s2 := sb.Save("goodbye") 18 s3 := sb.Save("cheese") 19 20 assert.Equal(t, "hello", sb.Get(s1)) 21 assert.Equal(t, "goodbye", sb.Get(s2)) 22 assert.Equal(t, "cheese", sb.Get(s3)) 23 } 24 25 func TestStringbankSize(t *testing.T) { 26 sb := Stringbank{} 27 assert.Zero(t, sb.Size()) 28 sb.Save("hello") 29 assert.Equal(t, stringbankSize, sb.Size()) 30 } 31 32 func TestPackageBank(t *testing.T) { 33 s1 := Save("hello") 34 s2 := Save("goodbye") 35 s3 := Save("cheese") 36 37 assert.Equal(t, "hello", s1.String()) 38 assert.Equal(t, "goodbye", s2.String()) 39 assert.Equal(t, "cheese", s3.String()) 40 } 41 42 func TestLengths(t *testing.T) { 43 tests := []struct { 44 len int 45 }{ 46 {1}, 47 {127}, 48 {128}, 49 {254}, 50 {255}, 51 {256}, 52 {0xFFFFFFFFFF}, 53 } 54 55 for _, test := range tests { 56 t.Run(strconv.Itoa(test.len), func(t *testing.T) { 57 buf := make([]byte, 10) 58 59 l := writeLength(test.len, buf) 60 assert.Equal(t, l, spaceForLength(test.len)) 61 len, lenlen := readLength(buf) 62 assert.Equal(t, l, lenlen) 63 assert.Equal(t, test.len, len) 64 }) 65 } 66 } 67 68 func TestGC(t *testing.T) { 69 sb := Stringbank{} 70 for i := 0; i < 10000000; i++ { 71 sb.Save(strconv.Itoa(i)) 72 } 73 runtime.GC() 74 75 start := time.Now() 76 runtime.GC() 77 assert.True(t, time.Since(start) < 1000*time.Microsecond) 78 runtime.KeepAlive(sb) 79 } 80 81 func BenchmarkStringbank(b *testing.B) { 82 s := make([]string, b.N) 83 for i := range s { 84 s[i] = strconv.Itoa(i) 85 } 86 87 index := make([]int, b.N) 88 89 b.ReportAllocs() 90 b.ResetTimer() 91 sb := Stringbank{} 92 for i, v := range s { 93 index[i] = sb.Save(v) 94 } 95 96 var out string 97 for _, i := range index { 98 out = sb.Get(i) 99 } 100 if out != s[b.N-1] { 101 b.Fatalf("final string should be %s, is %s", s[b.N-1], out) 102 } 103 } 104 105 func ExampleSave() { 106 i := Save("hello") 107 fmt.Println(i) 108 // Output: hello 109 } 110 111 func ExampleStringbank() { 112 sb := Stringbank{} 113 i := sb.Save("goodbye") 114 fmt.Println(sb.Get(i)) 115 // Output: goodbye 116 }