github.com/lolorenzo777/zazzy@v0.4.3/zazzy_build_test.go (about)

     1  package main
     2  
     3  import (
     4  	"crypto/md5"
     5  	"encoding/hex"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  const TESTDIR = ".test"
    15  
    16  func TestBuild(t *testing.T) {
    17  	files, _ := ioutil.ReadDir("testdata")
    18  	for _, f := range files {
    19  		if f.IsDir() {
    20  			dir := f.Name()
    21  			if dir[0] != '.' {
    22  				testBuild(filepath.Join("testdata", f.Name()), t)
    23  			}
    24  		}
    25  	}
    26  }
    27  
    28  func testBuild(path string, t *testing.T) {
    29  	wd, _ := os.Getwd()
    30  	os.Chdir(path)
    31  	args := os.Args[:]
    32  	os.Args = []string{"zazzy", "build"}
    33  	t.Log("--- BUILD", path)
    34  	main()
    35  
    36  	compare(PUBDIR, TESTDIR, t)
    37  
    38  	os.Chdir(wd)
    39  	os.Args = args
    40  }
    41  
    42  func compare(pub, test string, t *testing.T) {
    43  	a := md5dir(pub)
    44  	b := md5dir(test)
    45  	for k, v := range a {
    46  		if s, ok := b[k]; !ok {
    47  			t.Error("Unexpected file:", k, v)
    48  		} else if s != v {
    49  			t.Error("Different file:", k, v, s)
    50  		} else {
    51  			t.Log("Matching file", k, v)
    52  		}
    53  	}
    54  	for k, v := range b {
    55  		if _, ok := a[k]; !ok {
    56  			t.Error("Missing file:", k, v)
    57  		}
    58  	}
    59  }
    60  
    61  func md5dir(path string) map[string]string {
    62  	files := map[string]string{}
    63  	filepath.Walk(path, func(s string, info os.FileInfo, err error) error {
    64  		if err == nil && !info.IsDir() {
    65  			if f, err := os.Open(s); err == nil {
    66  				defer f.Close()
    67  				hash := md5.New()
    68  				io.Copy(hash, f)
    69  				files[strings.TrimPrefix(s, path)] = hex.EncodeToString(hash.Sum(nil))
    70  			}
    71  		}
    72  		return nil
    73  	})
    74  	return files
    75  }