-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaspace_test.go
More file actions
207 lines (187 loc) · 7 KB
/
aspace_test.go
File metadata and controls
207 lines (187 loc) · 7 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
)
const testDataPath = "./test-data/"
const daoURI = "/repositories/2/digital_objects/test"
var jsonTests = []struct {
_type string
beforeFile string
afterFile string
name string
}{
{"archival-object", "ao_with_instances.json", "ao_with_instances_1.json", "AO with multiple instances"},
{"archival-object", "ao_no_instances.json", "ao_no_instances_1.json", "AO with no instances"},
}
func TestLinkDAO(t *testing.T) {
for _, test := range jsonTests {
aoJSON, err := os.ReadFile(testDataPath + test.beforeFile)
check(t, err, test.beforeFile)
var ao AO
_ = json.Unmarshal(aoJSON, &ao)
newAOJSON, err := linkDAO(daoURI, ao)
if err != nil {
t.Errorf("Error creating updated JSON for %s, %s", test.name, err)
}
aoJSON_1, err := os.ReadFile(testDataPath + test.afterFile)
check(t, err, test.afterFile)
// Compare lengths of byte arrays
// We can't compare the JSON objects as strings, since the order of the map keys is not guaranteed
if len(newAOJSON) != len(aoJSON_1) {
t.Errorf("JSON objects do not match for %s test. Expected %s, got %s", test.name, string(aoJSON_1), string(newAOJSON))
}
}
}
func TestCreateDAO(t *testing.T) {
dao_id := "dao_id_123456789"
title := "Test Work 1"
file_uri := "gwss_test_uri/123456-34343-35353/"
dao := newDAO(file_uri, title, dao_id)
b, err := json.Marshal(dao)
if err != nil {
t.Errorf("Unable to convert DAO struct to JSON: %+v", dao)
}
daoJSON, err := os.ReadFile(testDataPath + "dao.json")
if err != nil {
t.Fatal("Could not open DAO JSON")
}
if len(daoJSON) != len(b) {
t.Errorf("DAO JSON objects do not match. Expected %s, got %s", string(daoJSON), string(b))
}
var daoCopy DAO
json.Unmarshal(b, &daoCopy)
if daoCopy.DigitalObjectID != dao_id {
t.Errorf("DAO JSON should have value %s for digital_object_id, but got %s", dao_id, daoCopy.DigitalObjectID)
}
if daoCopy.FileVersions[0].FileURI != file_uri {
t.Errorf("DAO JSON should have value %s for file_uri, but got %s", file_uri, daoCopy.FileVersions[0].FileURI)
}
}
func TestCreateRequests(t *testing.T) {
baseURL := "http://localhost:8080"
token := "123456789"
aoURI := "repositories/2/archival_objects/121083"
daoURI := "repositories/2/digital_objects"
payload := []byte(`{"digital_object":"some_object"}`)
t.Setenv("ASPACE_USER", "test")
t.Setenv("ASPACE_PASS", "password")
type Request struct {
Method string
URL *url.URL
}
makeURL := func(rawURL string) *url.URL {
url, _ := url.Parse(rawURL)
return url
}
table := []struct {
pipeline ASpacePipelineData
req Request
payload []byte
}{
{ASpacePipelineData{baseURL: baseURL}, Request{Method: "POST", URL: makeURL("http://localhost:8080/users/test/login")}, []byte("expiring=false&password=password")},
{ASpacePipelineData{baseURL: baseURL, ASpaceSession: ASpaceSession{token}, URI: aoURI}, Request{Method: "GET", URL: makeURL("http://localhost:8080/repositories/2/archival_objects/121083")}, payload},
{ASpacePipelineData{baseURL: baseURL, ASpaceSession: ASpaceSession{token}, URI: daoURI, payload: payload}, Request{Method: "POST", URL: makeURL("http://localhost:8080/repositories/2/digital_objects")}, payload},
}
for _, test := range table {
req, err := test.pipeline.prepareRequest()
if err != nil {
t.Fatal(err)
}
if req.Method != test.req.Method {
t.Errorf("Expected method as %s, got %s", test.req.Method, req.Method)
}
if req.URL.Host != test.req.URL.Host || req.URL.Path != test.req.URL.Path {
t.Errorf("Expected URL as %+v, got %+v", test.req.URL, req.URL)
}
if req.Body != nil {
body, _ := io.ReadAll(req.Body)
defer req.Body.Close()
if string(body) != string(test.payload) {
t.Errorf("Expected payload as %s but got %s", string(body), string(test.payload))
}
}
}
}
/* We mock a success handler and a handler that fails on the authentication step to use with testing the ASpace API pipeline. */
func mockApiOkay(w http.ResponseWriter, req *http.Request) {
// Each condition represents a separate path on the API
w.Header().Set("Content-Type", "application/json")
if strings.Contains(req.URL.Path, "user") {
json.NewEncoder(w).Encode(ASpaceSession{"123456"})
} else if strings.Contains(req.URL.Path, "archival_objects") && (req.Method == "GET") {
json.NewEncoder(w).Encode(map[string][]string{"instances": []string{}})
} else if strings.Contains(req.URL.Path, "digital_objects") {
json.NewEncoder(w).Encode(ASpaceResponse{URI: "http://localhost:8080/repositories/2/digital_objects/1"})
} else if strings.Contains(req.URL.Path, "archival_objects") && (req.Method == "POST") {
json.NewEncoder(w).Encode(map[string]string{"status": "ok", "uri": "test"})
}
}
func mockApiAuthError(w http.ResponseWriter, req *http.Request) {
// Sends an error at the authentication step
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
if strings.Contains(req.URL.Path, "user") {
json.NewEncoder(w).Encode(struct {
Error string `json:"error"`
}{Error: "User not found"})
}
}
func createClientServer(port string, wg *sync.WaitGroup) (*http.Client, *http.Server) {
// Spin up a basic server, listening on localhost
srv := &http.Server{Addr: ":" + port}
go func() {
// Signal when shutdown
defer wg.Done()
srv.ListenAndServe()
}()
// Client for making the requests
client := &http.Client{Timeout: time.Duration(5) * time.Second}
return client, srv
}
func TestAPIClient(t *testing.T) {
// Test table contains a successful condition and a condition with an error
// We register a separate http.Handler function for each condition. The net/http library does not have a built-in way to de-register a handler, so we use a different route for each condition
table := []struct {
ExpectedError error
handler func(w http.ResponseWriter, req *http.Request)
endPoint string
}{
{nil, mockApiOkay, ""},
{errors.New("User not found"), mockApiAuthError, "A/"},
}
var wg sync.WaitGroup
wg.Add(1)
client, srv := createClientServer("8080", &wg)
for _, test := range table {
// Update the route used by the updateASpace function
t.Setenv("ASPACE_HOST", "http://localhost:8080/"+test.endPoint)
t.Setenv("ASPACE_USER", "test_user")
t.Setenv("ASPACE_PASS", "password")
// register a handler on this route
http.HandleFunc("/"+test.endPoint, test.handler)
// pipeline of requests
err := updateASpace(AOMetadata{"test", "repositories/2/archival_objects/121083", "1"}, "test_uri", client)
// Error in the success condition
if (test.ExpectedError == nil) && (err != nil) {
t.Errorf("Unexpected error in request pipeline: %v", err)
// Failure condition: checking for absence of errors or a mismatched error
} else if test.ExpectedError != nil {
if (err == nil) || (!strings.Contains(err.Error(), test.ExpectedError.Error())) {
t.Errorf("Expected error of %s, got %v", test.ExpectedError.Error(), err)
}
}
}
// Shut down server and wait for cleanup
srv.Shutdown(context.TODO())
wg.Wait()
}