preallocate_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 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. "testing"
  19. )
  20. func TestPreallocateExtend(t *testing.T) {
  21. pf := func(f *os.File, sz int64) error { return Preallocate(f, sz, true) }
  22. tf := func(t *testing.T, f *os.File) { testPreallocateExtend(t, f, pf) }
  23. runPreallocTest(t, tf)
  24. }
  25. func TestPreallocateExtendTrunc(t *testing.T) {
  26. tf := func(t *testing.T, f *os.File) { testPreallocateExtend(t, f, preallocExtendTrunc) }
  27. runPreallocTest(t, tf)
  28. }
  29. func testPreallocateExtend(t *testing.T, f *os.File, pf func(*os.File, int64) error) {
  30. size := int64(64 * 1000)
  31. if err := pf(f, size); err != nil {
  32. t.Fatal(err)
  33. }
  34. stat, err := f.Stat()
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. if stat.Size() != size {
  39. t.Errorf("size = %d, want %d", stat.Size(), size)
  40. }
  41. }
  42. func TestPreallocateFixed(t *testing.T) { runPreallocTest(t, testPreallocateFixed) }
  43. func testPreallocateFixed(t *testing.T, f *os.File) {
  44. size := int64(64 * 1000)
  45. if err := Preallocate(f, size, false); err != nil {
  46. t.Fatal(err)
  47. }
  48. stat, err := f.Stat()
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. if stat.Size() != 0 {
  53. t.Errorf("size = %d, want %d", stat.Size(), 0)
  54. }
  55. }
  56. func runPreallocTest(t *testing.T, test func(*testing.T, *os.File)) {
  57. p, err := ioutil.TempDir(os.TempDir(), "preallocateTest")
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. defer os.RemoveAll(p)
  62. f, err := ioutil.TempFile(p, "")
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. test(t, f)
  67. }