utils_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2014, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "bytes"
  22. "encoding/json"
  23. "reflect"
  24. "testing"
  25. )
  26. func TestGetStringSlice(t *testing.T) {
  27. originalSlice := []string{"a", "b", "c"}
  28. j, err := json.Marshal(originalSlice)
  29. if err != nil {
  30. t.Errorf("json.Marshal failed: %s", err)
  31. }
  32. var value interface{}
  33. err = json.Unmarshal(j, &value)
  34. if err != nil {
  35. t.Errorf("json.Unmarshal failed: %s", err)
  36. }
  37. newSlice, ok := GetStringSlice(value)
  38. if !ok {
  39. t.Errorf("GetStringSlice failed")
  40. }
  41. if !reflect.DeepEqual(originalSlice, newSlice) {
  42. t.Errorf("unexpected GetStringSlice output")
  43. }
  44. }
  45. func TestCompress(t *testing.T) {
  46. originalData := []byte("test data")
  47. compressedData := Compress(originalData)
  48. decompressedData, err := Decompress(compressedData)
  49. if err != nil {
  50. t.Errorf("Uncompress failed: %s", err)
  51. }
  52. if !bytes.Equal(originalData, decompressedData) {
  53. t.Error("decompressed data doesn't match original data")
  54. }
  55. }
  56. func TestFormatByteCount(t *testing.T) {
  57. testCases := []struct {
  58. n uint64
  59. expectedOutput string
  60. }{
  61. {500, "500B"},
  62. {1024, "1.0K"},
  63. {10000, "9.8K"},
  64. {1024*1024 + 1, "1.0M"},
  65. {100*1024*1024 + 99999, "100.1M"},
  66. }
  67. for _, testCase := range testCases {
  68. t.Run(testCase.expectedOutput, func(t *testing.T) {
  69. output := FormatByteCount(testCase.n)
  70. if output != testCase.expectedOutput {
  71. t.Errorf("unexpected output: %s", output)
  72. }
  73. })
  74. }
  75. }