|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "runtime" |
| 7 | + "strconv" |
| 8 | + "testing" |
| 9 | +) |
| 10 | + |
| 11 | +var goroutineSpace = []byte("goroutine ") |
| 12 | + |
| 13 | +func curGoroutineID() uint64 { |
| 14 | + b := make([]byte, 64) |
| 15 | + b = b[:runtime.Stack(b, false)] |
| 16 | + // Parse the 4707 out of "goroutine 4707 [" |
| 17 | + b = bytes.TrimPrefix(b, goroutineSpace) |
| 18 | + i := bytes.IndexByte(b, ' ') |
| 19 | + if i < 0 { |
| 20 | + panic(fmt.Sprintf("No space found in %q", b)) |
| 21 | + } |
| 22 | + b = b[:i] |
| 23 | + n, err := strconv.ParseUint(string(b), 10, 64) |
| 24 | + if err != nil { |
| 25 | + panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) |
| 26 | + } |
| 27 | + return n |
| 28 | +} |
| 29 | + |
| 30 | +// 被测代码 |
| 31 | +func Add(a, b int) int { |
| 32 | + return a + b |
| 33 | +} |
| 34 | + |
| 35 | +// 测试代码 |
| 36 | +func TestAdd(t *testing.T) { |
| 37 | + t.Log("g:", curGoroutineID()) |
| 38 | + t.Parallel() |
| 39 | + got := Add(2, 3) |
| 40 | + if got != 5 { |
| 41 | + t.Errorf("Add(2, 3) got %d, want 5", got) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +func TestAddZero(t *testing.T) { |
| 46 | + t.Parallel() |
| 47 | + got := Add(2, 0) |
| 48 | + if got != 2 { |
| 49 | + t.Fatalf("Add(2, 0) got %d, want 2", got) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func TestAddOppositeNum(t *testing.T) { |
| 54 | + got := Add(2, -2) |
| 55 | + t.Parallel() |
| 56 | + if got != 0 { |
| 57 | + t.Errorf("Add(2, -2) got %d, want 0", got) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func TestAddWithTable(t *testing.T) { |
| 62 | + t.Log("g:", curGoroutineID()) |
| 63 | + t.Parallel() |
| 64 | + cases := []struct { |
| 65 | + name string |
| 66 | + a int |
| 67 | + b int |
| 68 | + r int |
| 69 | + }{ |
| 70 | + {"2+3", 2, 3, 5}, |
| 71 | + {"2+0", 2, 0, 2}, |
| 72 | + {"2+(-2)", 2, -2, 0}, |
| 73 | + //... ... |
| 74 | + } |
| 75 | + |
| 76 | + for _, caze := range cases { |
| 77 | + got := Add(caze.a, caze.b) |
| 78 | + if got != caze.r { |
| 79 | + t.Errorf("%s got %d, want %d", caze.name, got, caze.r) |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments