github.hscsec.cn/u-root/u-root@v7.0.0+incompatible/cmds/core/tail/tail_test.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"os"
    11  	"testing"
    12  )
    13  
    14  func TestTailReadBackwards(t *testing.T) {
    15  	input, err := os.Open("./test_samples/read_backwards.txt")
    16  	if err != nil {
    17  		t.Error(err)
    18  	}
    19  	output := &bytes.Buffer{}
    20  	err = readLastLinesBackwards(input, output, 2)
    21  	if err != nil {
    22  		t.Error(err)
    23  	}
    24  	expected := []byte("second\nthird\n")
    25  	got := output.Bytes()
    26  	if !bytes.Equal(got, expected) {
    27  		t.Fatalf("Invalid result reading backwards. Got %v; want %v", got, expected)
    28  	}
    29  	// try reading more, which should return EOF
    30  	buf := make([]byte, 16)
    31  	n, err := input.Read(buf)
    32  	if err == nil {
    33  		t.Fatalf("Expected EOF, got more bytes instead: %v", string(buf[:n]))
    34  	}
    35  	if err != io.EOF {
    36  		t.Fatalf("Expected EOF, got another error instead: %v", err)
    37  	}
    38  }
    39  
    40  func TestTailReadFromBeginning(t *testing.T) {
    41  	input, err := os.Open("./test_samples/read_from_beginning.txt")
    42  	if err != nil {
    43  		t.Error(err)
    44  	}
    45  	output := &bytes.Buffer{}
    46  	err = readLastLinesFromBeginning(input, output, 3)
    47  	if err != nil {
    48  		t.Error(err)
    49  	}
    50  	expected := []byte("eight\nnine\nten\n")
    51  	got := make([]byte, 4096) // anything larger than the expected result
    52  	n, err := output.Read(got)
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if !bytes.Equal(got[:n], expected) {
    57  		t.Fatalf("Invalid data while reading from the beginning. Got %v; want %v", string(got[:n]), string(expected))
    58  	}
    59  	// try reading more, which should return EOF
    60  	buf := make([]byte, 16)
    61  	n, err = input.Read(buf)
    62  	if err == nil {
    63  		t.Fatalf("Expected EOF, got more bytes instead: %v", string(buf[:n]))
    64  	}
    65  	if err != io.EOF {
    66  		t.Fatalf("Expected EOF, got another error instead: %v", err)
    67  	}
    68  }