| 1 |
// Copyright 2022 The Go Cloud Development Kit 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 |
// https://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 blob_test |
| 16 |
|
| 17 |
import ( |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"io" |
| 21 |
"testing" |
| 22 |
"testing/iotest" |
| 23 |
|
| 24 |
"gocloud.dev/blob/memblob" |
| 25 |
) |
| 26 |
|
| 27 |
// TestReader verifies that blob.Reader implements io package interfaces correctly. |
| 28 |
func TestReader(t *testing.T) { |
| 29 |
const myKey = "testkey" |
| 30 |
|
| 31 |
bucket := memblob.OpenBucket(nil) |
| 32 |
defer bucket.Close() |
| 33 |
|
| 34 |
// Get some random data, of a large enough size to require multiple |
| 35 |
// reads/writes given our buffer size of 1024. |
| 36 |
data, err := randomData(1024*10 + 10) |
| 37 |
if err != nil { |
| 38 |
t.Fatal(err) |
| 39 |
} |
| 40 |
|
| 41 |
// Write the data to a key. |
| 42 |
ctx := context.Background() |
| 43 |
bucket.WriteAll(ctx, myKey, data, nil) |
| 44 |
|
| 45 |
// Create a blob.Reader. |
| 46 |
r1, err := bucket.NewReader(ctx, myKey, nil) |
| 47 |
if err != nil { |
| 48 |
t.Fatal(err) |
| 49 |
} |
| 50 |
r1.Close() |
| 51 |
if err := iotest.TestReader(r1, data); err != nil { |
| 52 |
t.Error(err) |
| 53 |
} |
| 54 |
|
| 55 |
// Create another blob.Reader to exercise the ReadFrom code path |
| 56 |
r2, err := bucket.NewReader(ctx, myKey, nil) |
| 57 |
if err != nil { |
| 58 |
t.Fatal(err) |
| 59 |
} |
| 60 |
defer r2.Close() |
| 61 |
|
| 62 |
var buffer bytes.Buffer |
| 63 |
n, err := io.Copy(&buffer, r2) |
| 64 |
if err != nil { |
| 65 |
t.Fatal(err) |
| 66 |
} else if n != int64(len(data)) { |
| 67 |
t.Fatal("wrote fewer bytes than expected") |
| 68 |
} else if !bytes.Equal(buffer.Bytes(), data) { |
| 69 |
t.Fatal("wrote invalid bytes") |
| 70 |
} |
| 71 |
} |