util_test.go 2.0 KB

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