...
1 package diskv
2
3 import (
4 "compress/flate"
5 "fmt"
6 "math/rand"
7 "os"
8 "testing"
9 "time"
10 )
11
12 func init() {
13 rand.Seed(time.Now().UnixNano())
14 }
15
16 func testCompressionWith(t *testing.T, c Compression, name string) {
17 d := New(Options{
18 BasePath: "compression-test",
19 CacheSizeMax: 0,
20 Compression: c,
21 })
22 defer d.EraseAll()
23
24 sz := 4096
25 val := make([]byte, sz)
26 for i := 0; i < sz; i++ {
27 val[i] = byte('a' + rand.Intn(26))
28 }
29
30 key := "a"
31 if err := d.Write(key, val); err != nil {
32 t.Fatalf("write failed: %s", err)
33 }
34
35 targetFile := fmt.Sprintf("%s%c%s", d.BasePath, os.PathSeparator, key)
36 fi, err := os.Stat(targetFile)
37 if err != nil {
38 t.Fatalf("%s: %s", targetFile, err)
39 }
40
41 if fi.Size() >= int64(sz) {
42 t.Fatalf("%s: size=%d, expected smaller", targetFile, fi.Size())
43 }
44 t.Logf("%s compressed %d to %d", name, sz, fi.Size())
45
46 readVal, err := d.Read(key)
47 if len(readVal) != sz {
48 t.Fatalf("read: expected size=%d, got size=%d", sz, len(readVal))
49 }
50
51 for i := 0; i < sz; i++ {
52 if readVal[i] != val[i] {
53 t.Fatalf("i=%d: expected %v, got %v", i, val[i], readVal[i])
54 }
55 }
56 }
57
58 func TestGzipDefault(t *testing.T) {
59 testCompressionWith(t, NewGzipCompression(), "gzip")
60 }
61
62 func TestGzipBestCompression(t *testing.T) {
63 testCompressionWith(t, NewGzipCompressionLevel(flate.BestCompression), "gzip-max")
64 }
65
66 func TestGzipBestSpeed(t *testing.T) {
67 testCompressionWith(t, NewGzipCompressionLevel(flate.BestSpeed), "gzip-min")
68 }
69
70 func TestZlib(t *testing.T) {
71 testCompressionWith(t, NewZlibCompression(), "zlib")
72 }
73
View as plain text