Serge Bazanski | 248b2ec | 2020-10-26 15:55:51 +0100 | [diff] [blame^] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package logbuffer |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "testing" |
| 22 | ) |
| 23 | |
| 24 | func TestLineBuffer(t *testing.T) { |
| 25 | var lines []*Line |
| 26 | lb := NewLineBuffer(1024, func(l *Line) { |
| 27 | lines = append(lines, l) |
| 28 | }) |
| 29 | |
| 30 | compare := func(a []*Line, b ...string) string { |
| 31 | msg := fmt.Sprintf("want %v, got %v", a, b) |
| 32 | if len(a) != len(b) { |
| 33 | return msg |
| 34 | } |
| 35 | for i, _ := range a { |
| 36 | if a[i].String() != b[i] { |
| 37 | return msg |
| 38 | } |
| 39 | } |
| 40 | return "" |
| 41 | } |
| 42 | |
| 43 | // Write some data. |
| 44 | fmt.Fprintf(lb, "foo ") |
| 45 | if diff := compare(lines); diff != "" { |
| 46 | t.Fatal(diff) |
| 47 | } |
| 48 | fmt.Fprintf(lb, "bar\n") |
| 49 | if diff := compare(lines, "foo bar"); diff != "" { |
| 50 | t.Fatal(diff) |
| 51 | } |
| 52 | fmt.Fprintf(lb, "baz") |
| 53 | if diff := compare(lines, "foo bar"); diff != "" { |
| 54 | t.Fatal(diff) |
| 55 | } |
| 56 | fmt.Fprintf(lb, " baz") |
| 57 | if diff := compare(lines, "foo bar"); diff != "" { |
| 58 | t.Fatal(diff) |
| 59 | } |
| 60 | // Close and expect flush. |
| 61 | if err := lb.Close(); err != nil { |
| 62 | t.Fatalf("Close: %v", err) |
| 63 | } |
| 64 | if diff := compare(lines, "foo bar", "baz baz"); diff != "" { |
| 65 | t.Fatal(diff) |
| 66 | } |
| 67 | |
| 68 | // Check behaviour after close |
| 69 | if _, err := fmt.Fprintf(lb, "nope"); err == nil { |
| 70 | t.Fatalf("Write after Close: wanted error, got nil") |
| 71 | } |
| 72 | if err := lb.Close(); err == nil { |
| 73 | t.Fatalf("second Close: wanted error, got nil") |
| 74 | } |
| 75 | } |