stream_decompressor_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "bytes"
  5. "compress/zlib"
  6. "crypto/rand"
  7. "fmt"
  8. "io"
  9. "testing"
  10. )
  11. var _ = fmt.Print
  12. func TestStreamDecompressor(t *testing.T) {
  13. input := make([]byte, 9723)
  14. io.ReadFull(rand.Reader, input)
  15. b := bytes.Buffer{}
  16. w := zlib.NewWriter(&b)
  17. io.Copy(w, bytes.NewReader(input))
  18. w.Close()
  19. o := bytes.Buffer{}
  20. sd := NewStreamDecompressor(zlib.NewReader, &o)
  21. data := b.Bytes()
  22. for len(data) > 0 {
  23. chunk := data[:Min(117, len(data))]
  24. data = data[len(chunk):]
  25. if err := sd(chunk, len(data) == 0); err != nil {
  26. t.Fatal(err)
  27. }
  28. }
  29. if !bytes.Equal(o.Bytes(), input) {
  30. t.Fatalf("Roundtripping via zlib failed output (%d) != input (%d)", len(o.Bytes()), len(input))
  31. }
  32. o.Reset()
  33. sd = NewStreamDecompressor(zlib.NewReader, &o)
  34. err := sd([]byte("abcd"), true)
  35. if err == nil {
  36. t.Fatalf("Did not get an invalid header error from zlib")
  37. }
  38. o.Reset()
  39. sd = NewStreamDecompressor(zlib.NewReader, &o)
  40. err = sd(b.Bytes(), false)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. if !bytes.Equal(o.Bytes(), input) {
  45. t.Fatalf("Roundtripping via zlib failed output (%d) != input (%d)", len(o.Bytes()), len(input))
  46. }
  47. err = sd([]byte("extra trailing data"), true)
  48. if err == nil {
  49. t.Fatalf("Did not get an invalid header error from zlib")
  50. }
  51. }