github.hscsec.cn/u-root/u-root@v7.0.0+incompatible/cmds/core/mkfifo/mkfifo_test.go (about)

     1  // Copyright 2017 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  package main
     6  
     7  import (
     8  	"bytes"
     9  	"io/ioutil"
    10  	"os"
    11  	"path/filepath"
    12  	"strings"
    13  	"testing"
    14  
    15  	"github.com/u-root/u-root/pkg/testutil"
    16  )
    17  
    18  type test struct {
    19  	name   string
    20  	flags  []string
    21  	stdErr string
    22  }
    23  
    24  func TestMkfifo(t *testing.T) {
    25  	tmpDir, err := ioutil.TempDir("", "ls")
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  	defer os.RemoveAll(tmpDir)
    30  
    31  	// used later in testing
    32  	testDir := filepath.Join(tmpDir, "mkfifoDir")
    33  	if err := os.Mkdir(testDir, 0700); err != nil {
    34  		t.Error(err)
    35  	}
    36  
    37  	var tests = []test{
    38  		{
    39  			name:   "no path or mode, error",
    40  			flags:  []string{},
    41  			stdErr: "please provide a path, or multiple, to create a fifo",
    42  		},
    43  		{
    44  			name:   "single path",
    45  			flags:  []string{filepath.Join(testDir, "testfifo")},
    46  			stdErr: "",
    47  		},
    48  		{
    49  			name:   "duplicate path",
    50  			flags:  []string{filepath.Join(testDir, "testfifo1"), filepath.Join(testDir, "testfifo1")},
    51  			stdErr: "file exists",
    52  		},
    53  	}
    54  
    55  	for _, tt := range tests {
    56  		var out, stdErr bytes.Buffer
    57  		cmd := testutil.Command(t, tt.flags...)
    58  		cmd.Stdout = &out
    59  		cmd.Stderr = &stdErr
    60  		err := cmd.Run()
    61  
    62  		if err != nil && !strings.Contains(stdErr.String(), tt.stdErr) {
    63  			t.Errorf("expected %v got %v", tt.stdErr, stdErr.String())
    64  		}
    65  
    66  		for _, path := range tt.flags {
    67  			testFile, err := os.Stat(path)
    68  
    69  			if err != nil {
    70  				t.Errorf("Unable to stat file %s", path)
    71  			}
    72  
    73  			mode := testFile.Mode()
    74  			if typ := mode & os.ModeType; typ != os.ModeNamedPipe {
    75  				t.Errorf("got %v, want %v", typ, os.ModeNamedPipe)
    76  			}
    77  		}
    78  	}
    79  }
    80  
    81  func TestMain(m *testing.M) {
    82  	testutil.Run(m, main)
    83  }