From 76ef9c1fe6c96845a3a54e09ee56712423e04ab7 Mon Sep 17 00:00:00 2001 From: Niko Abeler Date: Thu, 3 Nov 2022 19:23:13 +0100 Subject: [PATCH] Refactoring tests (done) --- cmd/owl/web/multi_user_test.go | 5 +- cmd/owl/web/single_user_test.go | 11 +--- post_test.go | 8 +-- priv/assertions/asserts.go | 21 +++++++ renderer_test.go | 13 +--- repository_test.go | 107 +++++++++++--------------------- user_test.go | 52 ++++------------ 7 files changed, 77 insertions(+), 140 deletions(-) diff --git a/cmd/owl/web/multi_user_test.go b/cmd/owl/web/multi_user_test.go index 58d89c0..62382ed 100644 --- a/cmd/owl/web/multi_user_test.go +++ b/cmd/owl/web/multi_user_test.go @@ -104,8 +104,5 @@ func TestMultiUserPostMediaHandler(t *testing.T) { assertions.AssertStatus(t, rr, http.StatusOK) // Check the response body contains data of media file - if !(rr.Body.String() == "test") { - t.Error("Got wrong media file content. Expected 'test' Got: ") - t.Error(rr.Body.String()) - } + assertions.Assert(t, rr.Body.String() == "test", "Response body is not equal to test") } diff --git a/cmd/owl/web/single_user_test.go b/cmd/owl/web/single_user_test.go index 08ef094..069b3ec 100644 --- a/cmd/owl/web/single_user_test.go +++ b/cmd/owl/web/single_user_test.go @@ -8,7 +8,6 @@ import ( "net/http/httptest" "os" "path" - "strings" "testing" ) @@ -68,10 +67,7 @@ func TestSingleUserPostMediaHandler(t *testing.T) { assertions.AssertStatus(t, rr, http.StatusOK) // Check the response body contains data of media file - if !(rr.Body.String() == "test") { - t.Error("Got wrong media file content. Expected 'test' Got: ") - t.Error(rr.Body.String()) - } + assertions.Assert(t, rr.Body.String() == "test", "Media file data not returned") } func TestHasNoDraftsInList(t *testing.T) { @@ -101,8 +97,5 @@ func TestHasNoDraftsInList(t *testing.T) { router.ServeHTTP(rr, req) // Check if title is in the response body - if strings.Contains(rr.Body.String(), "Articles September 2019") { - t.Error("Articles September 2019 listed on index page. Got: ") - t.Error(rr.Body.String()) - } + assertions.AssertNotContains(t, rr.Body.String(), "Articles September 2019") } diff --git a/post_test.go b/post_test.go index 1df2ebc..749fc93 100644 --- a/post_test.go +++ b/post_test.go @@ -310,9 +310,7 @@ func TestCanSendWebmention(t *testing.T) { assertions.AssertLen(t, webmentions, 1) assertions.AssertEqual(t, webmentions[0].Target, "http://example.com") - if webmentions[0].LastSentAt.IsZero() { - t.Errorf("Expected LastSentAt to be set") - } + assertions.AssertEqual(t, webmentions[0].LastSentAt.IsZero(), false) } func TestSendWebmentionOnlyScansOncePerWeek(t *testing.T) { @@ -332,9 +330,7 @@ func TestSendWebmentionOnlyScansOncePerWeek(t *testing.T) { webmention = webmentions[0] err := post.SendWebmention(webmention) - if err == nil { - t.Errorf("Expected error, got nil") - } + assertions.AssertError(t, err, "Expected error, got nil") webmentions = post.OutgoingWebmentions() diff --git a/priv/assertions/asserts.go b/priv/assertions/asserts.go index bfdc6ad..d30b69c 100644 --- a/priv/assertions/asserts.go +++ b/priv/assertions/asserts.go @@ -41,6 +41,13 @@ func AssertNoError(t *testing.T, err error, message string) { } } +func AssertError(t *testing.T, err error, message string) { + t.Helper() + if err == nil { + t.Errorf(message) + } +} + func AssertLen[T any](t *testing.T, list []T, expected int) { t.Helper() if len(list) != expected { @@ -69,3 +76,17 @@ func AssertStatus(t *testing.T, rr *httptest.ResponseRecorder, expStatus int) { return } } + +func AssertLessThan(t *testing.T, actual int, expected int) { + t.Helper() + if actual >= expected { + t.Errorf("Expected '%d' to be less than '%d'", actual, expected) + } +} + +func AssertGreaterThan(t *testing.T, actual int, expected int) { + t.Helper() + if actual <= expected { + t.Errorf("Expected '%d' to be greater than '%d'", actual, expected) + } +} diff --git a/renderer_test.go b/renderer_test.go index f3ae465..34f70b1 100644 --- a/renderer_test.go +++ b/renderer_test.go @@ -5,7 +5,6 @@ import ( "h4kor/owl-blogs/priv/assertions" "os" "path" - "strings" "testing" "time" ) @@ -113,9 +112,7 @@ func TestRenderIndexPageWithBrokenBaseTemplate(t *testing.T) { os.WriteFile(path.Join(user.Dir(), "meta/base.html"), []byte("{{content}}"), 0644) _, err := owl.RenderIndexPage(user) - if err == nil { - t.Error("Expected error rendering index page, got nil") - } + assertions.AssertError(t, err, "Expected error rendering index page") } func TestRenderUserList(t *testing.T) { @@ -174,9 +171,7 @@ func TestRenderPostAddsLinksToApprovedWebmention(t *testing.T) { result, _ := owl.RenderPost(post) assertions.AssertContains(t, result, "http://example.com/source3") assertions.AssertContains(t, result, "Test Title") - if strings.Contains(result, "http://example.com/source4") { - t.Error("unapproved webmention rendered. Got: " + result) - } + assertions.AssertNotContains(t, result, "http://example.com/source4") } @@ -185,9 +180,7 @@ func TestRenderPostNotMentioningWebmentionsIfNoAvail(t *testing.T) { post, _ := user.CreateNewPost("testpost", false) result, _ := owl.RenderPost(post) - if strings.Contains(result, "Webmention") { - t.Error("Webmention mentioned. Got: " + result) - } + assertions.AssertNotContains(t, result, "Webmention") } diff --git a/repository_test.go b/repository_test.go index e87efad..8fafbc1 100644 --- a/repository_test.go +++ b/repository_test.go @@ -19,18 +19,15 @@ func TestCannotCreateExistingRepository(t *testing.T) { repoName := testRepoName() owl.CreateRepository(repoName, owl.RepoConfig{}) _, err := owl.CreateRepository(repoName, owl.RepoConfig{}) - if err == nil { - t.Error("No error returned when creating existing repository") - } + assertions.AssertError(t, err, "No error returned when creating existing repository") } func TestCanCreateANewUser(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) user, _ := repo.CreateUser(randomUserName()) - if _, err := os.Stat(path.Join(user.Dir(), "")); err != nil { - t.Error("User directory not created") - } + _, err := os.Stat(path.Join(user.Dir(), "")) + assertions.AssertNoError(t, err, "Error creating user: ") } func TestCannotRecreateExisitingUser(t *testing.T) { @@ -39,45 +36,39 @@ func TestCannotRecreateExisitingUser(t *testing.T) { userName := randomUserName() repo.CreateUser(userName) _, err := repo.CreateUser(userName) - if err == nil { - t.Error("No error returned when creating existing user") - } + assertions.AssertError(t, err, "No error returned when creating existing user") } func TestCreateUserAddsVersionFile(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) user, _ := repo.CreateUser(randomUserName()) - if _, err := os.Stat(path.Join(user.Dir(), "/meta/VERSION")); err != nil { - t.Error("Version file not created") - } + _, err := os.Stat(path.Join(user.Dir(), "/meta/VERSION")) + assertions.AssertNoError(t, err, "Version file not created") } func TestCreateUserAddsBaseHtmlFile(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) user, _ := repo.CreateUser(randomUserName()) - if _, err := os.Stat(path.Join(user.Dir(), "/meta/base.html")); err != nil { - t.Error("Base html file not created") - } + _, err := os.Stat(path.Join(user.Dir(), "/meta/base.html")) + assertions.AssertNoError(t, err, "Base html file not created") } func TestCreateUserAddConfigYml(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) user, _ := repo.CreateUser(randomUserName()) - if _, err := os.Stat(path.Join(user.Dir(), "/meta/config.yml")); err != nil { - t.Error("Config file not created") - } + _, err := os.Stat(path.Join(user.Dir(), "/meta/config.yml")) + assertions.AssertNoError(t, err, "Config file not created") } func TestCreateUserAddsPublicFolder(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) user, _ := repo.CreateUser(randomUserName()) - if _, err := os.Stat(path.Join(user.Dir(), "/public")); err != nil { - t.Error("Public folder not created") - } + _, err := os.Stat(path.Join(user.Dir(), "/public")) + assertions.AssertNoError(t, err, "Public folder not created") } func TestCanListRepoUsers(t *testing.T) { @@ -89,9 +80,11 @@ func TestCanListRepoUsers(t *testing.T) { users, _ := repo.Users() assertions.AssertLen(t, users, 2) for _, user := range users { - if user.Name() != user1.Name() && user.Name() != user2.Name() { - t.Error("User found: " + user.Name()) - } + assertions.AssertNot( + t, + user.Name() != user1.Name() && user.Name() != user2.Name(), + "User found: "+user.Name(), + ) } } @@ -102,16 +95,12 @@ func TestCanOpenRepository(t *testing.T) { // Open the repository repo2, err := owl.OpenRepository(repoName) assertions.AssertNoError(t, err, "Error opening repository: ") - if repo2.Dir() != repo.Dir() { - t.Error("Repository directories do not match") - } + assertions.Assert(t, repo2.Dir() == repo.Dir(), "Repository directories do not match") } func TestCannotOpenNonExisitingRepo(t *testing.T) { _, err := owl.OpenRepository(testRepoName()) - if err == nil { - t.Error("No error returned when opening non-existing repository") - } + assertions.AssertError(t, err, "No error returned when opening non-existing repository") } func TestGetUser(t *testing.T) { @@ -121,18 +110,14 @@ func TestGetUser(t *testing.T) { // Get the user user2, err := repo.GetUser(user.Name()) assertions.AssertNoError(t, err, "Error getting user: ") - if user2.Name() != user.Name() { - t.Error("User names do not match") - } + assertions.Assert(t, user2.Name() == user.Name(), "User names do not match") } func TestCannotGetNonexistingUser(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) _, err := repo.GetUser(randomUserName()) - if err == nil { - t.Error("No error returned when getting non-existing user") - } + assertions.AssertError(t, err, "No error returned when getting non-existing user") } func TestGetStaticDirOfRepo(t *testing.T) { @@ -140,24 +125,19 @@ func TestGetStaticDirOfRepo(t *testing.T) { repo := getTestRepo(owl.RepoConfig{}) // Get the user staticDir := repo.StaticDir() - if staticDir == "" { - t.Error("Static dir not returned") - } + assertions.Assert(t, staticDir != "", "Static dir is empty") } func TestNewRepoGetsStaticFiles(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) - if _, err := os.Stat(repo.StaticDir()); err != nil { - t.Error("Static directory not found") - } + _, err := os.Stat(repo.StaticDir()) + assertions.AssertNoError(t, err, "Static dir not created") dir, _ := os.Open(repo.StaticDir()) defer dir.Close() files, _ := dir.Readdirnames(-1) - if len(files) == 0 { - t.Error("No static files found") - } + assertions.AssertLen(t, files, 1) } func TestNewRepoGetsStaticFilesPicoCSSWithContent(t *testing.T) { @@ -167,17 +147,14 @@ func TestNewRepoGetsStaticFilesPicoCSSWithContent(t *testing.T) { assertions.AssertNoError(t, err, "Error opening pico.min.css") // check that the file has content stat, _ := file.Stat() - if stat.Size() == 0 { - t.Error("pico.min.css is empty") - } + assertions.Assert(t, stat.Size() > 0, "pico.min.css is empty") } func TestNewRepoGetsBaseHtml(t *testing.T) { // Create a new user repo := getTestRepo(owl.RepoConfig{}) - if _, err := os.Stat(path.Join(repo.Dir(), "/base.html")); err != nil { - t.Error("Base html file not found") - } + _, err := os.Stat(path.Join(repo.Dir(), "/base.html")) + assertions.AssertNoError(t, err, "Base html file not found") } func TestCanGetRepoTemplate(t *testing.T) { @@ -186,9 +163,7 @@ func TestCanGetRepoTemplate(t *testing.T) { // Get the user template, err := repo.Template() assertions.AssertNoError(t, err, "Error getting template: ") - if template == "" { - t.Error("Template not returned") - } + assertions.Assert(t, template != "", "Template is empty") } func TestCanOpenRepositoryInSingleUserMode(t *testing.T) { @@ -205,9 +180,7 @@ func TestCanOpenRepositoryInSingleUserMode(t *testing.T) { users, _ := repo.Users() assertions.AssertLen(t, users, 1) - if users[0].Name() != userName { - t.Error("User name does not match") - } + assertions.Assert(t, users[0].Name() == userName, "User name does not match") } func TestSingleUserRepoUserUrlPathIsSimple(t *testing.T) { @@ -220,9 +193,7 @@ func TestSingleUserRepoUserUrlPathIsSimple(t *testing.T) { // Open the repository repo, _ := owl.OpenRepository(repoName) user, _ := repo.GetUser(userName) - if user.UrlPath() != "/" { - t.Error("User url is not '/'. Got: ", user.UrlPath()) - } + assertions.Assert(t, user.UrlPath() == "/", "User url path is not /") } func TestCanGetMapWithAllPostAliases(t *testing.T) { @@ -246,12 +217,8 @@ func TestCanGetMapWithAllPostAliases(t *testing.T) { aliases, err := repo.PostAliases() assertions.AssertNoError(t, err, "Error getting post aliases: ") assertions.AssertMapLen(t, aliases, 2) - if aliases["/foo/bar"] == nil { - t.Error("Alias '/foo/bar' not found") - } - if aliases["/foo/baz"] == nil { - t.Error("Alias '/foo/baz' not found") - } + assertions.Assert(t, aliases["/foo/bar"] != nil, "Alias '/foo/bar' not found") + assertions.Assert(t, aliases["/foo/baz"] != nil, "Alias '/foo/baz' not found") } @@ -284,11 +251,7 @@ func TestAliasesHaveCorrectPost(t *testing.T) { aliases, err := repo.PostAliases() assertions.AssertNoError(t, err, "Error getting post aliases: ") assertions.AssertMapLen(t, aliases, 2) - if aliases["/foo/1"].Id() != post1.Id() { - t.Error("Alias '/foo/1' points to wrong post: ", aliases["/foo/1"].Id()) - } - if aliases["/foo/2"].Id() != post2.Id() { - t.Error("Alias '/foo/2' points to wrong post: ", aliases["/foo/2"].Id()) - } + assertions.Assert(t, aliases["/foo/1"].Id() == post1.Id(), "Alias '/foo/1' does not point to post 1") + assertions.Assert(t, aliases["/foo/2"].Id() == post2.Id(), "Alias '/foo/2' does not point to post 2") } diff --git a/user_test.go b/user_test.go index 1999559..5f42c41 100644 --- a/user_test.go +++ b/user_test.go @@ -50,9 +50,7 @@ func TestCreateNewPostMultipleCalls(t *testing.T) { user.CreateNewPost("testpost", false) files, err := os.ReadDir(path.Join(user.Dir(), "public")) assertions.AssertNoError(t, err, "Error reading directory") - if len(files) < 3 { - t.Errorf("Only %d posts created", len(files)) - } + assertions.AssertEqual(t, len(files), 3) } func TestCanListUserPosts(t *testing.T) { @@ -186,23 +184,17 @@ func TestCanLoadPost(t *testing.T) { posts, _ := user.Posts() post, _ := user.GetPost(posts[0].Id()) - if post.Title() != "testpost" { - t.Error("Wrong title, Got: " + post.Title()) - } + assertions.Assert(t, post.Title() == "testpost", "Post title is not correct") } func TestUserUrlPath(t *testing.T) { user := getTestUser() - if !(user.UrlPath() == "/user/"+user.Name()+"/") { - t.Error("Wrong url path, Expected: " + "/user/" + user.Name() + "/" + " Got: " + user.UrlPath()) - } + assertions.Assert(t, user.UrlPath() == "/user/"+user.Name()+"/", "Wrong url path") } func TestUserFullUrl(t *testing.T) { user := getTestUser() - if !(user.FullUrl() == "http://localhost:8080/user/"+user.Name()+"/") { - t.Error("Wrong url path, Expected: " + "http://localhost:8080/user/" + user.Name() + "/" + " Got: " + user.FullUrl()) - } + assertions.Assert(t, user.FullUrl() == "http://localhost:8080/user/"+user.Name()+"/", "Wrong url path") } func TestPostsSortedByPublishingDateLatestFirst(t *testing.T) { @@ -226,12 +218,8 @@ func TestPostsSortedByPublishingDateLatestFirst(t *testing.T) { os.WriteFile(post2.ContentFile(), []byte(content), 0644) posts, _ := user.Posts() - if posts[0].Id() != post2.Id() { - t.Error("Wrong Id, Got: " + posts[0].Id()) - } - if posts[1].Id() != post1.Id() { - t.Error("Wrong Id, Got: " + posts[1].Id()) - } + assertions.Assert(t, posts[0].Id() == post2.Id(), "Wrong Id") + assertions.Assert(t, posts[1].Id() == post1.Id(), "Wrong Id") } func TestPostsSortedByPublishingDateLatestFirst2(t *testing.T) { @@ -251,9 +239,7 @@ func TestPostsSortedByPublishingDateLatestFirst2(t *testing.T) { retPosts, _ := user.Posts() for i, p := range retPosts { - if p.Id() != posts[i].Id() { - t.Error("Wrong Id, Got: " + p.Id()) - } + assertions.Assert(t, p.Id() == posts[i].Id(), "Wrong Id") } } @@ -278,27 +264,19 @@ func TestPostsSortedByPublishingDateBrokenAtBottom(t *testing.T) { os.WriteFile(post2.ContentFile(), []byte(content), 0644) posts, _ := user.Posts() - if posts[0].Id() != post2.Id() { - t.Error("Wrong Id, Got: " + posts[0].Id()) - } - if posts[1].Id() != post1.Id() { - t.Error("Wrong Id, Got: " + posts[1].Id()) - } + assertions.Assert(t, posts[0].Id() == post2.Id(), "Wrong Id") + assertions.Assert(t, posts[1].Id() == post1.Id(), "Wrong Id") } func TestAvatarEmptyIfNotExist(t *testing.T) { user := getTestUser() - if user.AvatarUrl() != "" { - t.Error("Avatar should be empty") - } + assertions.Assert(t, user.AvatarUrl() == "", "Avatar should be empty") } func TestAvatarSetIfFileExist(t *testing.T) { user := getTestUser() os.WriteFile(path.Join(user.MediaDir(), "avatar.png"), []byte("test"), 0644) - if user.AvatarUrl() == "" { - t.Error("Avatar should not be empty") - } + assertions.Assert(t, user.AvatarUrl() != "", "Avatar should not be empty") } func TestPostNameIllegalFileName(t *testing.T) { @@ -309,15 +287,11 @@ func TestPostNameIllegalFileName(t *testing.T) { func TestFaviconIfNotExist(t *testing.T) { user := getTestUser() - if user.FaviconUrl() != "" { - t.Error("Favicon should be empty") - } + assertions.Assert(t, user.FaviconUrl() == "", "Favicon should be empty") } func TestFaviconSetIfFileExist(t *testing.T) { user := getTestUser() os.WriteFile(path.Join(user.MediaDir(), "favicon.ico"), []byte("test"), 0644) - if user.FaviconUrl() == "" { - t.Error("Favicon should not be empty") - } + assertions.Assert(t, user.FaviconUrl() != "", "Favicon should not be empty") }