github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/runtime/debug/heapdump_test.go (about)

     1  // Copyright 2014 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 debug_test
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"runtime"
    11  	. "runtime/debug"
    12  	"testing"
    13  )
    14  
    15  func TestWriteHeapDumpNonempty(t *testing.T) {
    16  	if runtime.GOOS == "nacl" {
    17  		t.Skip("WriteHeapDump is not available on NaCl.")
    18  	}
    19  	f, err := ioutil.TempFile("", "heapdumptest")
    20  	if err != nil {
    21  		t.Fatalf("TempFile failed: %v", err)
    22  	}
    23  	defer os.Remove(f.Name())
    24  	defer f.Close()
    25  	WriteHeapDump(f.Fd())
    26  	fi, err := f.Stat()
    27  	if err != nil {
    28  		t.Fatalf("Stat failed: %v", err)
    29  	}
    30  	const minSize = 1
    31  	if size := fi.Size(); size < minSize {
    32  		t.Fatalf("Heap dump size %d bytes, expected at least %d bytes", size, minSize)
    33  	}
    34  }
    35  
    36  type Obj struct {
    37  	x, y int
    38  }
    39  
    40  func objfin(x *Obj) {
    41  	//println("finalized", x)
    42  }
    43  
    44  func TestWriteHeapDumpFinalizers(t *testing.T) {
    45  	if runtime.GOOS == "nacl" {
    46  		t.Skip("WriteHeapDump is not available on NaCl.")
    47  	}
    48  	f, err := ioutil.TempFile("", "heapdumptest")
    49  	if err != nil {
    50  		t.Fatalf("TempFile failed: %v", err)
    51  	}
    52  	defer os.Remove(f.Name())
    53  	defer f.Close()
    54  
    55  	// bug 9172: WriteHeapDump couldn't handle more than one finalizer
    56  	println("allocating objects")
    57  	x := &Obj{}
    58  	runtime.SetFinalizer(x, objfin)
    59  	y := &Obj{}
    60  	runtime.SetFinalizer(y, objfin)
    61  
    62  	// Trigger collection of x and y, queueing of their finalizers.
    63  	println("starting gc")
    64  	runtime.GC()
    65  
    66  	// Make sure WriteHeapDump doesn't fail with multiple queued finalizers.
    67  	println("starting dump")
    68  	WriteHeapDump(f.Fd())
    69  	println("done dump")
    70  }