src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/diag/context_test.go (about)

     1  package diag
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  )
     7  
     8  var sourceRangeTests = []struct {
     9  	Name    string
    10  	Context *Context
    11  	Indent  string
    12  
    13  	WantShow string
    14  }{
    15  	{
    16  		Name:    "single-line culprit",
    17  		Context: contextInParen("[test]", "echo (bad)"),
    18  		Indent:  "_",
    19  
    20  		WantShow: dedent(`
    21  			[test]:1:6-10: echo <(bad)>`),
    22  	},
    23  	{
    24  		Name:    "multi-line culprit",
    25  		Context: contextInParen("[test]", "echo (bad\nbad)\nmore"),
    26  		Indent:  "_",
    27  
    28  		WantShow: dedent(`
    29  			[test]:1:6-2:4:
    30  			_  echo <(bad>
    31  			_  <bad)>`),
    32  	},
    33  	{
    34  		Name:    "trailing newline in culprit is removed",
    35  		Context: NewContext("[test]", "echo bad\n", Ranging{5, 9}),
    36  		Indent:  "_",
    37  
    38  		WantShow: dedent(`
    39  			[test]:1:6-8: echo <bad>`),
    40  	},
    41  	{
    42  		Name:    "empty culprit",
    43  		Context: NewContext("[test]", "echo x", Ranging{5, 5}),
    44  
    45  		WantShow: dedent(`
    46  			[test]:1:6: echo <>x`),
    47  	},
    48  }
    49  
    50  func TestContext(t *testing.T) {
    51  	setContextBodyMarkers(t, "<", ">")
    52  	for _, test := range sourceRangeTests {
    53  		t.Run(test.Name, func(t *testing.T) {
    54  			gotShow := test.Context.Show(test.Indent)
    55  			if gotShow != test.WantShow {
    56  				t.Errorf("Show() -> %q, want %q", gotShow, test.WantShow)
    57  			}
    58  		})
    59  	}
    60  }
    61  
    62  // Returns a Context with the given name and source, and a range for the part
    63  // between ( and ).
    64  func contextInParen(name, src string) *Context {
    65  	return NewContext(name, src,
    66  		Ranging{strings.Index(src, "("), strings.Index(src, ")") + 1})
    67  }