LoginSignup
2

More than 5 years have passed since last update.

paiza/atCoder で使うGoコードをテスト環境から実行する

Last updated at Posted at 2018-03-20

paizaやAtCoderで使うような、標準入力から入力を受けとり、標準出力に結果を出力するようなコードを簡単にテストする環境を作ります。

次のようなヘルパ関数を作ります


package main_test

import (
    "bytes"
    "fmt"
    "io"
    "strings"
    "testing"
)

func checker(input string, f func(io.Reader, io.Writer)) string {
    reader := strings.NewReader(input)
    writer := bytes.NewBufferString("")
    f(reader, writer)
    return writer.String()
}

標準入力と標準出力の代わりにstringを使うようにします。
func(io.Reader, io.Writer) に実際にpaiza/atCoderで使うコードを書くことになります。

以下にコード全体を載せます。

package main_test

import (
    "bytes"
    "fmt"
    "io"
    "strings"
    "testing"
)

func checker(input string, f func(io.Reader, io.Writer)) string {
    reader := strings.NewReader(input)
    writer := bytes.NewBufferString("")
    f(reader, writer)
    return writer.String()
}

func sampleCode(reader io.Reader, writer io.Writer) {
    var a, b, c, d int
    fmt.Fscanf(reader, "%d %d %d %d\n", &a, &b, &c, &d)
    fmt.Fprintf(writer, "%d\n%d\n%d\n%d\n", a, b, c, d)
    fmt.Fscanf(reader, "%d %d %d\n", &a, &b, &c)
    fmt.Fprintf(writer, "%d\n%d\n%d", a, b, c)
}

func TestSample(t *testing.T) {
    inputString :=
        `1 2 3 4
5 6 7`
    expect := `1
2
3
4
5
6
7`
    output := checker(inputString, sampleCode)
    if output != expect {
        t.Errorf("expcet %v,but%v", expect, output)
    }
}

実際にpaiza/atCoderに投稿するときは以下のようにします

package main
import (
"fmt"
"os"
)
func sampleCode(reader io.Reader, writer io.Writer) {
    var a, b, c, d int
    fmt.Fscanf(reader, "%d %d %d %d\n", &a, &b, &c, &d)
    fmt.Fprintf(writer, "%d\n%d\n%d\n%d\n", a, b, c, d)
    fmt.Fscanf(reader, "%d %d %d\n", &a, &b, &c)
    fmt.Fprintf(writer, "%d\n%d\n%d", a, b, c)
}

func main() {
  sampleCode(os.Stdin,os.Stdout)
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2