This repository has been archived by the owner on Nov 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlookup_service_http_test.go
93 lines (76 loc) · 2.41 KB
/
lookup_service_http_test.go
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
93
package main_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-test/deep"
pass "github.com/oa-pass/pass-download-service"
)
type MockLookupService func(string) (*pass.DoiInfo, error)
func (f MockLookupService) Lookup(doi string) (*pass.DoiInfo, error) {
return f(doi)
}
type NoLookupService struct{}
func (n NoLookupService) Lookup(doi string) (*pass.DoiInfo, error) {
return nil, nil
}
func TestMethodNotAllowed(t *testing.T) {
for _, method := range []string{http.MethodPost, http.MethodDelete, http.MethodPut} {
resp := httptest.NewRecorder()
pass.LookupServiceHandler(NoLookupService{}).ServeHTTP(resp, httptest.NewRequest(method, "/foo", nil))
if resp.Code != http.StatusMethodNotAllowed {
t.Errorf("Method should not be allowed: %s", method)
}
}
}
func TestNoDoi(t *testing.T) {
resp := httptest.NewRecorder()
pass.LookupServiceHandler(NoLookupService{}).ServeHTTP(
resp, httptest.NewRequest(http.MethodGet, "/lookup?param=notDoi", nil))
if resp.Code != http.StatusBadRequest {
t.Errorf("Expected bad request error code")
}
}
func TestResponse(t *testing.T) {
testDoi := "abc/123"
info := &pass.DoiInfo{
Manuscripts: []pass.Manuscript{
{
RepositoryInstitution: "One",
Location: "http://example.org/first",
Type: "application/pdf",
Source: "Unpaywall",
Name: "first",
},
{
RepositoryInstitution: "Two",
Location: "http://example.org/second",
Type: "application/pdf",
Source: "Unpaywall",
Name: "second",
},
},
}
resp := httptest.NewRecorder()
pass.LookupServiceHandler(MockLookupService(func(doi string) (*pass.DoiInfo, error) {
if doi == testDoi {
return info, nil
}
t.Fatalf("DOI didn't match!")
return nil, nil
})).ServeHTTP(resp, httptest.NewRequest(http.MethodGet, "/foo?doi="+testDoi, nil))
var returnedDoiInfo pass.DoiInfo
err := json.Unmarshal(resp.Body.Bytes(), &returnedDoiInfo)
if err != nil {
t.Fatalf("Encountered error reading response: %v", err)
}
diffs := deep.Equal(info, &returnedDoiInfo)
if len(diffs) > 0 {
t.Fatalf("Got different response than expected:\n%s", strings.Join(diffs, "\n"))
}
if !strings.Contains(resp.Header().Get("Content-Type"), "application/json") {
t.Fatalf("Bad content type: %s", resp.Header().Get("Content-Type"))
}
}