waka-api 1.0.1

WakaTime HTTP client library
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
//! Integration tests for [`WakaClient`] using a `wiremock` mock server.

use std::time::Duration;

use waka_api::{ApiError, SummaryParams, WakaClient};
use wiremock::matchers::{header, header_exists, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ─── helpers ──────────────────────────────────────────────────────────────────

/// Loads the fixture at `tests/fixtures/<name>`.
fn fixture(name: &str) -> String {
    let base = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent() // crates/waka-api -> crates
        .unwrap() // safe: always has a parent
        .parent() // crates -> workspace root
        .unwrap() // safe: always has a parent
        .join("tests/fixtures")
        .join(name);
    std::fs::read_to_string(&base)
        .unwrap_or_else(|e| panic!("failed to read fixture {}: {e}", base.display()))
}

/// Returns a [`WakaClient`] pointed at the mock server.
fn client(server: &MockServer) -> WakaClient {
    WakaClient::with_base_url("test_key", &format!("{}/api/v1/", server.uri()))
        .expect("with_base_url should succeed for a valid URL")
}

// ─── happy-path ───────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_returns_user_on_200() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .and(header_exists("authorization"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("user_current.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let user = c.me().await.expect("should succeed on 200");

    assert_eq!(user.username, "janedeveloper");
}

// ─── 401 ─────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_returns_unauthorized_on_401() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .respond_with(
            ResponseTemplate::new(401)
                .set_body_string(fixture("errors/401_unauthorized.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.me().await.expect_err("should fail on 401");

    assert!(
        matches!(err, ApiError::Unauthorized),
        "expected Unauthorized, got {err:?}"
    );
}

// ─── 429 ─────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_returns_rate_limit_on_429_with_retry_after() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .respond_with(
            ResponseTemplate::new(429)
                .set_body_string(fixture("errors/429_rate_limit.json"))
                .insert_header("content-type", "application/json")
                .insert_header("Retry-After", "60"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.me().await.expect_err("should fail on 429");

    assert!(
        matches!(
            err,
            ApiError::RateLimit {
                retry_after: Some(60)
            }
        ),
        "expected RateLimit{{retry_after: Some(60)}}, got {err:?}"
    );
}

#[tokio::test]
async fn me_returns_rate_limit_on_429_without_retry_after() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .respond_with(
            ResponseTemplate::new(429)
                .set_body_string(fixture("errors/429_rate_limit.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.me().await.expect_err("should fail on 429");

    assert!(
        matches!(err, ApiError::RateLimit { retry_after: None }),
        "expected RateLimit{{retry_after: None}}, got {err:?}"
    );
}

// ─── 5xx retry ───────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_returns_server_error_after_retries_on_500() {
    let server = MockServer::start().await;

    // Return 500 on all 3 attempts.
    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .respond_with(
            ResponseTemplate::new(500)
                .set_body_string(fixture("errors/500_server_error.json"))
                .insert_header("content-type", "application/json")
                .set_delay(Duration::from_millis(0)),
        )
        .expect(3) // must be called exactly MAX_ATTEMPTS (3) times
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.me().await.expect_err("should fail after 3 attempts");

    assert!(
        matches!(err, ApiError::ServerError { status: 500 }),
        "expected ServerError{{status: 500}}, got {err:?}"
    );
}

// ─── auth header ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn me_sends_basic_auth_header() {
    let server = MockServer::start().await;

    // Authorization header for Basic auth: base64("test_key:") = "dGVzdF9rZXk6"
    Mock::given(method("GET"))
        .and(path("/api/v1/users/current"))
        .and(header("authorization", "Basic dGVzdF9rZXk6"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("user_current.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    c.me()
        .await
        .expect("should succeed with correct Basic auth header");
}

// ─── with_base_url validation ────────────────────────────────────────────────

#[test]
fn with_base_url_rejects_invalid_url() {
    let err = WakaClient::with_base_url("key", "not a url");
    assert!(err.is_err(), "expected Err for invalid URL, got Ok");
}

// ─── summaries ────────────────────────────────────────────────────────────────

#[tokio::test]
async fn summaries_returns_response_on_200() {
    use chrono::NaiveDate;
    use wiremock::matchers::query_param;

    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/summaries"))
        .and(query_param("start", "2025-01-13"))
        .and(query_param("end", "2025-01-13"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("summaries_today.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let date = NaiveDate::from_ymd_opt(2025, 1, 13).unwrap();
    let params = SummaryParams::for_range(date, date);
    let resp = c.summaries(params).await.expect("should succeed on 200");

    assert!(!resp.data.is_empty(), "response data should not be empty");
}

#[tokio::test]
async fn summaries_sends_project_query_param() {
    use chrono::NaiveDate;
    use wiremock::matchers::query_param;

    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/summaries"))
        .and(query_param("project", "my-saas"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("summaries_today.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let date = NaiveDate::from_ymd_opt(2025, 1, 13).unwrap();
    let params = SummaryParams::for_range(date, date).project("my-saas");
    c.summaries(params)
        .await
        .expect("should forward project param");
}

#[tokio::test]
async fn summaries_returns_unauthorized_on_401() {
    use chrono::NaiveDate;

    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/summaries"))
        .respond_with(
            ResponseTemplate::new(401)
                .set_body_string(fixture("errors/401_unauthorized.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let date = NaiveDate::from_ymd_opt(2025, 1, 13).unwrap();
    let params = SummaryParams::for_range(date, date);
    let err = c.summaries(params).await.expect_err("should fail on 401");

    assert!(
        matches!(err, ApiError::Unauthorized),
        "expected Unauthorized, got {err:?}"
    );
}

// ─── projects ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn projects_returns_list_on_200() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/projects"))
        .and(header_exists("authorization"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("projects.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let resp = c.projects().await.expect("should succeed on 200");

    assert_eq!(resp.data.len(), 2);
    assert_eq!(resp.data[0].name, "waka");
    assert_eq!(resp.data[1].name, "my-saas");
}

#[tokio::test]
async fn projects_returns_unauthorized_on_401() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/projects"))
        .respond_with(
            ResponseTemplate::new(401)
                .set_body_string(fixture("errors/401_unauthorized.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.projects().await.expect_err("should fail on 401");

    assert!(
        matches!(err, ApiError::Unauthorized),
        "expected Unauthorized, got {err:?}"
    );
}

// ─── stats ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn stats_uses_range_path_segment() {
    use waka_api::StatsRange;

    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/stats/last_7_days"))
        .and(header_exists("authorization"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("stats_last_7_days.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let resp = c
        .stats(StatsRange::Last7Days)
        .await
        .expect("should succeed on 200");

    assert_eq!(resp.data.range, "last_7_days");
    assert!(
        resp.data.total_seconds > 0.0,
        "total_seconds should be positive"
    );
}

#[tokio::test]
async fn stats_returns_unauthorized_on_401() {
    use waka_api::StatsRange;

    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/stats/last_30_days"))
        .respond_with(
            ResponseTemplate::new(401)
                .set_body_string(fixture("errors/401_unauthorized.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c
        .stats(StatsRange::Last30Days)
        .await
        .expect_err("should fail on 401");

    assert!(
        matches!(err, ApiError::Unauthorized),
        "expected Unauthorized, got {err:?}"
    );
}

// ─── goals ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn goals_returns_list_on_200() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/goals"))
        .and(header_exists("authorization"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(fixture("goals.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let resp = c.goals().await.expect("should succeed on 200");

    assert_eq!(resp.total, 2);
    assert_eq!(resp.data.len(), 2);
    assert_eq!(resp.data[0].title, "Code 8 hours per day");
    assert_eq!(resp.data[1].status, "fail");
}

#[tokio::test]
async fn goals_returns_unauthorized_on_401() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/goals"))
        .respond_with(
            ResponseTemplate::new(401)
                .set_body_string(fixture("errors/401_unauthorized.json"))
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let err = c.goals().await.expect_err("should fail on 401");

    assert!(
        matches!(err, ApiError::Unauthorized),
        "expected Unauthorized, got {err:?}"
    );
}

// ─── leaderboard ──────────────────────────────────────────────────────────────

#[tokio::test]
async fn leaderboard_sends_page_query_param() {
    use wiremock::matchers::query_param;

    let server = MockServer::start().await;

    // Build a minimal leaderboard fixture inline.
    let body = serde_json::json!({
        "current_user": null,
        "data": [],
        "language": null,
        "modified_at": "2025-01-13T12:00:00Z",
        "page": 2,
        "range": {
            "end_date": "2025-01-13",
            "end_text": "Jan 13",
            "name": "last_7_days",
            "start_date": "2025-01-07",
            "start_text": "Jan 7",
            "text": "Last 7 Days"
        },
        "timeout": 15,
        "total_pages": 5,
        "writes_only": false
    })
    .to_string();

    Mock::given(method("GET"))
        .and(path("/api/v1/users/current/leaderboards"))
        .and(header_exists("authorization"))
        .and(query_param("page", "2"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string(body)
                .insert_header("content-type", "application/json"),
        )
        .mount(&server)
        .await;

    let c = client(&server);
    let resp = c.leaderboard(2).await.expect("should succeed on 200");

    assert_eq!(resp.page, 2);
    assert_eq!(resp.total_pages, 5);
    assert!(resp.data.is_empty());
}