reloader_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2016, 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. "io/ioutil"
  23. "testing"
  24. )
  25. func TestReloader(t *testing.T) {
  26. fileName := "reloader_test.dat"
  27. initialContents := []byte("contents1\n")
  28. modifiedContents := []byte("contents2\n")
  29. var file struct {
  30. ReloadableFile
  31. contents []byte
  32. }
  33. file.ReloadableFile = NewReloadableFile(
  34. fileName,
  35. func(fileContent []byte) error {
  36. file.contents = fileContent
  37. return nil
  38. })
  39. // Test: initial load
  40. err := ioutil.WriteFile(fileName, initialContents, 0600)
  41. if err != nil {
  42. t.Fatalf("WriteFile failed: %s", err)
  43. }
  44. reloaded, err := file.Reload()
  45. if err != nil {
  46. t.Fatalf("Reload failed: %s", err)
  47. }
  48. if !reloaded {
  49. t.Fatalf("Unexpected non-reload")
  50. }
  51. if bytes.Compare(file.contents, initialContents) != 0 {
  52. t.Fatalf("Unexpected contents")
  53. }
  54. // Test: reload unchanged file
  55. reloaded, err = file.Reload()
  56. if err != nil {
  57. t.Fatalf("Reload failed: %s", err)
  58. }
  59. if reloaded {
  60. t.Fatalf("Unexpected reload")
  61. }
  62. if bytes.Compare(file.contents, initialContents) != 0 {
  63. t.Fatalf("Unexpected contents")
  64. }
  65. // Test: reload changed file
  66. err = ioutil.WriteFile(fileName, modifiedContents, 0600)
  67. if err != nil {
  68. t.Fatalf("WriteFile failed: %s", err)
  69. }
  70. reloaded, err = file.Reload()
  71. if err != nil {
  72. t.Fatalf("Reload failed: %s", err)
  73. }
  74. if !reloaded {
  75. t.Fatalf("Unexpected non-reload")
  76. }
  77. if bytes.Compare(file.contents, modifiedContents) != 0 {
  78. t.Fatalf("Unexpected contents")
  79. }
  80. }