...

Source file src/github.com/bazelbuild/buildtools/testutils/diff.go

Documentation: github.com/bazelbuild/buildtools/testutils

     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 testutils provides some useful helpers for buildozer/buildifer tests.
    18  package testutils
    19  
    20  import (
    21  	"io/ioutil"
    22  	"os"
    23  	"os/exec"
    24  	"testing"
    25  )
    26  
    27  // Diff returns the output of running diff on b1 and b2.
    28  func Diff(b1, b2 []byte) ([]byte, error) {
    29  	f1, err := ioutil.TempFile("", "testdiff")
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	defer os.Remove(f1.Name())
    34  	defer f1.Close()
    35  
    36  	f2, err := ioutil.TempFile("", "testdiff")
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	defer os.Remove(f2.Name())
    41  	defer f2.Close()
    42  
    43  	f1.Write(b1)
    44  	f2.Write(b2)
    45  
    46  	data, err := exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
    47  	if len(data) > 0 {
    48  		// diff exits with a non-zero status when the files don't match.
    49  		// Ignore that failure as long as we get output.
    50  		err = nil
    51  	}
    52  	return data, err
    53  }
    54  
    55  // Tdiff logs the Diff output to t.Error.
    56  func Tdiff(t *testing.T, a, b []byte) {
    57  	data, err := Diff(a, b)
    58  	if err != nil {
    59  		t.Error(err)
    60  		return
    61  	}
    62  	t.Error(string(data))
    63  }
    64  

View as plain text