Skip to content

Commit

Permalink
add test for parsing a searchresult
Browse files Browse the repository at this point in the history
  • Loading branch information
kubegu committed Feb 27, 2024
1 parent 7052a84 commit 39b0fab
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
3 changes: 2 additions & 1 deletion library-le/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ func (libClient Client) FindAvailabelGames(branchCode int, platform string) []do
}
defer response.Body.Close()

games, parseResultErr := parseSearchResult(response, branchCode)
games, parseResultErr := parseSearchResult(response.Body)
//Add branchCode to games?
if parseResultErr != nil {
log.Fatalln(parseResultErr)
return nil
Expand Down
10 changes: 5 additions & 5 deletions library-le/searchresult.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package libraryle

import (
"io"
"log"
"net/http"

"github.com/PuerkitoBio/goquery"
"github.com/gunni1/leipzig-library-game-stock-api/domain"
Expand All @@ -14,10 +14,10 @@ const (
availabilitySelector string = "span[class^=textgruen]"
)

// Takes a http.Response from a webopac search and
// Takes a html as reader from a webopac search and
// try to parse it to an array of games that are listed as available.
func parseSearchResult(searchResult *http.Response, branchCode int) ([]domain.Game, error) {
doc, docErr := goquery.NewDocumentFromReader(searchResult.Body)
func parseSearchResult(searchResult io.Reader) ([]domain.Game, error) {
doc, docErr := goquery.NewDocumentFromReader(searchResult)
if docErr != nil {
log.Fatal("Could not create document from response.")
return nil, docErr
Expand All @@ -26,7 +26,7 @@ func parseSearchResult(searchResult *http.Response, branchCode int) ([]domain.Ga
doc.Find(resultItemSelector).Each(func(i int, resultItem *goquery.Selection) {
title := resultItem.Find(gameTitleSelector).Text()
if isAvailable(resultItem.Parent()) {
games = append(games, domain.Game{Title: title, Branch: BranchCodes[branchCode]})
games = append(games, domain.Game{Title: title})
}
})
return games, nil
Expand Down
24 changes: 24 additions & 0 deletions library-le/searchresult_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,33 @@
package libraryle

import (
"bufio"
"log"
"os"
"testing"

"github.com/gunni1/leipzig-library-game-stock-api/domain"
. "github.com/stretchr/testify/assert"
)

func TestAvailability(t *testing.T) {
file, fileErr := os.Open("searchresult_example.html")
if fileErr != nil {
log.Fatal(fileErr)
}
fileReader := bufio.NewReader(file)
games, _ := parseSearchResult(fileReader)

True(t, hasElement(games, "Spiel2"))
False(t, hasElement(games, "Spiel1"))

}

func hasElement(games []domain.Game, title string) bool {
for _, game := range games {
if game.Title == title {
return true
}
}
return false
}

0 comments on commit 39b0fab

Please sign in to comment.