util_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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{"snap/", "wal/", "wal/1"}, WALv0_5},
  29. {[]string{"snapshot/", "conf", "log"}, WALv0_4},
  30. {[]string{"weird"}, WALUnknown},
  31. {[]string{"snap/", "wal/"}, WALUnknown},
  32. }
  33. for i, tt := range tests {
  34. p := mustMakeDir(t, tt.names...)
  35. ver, err := DetectVersion(p)
  36. if ver != tt.wver {
  37. t.Errorf("#%d: version = %s, want %s", i, ver, tt.wver)
  38. }
  39. if err != nil {
  40. t.Errorf("#%d: err = %s, want nil", i, err)
  41. }
  42. os.RemoveAll(p)
  43. }
  44. // detect on non-exist directory
  45. v, err := DetectVersion(path.Join(os.TempDir(), "waltest", "not-exist"))
  46. if v != WALNotExist {
  47. t.Errorf("#non-exist: version = %s, want %s", v, WALNotExist)
  48. }
  49. if err != nil {
  50. t.Errorf("#non-exist: err = %s, want %s", v, WALNotExist)
  51. }
  52. }
  53. // mustMakeDir builds the directory that contains files with the given
  54. // names. If the name ends with '/', it is created as a directory.
  55. func mustMakeDir(t *testing.T, names ...string) string {
  56. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. for _, n := range names {
  61. if strings.HasSuffix(n, "/") {
  62. if err := os.MkdirAll(path.Join(p, n), 0700); err != nil {
  63. t.Fatal(err)
  64. }
  65. } else {
  66. if _, err := os.Create(path.Join(p, n)); err != nil {
  67. t.Fatal(err)
  68. }
  69. }
  70. }
  71. return p
  72. }