パッケージを作る

パッケージの作る方法は「Goコードの書き方」にあります。これに従って、Makefileを作ります。my_sort.goにmysortパッケージを作るとすると、Makefile


include $(GOROOT)/src/Make.inc

TARG=mysort
GOFILES=\
my_sort.go\

include $(GOROOT)/src/Make.pkg


とすればOKです。テストを書く場合はmy_sort_test.goにテストを書いて、gotest my_sort_test.goとすれば、テストが実行されます。テストはtestingパッケージをimportして、例えば次のように書きます。

package my_sort_test
import (
        "testing"
        . "mysort"
        )

func TestIsSorted(t *testing.T) {
        if !IsSorted([]int{1,2,3,4,5}) {
                t.Errorf("should not be sorted")
        }
        if IsSorted([]int{4,5,3,1,2}) {
                t.Errorf("should be sorted")
        }
}

mysort.goを

package mysort

として、gotestを実行します。


$gotest my_sort_test.go
rm -f _test/mysort.a
8g -o _gotest_.8 my_sort.go
rm -f _test/mysort.a
gopack grc _test/mysort.a _gotest_.8
my_sort_test.go:5: imported and not used: mysort
my_sort_test.go:9: undefined: IsSorted
my_sort_test.go:12: undefined: IsSorted
gotest: "/home/noriaki/go/bin/8g -I _test -o _xtest_.8 my_sort_test.go" failed: exit status 1

IsSortedが定義されてないことを教えてくれます。my_sort.goにIsSortedを仮実装します。

func IsSorted(data []int) bool {
  return false
}

今度はコンパイルには成功しますが、テストに失敗します。


rm -f _test/mysort.a
8g -o _gotest_.8 my_sort.go
rm -f _test/mysort.a
gopack grc _test/mysort.a _gotest_.8
ーーー FAIL: my_sort_test.TestIsSorted (0.00 seconds)
should not be sorted
FAIL
gotest: "./8.out" failed: exit status 1

シェルが値を返しました 2


IsSortedを実装し直します。

func IsSorted(data []int) bool {
        for i := 0; i < len(data)-1; i++ {
                if data[i] > data[i+1] {
                        return false
                }
        }
        return true
}

今度はテストに成功します。


rm -f _test/mysort.a
rm -f _test/mysort.a
gopack grc _test/mysort.a _gotest_.8
PASS

テストと関数の仮実装だけ用意して、テストを実行します。

func TestInsertionSort(t *testing.T) {
        data    := []int{3,2,5,1,4,8,7,6}
        sorted := []int{1,2,3,4,5,6,7,8}
        InsertionSort(data)
        if !IsSorted(data) {
                t.Errorf("sorted %v", sorted)
                t.Errorf("got %v", data)
        }
}
func InsertionSort(data []int) {
}

無事、テストに失敗します。今回はこれを直して終了にします。


m -f _test/mysort.a
8g -o _gotest_.8 my_sort.go
rm -f _test/mysort.a
gopack grc _test/mysort.a _gotest_.8
ーーー FAIL: my_sort_test.TestInsertionSort (0.00 seconds)
sorted [1 2 3 4 5 6 7 8]
got [3 2 5 1 4 8 7 6]
FAIL
gotest: "./8.out" failed: exit status 1

シェルが値を返しました 2

func InsertionSort(data []int) {
        for i := 1; i < len(data); i++ {
                for j := i; j > 0 && (data[j] < data[j-1]); j-- {
                        data[j-1], data[j] = data[j], data[j-1]
                }
        }
}

再び全てのテストに成功します。


rm -f _test/mysort.a
8g -o _gotest_.8 my_sort.go
rm -f _test/mysort.a
gopack grc _test/mysort.a _gotest_.8
PASS

今回はC言語のような書き方をしましたが、それはパッケージの作り方とそのテストに(ぼくが)集中するためです。