github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/testutil/filepresencechecker.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2015-2018 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package testutil
    21  
    22  import (
    23  	"fmt"
    24  	"os"
    25  
    26  	"gopkg.in/check.v1"
    27  )
    28  
    29  type filePresenceChecker struct {
    30  	*check.CheckerInfo
    31  	present bool
    32  }
    33  
    34  // FilePresent verifies that the given file exists.
    35  var FilePresent check.Checker = &filePresenceChecker{
    36  	CheckerInfo: &check.CheckerInfo{Name: "FilePresent", Params: []string{"filename"}},
    37  	present:     true,
    38  }
    39  
    40  // FileAbsent verifies that the given file does not exist.
    41  var FileAbsent check.Checker = &filePresenceChecker{
    42  	CheckerInfo: &check.CheckerInfo{Name: "FileAbsent", Params: []string{"filename"}},
    43  	present:     false,
    44  }
    45  
    46  func (c *filePresenceChecker) Check(params []interface{}, names []string) (result bool, error string) {
    47  	filename, ok := params[0].(string)
    48  	if !ok {
    49  		return false, "filename must be a string"
    50  	}
    51  	_, err := os.Stat(filename)
    52  	if os.IsNotExist(err) && c.present {
    53  		return false, fmt.Sprintf("file %q is absent but should exist", filename)
    54  	}
    55  	if err == nil && !c.present {
    56  		return false, fmt.Sprintf("file %q is present but should not exist", filename)
    57  	}
    58  	return true, ""
    59  }