jmap-tasks-client 0.1.1

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
//! Wiremock integration tests for Task/* 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 §4 (Task 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: Task/get — ids and properties round-trip
// ---------------------------------------------------------------------------

/// Task/get with ids=["task1"] and properties=["id","title","isDraft"] sends
/// both fields on the wire and returns a partial Task with the correct values.
///
/// Oracle: draft-tasks-06 §4.5 — ids and properties are passed verbatim to the server.
/// Response shape: RFC 8620 §5.1 GetResponse.
#[tokio::test]
async fn task_get_sends_ids_and_properties() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/get",
            {
                "accountId": "A13824",
                "state": "s5",
                "list": [{
                    "id": "task1",
                    "title": "Write tests",
                    "isDraft": true
                }],
                "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_get(
            Some(&[Id::from("task1")]),
            Some(&["id", "title", "isDraft"]),
        )
        .await
        .expect("task_get_sends_ids_and_properties: must succeed");

    // Response assertions.
    assert_eq!(resp.list.len(), 1, "list must contain one Task");
    assert_eq!(
        resp.list[0].id.as_ref().map(|id| id.as_ref()),
        Some("task1"),
        "list[0].id must be 'task1'"
    );
    assert_eq!(
        resp.list[0].title.as_deref(),
        Some("Write tests"),
        "list[0].title must be 'Write tests'"
    );
    assert_eq!(
        resp.list[0].is_draft,
        Some(true),
        "list[0].is_draft must be Some(true)"
    );

    // 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!(["task1"]),
        "ids must be [\"task1\"] on the wire"
    );
    assert_eq!(
        args["properties"],
        json!(["id", "title", "isDraft"]),
        "properties must be [\"id\",\"title\",\"isDraft\"] on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 2: Task/get — ids=None sends null
// ---------------------------------------------------------------------------

/// Task/get with ids=None sends null for ids, requesting all Tasks.
///
/// Oracle: draft-tasks-06 §4.5 — ids=null means "all Tasks for the account".
#[tokio::test]
async fn task_get_all_ids_null() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/get",
            {
                "accountId": "A13824",
                "state": "s5",
                "list": [],
                "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);
    sc.task_get(None, None)
        .await
        .expect("task_get_all_ids_null: 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!(
        args["ids"].is_null(),
        "ids must be null when None is passed: {}",
        args
    );
}

// ---------------------------------------------------------------------------
// Test 3: Task/changes — sinceState, maxChanges, hasMoreChanges
// ---------------------------------------------------------------------------

/// Task/changes sends sinceState and maxChanges and parses hasMoreChanges=true.
///
/// Oracle: RFC 8620 §5.2 — /changes request must include sinceState; maxChanges is optional.
#[tokio::test]
async fn task_changes_paginated() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/changes",
            {
                "accountId": "A13824",
                "oldState": "s5",
                "newState": "s6",
                "hasMoreChanges": true,
                "created": ["task-new"],
                "updated": [],
                "destroyed": []
            },
            "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_changes(&State::from("s5"), Some(10))
        .await
        .expect("task_changes_paginated: must succeed");

    // Response assertions.
    assert!(resp.has_more_changes, "hasMoreChanges must be true");
    assert_eq!(resp.old_state, "s5", "oldState must round-trip");

    // 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["sinceState"],
        json!("s5"),
        "sinceState must be 's5' on the wire"
    );
    assert_eq!(
        args["maxChanges"],
        json!(10),
        "maxChanges must be 10 on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 4: Task/set — create round-trip
// ---------------------------------------------------------------------------

/// Task/set with create returns the created object in the response.
///
/// Oracle: RFC 8620 §5.3 — created keys are caller-supplied; server returns
/// them in the `created` map with the assigned id and any server-set fields.
#[tokio::test]
async fn task_set_create_round_trip() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/set",
            {
                "accountId": "A13824",
                "oldState": null,
                "newState": "s2",
                "created": {
                    "k1": { "id": "task-new1" }
                },
                "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);
    let resp = sc
        .task_set(
            Some(json!({"k1": {"title": "New task", "isDraft": true}})),
            None,
            None,
        )
        .await
        .expect("task_set_create_round_trip: must succeed");

    // Response assertions.
    let created = resp
        .created
        .as_ref()
        .expect("created must be Some when a task was created");
    assert!(
        created.contains_key("k1"),
        "created map must contain key 'k1'"
    );
    assert_eq!(
        created["k1"].id.as_ref().map(|id| id.as_ref()),
        Some("task-new1"),
        "created[\"k1\"].id must be 'task-new1'"
    );
}

// ---------------------------------------------------------------------------
// Test 5: Task/copy — fromAccountId and accountId on the wire
// ---------------------------------------------------------------------------

/// Task/copy sends fromAccountId from the argument and accountId from the session.
///
/// Oracle: draft-tasks-06 §4.8 — fromAccountId is the source account; accountId
/// is the destination (the session's primary tasks account).
#[tokio::test]
async fn task_copy_includes_from_account_id() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/copy",
            {
                "accountId": "A13824",
                "oldState": null,
                "newState": "s2",
                "created": {
                    "c1": { "id": "task-copy1" }
                },
                "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_copy(
        &Id::from("srcacc"),
        json!({"c1": {"id": "task-src1", "taskListId": "list1"}}),
    )
    .await
    .expect("task_copy_includes_from_account_id: 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["fromAccountId"],
        json!("srcacc"),
        "fromAccountId must be 'srcacc' on the wire"
    );
    assert_eq!(
        args["accountId"],
        json!("A13824"),
        "accountId must be 'A13824' (session primary account) on the wire"
    );
}

// ---------------------------------------------------------------------------
// Test 6: Task/query — filter, position, limit round-trip
// ---------------------------------------------------------------------------

/// Task/query with filter and pagination sends all fields and returns ids.
///
/// Oracle: draft-tasks-06 §4.13 — filter, position, and limit are optional
/// query arguments; ids in the response are server-ordered.
#[tokio::test]
async fn task_query_with_filter() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/query",
            {
                "accountId": "A13824",
                "queryState": "qs1",
                "canCalculateChanges": true,
                "position": 0,
                "ids": ["task1", "task2"],
                "total": 2,
                "limit": 20
            },
            "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_query(
            Some(json!({"after": "2026-01-01T00:00:00Z"})),
            None,
            Some(0),
            Some(20),
        )
        .await
        .expect("task_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"]["after"],
        json!("2026-01-01T00:00:00Z"),
        "filter.after must be '2026-01-01T00:00:00Z' on the wire"
    );
    assert_eq!(args["position"], json!(0), "position must be 0 on the wire");
    assert_eq!(args["limit"], json!(20), "limit must be 20 on the wire");
}

// ---------------------------------------------------------------------------
// Test 7: Task/queryChanges — sinceQueryState, maxChanges, removed, added
// ---------------------------------------------------------------------------

/// Task/queryChanges sends sinceQueryState and maxChanges and parses removed/added.
///
/// Oracle: RFC 8620 §5.6 — /queryChanges response contains removed (Ids) and
/// added (AddedItem with id and index).
#[tokio::test]
async fn task_query_changes_round_trip() {
    let server = MockServer::start().await;
    let resp_body = json!({
        "sessionState": "s1",
        "methodResponses": [[
            "Task/queryChanges",
            {
                "accountId": "A13824",
                "oldQueryState": "qs1",
                "newQueryState": "qs2",
                "total": 1,
                "removed": ["task-old"],
                "added": [{"id": "task-new", "index": 0}]
            },
            "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_query_changes(&State::from("qs1"), Some(5))
        .await
        .expect("task_query_changes_round_trip: must succeed");

    // Response assertions.
    assert!(
        resp.removed.iter().any(|id| id.as_ref() == "task-old"),
        "removed must contain 'task-old'"
    );
    assert_eq!(resp.added.len(), 1, "added must contain one entry");
    assert_eq!(
        resp.added[0].id.as_ref(),
        "task-new",
        "added[0].id must be 'task-new'"
    );
    assert_eq!(resp.added[0].index, 0, "added[0].index must be 0");

    // 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!(5),
        "maxChanges must be 5 on the wire"
    );
}