fix(testing): Fix random failure test (#37887)

Fix the flaky npm package web view test that compared rendered HTML as a
raw string.

Fix
https://github.com/go-gitea/gitea/actions/runs/26524574688/job/78124662707?pr=36564

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Nicolas <bircni@icloud.com>
This commit is contained in:
Lunny Xiao
2026-05-28 10:53:38 -07:00
committed by GitHub
parent 49f88a4b9e
commit 428ee9fcce
2 changed files with 40 additions and 1 deletions

View File

@@ -304,7 +304,7 @@ func TestPackageNpm(t *testing.T) {
resp := MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
rendered, _ := doc.Find(".markup.markdown").Html()
assert.Equal(t, `<p dir="auto"><a href="/user2/repo1/src/branch/master/package-subdir/docs/usage.md" rel="nofollow">docs</a>
assertHTMLEq(t, `<p dir="auto"><a href="/user2/repo1/src/branch/master/package-subdir/docs/usage.md" rel="nofollow">docs</a>
<a href="/user2/repo1/src/branch/master/package-subdir/logo.png" rel="nofollow noopener" target="_blank"><img src="/user2/repo1/media/branch/master/package-subdir/logo.png" alt="logo" loading="lazy"/></a></p>
`, rendered)
})

View File

@@ -5,10 +5,13 @@ package integration
import (
"io"
"slices"
"strings"
"testing"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
"golang.org/x/net/html"
)
// HTMLDoc struct
@@ -47,3 +50,39 @@ func AssertHTMLElement[T int | bool](t testing.TB, doc *HTMLDoc, selector string
assert.Equal(t, v, sel.Length())
}
}
func assertHTMLEq(t testing.TB, expected, actual string) {
t.Helper()
if expected == actual {
return
}
exp, err := html.Parse(strings.NewReader(expected))
if !assert.NoError(t, err) {
return
}
act, err := html.Parse(strings.NewReader(actual))
if !assert.NoError(t, err) {
return
}
var normalize func(n *html.Node)
normalize = func(n *html.Node) {
slices.SortFunc(n.Attr, func(a, b html.Attribute) int {
if cmp := strings.Compare(a.Namespace, b.Namespace); cmp != 0 {
return cmp
}
if cmp := strings.Compare(a.Key, b.Key); cmp != 0 {
return cmp
}
return strings.Compare(a.Val, b.Val)
})
for c := n.FirstChild; c != nil; c = c.NextSibling {
normalize(c)
}
}
normalize(exp)
normalize(act)
var expNormalized, actNormalized strings.Builder
assert.NoError(t, html.Render(&expNormalized, exp))
assert.NoError(t, html.Render(&actNormalized, act))
assert.Equal(t, expNormalized.String(), actNormalized.String())
}