Prechádzať zdrojové kódy

finish abstracting main and writing tests

Casey DeLorme 8 rokov pred
rodič
commit
809d4a5fae
2 zmenil súbory, kde vykonal 70 pridanie a 6 odobranie
  1. 17 6
      cmd/staticmd/main.go
  2. 53 0
      cmd/staticmd/main_test.go

+ 17 - 6
cmd/staticmd/main.go

@@ -11,10 +11,21 @@ import (
 	"github.com/cdelorme/staticmd"
 )
 
-func configure() *staticmd.Generator {
+var exit = os.Exit
+var getwd = os.Getwd
+
+type generator interface {
+	Generate() error
+}
+
+type logger interface {
+	Error(string, ...interface{})
+}
+
+func configure() (generator, logger) {
 
 	// get current directory
-	cwd, _ := os.Getwd()
+	cwd, _ := getwd()
 
 	// prepare staticmd with dependencies & defaults
 	smd := &staticmd.Generator{
@@ -41,13 +52,13 @@ func configure() *staticmd.Generator {
 	smd.Book, _ = maps.Bool(flags, smd.Book, "book")
 	smd.Relative, _ = maps.Bool(flags, smd.Relative, "relative")
 
-	return smd
+	return smd, smd.Logger
 }
 
 func main() {
-	smd := configure()
+	smd, l := configure()
 	if err := smd.Generate(); err != nil {
-		smd.Logger.Error("%s", err)
-		os.Exit(1)
+		l.Error("generator failed (%s)", err)
+		exit(1)
 	}
 }

+ 53 - 0
cmd/staticmd/main_test.go

@@ -0,0 +1,53 @@
+package main
+
+import (
+	"os"
+	"testing"
+
+	"github.com/cdelorme/staticmd"
+)
+
+func init() {
+	exit = func(_ int) {}
+	getwd = func() (string, error) { return "", nil }
+}
+
+var mockError error
+
+type mockGenerator struct{}
+
+func (self *mockGenerator) Generate() error { return mockError }
+
+type mockLogger struct{}
+
+func (self *mockLogger) Error(_ string, _ ...interface{}) {}
+
+func TestPlacebo(_ *testing.T) {}
+
+func TestMain(_ *testing.T) {
+	os.Args = []string{}
+	main()
+}
+
+func TestConfigure(t *testing.T) {
+
+	// set a value on all parameters
+	os.Args = []string{"-t", "afile", "-i", "/in/", "-o", "/out/", "-b", "-r"}
+
+	// run configure & check results
+	s, l := configure()
+	if s == nil || l == nil {
+		t.FailNow()
+	}
+
+	// cast and check values on s
+	g, e := s.(*staticmd.Generator)
+	if !e {
+		t.FailNow()
+	}
+
+	// check values on generator match cli parameters
+	if g.Input != "/in/" || g.Output != "/out/" || !g.Book || g.TemplateFile != "afile" {
+		t.FailNow()
+	}
+}