github.com/cloudfoundry/libcfbuildpack@v1.91.23/test/have_profile.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  	"path/filepath"
    23  	"reflect"
    24  
    25  	"github.com/onsi/gomega/types"
    26  )
    27  
    28  // HaveProfile tests that a layer has a profile.d file with the expected content.
    29  func HaveProfile(name string, format string, args ...interface{}) types.GomegaMatcher {
    30  	return &haveProfileMatcher{
    31  		name,
    32  		fmt.Sprintf(format, args...),
    33  	}
    34  }
    35  
    36  type haveProfileMatcher struct {
    37  	name     string
    38  	expected string
    39  }
    40  
    41  func (m *haveProfileMatcher) Match(actual interface{}) (bool, error) {
    42  	path, err := m.path(actual, m.name)
    43  	if err != nil {
    44  		return false, err
    45  	}
    46  
    47  	b, err := ioutil.ReadFile(path)
    48  	if err != nil {
    49  		return false, fmt.Errorf("failed to read file: %s", err.Error())
    50  	}
    51  
    52  	return string(b) == m.expected, nil
    53  }
    54  
    55  func (m *haveProfileMatcher) FailureMessage(actual interface{}) string {
    56  	return fmt.Sprintf("Expected\n\t%#v\nto have layer profile %#v\n\t%#v", actual, m.name, m.expected)
    57  }
    58  
    59  func (m *haveProfileMatcher) NegatedFailureMessage(actual interface{}) string {
    60  	return fmt.Sprintf("Expected\n\t%#v\nnot to have layer profile %#v\n\t%#v", actual, m.name, m.expected)
    61  }
    62  
    63  func (m *haveProfileMatcher) path(actual interface{}, name string) (string, error) {
    64  	v := reflect.ValueOf(actual).FieldByName("Root")
    65  	if v == (reflect.Value{}) {
    66  		return "", fmt.Errorf("HaveProfile matcher expects a layer")
    67  	}
    68  
    69  	return filepath.Join(v.Interface().(string), "profile.d", name), nil
    70  }