jmap-tasks-client 0.1.2

JMAP Tasks HTTP client — extension trait over jmap-base-client
Documentation
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
//! Wiremock integration tests for TaskNotification/* client methods.
//!
//! Each test verifies both the round-trip response parsing and the wire
//! request shape produced by the client.
//!
//! Oracle: draft-ietf-jmap-tasks-06 §5 (TaskNotification methods),
//!         RFC 8620 §5 (method shapes).

#[path = "helpers.rs"]
mod helpers;

use jmap_types::{Id, State};
use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ---------------------------------------------------------------------------
// Test 1: TaskNotification/get — round-trip with a real notification
// ---------------------------------------------------------------------------

/// TaskNotification/get returns a populated list with a correctly deserialised
/// TaskNotification object.
///
/// Oracle: draft-tasks-06 §5.1 — TaskNotification fields: id, created,
/// changedBy (Person), type, taskId.
#[tokio::test]
async fn task_notification_get_round_trip() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/get",
            {
                "accountId": "A13824",
                "state": "sn1",
                "list": [{
                    "id": "notif1",
                    "created": "2026-01-15T10:00:00Z",
                    "changedBy": {
                        "@type": "Person",
                        "name": "Alice"
                    },
                    "type": "created",
                    "taskId": "task1"
                }],
                "notFound": null
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    let resp = sc
        .task_notification_get(Some(&[Id::from("notif1")]), None)
        .await
        .expect("task_notification_get_round_trip: must succeed");

    // Response assertions.
    assert_eq!(resp.list.len(), 1, "list must contain one TaskNotification");
    assert_eq!(
        resp.list[0].id.as_ref(),
        "notif1",
        "list[0].id must be 'notif1'"
    );
    assert_eq!(
        resp.list[0].task_id.as_ref(),
        "task1",
        "list[0].task_id must be 'task1'"
    );
    assert_eq!(
        resp.list[0].created, "2026-01-15T10:00:00Z",
        "list[0].created must round-trip"
    );
    assert_eq!(
        resp.list[0].changed_by.name.as_deref(),
        Some("Alice"),
        "list[0].changed_by.name must be 'Alice'"
    );

    // Wire request assertions.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert_eq!(
        args["ids"],
        json!(["notif1"]),
        "ids must be [\"notif1\"] on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 2: TaskNotification/changes — destroyed round-trip, maxChanges absent
// ---------------------------------------------------------------------------

/// TaskNotification/changes with maxChanges=None omits maxChanges from the wire
/// and returns a destroyed list correctly.
///
/// Oracle: RFC 8620 §5.2 — maxChanges is optional; absent when not requested.
#[tokio::test]
async fn task_notification_changes_round_trip() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/changes",
            {
                "accountId": "A13824",
                "oldState": "sn1",
                "newState": "sn2",
                "hasMoreChanges": false,
                "created": [],
                "updated": [],
                "destroyed": ["notif-old"]
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    let resp = sc
        .task_notification_changes(&State::from("sn1"), None)
        .await
        .expect("task_notification_changes_round_trip: must succeed");

    // Response assertions.
    assert!(
        resp.destroyed.iter().any(|id| id.as_ref() == "notif-old"),
        "destroyed must contain 'notif-old'"
    );

    // Wire request assertions — maxChanges must be absent when None.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert!(
        args.get("maxChanges").is_none(),
        "maxChanges must be absent from the wire when None is passed: {args}"
    );
    assert_eq!(
        args["sinceState"],
        json!("sn1"),
        "sinceState must be 'sn1' on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 3: TaskNotification/set — destroy-only wire format (key correctness test)
// ---------------------------------------------------------------------------

/// TaskNotification/set sends destroy=[...] and no create or update keys.
///
/// Oracle: draft-tasks-06 §5.4 — TaskNotification/set is destroy-only.
/// The server rejects any create or update with `forbidden`; the client must
/// never send those keys.
#[tokio::test]
async fn task_notification_set_destroy_only_wire_format() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/set",
            {
                "accountId": "A13824",
                "oldState": "sn1",
                "newState": "sn2",
                "created": null,
                "updated": null,
                "destroyed": ["notif1", "notif2"],
                "notCreated": null,
                "notUpdated": null,
                "notDestroyed": null
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    sc.task_notification_set(vec![Id::from("notif1"), Id::from("notif2")])
        .await
        .expect("task_notification_set_destroy_only_wire_format: must succeed");

    // Wire request assertions — destroy present, create and update absent.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];

    let destroy = args["destroy"]
        .as_array()
        .expect("destroy must be an array on the wire");
    assert_eq!(destroy.len(), 2, "destroy must contain 2 entries");
    assert!(
        destroy.contains(&json!("notif1")),
        "destroy must contain 'notif1'"
    );
    assert!(
        destroy.contains(&json!("notif2")),
        "destroy must contain 'notif2'"
    );

    assert!(
        args.get("create").is_none() || args["create"].is_null(),
        "destroy-only set must not send 'create' key: {args}"
    );
    assert!(
        args.get("update").is_none() || args["update"].is_null(),
        "destroy-only set must not send 'update' key: {args}"
    );
}

// ---------------------------------------------------------------------------
// Test 4: TaskNotification/set — empty destroy list succeeds
// ---------------------------------------------------------------------------

/// TaskNotification/set with an empty destroy list sends destroy=[] on the wire.
///
/// Oracle: draft-tasks-06 §5.4 — an empty destroy is valid; the server returns
/// an empty /set response.
#[tokio::test]
async fn task_notification_set_empty_destroy_succeeds() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/set",
            {
                "accountId": "A13824",
                "oldState": "sn1",
                "newState": "sn1",
                "created": null,
                "updated": null,
                "destroyed": null,
                "notCreated": null,
                "notUpdated": null,
                "notDestroyed": null
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    sc.task_notification_set(vec![])
        .await
        .expect("task_notification_set_empty_destroy_succeeds: must succeed");

    // Wire request assertions.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];

    let destroy = args["destroy"]
        .as_array()
        .expect("destroy must be an array on the wire even when empty");
    assert!(destroy.is_empty(), "destroy must be [] on the wire");

    assert!(
        args.get("create").is_none() || args["create"].is_null(),
        "create must be absent from the wire: {args}"
    );
    assert!(
        args.get("update").is_none() || args["update"].is_null(),
        "update must be absent from the wire: {args}"
    );
}

// ---------------------------------------------------------------------------
// Test 5: TaskNotification/query — filter and sort on the wire
// ---------------------------------------------------------------------------

/// TaskNotification/query sends filter and sort correctly on the wire.
///
/// Oracle: draft-tasks-06 §5.5 — filter and sort are optional; when present
/// they are passed verbatim to the server.
#[tokio::test]
async fn task_notification_query_with_filter() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/query",
            {
                "accountId": "A13824",
                "queryState": "qs1",
                "canCalculateChanges": true,
                "position": 0,
                "ids": ["notif1", "notif2"],
                "total": 2
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    let resp = sc
        .task_notification_query(
            Some(json!({"type": "created", "taskIds": ["task1"]})),
            Some(json!([{"property": "created"}])),
            None,
            None,
        )
        .await
        .expect("task_notification_query_with_filter: must succeed");

    // Response assertions.
    assert_eq!(resp.ids.len(), 2, "ids must contain 2 entries");

    // Wire request assertions.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert_eq!(
        args["filter"]["type"],
        json!("created"),
        "filter.type must be 'created' on the wire"
    );
    assert_eq!(
        args["sort"][0]["property"],
        json!("created"),
        "sort[0].property must be 'created' on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 6: TaskNotification/queryChanges — sinceQueryState and maxChanges
// ---------------------------------------------------------------------------

/// TaskNotification/queryChanges sends sinceQueryState and maxChanges correctly.
///
/// Oracle: RFC 8620 §5.6 — sinceQueryState is required; maxChanges is optional.
#[tokio::test]
async fn task_notification_query_changes_round_trip() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/queryChanges",
            {
                "accountId": "A13824",
                "oldQueryState": "qs1",
                "newQueryState": "qs2",
                "total": 0,
                "removed": [],
                "added": []
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    sc.task_notification_query_changes(&State::from("qs1"), Some(20), None, None, None, None)
        .await
        .expect("task_notification_query_changes_round_trip: must succeed");

    // Wire request assertions.
    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert_eq!(
        args["sinceQueryState"],
        json!("qs1"),
        "sinceQueryState must be 'qs1' on the wire"
    );
    assert_eq!(
        args["maxChanges"],
        json!(20),
        "maxChanges must be 20 on the wire"
    );
}

/// `TaskNotification/queryChanges` with filter, sort, upToId, and
/// calculateTotal must emit all four optional args on the wire
/// (RFC 8620 §5.6).
///
/// Oracle: draft-ietf-jmap-tasks-06 §5.4 — `taskIds` is a valid
/// TaskNotification filter field; §5.5.2 mandates `"created"` as a
/// supported sort property.
#[tokio::test]
async fn task_notification_query_changes_with_filter_sort_upto_calculatetotal() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/queryChanges",
            {
                "accountId": "A13824",
                "oldQueryState": "qs1",
                "newQueryState": "qs2",
                "total": 0,
                "removed": [],
                "added": []
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    let since = State::from("qs1");
    let up_to = Id::from("tn-100");
    sc.task_notification_query_changes(
        &since,
        None,
        Some(json!({ "taskIds": ["task1"] })),
        Some(json!([{ "property": "created", "isAscending": false }])),
        Some(&up_to),
        Some(true),
    )
    .await
    .expect("task_notification_query_changes_with_filter_sort_upto_calculatetotal: must succeed");

    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert_eq!(
        args["filter"]["taskIds"][0],
        json!("task1"),
        "filter.taskIds[0] must be 'task1'"
    );
    assert_eq!(
        args["sort"][0]["property"],
        json!("created"),
        "sort[0].property must be 'created' (draft-ietf-jmap-tasks-06 §5.5.2)"
    );
    assert_eq!(
        args["upToId"],
        json!("tn-100"),
        "upToId must be on the wire (RFC 8620 §5.6)"
    );
    assert_eq!(
        args["calculateTotal"],
        json!(true),
        "calculateTotal must be on the wire (RFC 8620 §5.6)"
    );
}

/// `TaskNotification/queryChanges` with all None optional args must NOT
/// emit any of filter/sort/upToId/calculateTotal/maxChanges on the
/// wire.
///
/// Oracle: RFC 8620 §5.6 — all five are optional; the wire shape with
/// `None` for each must be byte-identical to the minimal
/// `sinceQueryState`-only call.
#[tokio::test]
async fn task_notification_query_changes_all_none_omits_optional_wire_keys() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "TaskNotification/queryChanges",
            {
                "accountId": "A13824",
                "oldQueryState": "qs1",
                "newQueryState": "qs2",
                "total": 0,
                "removed": [],
                "added": []
            },
            "r1"
        ]]
    });
    Mock::given(method("POST"))
        .and(path("/api/"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&resp_body))
        .mount(&server)
        .await;

    let sc = helpers::make_client(&server);
    let since = State::from("qs1");
    sc.task_notification_query_changes(&since, None, None, None, None, None)
        .await
        .expect("task_notification_query_changes_all_none_omits_optional_wire_keys: must succeed");

    let reqs = server
        .received_requests()
        .await
        .expect("must have recorded requests");
    let body: serde_json::Value =
        serde_json::from_slice(&reqs[0].body).expect("request body must be valid JSON");
    let args = &body["methodCalls"][0][1];
    assert!(args.get("filter").is_none(), "filter must be omitted");
    assert!(args.get("sort").is_none(), "sort must be omitted");
    assert!(args.get("upToId").is_none(), "upToId must be omitted");
    assert!(
        args.get("calculateTotal").is_none(),
        "calculateTotal must be omitted"
    );
    assert!(
        args.get("maxChanges").is_none(),
        "maxChanges must be omitted"
    );
}