github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/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
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"regexp"
    11  	"testing"
    12  )
    13  
    14  func TestTempFile(t *testing.T) {
    15  	f, err := TempFile("/_not_exists_", "foo")
    16  	if f != nil || err == nil {
    17  		t.Errorf("TempFile(`/_not_exists_`, `foo`) = %v, %v", f, err)
    18  	}
    19  
    20  	dir := os.TempDir()
    21  	f, err = TempFile(dir, "ioutil_test")
    22  	if f == nil || err != nil {
    23  		t.Errorf("TempFile(dir, `ioutil_test`) = %v, %v", f, err)
    24  	}
    25  	if f != nil {
    26  		f.Close()
    27  		os.Remove(f.Name())
    28  		re := regexp.MustCompile("^" + regexp.QuoteMeta(filepath.Join(dir, "ioutil_test")) + "[0-9]+$")
    29  		if !re.MatchString(f.Name()) {
    30  			t.Errorf("TempFile(`"+dir+"`, `ioutil_test`) created bad name %s", f.Name())
    31  		}
    32  	}
    33  }
    34  
    35  func TestTempDir(t *testing.T) {
    36  	name, err := TempDir("/_not_exists_", "foo")
    37  	if name != "" || err == nil {
    38  		t.Errorf("TempDir(`/_not_exists_`, `foo`) = %v, %v", name, err)
    39  	}
    40  
    41  	dir := os.TempDir()
    42  	name, err = TempDir(dir, "ioutil_test")
    43  	if name == "" || err != nil {
    44  		t.Errorf("TempDir(dir, `ioutil_test`) = %v, %v", name, err)
    45  	}
    46  	if name != "" {
    47  		os.Remove(name)
    48  		re := regexp.MustCompile("^" + regexp.QuoteMeta(filepath.Join(dir, "ioutil_test")) + "[0-9]+$")
    49  		if !re.MatchString(name) {
    50  			t.Errorf("TempDir(`"+dir+"`, `ioutil_test`) created bad name %s", name)
    51  		}
    52  	}
    53  }
    54  
    55  // test that we return a nice error message if the dir argument to TempDir doesn't
    56  // exist (or that it's empty and os.TempDir doesn't exist)
    57  func TestTempDir_BadDir(t *testing.T) {
    58  	dir, err := TempDir("", "TestTempDir_BadDir")
    59  	if err != nil {
    60  		t.Fatal(err)
    61  	}
    62  	defer os.RemoveAll(dir)
    63  
    64  	badDir := filepath.Join(dir, "not-exist")
    65  	_, err = TempDir(badDir, "foo")
    66  	if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != badDir {
    67  		t.Errorf("TempDir error = %#v; want PathError for path %q satisifying os.IsNotExist", err, badDir)
    68  	}
    69  }