From 24566d4236fff1d63e768ea087706958a2f506e2 Mon Sep 17 00:00:00 2001 From: Andrew Gerrand Date: Sun, 30 May 2010 19:21:49 +0200 Subject: [PATCH] doc/code: example package with tests R=r CC=golang-dev https://golang.org/cl/1404041 --- doc/code.html | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/doc/code.html b/doc/code.html index 5c60222aab..9072d0506b 100644 --- a/doc/code.html +++ b/doc/code.html @@ -203,3 +203,88 @@ Once your new code is tested and working, it's time to get it reviewed and submitted.

+

An example package with tests

+ +

+This example package, numbers, consists of the function +Double, which takes an int and returns that value +multiplied by 2. It consists of three files. +

+ +

+First, the package implementation, numbers.go: +

+ +
+package numbers
+
+func Double(i int) int {
+	return i * 2
+}
+
+ +

+Next, the tests, numbers_test.go: +

+ +
+package numbers
+
+import (
+	"testing"
+)
+
+type doubleTest struct {
+	in, out int
+}
+
+var doubleTests = []doubleTest{
+	doubleTest{1, 2},
+	doubleTest{2, 4},
+	doubleTest{-5, -10},
+}
+
+func TestDouble(t *testing.T) {
+	for _, dt := range doubleTests {
+		v := Double(dt.in)
+		if v != dt.out {
+			t.Errorf("Double(%d) returns %d; should be %d.", dt.in, v, dt.out)
+		}
+	}
+}
+
+ +

+Finally, the Makefile: +

+ +
+include $(GOROOT)/src/Make.$(GOARCH)
+
+TARG=numbers
+GOFILES=\
+	numbers.go\
+
+include $(GOROOT)/src/Make.pkg
+
+ +

+Running make install will build and install the package to +the $GOROOT/pkg/ directory (it can then be used by any +program on the system). +

+ +

+Running make test (or just running the command +gotest) will rebuild the package, including the +numbers_test.go file, and then run the TestDouble +function. The output "PASS" indicates that all tests passed +successfully. Breaking the implementation by changing the multiplier from +2 to 3 will allow you to see how failing tests are +reported. +

+ +

+See the gotest documentation and the +testing package for more detail. +