gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/state/statefile/async_io_test.go (about)

     1  // Copyright 2024 The gVisor 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 statefile
    16  
    17  import (
    18  	"bytes"
    19  	"math/rand"
    20  	"os"
    21  	"testing"
    22  
    23  	"golang.org/x/sys/unix"
    24  	"gvisor.dev/gvisor/pkg/fd"
    25  )
    26  
    27  func TestAsyncReader(t *testing.T) {
    28  	const chunkSize = 4096
    29  	const dataLen = 1024 * chunkSize
    30  	data := make([]byte, dataLen)
    31  	_, _ = rand.Read(data)
    32  	testFile, err := os.CreateTemp(t.TempDir(), "source")
    33  	if err != nil {
    34  		t.Fatalf("failed to create temp source file: %v", err)
    35  	}
    36  	if _, err := testFile.Write(data); err != nil {
    37  		t.Fatalf("failed to write temp source file: %v", err)
    38  	}
    39  	testFilePath := testFile.Name()
    40  	if err := testFile.Close(); err != nil {
    41  		t.Fatalf("failed to close temp source file: %v", err)
    42  	}
    43  
    44  	sourceFD, err := fd.Open(testFilePath, unix.O_RDONLY, 0)
    45  	if err != nil {
    46  		t.Fatalf("failed to open source file %q: %v", testFilePath, err)
    47  	}
    48  	ar := NewAsyncReader(sourceFD, 0 /* off */)
    49  	p := make([]byte, dataLen)
    50  	for i := 0; i < dataLen; i += chunkSize {
    51  		ar.ReadAsync(p[i : i+chunkSize])
    52  	}
    53  	if err := ar.Close(); err != nil {
    54  		t.Fatalf("AsyncReader.Wait returned error: %v", err)
    55  	}
    56  	if ret := bytes.Compare(p, data); ret != 0 {
    57  		t.Errorf("bytes differ")
    58  	}
    59  }