summaryrefslogtreecommitdiff
path: root/api/api_test.go
blob: 624b68431820192a444b7446e73104975ac51885 (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
package api_test

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"flyscrape/api"

	"github.com/stretchr/testify/require"
)

func TestScrapeURL(t *testing.T) {
	svc := &api.ServiceMock{
		ScrapeURLFunc: func(url string, params map[string]any) (any, error) {
			return map[string]any{"foo": "bar"}, nil
		},
	}
	h := api.NewHandler(svc)

	r := httptest.NewRequest("POST", "/scrape", strings.NewReader(`{"url": "https://example.com", "data": {"foo":".foo"}}`))
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	require.Equal(t, w.Result().StatusCode, http.StatusOK)
	require.Equal(t, w.Result().Header.Get("Content-Type"), "application/json")

	result := map[string]any{}
	require.NoError(t, json.NewDecoder(w.Result().Body).Decode(&result))
	require.Equal(t, result["url"].(string), "https://example.com")
	require.Equal(t, result["data"].(map[string]any)["foo"], "bar")
}

func TestScrapeURLInternalServerError(t *testing.T) {
	svc := &api.ServiceMock{
		ScrapeURLFunc: func(url string, params map[string]any) (any, error) {
			return nil, errors.New("whoops")
		},
	}
	h := api.NewHandler(svc)

	r := httptest.NewRequest("POST", "/scrape", strings.NewReader(`{"url": "https://example.com", "data": {"foo":".foo"}}`))
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	require.Equal(t, w.Result().StatusCode, http.StatusInternalServerError)
	require.Equal(t, w.Result().Header.Get("Content-Type"), "application/json")
}

func TestScrapeURLBadRequest(t *testing.T) {
	svc := &api.ServiceMock{
		ScrapeURLFunc: func(url string, params map[string]any) (any, error) {
			return nil, errors.New("whoops")
		},
	}
	h := api.NewHandler(svc)

	r := httptest.NewRequest("POST", "/scrape", strings.NewReader(`{"}`))
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)

	require.Equal(t, w.Result().StatusCode, http.StatusBadRequest)
	require.Equal(t, w.Result().Header.Get("Content-Type"), "application/json")
}