summaryrefslogtreecommitdiff
path: root/modules/urlfilter/urlfilter_test.go
blob: 442780d4e3e8cbfba2db105e495c52a04d1b59b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package urlfilter_test

import (
	"net/http"
	"sync"
	"testing"

	"github.com/philippta/flyscrape"
	"github.com/philippta/flyscrape/modules/followlinks"
	"github.com/philippta/flyscrape/modules/hook"
	"github.com/philippta/flyscrape/modules/starturl"
	"github.com/philippta/flyscrape/modules/urlfilter"
	"github.com/stretchr/testify/require"
)

func TestURLFilterAllowed(t *testing.T) {
	var urls []string
	var mu sync.Mutex

	mods := []flyscrape.Module{
		&starturl.Module{URL: "http://www.example.com/"},
		&followlinks.Module{},
		&urlfilter.Module{
			URL:         "http://www.example.com/",
			AllowedURLs: []string{`/foo\?id=\d+`, `/bar$`},
		},
		hook.Module{
			AdaptTransportFn: func(rt http.RoundTripper) http.RoundTripper {
				return flyscrape.MockTransport(200, `
				<a href="foo?id=123">123</a>
				<a href="foo?id=ABC">ABC</a>
				<a href="/bar">bar</a>
				<a href="/barz">barz</a>`)
			},
			ReceiveResponseFn: func(r *flyscrape.Response) {
				mu.Lock()
				urls = append(urls, r.Request.URL)
				mu.Unlock()
			},
		},
	}

	scraper := flyscrape.NewScraper()
	scraper.Modules = mods
	scraper.Run()

	require.Len(t, urls, 3)
	require.Contains(t, urls, "http://www.example.com/")
	require.Contains(t, urls, "http://www.example.com/foo?id=123")
	require.Contains(t, urls, "http://www.example.com/bar")
}

func TestURLFilterBlocked(t *testing.T) {
	var urls []string
	var mu sync.Mutex

	mods := []flyscrape.Module{
		&starturl.Module{URL: "http://www.example.com/"},
		&followlinks.Module{},
		&urlfilter.Module{
			URL:         "http://www.example.com/",
			BlockedURLs: []string{`/foo\?id=\d+`, `/bar$`},
		},
		hook.Module{
			AdaptTransportFn: func(rt http.RoundTripper) http.RoundTripper {
				return flyscrape.MockTransport(200, `
				<a href="foo?id=123">123</a>
				<a href="foo?id=ABC">ABC</a>
				<a href="/bar">bar</a>
				<a href="/barz">barz</a>`)
			},
			ReceiveResponseFn: func(r *flyscrape.Response) {
				mu.Lock()
				urls = append(urls, r.Request.URL)
				mu.Unlock()
			},
		},
	}

	scraper := flyscrape.NewScraper()
	scraper.Modules = mods
	scraper.Run()

	require.Len(t, urls, 3)
	require.Contains(t, urls, "http://www.example.com/")
	require.Contains(t, urls, "http://www.example.com/foo?id=ABC")
	require.Contains(t, urls, "http://www.example.com/barz")
}