util_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wal
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "strings"
  20. "testing"
  21. )
  22. func TestDetectVersion(t *testing.T) {
  23. tests := []struct {
  24. names []string
  25. wver WalVersion
  26. }{
  27. {[]string{}, WALNotExist},
  28. {[]string{"member/", "member/wal/", "member/wal/1", "member/snap/"}, WALv2_0_1},
  29. {[]string{"snap/", "wal/", "wal/1"}, WALv2_0},
  30. {[]string{"snapshot/", "conf", "log"}, WALv0_4},
  31. {[]string{"weird"}, WALUnknown},
  32. {[]string{"snap/", "wal/"}, WALUnknown},
  33. }
  34. for i, tt := range tests {
  35. p := mustMakeDir(t, tt.names...)
  36. ver, err := DetectVersion(p)
  37. if ver != tt.wver {
  38. t.Errorf("#%d: version = %s, want %s", i, ver, tt.wver)
  39. }
  40. if err != nil {
  41. t.Errorf("#%d: err = %s, want nil", i, err)
  42. }
  43. os.RemoveAll(p)
  44. }
  45. // detect on non-exist directory
  46. v, err := DetectVersion(path.Join(os.TempDir(), "waltest", "not-exist"))
  47. if v != WALNotExist {
  48. t.Errorf("#non-exist: version = %s, want %s", v, WALNotExist)
  49. }
  50. if err != nil {
  51. t.Errorf("#non-exist: err = %s, want %s", v, WALNotExist)
  52. }
  53. }
  54. // mustMakeDir builds the directory that contains files with the given
  55. // names. If the name ends with '/', it is created as a directory.
  56. func mustMakeDir(t *testing.T, names ...string) string {
  57. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. for _, n := range names {
  62. if strings.HasSuffix(n, "/") {
  63. if err := os.MkdirAll(path.Join(p, n), 0700); err != nil {
  64. t.Fatal(err)
  65. }
  66. } else {
  67. if _, err := os.Create(path.Join(p, n)); err != nil {
  68. t.Fatal(err)
  69. }
  70. }
  71. }
  72. return p
  73. }