github.com/cloudfoundry/libcfbuildpack@v1.91.23/test/have_content.go (about)

     1  /*
     2   * Copyright 2018-2020 the original author or authors.
     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 test
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  
    23  	"github.com/onsi/gomega/types"
    24  )
    25  
    26  // HaveContent tests that a file has expected content.
    27  func HaveContent(expected string) types.GomegaMatcher {
    28  	return &haveContentMatcher{
    29  		expected: expected,
    30  	}
    31  }
    32  
    33  type haveContentMatcher struct {
    34  	expected string
    35  }
    36  
    37  func (m *haveContentMatcher) Match(actual interface{}) (bool, error) {
    38  	path, ok := actual.(string)
    39  	if !ok {
    40  		return false, fmt.Errorf("HaveContent matcher expects a path")
    41  	}
    42  
    43  	b, err := ioutil.ReadFile(path)
    44  	if err != nil {
    45  		return false, fmt.Errorf("failed to read file: %s", err.Error())
    46  	}
    47  
    48  	return string(b) == m.expected, nil
    49  }
    50  
    51  func (m *haveContentMatcher) FailureMessage(actual interface{}) string {
    52  	return fmt.Sprintf("Expected\n\t%#v\nto contain\n\t%#v", actual, m.expected)
    53  }
    54  
    55  func (m *haveContentMatcher) NegatedFailureMessage(actual interface{}) string {
    56  	return fmt.Sprintf("Expected\n\t%#v\nnot to contain\n\t%#v", actual, m.expected)
    57  }