github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/api/query/test/types.go (about) 1 // Copyright 2018 The WPT Dashboard Project. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package test 6 7 import ( 8 "bytes" 9 "io" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 ) 14 15 // MockWriteCloser tracks write+close state for testing purposes. 16 type MockWriteCloser struct { 17 b bytes.Buffer 18 closed bool 19 t *testing.T 20 } 21 22 // Write ensures MockWriteCloser isn't closed and delegates to an underlying 23 // buffer for writing. 24 func (mwc *MockWriteCloser) Write(p []byte) (n int, err error) { 25 assert.False(mwc.t, mwc.closed) 26 27 return mwc.b.Write(p) 28 } 29 30 // Close stores "closed" state and synchronizes by sending true to 31 // MockWriteCloser.c iff it is not nil. Note that the synchronization message 32 // is sent from this goroutine; i.e., Close() will not return until another 33 // goroutine receives the message. 34 func (mwc *MockWriteCloser) Close() error { 35 mwc.closed = true 36 37 return nil 38 } 39 40 // NewMockWriteCloser constructs a MockWriteCloser for a given test. 41 func NewMockWriteCloser(t *testing.T) *MockWriteCloser { 42 return &MockWriteCloser{ 43 b: bytes.Buffer{}, 44 closed: false, 45 t: t, 46 } 47 } 48 49 // MockReadCloser implements reading from a predefined byte slice and tracks 50 // closed state for testing. 51 type MockReadCloser struct { 52 rc io.ReadCloser 53 closed bool 54 t *testing.T 55 } 56 57 // Read ensures that MockReadCloser has not be closed, then delegates to a 58 // reader that wraps a predefined byte slice. 59 func (mrc *MockReadCloser) Read(p []byte) (n int, err error) { 60 assert.False(mrc.t, mrc.closed) 61 62 return mrc.rc.Read(p) 63 } 64 65 // Close tracks closed state and returns nil. 66 func (mrc *MockReadCloser) Close() error { 67 mrc.closed = true 68 69 return nil 70 } 71 72 // NewMockReadCloser constructs a ReadCloser bound to the given test and byte 73 // slice. 74 func NewMockReadCloser(t *testing.T, data []byte) *MockReadCloser { 75 return &MockReadCloser{ 76 rc: io.NopCloser(bytes.NewReader(data)), 77 closed: false, 78 t: t, 79 } 80 } 81 82 // IsClosed allows test code to query whether or not a MockReadCloser has been 83 // closed. 84 func (mrc *MockReadCloser) IsClosed() bool { 85 return mrc.closed 86 }