go.etcd.io/etcd@v3.3.27+incompatible/pkg/fileutil/preallocate_test.go (about)

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