diff options
| author | Shulhan <ms@kilabit.info> | 2018-09-13 03:25:25 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2018-09-13 03:25:25 +0700 |
| commit | 261b862720f7d259fa4aa2a6dd7917b2e6e87123 (patch) | |
| tree | 296a4b7eab1027d79af2a3339e3d78218f78667b /lib/test | |
| parent | 7ce478ca7702ccb451152d081679f6d9d201e64a (diff) | |
| download | pakakeh.go-261b862720f7d259fa4aa2a6dd7917b2e6e87123.tar.xz | |
lib/test/mock: mock the standard input with temporary file
Diffstat (limited to 'lib/test')
| -rw-r--r-- | lib/test/mock/mock.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/test/mock/mock.go b/lib/test/mock/mock.go index cd22c165..53d35226 100644 --- a/lib/test/mock/mock.go +++ b/lib/test/mock/mock.go @@ -14,6 +14,7 @@ import ( var ( _stderr *os.File + _stdin *os.File _stdout *os.File ) @@ -31,6 +32,16 @@ func Close() { log.Printf("! Close: os.Remove: %s\n", err) } } + if _stdin != nil { + err := _stdin.Close() + if err != nil { + log.Printf("! Close: %s\n", err) + } + err = os.Remove(_stdin.Name()) + if err != nil { + log.Printf("! Close: os.Remove: %s\n", err) + } + } if _stdout != nil { err := _stdout.Close() if err != nil { @@ -94,6 +105,20 @@ func Stderr() *os.File { } // +// Stdin mock the standar input using temporary file. +// +func Stdin() *os.File { + var err error + + _stdin, err = ioutil.TempFile("", "") + if err != nil { + log.Fatal(err) + } + + return _stdin +} + +// // Stdout mock standard output to temporary file. // func Stdout() *os.File { @@ -134,6 +159,24 @@ func ResetStderr(truncate bool) { } // +// ResetStdin reset mocked standard input offset back to 0. +// If truncated is true, it also reset the size to 0. +// +func ResetStdin(truncate bool) { + if _stdin == nil { + return + } + + _, err := _stdin.Seek(0, io.SeekStart) + if err != nil { + log.Fatal(err) + } + if truncate { + _stdin.Truncate(0) + } +} + +// // ResetStdout reset mocked standard output offset back to 0. // If truncated is true, it also reset the size to 0. // |
