Home

tmpl @47ef9ea0be51e0b392957154ce958434fffff171 - refs - log -
-
https://git.jolheiser.com/tmpl.git
Template automation
tmpl / registry / template_test.go
- raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package registry

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
)

var (
	tmplContents = `{{title name}} {{.year}}`
	tmplTemplate = `name = "john olheiser"

[year]
default = ${TMPL_TEST}

[package]
default = "pkg"`
	tmplGold    = "John Olheiser 2020"
	tmplNewGold = "DO NOT OVERWRITE!"
)

func testExecute(t *testing.T) {
	// Set environment variable
	if err := os.Setenv("TMPL_TEST", "2020"); err != nil {
		t.Logf("could not set environment: %v", err)
		t.FailNow()
	}

	// Get template
	tmpl, err := reg.GetTemplate("test")
	if err != nil {
		t.Logf("could not get template")
		t.FailNow()
	}

	// Execute template
	if err := tmpl.Execute(destDir, true, true); err != nil {
		t.Logf("could not execute template: %v\n", err)
		t.FailNow()
	}

	// Check contents of file
	testPath := filepath.Join(destDir, "TEST")
	contents, err := ioutil.ReadFile(testPath)
	if err != nil {
		t.Logf("could not read file: %v\n", err)
		t.FailNow()
	}

	if string(contents) != tmplGold {
		t.Logf("contents did not match:\n\tExpected: %s\n\tGot: %s", tmplGold, string(contents))
		t.FailNow()
	}

	// Check if directory was created
	pkgPath := filepath.Join(destDir, "PKG")
	if _, err := os.Lstat(pkgPath); err != nil {
		t.Logf("expected a directory at %s: %v\n", pkgPath, err)
		t.FailNow()
	}

	// Change file to test non-overwrite
	if err := ioutil.WriteFile(testPath, []byte(tmplNewGold), os.ModePerm); err != nil {
		t.Logf("could not write file: %v\n", err)
		t.FailNow()
	}

	if err := tmpl.Execute(destDir, true, false); err != nil {
		t.Logf("could not execute template: %v\n", err)
		t.FailNow()
	}

	contents, err = ioutil.ReadFile(testPath)
	if err != nil {
		t.Logf("could not read file: %v\n", err)
		t.FailNow()
	}

	if string(contents) != tmplNewGold {
		t.Logf("contents did not match:\n\tExpected: %s\n\tGot: %s", tmplNewGold, string(contents))
		t.FailNow()
	}
}