Source file src/os/tempfile_test.go

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

View as plain text