compression_test.go 1.5 KB

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