github.com/josa42/go-gitignore@v1.0.0/gitignore_test.go (about)

     1  package gitignore_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/josa42/go-gitignore"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func cd(p string) func() {
    14  	pwd, _ := os.Getwd()
    15  	os.Chdir(p)
    16  	return func() {
    17  		os.Chdir(pwd)
    18  	}
    19  }
    20  
    21  func TestNewGitignoreFromString(t *testing.T) {
    22  	assert.NotNil(t, gitignore.NewGitignoreFromString(""))
    23  }
    24  
    25  func TestNewGitignoreFromFile(t *testing.T) {
    26  	defer cd("testdata/empty")()
    27  
    28  	gitgnore, err := gitignore.NewGitignoreFromFile(".gitignore")
    29  
    30  	assert.NotNil(t, gitgnore)
    31  	assert.Nil(t, err)
    32  }
    33  
    34  func TestNewGitignoreFromFile_notFound(t *testing.T) {
    35  	defer cd("testdata/no-gitignore")()
    36  
    37  	gitgnore, err := gitignore.NewGitignoreFromFile(".gitignore")
    38  
    39  	assert.NotNil(t, gitgnore)
    40  	assert.NotNil(t, err)
    41  }
    42  
    43  type Case struct {
    44  	Skip     bool   `json:"skip"`
    45  	Name     string `json:"name"`
    46  	Pattern  string `json:"pattern"`
    47  	FilePath string `json:"file_path"`
    48  	Ignored  bool   `json:"ignored"`
    49  }
    50  
    51  func TestGitignore(t *testing.T) {
    52  
    53  	cases := []Case{}
    54  
    55  	content, _ := ioutil.ReadFile("testdata/cases.json")
    56  	json.Unmarshal(content, &cases)
    57  
    58  	for _, c := range cases {
    59  		t.Run(c.Name, func(t *testing.T) {
    60  			if c.Skip {
    61  				t.Skip()
    62  			}
    63  
    64  			ignore := gitignore.NewGitignoreFromString(c.Pattern)
    65  
    66  			assert.Equal(t, c.Ignored, ignore.Match(c.FilePath))
    67  		})
    68  	}
    69  
    70  }