github.com/cockroachdb/pebble@v0.0.0-20231214172447-ab4952c5f87b/internal/mkbench/testutil.go (about)

     1  // Copyright 2021 The LevelDB-Go and Pebble Authors. All rights reserved. Use
     2  // of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  	"runtime"
    13  	"testing"
    14  
    15  	"github.com/cockroachdb/errors"
    16  	"github.com/cockroachdb/errors/oserror"
    17  	"github.com/pmezard/go-difflib/difflib"
    18  )
    19  
    20  // filesEqual returns the diff between contents of a and b.
    21  func filesEqual(a, b string) error {
    22  	aBytes, err := os.ReadFile(a)
    23  	if err != nil {
    24  		return err
    25  	}
    26  	bBytes, err := os.ReadFile(b)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	// Normalize newlines.
    32  	aBytes = bytes.Replace(aBytes, []byte{13, 10} /* \r\n */, []byte{10} /* \n */, -1)
    33  	bBytes = bytes.Replace(bBytes, []byte{13, 10}, []byte{10}, -1)
    34  
    35  	d, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
    36  		A: difflib.SplitLines(string(aBytes)),
    37  		B: difflib.SplitLines(string(bBytes)),
    38  	})
    39  	if d != "" {
    40  		return errors.Errorf("a != b\ndiff = %s", d)
    41  	}
    42  
    43  	return nil
    44  }
    45  
    46  // copyDir recursively copies the fromPath to toPath, excluding certain paths.
    47  func copyDir(fromPath, toPath string) error {
    48  	walkFn := func(path, pathRel string, info os.FileInfo) error {
    49  		// Preserve the directory structure.
    50  		if info.IsDir() {
    51  			err := os.Mkdir(filepath.Join(toPath, pathRel), 0700)
    52  			if err != nil && !oserror.IsNotExist(err) {
    53  				return err
    54  			}
    55  			return nil
    56  		}
    57  
    58  		// Copy files.
    59  		fIn, err := os.Open(path)
    60  		if err != nil {
    61  			return err
    62  		}
    63  		defer func() { _ = fIn.Close() }()
    64  
    65  		fOut, err := os.OpenFile(filepath.Join(toPath, pathRel), os.O_CREATE|os.O_WRONLY, 0700)
    66  		if err != nil {
    67  			return err
    68  		}
    69  		defer func() { _ = fOut.Close() }()
    70  
    71  		_, err = io.Copy(fOut, fIn)
    72  		return err
    73  	}
    74  	return walkDir(fromPath, walkFn)
    75  }
    76  
    77  func maybeSkip(t *testing.T) {
    78  	// The paths in the per-run summary.json files are UNIX-oriented. To avoid
    79  	// duplicating the test fixtures just for Windows, just skip the tests on
    80  	// Windows.
    81  	if runtime.GOOS == "windows" {
    82  		t.Skipf("skipped on windows")
    83  	}
    84  }