package ui import ( "fmt" "testing" "github.com/gorilla/mux" ) /* Not a Test function, a test helper. AssetsPath is "public" instead of "web/public" because tests normally run from the package directory, not the project directory. */ func testSetupGlobals() { globals = Globals{ AssetsBaseURL: "https://cdn.osinet.fr", AssetsVersion: 1, AssetsPath: "public", SiteBaseURL: "http://sut.kurz.osinet.fr", RefreshDelay: 1, SiteName: "Kurz test site", } } func TestURLForAsset(t *testing.T) { testSetupGlobals() type check struct { Expected string Name string NS string OK bool Path string } checks := []check{ {"https://cdn.osinet.fr/favicon.ico?v=1", "empty favicon", "", true, "favicon.ico"}, {"https://cdn.osinet.fr/favicon.ico?v=1", "root favicon", "/", false, "favicon.ico"}, {"https://cdn.osinet.fr/css?v=1", "empty css path", "css", true, ""}, {"https://cdn.osinet.fr/css?v=1", "root css path", "css", true, "/"}, } for _, check := range checks { t.Run(check.Name, func(t *testing.T) { actual, err := URLForAsset(check.NS, check.Path) if !check.OK { if err == nil { t.Errorf("Should have failed for: %s %s but did not\n", check.NS, check.Path) t.FailNow() } return } if check.OK && err != nil { t.Errorf("Error building asset Expected: %v\n", err) t.FailNow() } else if actual != check.Expected || err != nil { t.Errorf("Incorrect asset expecting <%s>, got <%s>\n", check.Expected, actual) t.Fail() } }) } } func TestURLForAssetSad(t *testing.T) { testSetupGlobals() globals.AssetsBaseURL = ":::" defer func() { if r := recover(); r == nil { fmt.Println("Invalid AssetsBaseURL did not cause asset URL generation to fail") } }() URLForAsset("", "") } func TestURLFromRoute(t *testing.T) { testSetupGlobals() router := mux.NewRouter() SetupUI(router, globals.AssetsPath) type strings map[string]string type check struct { Expected string OK bool Params strings Route string } checks := []check{ {globals.SiteBaseURL + "/", true, nil, RouteGetRoot}, {globals.SiteBaseURL + "/foo", true, strings{"short": "foo"}, RouteGetShort}, {"", false, nil, "NoSuchRoute"}, {"", false, nil, RouteGetShort}, } for _, check := range checks { actual, err := URLFromRoute(router, check.Route, check.Params) if check.OK && err != nil { t.Errorf("Error building route %s: %v\n", check.Route, err) t.FailNow() } else if actual != check.Expected { t.Errorf("Route %s failure. Expected %s, got %s\n", RouteGetRoot, check.Expected, actual) t.Fail() } } }