github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/test/scenario/results.go (about)

     1  package scenario
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"go.ptx.dk/multierrgroup"
    10  )
    11  
    12  // A CheckResults is a function that will examine job output that has been
    13  // written to storage and assert something about it. If the condition it is
    14  // checking is false, it returns an error, else it returns nil.
    15  type CheckResults func(resultsDir string) error
    16  
    17  // FileContains returns a CheckResults that asserts that the expected string is
    18  // in the output file and that the file itself is of the correct size.
    19  func FileContains(
    20  	outputFilePath string,
    21  	expectedString string,
    22  	expectedLines int,
    23  ) CheckResults {
    24  	return func(resultsDir string) error {
    25  		outputFile := filepath.Join(resultsDir, outputFilePath)
    26  		resultsContent, err := os.ReadFile(outputFile)
    27  		if err != nil {
    28  			return err
    29  		}
    30  
    31  		actualLineCount := len(strings.Split(string(resultsContent), "\n"))
    32  		if actualLineCount != expectedLines {
    33  			return fmt.Errorf("%s: count mismatch:\nExpected: %d\nActual: %d", outputFile, expectedLines, actualLineCount)
    34  		}
    35  
    36  		if !strings.Contains(string(resultsContent), expectedString) {
    37  			return fmt.Errorf("%s: content mismatch:\nExpected Contains: %q\nActual: %q", outputFile, expectedString, resultsContent)
    38  		}
    39  
    40  		return nil
    41  	}
    42  }
    43  
    44  // FileEquals returns a CheckResults that asserts that the expected string is
    45  // exactly equal to the full contents of the output file.
    46  func FileEquals(
    47  	outputFilePath string,
    48  	expectedString string,
    49  ) CheckResults {
    50  	return func(resultsDir string) error {
    51  		outputFile := filepath.Join(resultsDir, outputFilePath)
    52  		resultsContent, err := os.ReadFile(outputFile)
    53  		if err != nil {
    54  			return err
    55  		}
    56  
    57  		if string(resultsContent) != expectedString {
    58  			return fmt.Errorf("%s: content mismatch:\nExpected: %q\nActual: %q", outputFile, expectedString, resultsContent)
    59  		}
    60  		return nil
    61  	}
    62  }
    63  
    64  // ManyCheckes returns a CheckResults that runs the passed checkers and returns
    65  // an error if any of them fail.
    66  func ManyChecks(checks ...CheckResults) CheckResults {
    67  	return func(resultsDir string) error {
    68  		var wg multierrgroup.Group
    69  		for _, check := range checks {
    70  			check := check
    71  			wg.Go(func() error { return check(resultsDir) })
    72  		}
    73  		return wg.Wait()
    74  	}
    75  }