gorgonia.org/gorgonia@v0.9.17/encoding/dot/issues_test.go (about)

     1  package dot
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"gorgonia.org/gorgonia"
    10  )
    11  
    12  // unmangleName replaces the pointer-based name with the node name.
    13  //
    14  // Node names are unique in Gorgonia graphs.
    15  // However we cannot use node names in a `.dot` file because there are some names
    16  // that will not be accepted by graphviz.
    17  //
    18  // Hence we use pointers as part of the name of the nodes. A node will have a name
    19  // like "Node_0xbadb100d" (shout out to Tay Tay!) in the `.dot` file.
    20  //
    21  // unmangleName replaces `Node_0xbadc0ffee` with the name of the node for the purposes of testing.
    22  func unmangleName(marshalled string, node *gorgonia.Node) string {
    23  	name := node.Name()
    24  	ptrName := fmt.Sprintf("%p", node)
    25  
    26  	return strings.Replace(marshalled, ptrName, name, -1)
    27  }
    28  
    29  func TestIssue_407(t *testing.T) {
    30  	// originally written by @wzzhu
    31  
    32  	assert := assert.New(t)
    33  	g := gorgonia.NewGraph()
    34  	var x, y, z *gorgonia.Node
    35  	var err error
    36  
    37  	// define the expression
    38  	x = gorgonia.NewScalar(g, gorgonia.Float64, gorgonia.WithName("x"))
    39  	y = gorgonia.NewScalar(g, gorgonia.Float64, gorgonia.WithName("y"))
    40  	if z, err = gorgonia.Add(x, y); err != nil {
    41  		t.Fatal(err)
    42  	}
    43  	b, err := Marshal(g)
    44  	if err != nil {
    45  		t.Errorf("Error printing graph: %v", err)
    46  	}
    47  	fst := fmt.Sprintf("\n%s", string(b))
    48  	fst = unmangleName(fst, x)
    49  	fst = unmangleName(fst, y)
    50  	fst = unmangleName(fst, z)
    51  
    52  	var x2, y2, z2 *gorgonia.Node
    53  
    54  	g2 := gorgonia.NewGraph()
    55  	x2 = gorgonia.NewScalar(g2, gorgonia.Float64, gorgonia.WithName("x"))
    56  	y2 = gorgonia.NewScalar(g2, gorgonia.Float64, gorgonia.WithName("y"))
    57  	if z2, err = gorgonia.Add(x2, y2); err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	b2, err := Marshal(g2)
    61  	if err != nil {
    62  		t.Errorf("Error printing graph: %v", err)
    63  	}
    64  	snd := fmt.Sprintf("\n%s", string(b2))
    65  	snd = unmangleName(snd, x2)
    66  	snd = unmangleName(snd, y2)
    67  	snd = unmangleName(snd, z2)
    68  	assert.Equal(fst, snd, "XXX")
    69  	t.Logf("%v %v", z, z2)
    70  }
    71  
    72  func TestStressTest407(t *testing.T) {
    73  	for i := 0; i < 1024; i++ {
    74  		TestIssue_407(t)
    75  		if t.Failed() {
    76  			t.Errorf("Failed at iteration %d", i)
    77  			break
    78  		}
    79  	}
    80  }