github.com/packtpublishing/learning-functional-programming-in-go@v0.0.0-20230130084745-8b849f6d58c4/Chapter01/03_sum/01_loop_test.go (about)

     1  package fib
     2  
     3  import "testing"
     4  
     5  var sumTests = []struct {
     6  	a     []int
     7  	expected int
     8  }{
     9  	{[]int{1}, 1},
    10  	{[]int{1, 2}, 3},
    11  	{[]int{1, 2, 3}, 6},
    12  	{[]int{1, 2, 3, 4}, 10},
    13  }
    14  
    15  func TestSumLoop(t *testing.T) {
    16  	for _, st := range sumTests {
    17  		if v := SumLoop(st.a); v != st.expected {
    18  			t.Errorf("SumLoop(%d) returned %d, expected %d", st.a, v, st.expected)
    19  		}
    20  	}
    21  }
    22  
    23  func BenchmarkSumLoop(b *testing.B) {
    24  	fn := SumLoop
    25  	for i := 0; i < b.N; i++ {
    26  		_ = fn([]int{1, 2, 3})
    27  	}
    28  }
    29  
    30  func benchmarkSumLoop(s []int, b *testing.B) {
    31  	for n := 0; n < b.N; n++ {
    32  		SumLoop(s)
    33  	}
    34  }
    35  
    36  func BenchmarkSumLoop1(b *testing.B)  { benchmarkSumLoop([]int{1}, b) }
    37  func BenchmarkSumLoop2(b *testing.B)  { benchmarkSumLoop([]int{1, 2}, b) }
    38  func BenchmarkSumLoop3(b *testing.B)  { benchmarkSumLoop([]int{1, 2, 3}, b) }
    39  func BenchmarkSumLoop10(b *testing.B) { benchmarkSumLoop([]int{1, 2, 3, 4}, b) }
    40  func BenchmarkSumLoop20(b *testing.B) { benchmarkSumLoop([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}, b) }
    41  func BenchmarkSumLoop40(b *testing.B) { benchmarkSumLoop([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40}, b) }