...

Source file src/github.com/bazelbuild/buildtools/bzlenv/bzlenv_test.go

Documentation: github.com/bazelbuild/buildtools/bzlenv

     1  /*
     2  Copyright 2020 Google LLC
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      https://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package bzlenv
    18  
    19  import (
    20  	"strconv"
    21  	"strings"
    22  	"testing"
    23  
    24  	"github.com/bazelbuild/buildtools/build"
    25  )
    26  
    27  func TestWalkEnvironment(t *testing.T) {
    28  	input := `
    29  a, b = 2, 3
    30  
    31  def bar(x, y = a):
    32      b = 4
    33      c = a
    34      [a for a in [b, c]]
    35      if True:
    36          return foo()
    37  
    38  def foo():
    39      pass
    40  `
    41  
    42  	expected := `
    43  a0, b1 = 2, 3
    44  
    45  def bar2(x4, y5 = a0):
    46      b6 = 4
    47      c7 = a0
    48      [a8 for a8 in [b6, c7]]
    49      if True:
    50          return foo3()
    51  
    52  def foo3():
    53      pass
    54  `
    55  
    56  	var buildFile build.Expr
    57  	buildFile, _ = build.Parse("test_file.bzl", []byte(input))
    58  
    59  	var walk func(e *build.Expr, env *Environment)
    60  	walk = func(e *build.Expr, env *Environment) {
    61  		switch e := (*e).(type) {
    62  		case *build.DefStmt:
    63  			binding := env.Get(e.Name)
    64  			if binding != nil {
    65  				e.Name += strconv.Itoa(binding.ID)
    66  			}
    67  		case *build.Ident:
    68  			binding := env.Get(e.Name)
    69  			if binding != nil {
    70  				e.Name += strconv.Itoa(binding.ID)
    71  			}
    72  		}
    73  		WalkOnceWithEnvironment(*e, env, walk)
    74  	}
    75  	walk(&buildFile, NewEnvironment())
    76  
    77  	output := strings.Trim(build.FormatString(buildFile), "\n")
    78  	expected = strings.Trim(expected, "\n")
    79  	if output != expected {
    80  		t.Errorf("\nexpected:\n%s\ngot:\n%s", expected, output)
    81  	}
    82  }
    83  

View as plain text