github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/io/ioutil/tempfile_test.go (about)

     1  // Copyright 2010 The Go 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 ioutil_test
     6  
     7  import (
     8  	"io/fs"
     9  	. "io/ioutil"
    10  	"os"
    11  	"path/filepath"
    12  	"regexp"
    13  	"strings"
    14  	"testing"
    15  )
    16  
    17  func TestTempFile(t *testing.T) {
    18  	dir, err := TempDir("", "TestTempFile_BadDir")
    19  	if err != nil {
    20  		t.Fatal(err)
    21  	}
    22  	defer os.RemoveAll(dir)
    23  
    24  	nonexistentDir := filepath.Join(dir, "_not_exists_")
    25  	f, err := TempFile(nonexistentDir, "foo")
    26  	if f != nil || err == nil {
    27  		t.Errorf("TempFile(%q, `foo`) = %v, %v", nonexistentDir, f, err)
    28  	}
    29  }
    30  
    31  func TestTempFile_pattern(t *testing.T) {
    32  	tests := []struct{ pattern, prefix, suffix string }{
    33  		{"ioutil_test", "ioutil_test", ""},
    34  		{"ioutil_test*", "ioutil_test", ""},
    35  		{"ioutil_test*xyz", "ioutil_test", "xyz"},
    36  	}
    37  	for _, test := range tests {
    38  		f, err := TempFile("", test.pattern)
    39  		if err != nil {
    40  			t.Errorf("TempFile(..., %q) error: %v", test.pattern, err)
    41  			continue
    42  		}
    43  		defer os.Remove(f.Name())
    44  		base := filepath.Base(f.Name())
    45  		f.Close()
    46  		if !(strings.HasPrefix(base, test.prefix) && strings.HasSuffix(base, test.suffix)) {
    47  			t.Errorf("TempFile pattern %q created bad name %q; want prefix %q & suffix %q",
    48  				test.pattern, base, test.prefix, test.suffix)
    49  		}
    50  	}
    51  }
    52  
    53  func TestTempFile_BadPattern(t *testing.T) {
    54  	tmpDir, err := TempDir("", t.Name())
    55  	if err != nil {
    56  		t.Fatal(err)
    57  	}
    58  	defer os.RemoveAll(tmpDir)
    59  
    60  	const sep = string(os.PathSeparator)
    61  	tests := []struct {
    62  		pattern string
    63  		wantErr bool
    64  	}{
    65  		{"ioutil*test", false},
    66  		{"ioutil_test*foo", false},
    67  		{"ioutil_test" + sep + "foo", true},
    68  		{"ioutil_test*" + sep + "foo", true},
    69  		{"ioutil_test" + sep + "*foo", true},
    70  		{sep + "ioutil_test" + sep + "*foo", true},
    71  		{"ioutil_test*foo" + sep, true},
    72  	}
    73  	for _, tt := range tests {
    74  		t.Run(tt.pattern, func(t *testing.T) {
    75  			tmpfile, err := TempFile(tmpDir, tt.pattern)
    76  			defer func() {
    77  				if tmpfile != nil {
    78  					tmpfile.Close()
    79  				}
    80  			}()
    81  			if tt.wantErr {
    82  				if err == nil {
    83  					t.Errorf("Expected an error for pattern %q", tt.pattern)
    84  				}
    85  				if g, w := err, ErrPatternHasSeparator; g != w {
    86  					t.Errorf("Error mismatch: got %#v, want %#v for pattern %q", g, w, tt.pattern)
    87  				}
    88  			} else if err != nil {
    89  				t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern)
    90  			}
    91  		})
    92  	}
    93  }
    94  
    95  func TestTempDir(t *testing.T) {
    96  	name, err := TempDir("/_not_exists_", "foo")
    97  	if name != "" || err == nil {
    98  		t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err)
    99  	}
   100  
   101  	tests := []struct {
   102  		pattern                string
   103  		wantPrefix, wantSuffix string
   104  	}{
   105  		{"ioutil_test", "ioutil_test", ""},
   106  		{"ioutil_test*", "ioutil_test", ""},
   107  		{"ioutil_test*xyz", "ioutil_test", "xyz"},
   108  	}
   109  
   110  	dir := os.TempDir()
   111  
   112  	runTestTempDir := func(t *testing.T, pattern, wantRePat string) {
   113  		name, err := TempDir(dir, pattern)
   114  		if name == "" || err != nil {
   115  			t.Fatalf("TempDir(dir, `ioutil_test`) = %v, %v", name, err)
   116  		}
   117  		defer os.Remove(name)
   118  
   119  		re := regexp.MustCompile(wantRePat)
   120  		if !re.MatchString(name) {
   121  			t.Errorf("TempDir(%q, %q) created bad name\n\t%q\ndid not match pattern\n\t%q", dir, pattern, name, wantRePat)
   122  		}
   123  	}
   124  
   125  	for _, tt := range tests {
   126  		t.Run(tt.pattern, func(t *testing.T) {
   127  			wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir, tt.wantPrefix)) + "[0-9]+" + regexp.QuoteMeta(tt.wantSuffix) + "$"
   128  			runTestTempDir(t, tt.pattern, wantRePat)
   129  		})
   130  	}
   131  
   132  	// Separately testing "*xyz" (which has no prefix). That is when constructing the
   133  	// pattern to assert on, as in the previous loop, using filepath.Join for an empty
   134  	// prefix filepath.Join(dir, ""), produces the pattern:
   135  	//     ^<DIR>[0-9]+xyz$
   136  	// yet we just want to match
   137  	//     "^<DIR>/[0-9]+xyz"
   138  	t.Run("*xyz", func(t *testing.T) {
   139  		wantRePat := "^" + regexp.QuoteMeta(filepath.Join(dir)) + regexp.QuoteMeta(string(filepath.Separator)) + "[0-9]+xyz$"
   140  		runTestTempDir(t, "*xyz", wantRePat)
   141  	})
   142  }
   143  
   144  // test that we return a nice error message if the dir argument to TempDir doesn't
   145  // exist (or that it's empty and os.TempDir doesn't exist)
   146  func TestTempDir_BadDir(t *testing.T) {
   147  	dir, err := TempDir("", "TestTempDir_BadDir")
   148  	if err != nil {
   149  		t.Fatal(err)
   150  	}
   151  	defer os.RemoveAll(dir)
   152  
   153  	badDir := filepath.Join(dir, "not-exist")
   154  	_, err = TempDir(badDir, "foo")
   155  	if pe, ok := err.(*fs.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir {
   156  		t.Errorf("TempDir error = %#v; want PathError for path %q satisifying os.IsNotExist", err, badDir)
   157  	}
   158  }
   159  
   160  func TestTempDir_BadPattern(t *testing.T) {
   161  	tmpDir, err := TempDir("", t.Name())
   162  	if err != nil {
   163  		t.Fatal(err)
   164  	}
   165  	defer os.RemoveAll(tmpDir)
   166  
   167  	const sep = string(os.PathSeparator)
   168  	tests := []struct {
   169  		pattern string
   170  		wantErr bool
   171  	}{
   172  		{"ioutil*test", false},
   173  		{"ioutil_test*foo", false},
   174  		{"ioutil_test" + sep + "foo", true},
   175  		{"ioutil_test*" + sep + "foo", true},
   176  		{"ioutil_test" + sep + "*foo", true},
   177  		{sep + "ioutil_test" + sep + "*foo", true},
   178  		{"ioutil_test*foo" + sep, true},
   179  	}
   180  	for _, tt := range tests {
   181  		t.Run(tt.pattern, func(t *testing.T) {
   182  			_, err := TempDir(tmpDir, tt.pattern)
   183  			if tt.wantErr {
   184  				if err == nil {
   185  					t.Errorf("Expected an error for pattern %q", tt.pattern)
   186  				}
   187  				if g, w := err, ErrPatternHasSeparator; g != w {
   188  					t.Errorf("Error mismatch: got %#v, want %#v for pattern %q", g, w, tt.pattern)
   189  				}
   190  			} else if err != nil {
   191  				t.Errorf("Unexpected error %v for pattern %q", err, tt.pattern)
   192  			}
   193  		})
   194  	}
   195  }