github.com/pmoroney/dnscontrol@v0.2.4-0.20171024134423-fad98f73f44a/pkg/js/js_test.go (about) 1 package js 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "testing" 9 "unicode" 10 11 "github.com/tdewolff/minify" 12 minjson "github.com/tdewolff/minify/json" 13 ) 14 15 const ( 16 testDir = "pkg/js/parse_tests" 17 errorDir = "pkg/js/error_tests" 18 ) 19 20 func init() { 21 os.Chdir("../..") // go up a directory so we helpers.js is in a consistent place. 22 } 23 24 func TestParsedFiles(t *testing.T) { 25 files, err := ioutil.ReadDir(testDir) 26 if err != nil { 27 t.Fatal(err) 28 } 29 for _, f := range files { 30 //run all js files that start with a number. Skip others. 31 if filepath.Ext(f.Name()) != ".js" || !unicode.IsNumber(rune(f.Name()[0])) { 32 continue 33 } 34 m := minify.New() 35 m.AddFunc("json", minjson.Minify) 36 t.Run(f.Name(), func(t *testing.T) { 37 content, err := ioutil.ReadFile(filepath.Join(testDir, f.Name())) 38 if err != nil { 39 t.Fatal(err) 40 } 41 conf, err := ExecuteJavascript(string(content), true) 42 if err != nil { 43 t.Fatal(err) 44 } 45 actualJSON, err := json.MarshalIndent(conf, "", " ") 46 if err != nil { 47 t.Fatal(err) 48 } 49 actualJSON, err = m.Bytes("json", actualJSON) 50 if err != nil { 51 t.Fatal(err) 52 } 53 expectedFile := filepath.Join(testDir, f.Name()[:len(f.Name())-3]+".json") 54 expectedData, err := ioutil.ReadFile(expectedFile) 55 if err != nil { 56 t.Fatal(err) 57 } 58 59 expectedJSON, err := m.String("json", string(expectedData)) 60 if err != nil { 61 t.Fatal(err) 62 } 63 if string(expectedJSON) != string(actualJSON) { 64 t.Error("Expected and actual json don't match") 65 t.Log("Expected:", string(expectedJSON)) 66 t.Log("Actual :", string(actualJSON)) 67 } 68 }) 69 } 70 } 71 72 func TestErrors(t *testing.T) { 73 tests := []struct{ desc, text string }{ 74 {"old dsp style", `D("foo.com","reg","dsp")`}, 75 {"MX no priority", `D("foo.com","reg",MX("@","test."))`}, 76 {"MX reversed", `D("foo.com","reg",MX("@","test.", 5))`}, 77 {"CF_REDIRECT With comma", `D("foo.com","reg",CF_REDIRECT("foo.com,","baaa"))`}, 78 {"CF_TEMP_REDIRECT With comma", `D("foo.com","reg",CF_TEMP_REDIRECT("foo.com","baa,a"))`}, 79 {"Bad cidr", `D(reverse("foo.com"), "reg")`}, 80 } 81 for _, tst := range tests { 82 t.Run(tst.desc, func(t *testing.T) { 83 if _, err := ExecuteJavascript(tst.text, true); err == nil { 84 t.Fatal("Expected error but found none") 85 } 86 }) 87 88 } 89 }