github.com/prattmic/llgo-embedded@v0.0.0-20150820070356-41cfecea0e1e/third_party/liner/line_test.go (about)

     1  package liner
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  func TestAppend(t *testing.T) {
    10  	var s State
    11  	s.AppendHistory("foo")
    12  	s.AppendHistory("bar")
    13  
    14  	var out bytes.Buffer
    15  	num, err := s.WriteHistory(&out)
    16  	if err != nil {
    17  		t.Fatal("Unexpected error writing history", err)
    18  	}
    19  	if num != 2 {
    20  		t.Fatalf("Expected 2 history entries, got %d", num)
    21  	}
    22  
    23  	s.AppendHistory("baz")
    24  	num, err = s.WriteHistory(&out)
    25  	if err != nil {
    26  		t.Fatal("Unexpected error writing history", err)
    27  	}
    28  	if num != 3 {
    29  		t.Fatalf("Expected 3 history entries, got %d", num)
    30  	}
    31  
    32  	s.AppendHistory("baz")
    33  	num, err = s.WriteHistory(&out)
    34  	if err != nil {
    35  		t.Fatal("Unexpected error writing history", err)
    36  	}
    37  	if num != 3 {
    38  		t.Fatalf("Expected 3 history entries after duplicate append, got %d", num)
    39  	}
    40  
    41  	s.AppendHistory("baz")
    42  
    43  }
    44  
    45  func TestHistory(t *testing.T) {
    46  	input := `foo
    47  bar
    48  baz
    49  quux
    50  dingle`
    51  
    52  	var s State
    53  	num, err := s.ReadHistory(strings.NewReader(input))
    54  	if err != nil {
    55  		t.Fatal("Unexpected error reading history", err)
    56  	}
    57  	if num != 5 {
    58  		t.Fatal("Wrong number of history entries read")
    59  	}
    60  
    61  	var out bytes.Buffer
    62  	num, err = s.WriteHistory(&out)
    63  	if err != nil {
    64  		t.Fatal("Unexpected error writing history", err)
    65  	}
    66  	if num != 5 {
    67  		t.Fatal("Wrong number of history entries written")
    68  	}
    69  	if strings.TrimSpace(out.String()) != input {
    70  		t.Fatal("Round-trip failure")
    71  	}
    72  
    73  	// Test reading with a trailing newline present
    74  	var s2 State
    75  	num, err = s2.ReadHistory(&out)
    76  	if err != nil {
    77  		t.Fatal("Unexpected error reading history the 2nd time", err)
    78  	}
    79  	if num != 5 {
    80  		t.Fatal("Wrong number of history entries read the 2nd time")
    81  	}
    82  
    83  	num, err = s.ReadHistory(strings.NewReader(input + "\n\xff"))
    84  	if err == nil {
    85  		t.Fatal("Unexpected success reading corrupted history", err)
    86  	}
    87  	if num != 5 {
    88  		t.Fatal("Wrong number of history entries read the 3rd time")
    89  	}
    90  }