github.com/go4org/go4@v0.0.0-20200104003542-c7e774b10ea0/readerutil/singlereader/opener_test.go (about)

     1  /*
     2  Copyright 2013 The Go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package singlereader
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"os"
    24  	"runtime"
    25  	"testing"
    26  )
    27  
    28  func TestOpenSingle(t *testing.T) {
    29  	if testing.Short() {
    30  		t.Skip("skipping in short mode")
    31  	}
    32  	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(4))
    33  	f, err := ioutil.TempFile("", "foo")
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	defer os.Remove(f.Name())
    38  	contents := []byte("Some file contents")
    39  	if _, err := f.Write(contents); err != nil {
    40  		t.Fatal(err)
    41  	}
    42  	f.Close()
    43  
    44  	const j = 4
    45  	errc := make(chan error, j)
    46  	for i := 1; i < j; i++ {
    47  		go func() {
    48  			buf := make([]byte, len(contents))
    49  			for i := 0; i < 400; i++ {
    50  				rac, err := Open(f.Name())
    51  				if err != nil {
    52  					errc <- err
    53  					return
    54  				}
    55  				n, err := rac.ReadAt(buf, 0)
    56  				if err != nil {
    57  					errc <- err
    58  					return
    59  				}
    60  				if n != len(contents) || !bytes.Equal(buf, contents) {
    61  					errc <- fmt.Errorf("read %d, %q; want %d, %q", n, buf, len(contents), contents)
    62  					return
    63  				}
    64  				if err := rac.Close(); err != nil {
    65  					errc <- err
    66  					return
    67  				}
    68  			}
    69  			errc <- nil
    70  		}()
    71  	}
    72  	for i := 1; i < j; i++ {
    73  		if err := <-errc; err != nil {
    74  			t.Error(err)
    75  		}
    76  	}
    77  }