github.com/wawandco/oxpecker@v1.5.7-0.20210910201653-5958d4afdd89/tools/grift/generator_test.go (about)

     1  package grift
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  	"log"
     7  	"os"
     8  	"path/filepath"
     9  	"regexp"
    10  	"testing"
    11  )
    12  
    13  func Test_ActionGenerator(t *testing.T) {
    14  	g := Generator{}
    15  
    16  	t.Run("generate task", func(t *testing.T) {
    17  		dir := t.TempDir()
    18  		modelsPath := filepath.Join(dir, "app", "tasks")
    19  		if err := os.MkdirAll(modelsPath, os.ModePerm); err != nil {
    20  			t.Errorf("creating templates folder should not be error, but got %v", err)
    21  		}
    22  
    23  		if err := g.Generate(context.Background(), dir, []string{"generate", "task", "simple"}); err != nil {
    24  			t.Errorf("should not be error, but got %v", err)
    25  		}
    26  
    27  		// Validating Files existence
    28  		if !g.exists(filepath.Join(modelsPath, "simple.go")) {
    29  			t.Error("'simple.go' file does not exists on the path")
    30  		}
    31  	})
    32  	t.Run("generate task and checking the content", func(t *testing.T) {
    33  		dir := t.TempDir()
    34  		modelsPath := filepath.Join(dir, "app", "tasks")
    35  		if err := os.MkdirAll(modelsPath, os.ModePerm); err != nil {
    36  			t.Errorf("creating templates folder should not be error, but got %v", err)
    37  		}
    38  
    39  		if err := g.Generate(context.Background(), dir, []string{"generate", "task", "simple"}); err != nil {
    40  			t.Errorf("should not be error, but got %v", err)
    41  		}
    42  
    43  		// Validating Files existence
    44  		if !g.exists(filepath.Join(modelsPath, "simple.go")) {
    45  			t.Error("'simple.go' file does not exists on the path")
    46  		}
    47  
    48  		content, err := ioutil.ReadFile(filepath.Join(modelsPath, "simple.go"))
    49  		if err != nil {
    50  			log.Fatal(err)
    51  		}
    52  		text := string(content)
    53  		matched, err := regexp.MatchString(`"simple", func`, text)
    54  
    55  		if !matched {
    56  			t.Fatalf("File's content is not correct, %v", err)
    57  		}
    58  	})
    59  }