-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathresource.test.ts
More file actions
567 lines (487 loc) · 19.7 KB
/
resource.test.ts
File metadata and controls
567 lines (487 loc) · 19.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//
// Copyright Inrupt Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Assertions are made conditionally on problem details responses because not all
// servers support this feature.
/* eslint-disable jest/no-conditional-expect */
import { File as NodeFile, Blob as NodeBlob } from "buffer";
import {
jest,
afterEach,
beforeEach,
describe,
expect,
it,
} from "@jest/globals";
import type { Session } from "@inrupt/solid-client-authn-node";
import {
getNodeTestingEnvironment,
setupTestResources,
teardownTestResources,
getAuthenticatedSession,
getPodRoot,
createFetch,
} from "@inrupt/internal-test-env";
import { DataFactory } from "n3";
import { DEFAULT_TYPE, type ProblemDetails } from "@inrupt/solid-client-errors";
import {
getSolidDataset,
setThing,
getThing,
setTerm,
saveSolidDatasetAt,
overwriteFile,
isRawData,
getSourceUrl,
deleteFile,
createContainerAt,
createContainerInContainer,
getBoolean,
setBoolean,
createThing,
createSolidDataset,
deleteSolidDataset,
getWellKnownSolid,
} from "../../src/index";
const { blankNode } = DataFactory;
const env = getNodeTestingEnvironment();
const TEST_SLUG = "solid-client-test-e2e-resource";
describe("Authenticated end-to-end", () => {
let fetchOptions: { fetch: typeof fetch };
let session: Session;
let sessionContainer: string;
let sessionResource: string;
let pod: string;
beforeEach(async () => {
session = await getAuthenticatedSession(env);
pod = await getPodRoot(session);
fetchOptions = { fetch: createFetch(session, TEST_SLUG) };
const testsetup = await setupTestResources(pod, fetchOptions);
sessionResource = testsetup.resourceUrl;
sessionContainer = testsetup.containerUrl;
});
afterEach(async () => {
await teardownTestResources(
session,
sessionContainer,
sessionResource,
fetchOptions,
);
});
it("can create, read, update and delete data", async () => {
const arbitraryPredicate = "https://arbitrary.vocab/predicate";
let newThing = createThing({ name: "e2e-test-thing" });
newThing = setBoolean(newThing, arbitraryPredicate, true);
let newDataset = createSolidDataset();
newDataset = setThing(newDataset, newThing);
const datasetUrl = sessionResource.concat("-crud");
await saveSolidDatasetAt(datasetUrl, newDataset, fetchOptions);
const firstSavedDataset = await getSolidDataset(datasetUrl, fetchOptions);
const firstSavedThing = getThing(
firstSavedDataset,
`${datasetUrl}#e2e-test-thing`,
)!;
expect(firstSavedThing).not.toBeNull();
expect(getBoolean(firstSavedThing, arbitraryPredicate)).toBe(true);
const updatedThing = setBoolean(firstSavedThing, arbitraryPredicate, false);
const updatedDataset = setThing(firstSavedDataset, updatedThing);
await saveSolidDatasetAt(datasetUrl, updatedDataset, fetchOptions);
const secondSavedDataset = await getSolidDataset(datasetUrl, fetchOptions);
const secondSavedThing = getThing(
secondSavedDataset,
`${datasetUrl}#e2e-test-thing`,
)!;
expect(secondSavedThing).not.toBeNull();
expect(getBoolean(secondSavedThing, arbitraryPredicate)).toBe(false);
await deleteSolidDataset(datasetUrl, fetchOptions);
// As the dataset was deleted retrieving it should produce an error.
const error = await getSolidDataset(datasetUrl, fetchOptions).catch(
(err) => err,
);
expect(error.statusCode).toBe(404);
expect(error.message).toContain(
`Fetching the Resource at [${datasetUrl}] failed:`,
);
expect(error.statusText).toContain("Not Found");
expect(error.problemDetails.type).toBe(DEFAULT_TYPE);
expect(error.problemDetails.title).toBe("Not Found");
expect(error.problemDetails.status).toBe(404);
if (env?.features?.PROBLEM_DETAILS === "true") {
expect(error.problemDetails.detail).toBe("Resource not found");
expect(error.problemDetails.instance).toBeDefined();
}
});
it("can create, delete, and differentiate between RDF and non-RDF Resources using a Blob from the node Buffer package", async () => {
const fileUrl = `${sessionResource}.txt`;
const sessionFile = await overwriteFile(
fileUrl,
// We need to type cast because the buffer definition
// of Blob does not have the prototype property expected
// by the lib.dom.ts
// See https://github.com/microsoft/TypeScript/issues/53668
// and https://github.com/microsoft/TypeScript/issues/52166
new NodeBlob(["test"], {
type: "text/plain",
}) as unknown as globalThis.Blob,
fetchOptions,
);
const sessionDataset = await getSolidDataset(sessionResource, fetchOptions);
expect(isRawData(sessionDataset)).toBe(false);
expect(isRawData(sessionFile)).toBe(true);
await deleteFile(fileUrl, fetchOptions);
});
it("can create, delete, and differentiate between RDF and non-RDF Resources using a Blob", async () => {
const fileUrl = `${sessionResource}.txt`;
const sessionFile = await overwriteFile(
fileUrl,
// We need to type cast because the buffer definition
// of Blob does not have the prototype property expected
// by the lib.dom.ts
new Blob(["test"], {
type: "text/plain",
}),
fetchOptions,
);
const sessionDataset = await getSolidDataset(sessionResource, fetchOptions);
// Eslint isn't detecting the fact that this is inside an it statement
// because of the conditional.
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionDataset)).toBe(false);
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionFile)).toBe(true);
await deleteFile(fileUrl, fetchOptions);
});
it("can create, delete, and differentiate between RDF and non-RDF Resources using a File", async () => {
const fileUrl = `${sessionResource}.txt`;
const sessionFile = await overwriteFile(
fileUrl,
// We need to type cast because the buffer definition
// of Blob does not have the prototype property expected
// by the lib.dom.ts
new File(["test"], fileUrl, { type: "text/plain" }),
fetchOptions,
);
const sessionDataset = await getSolidDataset(sessionResource, fetchOptions);
// Eslint isn't detecting the fact that this is inside an it statement
// because of the conditional.
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionDataset)).toBe(false);
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionFile)).toBe(true);
await deleteFile(fileUrl, fetchOptions);
});
it("can create, delete, and differentiate between RDF and non-RDF Resources using a File from the node Buffer package", async () => {
const fileUrl = `${sessionResource}.txt`;
const sessionFile = await overwriteFile(
fileUrl,
// We need to type cast because the buffer definition
// of Blob does not have the prototype property expected
// by the lib.dom.ts
new NodeFile(["test"], fileUrl, { type: "text/plain" }),
fetchOptions,
);
const sessionDataset = await getSolidDataset(sessionResource, fetchOptions);
// Eslint isn't detecting the fact that this is inside an it statement
// because of the conditional.
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionDataset)).toBe(false);
// eslint-disable-next-line jest/no-standalone-expect
expect(isRawData(sessionFile)).toBe(true);
await deleteFile(fileUrl, fetchOptions);
});
it("can create and remove Containers", async () => {
const containerUrl = `${pod}solid-client-tests/node/container-test/container1-${session.info.sessionId}/`;
const containerContainerUrl = `${pod}solid-client-tests/node/container-test/`;
const containerName = `container2-${session.info.sessionId}`;
const newContainer1 = await createContainerAt(containerUrl, fetchOptions);
const newContainer2 = await createContainerInContainer(
containerContainerUrl,
{ ...fetchOptions, slugSuggestion: containerName },
);
expect(getSourceUrl(newContainer1)).toBe(containerUrl);
expect(getSourceUrl(newContainer2)).toBe(
`${containerContainerUrl}${containerName}/`,
);
await deleteFile(containerUrl, fetchOptions);
await deleteFile(getSourceUrl(newContainer2), fetchOptions);
});
it("can update Things containing Blank Nodes in different instances of the same SolidDataset", async () => {
const regularPredicate = "https://arbitrary.vocab/regular-predicate";
const blankNodePredicate = "https://arbitrary.vocab/blank-node-predicate";
// Prepare the Resource on the Pod
let newThing = createThing({ name: "e2e-test-thing-with-blank-node" });
newThing = setBoolean(newThing, regularPredicate, true);
newThing = setTerm(newThing, blankNodePredicate, blankNode());
let newDataset = createSolidDataset();
newDataset = setThing(newDataset, newThing);
const datasetUrl = sessionResource.concat("-blank");
try {
await saveSolidDatasetAt(datasetUrl, newDataset, fetchOptions);
// Fetch the initialised SolidDataset for the first time,
// and change the non-blank node value:
const initialisedDataset = await getSolidDataset(
datasetUrl,
fetchOptions,
);
const initialisedThing = getThing(
initialisedDataset,
`${datasetUrl}#e2e-test-thing-with-blank-node`,
)!;
const updatedThing = setBoolean(
initialisedThing,
regularPredicate,
false,
);
// Now fetch the Resource again, and try to insert the updated Thing into it:
const refetchedDataset = await getSolidDataset(datasetUrl, fetchOptions);
const updatedDataset = setThing(refetchedDataset, updatedThing);
await expect(
saveSolidDatasetAt(datasetUrl, updatedDataset, fetchOptions),
).resolves.not.toThrow();
} finally {
// Clean up after ourselves
await deleteSolidDataset(datasetUrl, fetchOptions);
}
});
it("cannot fetch non public resources unauthenticated", async () => {
const error = await getSolidDataset(sessionResource).catch((err) => err);
expect(error.statusCode).toBe(401);
expect(error.message).toContain(
`Fetching the Resource at [${sessionResource}] failed:`,
);
expect(error.statusText).toBe("Unauthorized");
expect(error.problemDetails.type).toBe(DEFAULT_TYPE);
expect(error.problemDetails.title).toBe("Unauthorized");
expect(error.problemDetails.status).toBe(401);
if (env?.features?.PROBLEM_DETAILS === "true") {
expect(error.problemDetails.detail).toBeDefined();
expect(error.problemDetails.instance).toBeDefined();
}
});
it("can fetch getWellKnownSolid", async () => {
// We don't really care for what the resulting dataset is, just that across
// environments it reliably succeeds:
await expect(getWellKnownSolid(sessionResource)).resolves.not.toThrow();
});
it("can customize the fetch to get and set HTTP headers", async () => {
let headers: Headers = new Headers();
const customFetch: typeof fetch = async (
info: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1],
) => {
const response = await fetchOptions.fetch(info, {
...init,
headers: {
...init?.headers,
"User-Agent": "some-user-agent",
},
});
if (info.toString() === sessionResource) {
headers = response.headers;
}
return response;
};
const spiedFetch = jest.spyOn(fetchOptions, "fetch");
await getSolidDataset(sessionResource, { fetch: customFetch });
expect(spiedFetch).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
"User-Agent": "some-user-agent",
}),
}),
);
expect(headers.get("Content-Type")).toContain("text/turtle");
});
it("raises error getting a resource if service returns an error response", async () => {
const customFetch: typeof fetch = async (
info: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1],
) => {
return fetchOptions.fetch(info, {
...init,
headers: {
...init?.headers,
Accept: "plain/text",
},
});
};
// This request should produce an error
const error = await getSolidDataset(sessionResource, {
fetch: customFetch,
}).catch((err) => err);
expect(error.statusCode).toBe(406);
expect(error.message).toContain(
`Fetching the Resource at [${sessionResource}] failed: [406]`,
);
expect(error.statusText).toBe("Not Acceptable");
expect(error.problemDetails.type).toBe(DEFAULT_TYPE);
expect(error.problemDetails.title).toBe("Not Acceptable");
expect(error.problemDetails.status).toBe(406);
if (env?.features?.PROBLEM_DETAILS === "true") {
expect(error.problemDetails.detail).toBeDefined();
expect(error.problemDetails.instance).toBeDefined();
}
});
it("raises error creating a container if service returns an error response", async () => {
// This operation should throw an error
const error = await createContainerAt(sessionContainer, {
fetch: serverToRespondWithAn400Error("PUT"),
}).catch((err) => err);
expect(error.statusCode).toBe(400);
expect(error.message).toContain(
`Creating the empty Container at [${sessionContainer}] failed: [400]`,
);
expect(error.statusText).toBe("Bad Request");
expect400ProblemDetails(error.problemDetails);
});
it("raises error creating a container in a container if service returns an error response", async () => {
// This operation should throw an error
const error = await createContainerInContainer(sessionContainer, {
fetch: serverToRespondWithAn400Error("POST"),
}).catch((err) => err);
expect(error.statusCode).toBe(400);
expect(error.message).toContain(
`Creating an empty Container in the Container at [${sessionContainer}] failed: [400]`,
);
expect(error.statusText).toBe("Bad Request");
expect400ProblemDetails(error.problemDetails);
});
it("raises error deleting a resource if service returns an error response", async () => {
// This operation should throw an error
const error = await deleteFile(sessionResource, {
fetch: serverToRespondWithAn405Error(),
}).catch((err) => err);
expect(error.statusCode).toBe(405);
expect(error.message).toContain(
`Deleting the file at [${sessionResource}] failed: [405]`,
);
expect(error.statusText).toBe("Method Not Allowed");
expect405ProblemDetails(error.problemDetails);
});
it("raises error deleting a dataset if service returns an error response", async () => {
// This operation should throw an error
const error = await deleteSolidDataset(sessionResource, {
fetch: serverToRespondWithAn405Error(),
}).catch((err) => err);
expect(error.statusCode).toBe(405);
expect(error.message).toContain(
`Deleting the SolidDataset at [${sessionResource}] failed: [405]`,
);
expect(error.statusText).toBe("Method Not Allowed");
expect405ProblemDetails(error.problemDetails);
});
it("raises error retrieving a resource if service returns an error response", async () => {
// This operation should throw an error
const error = await getSolidDataset(sessionResource, {
fetch: serverToRespondWithAn405Error(),
}).catch((err) => err);
expect(error.statusCode).toBe(405);
expect(error.message).toContain(
`Fetching the Resource at [${sessionResource}] failed: [405]`,
);
expect(error.statusText).toBe("Method Not Allowed");
expect405ProblemDetails(error.problemDetails);
});
it("raises error overwriting a file if service returns an error response", async () => {
// This operation should throw an error
const error = await overwriteFile(
sessionResource,
// We need to type cast because the buffer definition
// of Blob does not have the prototype property expected
// by the lib.dom.ts
new Blob(["test"], {
type: "text/plain",
}),
{
fetch: serverToRespondWithAn405Error(),
},
).catch((err) => err);
expect(error.statusCode).toBe(405);
expect(error.message).toContain(
`Overwriting the file at [${sessionResource}] failed: [405]`,
);
expect(error.statusText).toBe("Method Not Allowed");
expect405ProblemDetails(error.problemDetails);
});
it("raises error saving a dataset if service returns an error response", async () => {
// This operation should throw an error
const error = await saveSolidDatasetAt(
sessionResource,
createSolidDataset(),
{ fetch: serverToRespondWithAn405Error() },
).catch((err) => err);
expect(error.statusCode).toBe(405);
expect(error.message).toContain(
`Storing the Resource at [${sessionResource}] failed: [405]`,
);
expect(error.statusText).toBe("Method Not Allowed");
expect405ProblemDetails(error.problemDetails);
});
function expect400ProblemDetails(problemDetails: ProblemDetails) {
expect(problemDetails.type).toBe(DEFAULT_TYPE);
expect(problemDetails.title).toBe("Bad Request");
expect(problemDetails.status).toBe(400);
if (env?.features?.PROBLEM_DETAILS === "true") {
expect(problemDetails.detail).toBeDefined();
expect(problemDetails.instance).toBeDefined();
}
}
function expect405ProblemDetails(problemDetails: ProblemDetails) {
expect(problemDetails.type).toBe(DEFAULT_TYPE);
expect(problemDetails.title).toBe("Method Not Allowed");
expect(problemDetails.status).toBe(405);
if (env?.features?.PROBLEM_DETAILS === "true") {
expect(problemDetails.detail).toBeDefined();
expect(problemDetails.instance).toBeDefined();
}
}
function serverToRespondWithAn405Error() {
// Change to invalid method to get the server to return a 405 error
const customFetch: typeof fetch = async (
info: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1],
) => {
return fetchOptions.fetch(info, {
...init,
method: "INVALID",
});
};
return customFetch;
}
function serverToRespondWithAn400Error(method: string) {
// Provide invalid body content to the PUT request to get the server to return a 400 error
const customFetch: typeof fetch = async (
info: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1],
) => {
// Only change the given method
if (init?.method === method) {
return fetchOptions.fetch(info, {
...init,
body: "Invalid content",
});
}
// All other requests fallback to the original fetch
return fetchOptions.fetch(info, init);
};
return customFetch;
}
});