github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/cat/cat_test.go (about)

     1  // Copyright 2012 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // by Rafael Campos Nunes <rafaelnunes@engineer.com>
     6  
     7  package main
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"io/ioutil"
    13  	"os"
    14  	"path/filepath"
    15  	"reflect"
    16  	"testing"
    17  )
    18  
    19  // setup writes a set of files, putting 1 byte in each file.
    20  func setup(t *testing.T, data []byte) (string, error) {
    21  	t.Logf(":: Creating simulation data. ")
    22  	dir, err := ioutil.TempDir("", "cat.dir")
    23  	if err != nil {
    24  		return "", err
    25  	}
    26  
    27  	for i, d := range data {
    28  		n := fmt.Sprintf("%v%d", filepath.Join(dir, "file"), i)
    29  		if err := ioutil.WriteFile(n, []byte{d}, 0666); err != nil {
    30  			return "", err
    31  		}
    32  	}
    33  
    34  	return dir, nil
    35  }
    36  
    37  // TestCat test cat function against 4 files, in each file it is written a bit of someData
    38  // array and the test expect the cat to return the exact same bit from someData array with
    39  // the corresponding file.
    40  func TestCat(t *testing.T) {
    41  	var files []string
    42  	someData := []byte{'l', 2, 3, 4, 'd'}
    43  
    44  	dir, err := setup(t, someData)
    45  	if err != nil {
    46  		t.Fatalf("setup has failed, %v", err)
    47  	}
    48  	defer os.RemoveAll(dir)
    49  
    50  	for i := range someData {
    51  		files = append(files, fmt.Sprintf("%v%d", filepath.Join(dir, "file"), i))
    52  	}
    53  
    54  	var b bytes.Buffer
    55  	if err := cat(&b, files); err != nil {
    56  		t.Fatal(err)
    57  	}
    58  	if !reflect.DeepEqual(b.Bytes(), someData) {
    59  		t.Fatalf("Reading files failed: got %v, want %v", b.Bytes(), someData)
    60  	}
    61  }