github.com/hashicorp/hcl/v2@v2.20.0/json/navigation_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package json
     5  
     6  import (
     7  	"fmt"
     8  	"strconv"
     9  	"testing"
    10  )
    11  
    12  func TestNavigationContextString(t *testing.T) {
    13  	src := `
    14  {
    15    "version": 1,
    16    "resource": {
    17      "null_resource": {
    18        "baz": {
    19          "id": "foo"
    20  			},
    21  			"boz": [
    22  				{
    23  					"ov": {   }
    24  				}
    25  			]
    26      }
    27    }
    28  }
    29  `
    30  	file, diags := Parse([]byte(src), "test.json")
    31  	if len(diags) != 0 {
    32  		fmt.Printf("offset %d\n", diags[0].Subject.Start.Byte)
    33  		t.Errorf("Unexpected diagnostics: %s", diags)
    34  	}
    35  	if file == nil {
    36  		t.Fatalf("Got nil file")
    37  	}
    38  	nav := file.Nav.(navigation)
    39  
    40  	tests := []struct {
    41  		Offset int
    42  		Want   string
    43  	}{
    44  		{0, ``},
    45  		{8, ``},
    46  		{36, `resource`},
    47  		{60, `resource.null_resource`},
    48  		{89, `resource.null_resource.baz`},
    49  		{141, `resource.null_resource.boz`},
    50  	}
    51  
    52  	for _, test := range tests {
    53  		t.Run(strconv.Itoa(test.Offset), func(t *testing.T) {
    54  			got := nav.ContextString(test.Offset)
    55  
    56  			if got != test.Want {
    57  				t.Errorf("wrong result\ngot:  %s\nwant: %s", got, test.Want)
    58  			}
    59  		})
    60  	}
    61  }