Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default resolver tests #300

Merged
merged 3 commits into from
Apr 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- Dev: Improve SevenTV tests. (#294)
- Dev: Improve FrankerFaceZ tests. (#295)
- Dev: Improve Livestreamfails tests. (#297, #301)
- Dev: Improve default resolver tests. (#300)

## 1.2.3

Expand Down
6 changes: 0 additions & 6 deletions internal/resolvers/betterttv/emote_resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,6 @@ func TestEmoteResolver(t *testing.T) {
},
}

const q = `SELECT value FROM cache WHERE key=$1`

for _, test := range tests {
c.Run(test.label, func(c *qt.C) {
outputBytes, outputError := resolver.Run(ctx, test.inputURL, test.inputReq)
Expand Down Expand Up @@ -141,8 +139,6 @@ func TestEmoteResolver(t *testing.T) {
},
}

const q = `SELECT value FROM cache WHERE key=$1`

for _, test := range tests {
c.Run(test.label, func(c *qt.C) {
rows := pgxmock.NewRows([]string{"value"}).AddRow(test.expectedBytes)
Expand Down Expand Up @@ -194,8 +190,6 @@ func TestEmoteResolver(t *testing.T) {
},
}

const q = `SELECT value FROM cache WHERE key=$1`

for _, test := range tests {
c.Run(test.label, func(c *qt.C) {
pool.ExpectQuery("SELECT").WillReturnError(pgx.ErrNoRows)
Expand Down
128 changes: 128 additions & 0 deletions internal/resolvers/default/link_resolver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package defaultresolver

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"testing"

"github.com/Chatterino/api/internal/logger"
"github.com/Chatterino/api/pkg/config"
"github.com/Chatterino/api/pkg/resolver"
qt "github.com/frankban/quicktest"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v4"
"github.com/pashagolub/pgxmock"
)

func newRequest(t *testing.T, ctx context.Context, method string, url string, payload io.Reader) *http.Request {
req, err := http.NewRequestWithContext(ctx, method, url, payload)
if err != nil {
t.Fatal("Unable to create request")
}

return req
}

func newLinkResolverRequest(t *testing.T, ctx context.Context, method string, u string, payload io.Reader) *http.Request {
finalURL := "/link_resolver/" + url.QueryEscape(u)
fmt.Println("Final URL", finalURL)
req, err := http.NewRequestWithContext(ctx, method, finalURL, payload)
if err != nil {
t.Fatal("Unable to create request")
}

return req
}

func TestLinkResolver(t *testing.T) {
ctx := logger.OnContext(context.Background(), logger.NewTest())
c := qt.New(t)

cfg := config.APIConfig{
MaxContentLength: 1024,
}
pool, _ := pgxmock.NewPool()

resolver.InitializeStaticResponses(ctx, cfg)

router := chi.NewRouter()

r := New(ctx, cfg, pool, nil)

router.Get("/link_resolver/{url}", r.HandleRequest)
router.Get("/thumbnail/{url}", r.HandleThumbnailRequest)

var resolverResponses = map[string]string{}

resolverResponses["/"] = "<html><head><title>/ title</title></head><body>xD</body></html>"

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if response, ok := resolverResponses[r.URL.Path]; ok {
w.Write([]byte(response))
return
}
http.Error(w, http.StatusText(404), 404)
}))
defer ts.Close()

c.Run("Request", func(c *qt.C) {
tests := []struct {
inputReq *http.Request
inputLinkKey string
expected resolver.Response
}{
{
inputReq: newLinkResolverRequest(t, ctx, "GET", ts.URL, nil),
inputLinkKey: ts.URL,
expected: resolver.Response{
Status: 200,
Link: ts.URL,
Tooltip: `<div style="text-align: left;">

<b>/ title</b><hr>


<b>URL:</b> http://127\.0\.0\.1:[\d]{2,7}</div>`,
},
},
}

for _, test := range tests {
c.Run("", func(c *qt.C) {
respRec := httptest.NewRecorder()

pool.ExpectQuery("SELECT").WillReturnError(pgx.ErrNoRows)
pool.ExpectExec("INSERT INTO cache").
WithArgs("default:link:"+test.inputLinkKey, pgxmock.AnyArg(), pgxmock.AnyArg()).
WillReturnResult(pgxmock.NewResult("INSERT", 1))

router.ServeHTTP(respRec, test.inputReq)
resp := respRec.Result()
response := resolver.Response{}
err := json.NewDecoder(resp.Body).Decode(&response)
c.Assert(err, qt.IsNil)

c.Assert(response.Status, qt.Equals, test.expected.Status)
c.Assert(response.Link, qt.Equals, test.expected.Link)

unescapedTooltip, err := url.QueryUnescape(response.Tooltip)
c.Assert(err, qt.IsNil)

if test.expected.Tooltip != "" {
c.Assert(unescapedTooltip, MatchesRegexp, regexp.MustCompile(test.expected.Tooltip), qt.Commentf("%s does not match %s", unescapedTooltip, test.expected.Tooltip))
}
if test.expected.Message != "" {
c.Assert(response.Message, qt.Matches, test.expected.Message, qt.Commentf("%s does not match %s", response.Message, test.expected.Message))
}

c.Assert(pool.ExpectationsWereMet(), qt.IsNil)
})
}
})
}
56 changes: 56 additions & 0 deletions internal/resolvers/default/model_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package defaultresolver

import (
"testing"

qt "github.com/frankban/quicktest"
)

func TestTooltipData(t *testing.T) {
c := qt.New(t)

c.Run("Truncate", func(c *qt.C) {
tests := []struct {
input tooltipData
expected tooltipData
}{
{
input: tooltipData{
Title: "foo",
Description: "bar",
},
expected: tooltipData{
Title: "foo",
Description: "bar",
},
},
{
input: tooltipData{
Title: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy",
Description: "bar",
},
expected: tooltipData{
Title: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy",
Description: "bar",
},
},
{
input: tooltipData{
Title: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyz",
Description: "bar",
},
expected: tooltipData{
Title: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…",
Description: "bar",
},
},
}

for _, test := range tests {
c.Run("", func(c *qt.C) {
test.input.Truncate()
c.Assert(test.input, qt.DeepEquals, test.expected)
})
}
})
}
46 changes: 46 additions & 0 deletions internal/resolvers/default/regexpchecker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package defaultresolver

import (
"errors"
"fmt"
"regexp"

qt "github.com/frankban/quicktest"
)

type argNames []string

func (a argNames) ArgNames() []string {
return a
}

var MatchesRegexp qt.Checker = &regexpChecker{
argNames: []string{"got value", "regexp"},
}

type regexpChecker struct {
argNames
}

// match checks that the given error message matches the given pattern.
func match(got string, pattern *regexp.Regexp, msg string, note func(key string, value interface{})) error {
if pattern.MatchString(got) {
return nil
}

return errors.New(msg)
}

func (c *regexpChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
switch pattern := args[0].(type) {
case *regexp.Regexp:
switch v := got.(type) {
case string:
return match(v, pattern, "value does not match regexp", note)
case fmt.Stringer:
return match(v.String(), pattern, "value.String() does not match regexp", note)
}
return qt.BadCheckf("value is not a string or a fmt.Stringer")
}
return qt.BadCheckf("pattern is not a *regexp.Regexp")
}
2 changes: 1 addition & 1 deletion pkg/utils/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import "strings"
// TruncateString truncates string down to the maximum length with a unicode triple dot if truncation took place
func TruncateString(s string, maxLength int) string {
runes := []rune(s)
if len(runes) < maxLength {
if len(runes) <= maxLength {
return s
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestTruncateString(t *testing.T) {
{
input: "foobar",
maxLength: 6,
expectedOutput: "fooba…",
expectedOutput: "foobar",
},
{
input: "foobar",
Expand Down