...

Package temptest

import "k8s.io/utils/temp/temptest"
Overview
Index
Examples

Overview ▾

Package temptest provides utilities for testing temp files/directories testing.

Example

Code:

package temptest

import (
    "errors"
    "fmt"
    "io"

    "k8s.io/utils/temp"
)

func TestedCode(dir temp.Directory) error {
    f, err := dir.NewFile("filename")
    if err != nil {
        return err
    }
    _, err = io.WriteString(f, "Bonjour!")
    if err != nil {
        return err
    }
    return dir.Delete()
}

func Example() {
    dir := FakeDir{}

    err := TestedCode(&dir)
    if err != nil {
        panic(err)
    }

    if dir.Deleted == false {
        panic(errors.New("Directory should have been deleted"))
    }

    if dir.Files["filename"] == nil {
        panic(errors.New(`"filename" should have been created`))
    }

    fmt.Println(dir.Files["filename"].Buffer.String())
    // Output: Bonjour!
}

type FakeDir

FakeDir implements a Directory that is not backed on the filesystem. This is useful for testing since the created "files" are simple bytes.Buffer that can be inspected.

type FakeDir struct {
    Files   map[string]*FakeFile
    Deleted bool
}

func (*FakeDir) Delete

func (d *FakeDir) Delete() error

Delete doesn't remove anything, but records that the directory has been deleted.

func (*FakeDir) NewFile

func (d *FakeDir) NewFile(name string) (io.WriteCloser, error)

NewFile returns a new FakeFile if the filename doesn't exist already. This function will fail if the directory has already been deleted.

type FakeFile

FakeFile is an implementation of a WriteCloser, that records what has been written in the file (in a bytes.Buffer) and if the file has been closed.

type FakeFile struct {
    Buffer bytes.Buffer
    Closed bool
}

func (*FakeFile) Close

func (f *FakeFile) Close() error

Close records that the file has been closed. If the file has already been closed, an error is returned.

func (*FakeFile) Write

func (f *FakeFile) Write(p []byte) (n int, err error)

Write appends the contents of p to the Buffer. If the file has already been closed, an error is returned.