github.com/jlowellwofford/u-root@v1.0.0/cmds/mknod/mknod_test.go (about)

     1  // Copyright 2016-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  	"fmt"
    10  	"io/ioutil"
    11  	"os"
    12  	"os/exec"
    13  	"path/filepath"
    14  	"testing"
    15  
    16  	"github.com/u-root/u-root/pkg/testutil"
    17  )
    18  
    19  type test struct {
    20  	args    []string
    21  	expects string
    22  }
    23  
    24  func run(c *exec.Cmd) (string, string, error) {
    25  	var o, e bytes.Buffer
    26  	c.Stdout, c.Stderr = &o, &e
    27  	err := c.Run()
    28  	return o.String(), e.String(), err
    29  }
    30  
    31  func TestMknodFifo(t *testing.T) {
    32  	tmpDir, err := ioutil.TempDir("", "ls")
    33  	if err != nil {
    34  		t.Fatal(err)
    35  	}
    36  	defer os.RemoveAll(tmpDir)
    37  
    38  	// Delete a preexisting pipe if it exists, thought it shouldn't
    39  	pipepath := filepath.Join(tmpDir, "testpipe")
    40  	_ = os.Remove(pipepath)
    41  	if _, err := os.Stat(pipepath); err != nil && !os.IsNotExist(err) {
    42  		// Couldn't delete the file for reasons other than it didn't exist.
    43  		t.Fatalf("couldn't delete preexisting pipe")
    44  	}
    45  
    46  	// Make a pipe and check that it exists.
    47  	fmt.Print(pipepath)
    48  	c := testutil.Command(t, pipepath, "p")
    49  	c.Run()
    50  	if _, err := os.Stat(pipepath); os.IsNotExist(err) {
    51  		t.Errorf("Pipe was not created.")
    52  	}
    53  }
    54  
    55  func TestInvocationErrors(t *testing.T) {
    56  	tmpDir, err := ioutil.TempDir("", "ls")
    57  	if err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	defer os.RemoveAll(tmpDir)
    61  
    62  	devpath := filepath.Join(tmpDir, "testdev")
    63  	var tests = []test{
    64  		{args: []string{devpath}, expects: "Usage: mknod path type [major minor]\n"},
    65  		{args: []string{""}, expects: "Usage: mknod path type [major minor]\n"},
    66  		{args: []string{devpath, "p", "254", "3"}, expects: "device type p requires no other arguments\n"},
    67  		{args: []string{devpath, "b", "254"}, expects: "Usage: mknod path type [major minor]\n"},
    68  		{args: []string{devpath, "b"}, expects: "device type b requires a major and minor number\n"},
    69  		{args: []string{devpath, "k"}, expects: "device type not recognized: k\n"},
    70  	}
    71  
    72  	for _, v := range tests {
    73  		c := testutil.Command(t, v.args...)
    74  		_, e, _ := run(c)
    75  		if e[20:] != v.expects {
    76  			t.Errorf("mknod for '%v' failed: got '%s', want '%s'", v.args, e[20:], v.expects)
    77  		}
    78  	}
    79  }
    80  
    81  func TestMain(m *testing.M) {
    82  	testutil.Run(m, main)
    83  }