github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/testing/sub_test.go (about)

     1  // Copyright 2016 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package testing
     6  
     7  import (
     8  	"reflect"
     9  )
    10  
    11  func TestCleanup(t *T) {
    12  	var cleanups []int
    13  	t.Run("test", func(t *T) {
    14  		t.Cleanup(func() { cleanups = append(cleanups, 1) })
    15  		t.Cleanup(func() { cleanups = append(cleanups, 2) })
    16  	})
    17  	if got, want := cleanups, []int{2, 1}; !reflect.DeepEqual(got, want) {
    18  		t.Errorf("unexpected cleanup record; got %v want %v", got, want)
    19  	}
    20  }
    21  
    22  func TestRunCleanup(t *T) {
    23  	outerCleanup := 0
    24  	innerCleanup := 0
    25  	t.Run("test", func(t *T) {
    26  		t.Cleanup(func() { outerCleanup++ })
    27  		t.Run("x", func(t *T) {
    28  			t.Cleanup(func() { innerCleanup++ })
    29  		})
    30  	})
    31  	if innerCleanup != 1 {
    32  		t.Errorf("unexpected inner cleanup count; got %d want 1", innerCleanup)
    33  	}
    34  	if outerCleanup != 1 {
    35  		t.Errorf("unexpected outer cleanup count; got %d want 1", outerCleanup) // wrong upstream!
    36  	}
    37  }
    38  
    39  func TestCleanupParallelSubtests(t *T) {
    40  	ranCleanup := 0
    41  	t.Run("test", func(t *T) {
    42  		t.Cleanup(func() { ranCleanup++ })
    43  		t.Run("x", func(t *T) {
    44  			t.Parallel()
    45  			if ranCleanup > 0 {
    46  				t.Error("outer cleanup ran before parallel subtest")
    47  			}
    48  		})
    49  	})
    50  	if ranCleanup != 1 {
    51  		t.Errorf("unexpected cleanup count; got %d want 1", ranCleanup)
    52  	}
    53  }
    54  
    55  func TestNestedCleanup(t *T) {
    56  	ranCleanup := 0
    57  	t.Run("test", func(t *T) {
    58  		t.Cleanup(func() {
    59  			if ranCleanup != 2 {
    60  				t.Errorf("unexpected cleanup count in first cleanup: got %d want 2", ranCleanup)
    61  			}
    62  			ranCleanup++
    63  		})
    64  		t.Cleanup(func() {
    65  			if ranCleanup != 0 {
    66  				t.Errorf("unexpected cleanup count in second cleanup: got %d want 0", ranCleanup)
    67  			}
    68  			ranCleanup++
    69  			t.Cleanup(func() {
    70  				if ranCleanup != 1 {
    71  					t.Errorf("unexpected cleanup count in nested cleanup: got %d want 1", ranCleanup)
    72  				}
    73  				ranCleanup++
    74  			})
    75  		})
    76  	})
    77  	if ranCleanup != 3 {
    78  		t.Errorf("unexpected cleanup count: got %d want 3", ranCleanup)
    79  	}
    80  }