Skip to content

rhysd/go-fakeio

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fakeio pacakge for Go

Linux/macOS Build Status Windows Build status Documentation

fakeio is a small library to fake stdout/stderr/stdin. This is mainly for unit testing of CLI applications. Please see documentation for more details.

Installation

$ go get github.com/rhysd/go-fakeio

Usage

Basic usage:

import (
    "bufio"
    "github.com/rhysd/go-fakeio"
)

// Fake stdout and input 'hello' to stdin
fake := fakeio.Stdout().Stdin("hello!")
defer fake.Restore()

// Do something...

// "hello!" is stored to variable `i`
i, err := bufio.NewReader(os.Stdin).ReadString('!')

// At this point, this line outputs nothing
fmt.Print("bye")

// "bye" is stored to variable `o`
o, err := fake.String()

Faking stdout/stderr/stdin

Faking stderr:

fake := fakeio.Stderr()
defer fake.Restore()

Faking stdin:

fake, err := fakeio.Stdin("hello")
defer fake.Restore()

Faking stderr/stdout/stdin

fake := fakeio.Stderr().Stdout().Stdin("Faked input to stdin")
defer fake.Restore()

Read bufferred stdout/stderr

Reading as string:

s, err := fake.String()
if err != nil {
    // Faking IO failed
    panic(err)
}
fmt.Println(s)

Reading as bytes:

b, err := fake.Bytes()
if err != nil {
    // Faking IO failed
    panic(err)
}
fmt.Println(b)

Reading via io.Reader interface:

s := bufio.NewScanner(fake)
for s.Scan() {
    // Reading line by line
    line := s.Text()
    fmt.Println(line)
}
if s.Err() != nil {
    // Error happened while reading
    panic(s.Err)
}

Shortcut

.Do() is a shortcut

s, err := fakeio.Stderr().Stdout().Do(func () {
    // Do something

    // Faked stderr and stdout are restored at exit of this scope
})
if err != nil {
    // Faking IO failed
    panic(err)
}
fmt.Println(s)

Examples

Please see examples for actual examples.

Repository

https://github.com/rhysd/go-fakeio

License

MIT License

About

Small Go library to fake stdout/stderr/stdin mainly for unit testing

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages