code.gitea.io/gitea@v1.21.7/tests/integration/html_helper.go (about)

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