read_dir_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2018 The etcd Authors
  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 fileutil
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "reflect"
  20. "testing"
  21. )
  22. func TestReadDir(t *testing.T) {
  23. tmpdir, err := ioutil.TempDir("", "")
  24. defer os.RemoveAll(tmpdir)
  25. if err != nil {
  26. t.Fatalf("unexpected ioutil.TempDir error: %v", err)
  27. }
  28. files := []string{"def", "abc", "xyz", "ghi"}
  29. for _, f := range files {
  30. writeFunc(t, filepath.Join(tmpdir, f))
  31. }
  32. fs, err := ReadDir(tmpdir)
  33. if err != nil {
  34. t.Fatalf("error calling ReadDir: %v", err)
  35. }
  36. wfs := []string{"abc", "def", "ghi", "xyz"}
  37. if !reflect.DeepEqual(fs, wfs) {
  38. t.Fatalf("ReadDir: got %v, want %v", fs, wfs)
  39. }
  40. files = []string{"def.wal", "abc.wal", "xyz.wal", "ghi.wal"}
  41. for _, f := range files {
  42. writeFunc(t, filepath.Join(tmpdir, f))
  43. }
  44. fs, err = ReadDir(tmpdir, WithExt(".wal"))
  45. if err != nil {
  46. t.Fatalf("error calling ReadDir: %v", err)
  47. }
  48. wfs = []string{"abc.wal", "def.wal", "ghi.wal", "xyz.wal"}
  49. if !reflect.DeepEqual(fs, wfs) {
  50. t.Fatalf("ReadDir: got %v, want %v", fs, wfs)
  51. }
  52. }
  53. func writeFunc(t *testing.T, path string) {
  54. fh, err := os.Create(path)
  55. if err != nil {
  56. t.Fatalf("error creating file: %v", err)
  57. }
  58. if err = fh.Close(); err != nil {
  59. t.Fatalf("error closing file: %v", err)
  60. }
  61. }