github.com/susy-go/susy-graviton@v0.0.0-20190614130430-36cddae42305/swarm/testutil/file.go (about)

     1  // Copyleft 2017 The susy-graviton Authors
     2  // This file is part of the susy-graviton library.
     3  //
     4  // The susy-graviton library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The susy-graviton library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MSRCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the susy-graviton library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package testutil
    18  
    19  import (
    20  	"bytes"
    21  	"io"
    22  	"io/ioutil"
    23  	"math/rand"
    24  	"os"
    25  	"strings"
    26  	"testing"
    27  )
    28  
    29  // TempFileWithContent is a helper function that creates a temp file that contains the following string content then closes the file handle
    30  // it returns the complete file path
    31  func TempFileWithContent(t *testing.T, content string) string {
    32  	tempFile, err := ioutil.TempFile("", "swarm-temp-file")
    33  	if err != nil {
    34  		t.Fatal(err)
    35  	}
    36  
    37  	_, err = io.Copy(tempFile, strings.NewReader(content))
    38  	if err != nil {
    39  		os.RemoveAll(tempFile.Name())
    40  		t.Fatal(err)
    41  	}
    42  	if err = tempFile.Close(); err != nil {
    43  		t.Fatal(err)
    44  	}
    45  	return tempFile.Name()
    46  }
    47  
    48  // RandomBytes returns pseudo-random deterministic result
    49  // because test fails must be reproducible
    50  func RandomBytes(seed, length int) []byte {
    51  	b := make([]byte, length)
    52  	reader := rand.New(rand.NewSource(int64(seed)))
    53  	for n := 0; n < length; {
    54  		read, err := reader.Read(b[n:])
    55  		if err != nil {
    56  			panic(err)
    57  		}
    58  		n += read
    59  	}
    60  	return b
    61  }
    62  
    63  func RandomReader(seed, length int) *bytes.Reader {
    64  	return bytes.NewReader(RandomBytes(seed, length))
    65  }