| 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 temptest |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
|
| 24 |
"k8s.io/utils/temp" |
| 25 |
) |
| 26 |
|
| 27 |
// FakeDir implements a Directory that is not backed on the |
| 28 |
// filesystem. This is useful for testing since the created "files" are |
| 29 |
// simple bytes.Buffer that can be inspected. |
| 30 |
type FakeDir struct { |
| 31 |
Files map[string]*FakeFile |
| 32 |
Deleted bool |
| 33 |
} |
| 34 |
|
| 35 |
var _ temp.Directory = &FakeDir{} |
| 36 |
|
| 37 |
// NewFile returns a new FakeFile if the filename doesn't exist already. |
| 38 |
// This function will fail if the directory has already been deleted. |
| 39 |
func (d *FakeDir) NewFile(name string) (io.WriteCloser, error) { |
| 40 |
if d.Deleted { |
| 41 |
return nil, errors.New("can't create file in deleted FakeDir") |
| 42 |
} |
| 43 |
if d.Files == nil { |
| 44 |
d.Files = map[string]*FakeFile{} |
| 45 |
} |
| 46 |
f := d.Files[name] |
| 47 |
if f != nil { |
| 48 |
return nil, fmt.Errorf( |
| 49 |
"FakeDir already has file named %q", |
| 50 |
name, |
| 51 |
) |
| 52 |
} |
| 53 |
f = &FakeFile{} |
| 54 |
d.Files[name] = f |
| 55 |
return f, nil |
| 56 |
} |
| 57 |
|
| 58 |
// Delete doesn't remove anything, but records that the directory has |
| 59 |
// been deleted. |
| 60 |
func (d *FakeDir) Delete() error { |
| 61 |
if d.Deleted { |
| 62 |
return errors.New("failed to re-delete FakeDir") |
| 63 |
} |
| 64 |
d.Deleted = true |
| 65 |
return nil |
| 66 |
} |