Source file src/cmd/compile/internal/ir/html_test.go

     1  // Copyright 2026 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 ir
     6  
     7  import (
     8  	"cmd/compile/internal/base"
     9  	"cmd/compile/internal/types"
    10  	"cmd/internal/obj"
    11  	"cmd/internal/src"
    12  	"os"
    13  	"path/filepath"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  func TestHTMLWriter(t *testing.T) {
    19  	// Initialize base.Ctxt to avoid panics
    20  	base.Ctxt = new(obj.Link)
    21  
    22  	// Setup a temporary directory for output
    23  	tmpDir := t.TempDir()
    24  
    25  	// Mock func
    26  	fn := &Func{
    27  		Nname: &Name{
    28  			sym: &types.Sym{Name: "TestFunc"},
    29  		},
    30  	}
    31  	// Func embeds miniExpr, so we might need to set op if checked
    32  	fn.op = ODCLFUNC
    33  
    34  	// Create HTMLWriter
    35  	outFile := filepath.Join(tmpDir, "test.html")
    36  	w := NewHTMLWriter(outFile, fn, "")
    37  	if w == nil {
    38  		t.Fatalf("Failed to create HTMLWriter")
    39  	}
    40  
    41  	// Write a phase
    42  	w.WritePhase("phase1", "Phase 1")
    43  
    44  	// Register a file/line
    45  	posBase := src.NewFileBase("test.go", "test.go")
    46  	// base.Ctxt.PosTable.Register(posBase) -- Not needed/doesn't exist
    47  	pos := src.MakePos(posBase, 10, 1)
    48  
    49  	// Create a dummy node
    50  	n := &Name{
    51  		sym:   &types.Sym{Name: "VarX"},
    52  		Class: PAUTO,
    53  	}
    54  	n.op = ONAME
    55  	n.pos = base.Ctxt.PosTable.XPos(pos)
    56  
    57  	// Add another phase which actually dumps something interesting
    58  	fn.Body = []Node{n}
    59  	w.WritePhase("phase2", "Phase 2")
    60  
    61  	// Test escaping
    62  	n2 := &Name{
    63  		sym:   &types.Sym{Name: "<Bad>"},
    64  		Class: PAUTO,
    65  	}
    66  	n2.op = ONAME
    67  	fn.Body = []Node{n2}
    68  	w.WritePhase("phase3", "Phase 3")
    69  
    70  	w.Close()
    71  
    72  	// Verify file exists and has content
    73  	content, err := os.ReadFile(outFile)
    74  	if err != nil {
    75  		t.Fatalf("Failed to read output file: %v", err)
    76  	}
    77  
    78  	s := string(content)
    79  	if len(s) == 0 {
    80  		t.Errorf("Output file is empty")
    81  	}
    82  
    83  	// Check for Expected strings
    84  	expected := []string{
    85  		"<html>",
    86  		"Phase 1",
    87  		"Phase 2",
    88  		"Phase 2",
    89  		"VarX",
    90  		"NAME",
    91  		"&lt;Bad&gt;",
    92  		"resizer",
    93  		"loc-",
    94  		"line-number",
    95  		"sym-",
    96  		"variable-name",
    97  	}
    98  
    99  	for _, e := range expected {
   100  		if !strings.Contains(s, e) {
   101  			t.Errorf("Output missing %q", e)
   102  		}
   103  	}
   104  }
   105  

View as plain text