| 1 |
/* |
| 2 |
Copyright 2017 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package temp |
| 18 |
|
| 19 |
import ( |
| 20 |
"io/ioutil" |
| 21 |
"os" |
| 22 |
"path/filepath" |
| 23 |
"strings" |
| 24 |
"testing" |
| 25 |
) |
| 26 |
|
| 27 |
func TestTempDir(t *testing.T) { |
| 28 |
dir, err := CreateTempDir("prefix") |
| 29 |
if err != nil { |
| 30 |
t.Fatal(err) |
| 31 |
} |
| 32 |
|
| 33 |
// Delete the directory no matter what. |
| 34 |
defer dir.Delete() |
| 35 |
|
| 36 |
// Make sure we have created the dir, with the proper name |
| 37 |
_, err = os.Stat(dir.Name) |
| 38 |
if err != nil { |
| 39 |
t.Fatal(err) |
| 40 |
} |
| 41 |
if !strings.HasPrefix(filepath.Base(dir.Name), "prefix") { |
| 42 |
t.Fatalf(`Directory doesn't start with "prefix": %q`, |
| 43 |
dir.Name) |
| 44 |
} |
| 45 |
|
| 46 |
// Verify that the directory is empty |
| 47 |
entries, err := ioutil.ReadDir(dir.Name) |
| 48 |
if err != nil { |
| 49 |
t.Fatal(err) |
| 50 |
} |
| 51 |
if len(entries) != 0 { |
| 52 |
t.Fatalf("Directory should be empty, has %d elements", |
| 53 |
len(entries)) |
| 54 |
} |
| 55 |
|
| 56 |
// Create a couple of files |
| 57 |
_, err = dir.NewFile("ONE") |
| 58 |
if err != nil { |
| 59 |
t.Fatal(err) |
| 60 |
} |
| 61 |
_, err = dir.NewFile("TWO") |
| 62 |
if err != nil { |
| 63 |
t.Fatal(err) |
| 64 |
} |
| 65 |
// We can't create the same file twice |
| 66 |
_, err = dir.NewFile("TWO") |
| 67 |
if err == nil { |
| 68 |
t.Fatal("NewFile should fail to create the same file twice") |
| 69 |
} |
| 70 |
|
| 71 |
// We have created only two files |
| 72 |
entries, err = ioutil.ReadDir(dir.Name) |
| 73 |
if err != nil { |
| 74 |
t.Fatal(err) |
| 75 |
} |
| 76 |
if len(entries) != 2 { |
| 77 |
t.Fatalf("ReadDir should have two elements, has %d elements", |
| 78 |
len(entries)) |
| 79 |
} |
| 80 |
|
| 81 |
// Verify that deletion works |
| 82 |
err = dir.Delete() |
| 83 |
if err != nil { |
| 84 |
t.Fatal(err) |
| 85 |
} |
| 86 |
_, err = os.Stat(dir.Name) |
| 87 |
if err == nil { |
| 88 |
t.Fatal("Directory should be gone, still present.") |
| 89 |
} |
| 90 |
} |