Created
January 18, 2016 10:22
-
-
Save evalphobia/b0fe0c8cc8efd9eb7c77 to your computer and use it in GitHub Desktop.
テストコード01
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"io" | |
"os" | |
"strings" | |
"testing" | |
"github.com/stretchr/testify/assert" | |
) | |
func TestMain(t *testing.T) { | |
assert := assert.New(t) | |
m := &StdoutMock{} | |
m.Set() | |
main() | |
output := m.Get() | |
actual := strings.Split(output, "\n") | |
assert.True(len(actual) >= 7) | |
assert.Contains(" * ", actual[0]) | |
assert.Contains(" *** ", actual[1]) | |
assert.Contains(" ***** ", actual[2]) | |
assert.Contains("*******", actual[3]) | |
assert.Contains(" ***** ", actual[4]) | |
assert.Contains(" *** ", actual[5]) | |
assert.Contains(" * ", actual[6]) | |
} | |
type StdoutMock struct { | |
stdout *os.File | |
stderr *os.File | |
writer *os.File | |
output chan string | |
} | |
func (m *StdoutMock) Set() { | |
backupOut := os.Stdout | |
backupErr := os.Stderr | |
r, w, _ := os.Pipe() | |
os.Stdout = w | |
os.Stderr = w | |
opChan := make(chan string) | |
go func() { | |
var buf bytes.Buffer | |
io.Copy(&buf, r) | |
opChan <- buf.String() | |
}() | |
m.stdout = backupOut | |
m.stderr = backupErr | |
m.writer = w | |
m.output = opChan | |
} | |
func (m *StdoutMock) Get() string { | |
m.writer.Close() | |
os.Stdout = m.stdout | |
os.Stderr = m.stderr | |
return <-m.output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
問題 1 のテストコード
https://gist.github.com/bsoo/bd361a7fe01fc6bff068
以下で実行できます。
(解答の関数は
main
で作って下さい)