|
| 1 | +package scheduler |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | +) |
| 9 | + |
| 10 | +func TestSelectors(t *testing.T) { |
| 11 | + html := ` |
| 12 | + <html> |
| 13 | + <body> |
| 14 | + <div id="main" class="content"> |
| 15 | + <h1>Title</h1> |
| 16 | + <p class="intro">Introduction paragraph 1</p> |
| 17 | + <a href="http://example.com">Example Link</a> |
| 18 | + <p>This is test paragraph</p> |
| 19 | + <p class="intro" data-mg="test">Introduction paragraph 3</p> |
| 20 | + </div> |
| 21 | + </body> |
| 22 | + </html> |
| 23 | + ` |
| 24 | + |
| 25 | + selector, err := NewSelector(strings.NewReader(html)) |
| 26 | + |
| 27 | + assert.NoError(t, err) |
| 28 | + |
| 29 | + cssSelector := selector.Css("p.intro") |
| 30 | + |
| 31 | + cssNodes := cssSelector.GetAll() |
| 32 | + assert.Len(t, cssNodes, 2, "expected nodes=2, got=%s", len(cssNodes)) |
| 33 | + |
| 34 | + cssNodesTexts := cssSelector.Text() |
| 35 | + assert.Equal(t, "Introduction paragraph 1", cssNodesTexts[0], "expected paragraph text=Introduction paragraph 1, got=%s", cssNodesTexts[0]) |
| 36 | + |
| 37 | + xpathSelector := selector.Xpath("//p[@data-mg='test']") |
| 38 | + |
| 39 | + xpathNodes := xpathSelector.GetAll() |
| 40 | + assert.Len(t, xpathNodes, 1, "expected xpath nodes=1, got=%s", len(xpathNodes)) |
| 41 | + |
| 42 | + xpathNodesTexts := xpathSelector.Text() |
| 43 | + assert.Len(t, xpathNodesTexts, 1, "expected xpathNodesTexts=1, got=%s", len(xpathNodesTexts)) |
| 44 | + assert.Equal(t, "Introduction paragraph 3", xpathNodesTexts[0], "expected paragraph text=Introduction paragraph 3, got=%s", xpathNodesTexts[0]) |
| 45 | + |
| 46 | + attrValues := selector.Css("a").Attr("href") |
| 47 | + assert.Len(t, xpathNodesTexts, 1, "expected attrValues=1, got=%s", len(attrValues)) |
| 48 | + assert.Equal(t, "http://example.com", attrValues[0], "expected href=http://example.com, got=%s", attrValues[0]) |
| 49 | + |
| 50 | + noCssElements := selector.Css("p.box").GetAll() |
| 51 | + assert.Empty(t, noCssElements, "expected element=0, got=%s", len(noCssElements)) |
| 52 | + |
| 53 | + noXpathElements := selector.Xpath("//p[@class='test']").GetAll() |
| 54 | + assert.Empty(t, noXpathElements, "expected element=0, got=%s", len(noXpathElements)) |
| 55 | + |
| 56 | +} |
0 commit comments