package final

import (
	"runtime"
	"testing"
	"time"
)

type A struct {
	tag string
	t   *testing.T
}

func NewA(tag string, t *testing.T) *A {
	t.Log(tag, "init")
	a := &A{tag: tag, t: t}
	SetFinalizer(a)
	return a
}

func (a *A) Finalizer() {
	a.t.Log(a.tag, "final")
}

func function(t *testing.T) {
	a := NewA("a in function", t)
	_ = a
}

// $ go test -run=TestFinal -v
// === RUN   TestFinal
//     TestFinal: final_test.go:15: a init
//     TestFinal: final_test.go:15: a in function init
//     TestFinal: final_test.go:22: a in function final
//     TestFinal: final_test.go:22: a final
// --- PASS: TestFinal (1.00s)
// PASS
func TestFinal(t *testing.T) {
	a := NewA("a", t)
	function(t)
	_ = a
	runtime.GC()
	time.Sleep(1 * time.Second)
	runtime.GC()
}
