gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "bytes"
  6. "testing"
  7. "github.com/PuerkitoBio/goquery"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. // HTMLDoc struct
  11. type HTMLDoc struct {
  12. doc *goquery.Document
  13. }
  14. // NewHTMLParser parse html file
  15. func NewHTMLParser(t testing.TB, body *bytes.Buffer) *HTMLDoc {
  16. t.Helper()
  17. doc, err := goquery.NewDocumentFromReader(body)
  18. assert.NoError(t, err)
  19. return &HTMLDoc{doc: doc}
  20. }
  21. // GetInputValueByName for get input value by name
  22. func (doc *HTMLDoc) GetInputValueByName(name string) string {
  23. text, _ := doc.doc.Find(`input[name="` + name + `"]`).Attr("value")
  24. return text
  25. }
  26. // Find gets the descendants of each element in the current set of
  27. // matched elements, filtered by a selector. It returns a new Selection
  28. // object containing these matched elements.
  29. func (doc *HTMLDoc) Find(selector string) *goquery.Selection {
  30. return doc.doc.Find(selector)
  31. }
  32. // GetCSRF for getting CSRF token value from input
  33. func (doc *HTMLDoc) GetCSRF() string {
  34. return doc.GetInputValueByName("_csrf")
  35. }
  36. // AssertHTMLElement check if the element by selector exists or does not exist depending on checkExists
  37. func AssertHTMLElement[T int | bool](t testing.TB, doc *HTMLDoc, selector string, checkExists T) {
  38. sel := doc.doc.Find(selector)
  39. switch v := any(checkExists).(type) {
  40. case bool:
  41. assert.Equal(t, v, sel.Length() > 0)
  42. case int:
  43. assert.Equal(t, v, sel.Length())
  44. }
  45. }