github.com/v2fly/tools@v0.100.0/internal/span/span_test.go (about)

     1  // Copyright 2019 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 span_test
     6  
     7  import (
     8  	"fmt"
     9  	"path/filepath"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/v2fly/tools/internal/span"
    14  )
    15  
    16  var (
    17  	tests = [][]string{
    18  		{"C:/file_a", "C:/file_a", "file:///C:/file_a:1:1#0"},
    19  		{"C:/file_b:1:2", "C:/file_b:#1", "file:///C:/file_b:1:2#1"},
    20  		{"C:/file_c:1000", "C:/file_c:#9990", "file:///C:/file_c:1000:1#9990"},
    21  		{"C:/file_d:14:9", "C:/file_d:#138", "file:///C:/file_d:14:9#138"},
    22  		{"C:/file_e:1:2-7", "C:/file_e:#1-#6", "file:///C:/file_e:1:2#1-1:7#6"},
    23  		{"C:/file_f:500-502", "C:/file_f:#4990-#5010", "file:///C:/file_f:500:1#4990-502:1#5010"},
    24  		{"C:/file_g:3:7-8", "C:/file_g:#26-#27", "file:///C:/file_g:3:7#26-3:8#27"},
    25  		{"C:/file_h:3:7-4:8", "C:/file_h:#26-#37", "file:///C:/file_h:3:7#26-4:8#37"},
    26  	}
    27  )
    28  
    29  func TestFormat(t *testing.T) {
    30  	converter := lines(10)
    31  	for _, test := range tests {
    32  		for ti, text := range test[:2] {
    33  			spn := span.Parse(text)
    34  			if ti <= 1 {
    35  				// we can check %v produces the same as the input
    36  				expect := toPath(test[ti])
    37  				if got := fmt.Sprintf("%v", spn); got != expect {
    38  					t.Errorf("printing %q got %q expected %q", text, got, expect)
    39  				}
    40  			}
    41  			complete, err := spn.WithAll(converter)
    42  			if err != nil {
    43  				t.Error(err)
    44  			}
    45  			for fi, format := range []string{"%v", "%#v", "%+v"} {
    46  				expect := toPath(test[fi])
    47  				if got := fmt.Sprintf(format, complete); got != expect {
    48  					t.Errorf("printing completed %q as %q got %q expected %q [%+v]", text, format, got, expect, spn)
    49  				}
    50  			}
    51  		}
    52  	}
    53  }
    54  
    55  func toPath(value string) string {
    56  	if strings.HasPrefix(value, "file://") {
    57  		return value
    58  	}
    59  	return filepath.FromSlash(value)
    60  }
    61  
    62  type lines int
    63  
    64  func (l lines) ToPosition(offset int) (int, int, error) {
    65  	return (offset / int(l)) + 1, (offset % int(l)) + 1, nil
    66  }
    67  
    68  func (l lines) ToOffset(line, col int) (int, error) {
    69  	return (int(l) * (line - 1)) + (col - 1), nil
    70  }