| 1 |
// Copyright The Notary Project Authors. |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package io |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"errors" |
| 19 |
"testing" |
| 20 |
) |
| 21 |
|
| 22 |
func TestLimitWriter(t *testing.T) { |
| 23 |
limit := int64(10) |
| 24 |
|
| 25 |
tests := []struct { |
| 26 |
input string |
| 27 |
expected string |
| 28 |
written int |
| 29 |
}{ |
| 30 |
{"hello", "hello", 5}, |
| 31 |
{" world", " world", 6}, |
| 32 |
{"!", "!", 1}, |
| 33 |
{"1234567891011", "1234567891", 10}, |
| 34 |
} |
| 35 |
|
| 36 |
for _, tt := range tests { |
| 37 |
var buf bytes.Buffer |
| 38 |
lw := LimitWriter(&buf, limit) |
| 39 |
n, err := lw.Write([]byte(tt.input)) |
| 40 |
if err != nil { |
| 41 |
t.Fatalf("unexpected error: %v", err) |
| 42 |
} |
| 43 |
if n != tt.written { |
| 44 |
t.Errorf("expected %d bytes written, got %d", tt.written, n) |
| 45 |
} |
| 46 |
if buf.String() != tt.expected { |
| 47 |
t.Errorf("expected buffer %q, got %q", tt.expected, buf.String()) |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
func TestLimitWriterFailed(t *testing.T) { |
| 53 |
limit := int64(10) |
| 54 |
longString := "1234567891011" |
| 55 |
|
| 56 |
var buf bytes.Buffer |
| 57 |
lw := LimitWriter(&buf, limit) |
| 58 |
_, err := lw.Write([]byte(longString)) |
| 59 |
if err != nil { |
| 60 |
t.Fatalf("unexpected error: %v", err) |
| 61 |
} |
| 62 |
_, err = lw.Write([]byte(longString)) |
| 63 |
expectedErr := errors.New("write limit exceeded") |
| 64 |
if err.Error() != expectedErr.Error() { |
| 65 |
t.Errorf("expected error %v, got %v", expectedErr, err) |
| 66 |
} |
| 67 |
} |