data-gov-ckan 0.4.0

Client for Data.Gov CKAN
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Unit tests for the CKAN client using mock HTTP responses.
//!
//! These tests validate URL construction, response parsing, and error handling
//! without requiring network access. Run with:
//!
//! ```bash
//! cargo test -p data-gov-ckan --test unit_tests
//! ```

use data_gov_ckan::{CkanClient, CkanError, Configuration};
use serde_json::json;
use std::sync::Arc;
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Create a test client pointed at the given mock server.
fn test_client(base_url: &str) -> CkanClient {
    let config = Arc::new(Configuration {
        base_path: base_url.to_string(),
        user_agent: Some("test/1.0".to_string()),
        client: reqwest::Client::new(),
        basic_auth: None,
        oauth_access_token: None,
        bearer_access_token: None,
        api_key: None,
    });
    CkanClient::new(config)
}

// ---------------------------------------------------------------------------
// package_search
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .and(query_param("q", "climate"))
        .and(query_param("rows", "5"))
        .and(query_param("start", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": {
                "count": 42,
                "results": [
                    {
                        "name": "climate-dataset-1",
                        "title": "Climate Dataset 1",
                        "id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
                    }
                ]
            }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let result = client
        .package_search(Some("climate"), Some(5), Some(0), None)
        .await
        .expect("should succeed");

    assert_eq!(result.count, Some(42));
    let results = result.results.expect("should have results");
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].name, "climate-dataset-1");
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .and(query_param("fq", "organization:epa-gov AND res_format:CSV"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": { "count": 10, "results": [] }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let result = client
        .package_search(
            None,
            None,
            None,
            Some("organization:epa-gov AND res_format:CSV"),
        )
        .await
        .expect("should succeed");

    assert_eq!(result.count, Some(10));
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": { "count": 0, "results": [] }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let result = client
        .package_search(None, None, None, None)
        .await
        .expect("should succeed");

    assert_eq!(result.count, Some(0));
}

/// Boundary: limit=0 must be sent verbatim as `rows=0` — not silently dropped
/// or replaced with a default. Callers rely on this to fetch only counts.
#[tokio::test]
async fn package_search_with_limit_zero_sends_rows_zero_and_returns_empty_results() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .and(query_param("rows", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": { "count": 1234, "results": [] }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let result = client
        .package_search(Some("climate"), Some(0), None, None)
        .await
        .expect("rows=0 should be a valid request");

    assert_eq!(result.count, Some(1234));
    assert!(
        result.results.unwrap_or_default().is_empty(),
        "server returned empty results; client must not synthesize any"
    );
}

/// Boundary: an offset past the end of the result set returns success with an
/// empty results array. The client must parse this as valid data, not an error.
#[tokio::test]
async fn package_search_with_offset_past_total_parses_empty_results_without_error() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .and(query_param("start", "100000"))
        .and(query_param("rows", "10"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": { "count": 42, "results": [] }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let result = client
        .package_search(Some("anything"), Some(10), Some(100000), None)
        .await
        .expect("offset past total is a valid server response, not a client error");

    assert_eq!(result.count, Some(42));
    assert!(result.results.unwrap_or_default().is_empty());
}

// ---------------------------------------------------------------------------
// package_show
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/package_show"))
        .and(query_param("id", "my-dataset"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": {
                "name": "my-dataset",
                "title": "My Dataset",
                "id": "11111111-2222-3333-4444-555555555555",
                "notes": "A description",
                "resources": [
                    {
                        "name": "data.csv",
                        "format": "CSV",
                        "url": "https://example.com/data.csv"
                    }
                ]
            }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let pkg = client
        .package_show("my-dataset")
        .await
        .expect("should succeed");

    assert_eq!(pkg.name, "my-dataset");
    assert_eq!(pkg.title.as_deref(), Some("My Dataset"));
    assert_eq!(pkg.notes.as_deref(), Some("A description"));

    let resources = pkg.resources.expect("should have resources");
    assert_eq!(resources.len(), 1);
    assert_eq!(resources[0].format.as_deref(), Some("CSV"));
}

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

    // The id has spaces/special chars — reqwest should URL-encode them
    Mock::given(method("GET"))
        .and(path("/action/package_show"))
        .and(query_param("id", "my dataset/test"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": { "name": "my-dataset-test" }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let pkg = client
        .package_show("my dataset/test")
        .await
        .expect("should succeed");

    assert_eq!(pkg.name, "my-dataset-test");
}

// ---------------------------------------------------------------------------
// organization_list
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/organization_list"))
        .and(query_param("sort", "name"))
        .and(query_param("limit", "3"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": ["epa-gov", "nasa-gov", "usda-gov"]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let orgs = client
        .organization_list(Some("name"), Some(3), None)
        .await
        .expect("should succeed");

    assert_eq!(orgs, vec!["epa-gov", "nasa-gov", "usda-gov"]);
}

// ---------------------------------------------------------------------------
// group_list
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/group_list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": ["agriculture", "science"]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let groups = client
        .group_list(None, None, None)
        .await
        .expect("should succeed");

    assert_eq!(groups, vec!["agriculture", "science"]);
}

// ---------------------------------------------------------------------------
// dataset_autocomplete
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/package_autocomplete"))
        .and(query_param("q", "elect"))
        .and(query_param("limit", "5"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": [
                { "name": "electric-vehicles", "title": "Electric Vehicles" },
                { "name": "election-data", "title": "Election Data" }
            ]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let results = client
        .dataset_autocomplete(Some("elect"), Some(5))
        .await
        .expect("should succeed");

    assert_eq!(results.len(), 2);
    assert_eq!(results[0].name.as_deref(), Some("electric-vehicles"));
}

// ---------------------------------------------------------------------------
// tag_autocomplete
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/tag_autocomplete"))
        .and(query_param("q", "health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": ["health", "healthcare", "health-data"]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let tags = client
        .tag_autocomplete(Some("health"), None, None)
        .await
        .expect("should succeed");

    assert_eq!(tags, vec!["health", "healthcare", "health-data"]);
}

// ---------------------------------------------------------------------------
// organization_autocomplete
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/organization_autocomplete"))
        .and(query_param("q", "dep"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": [
                { "name": "department-of-energy", "title": "Department of Energy" }
            ]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let orgs = client
        .organization_autocomplete(Some("dep"), None)
        .await
        .expect("should succeed");

    assert_eq!(orgs.len(), 1);
    assert_eq!(orgs[0].name.as_deref(), Some("department-of-energy"));
}

// ---------------------------------------------------------------------------
// resource_format_autocomplete
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/format_autocomplete"))
        .and(query_param("q", "csv"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": ["CSV", "CSV/XLS"]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let formats = client
        .resource_format_autocomplete(Some("csv"), None)
        .await
        .expect("should succeed");

    assert_eq!(formats, vec!["CSV", "CSV/XLS"]);
}

// ---------------------------------------------------------------------------
// Error handling
// ---------------------------------------------------------------------------

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

    Mock::given(method("GET"))
        .and(path("/action/package_show"))
        .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client
        .package_show("nonexistent")
        .await
        .expect_err("should fail");

    match err {
        CkanError::ApiError { status, message } => {
            assert_eq!(status, 404);
            assert!(message.contains("Not Found"));
        }
        other => panic!("expected ApiError, got: {:?}", other),
    }
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client
        .package_search(Some("test"), None, None, None)
        .await
        .expect_err("should fail");

    match err {
        CkanError::ApiError { status, .. } => assert_eq!(status, 500),
        other => panic!("expected ApiError, got: {:?}", other),
    }
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": false, "result": null,
            "error": { "message": "something went wrong" }
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client
        .package_search(Some("test"), None, None, None)
        .await
        .expect_err("should fail");

    match err {
        CkanError::ApiError { status: 400, .. } => {}
        other => panic!("expected ApiError with status 400, got: {:?}", other),
    }
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_show"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true, "result": null
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client.package_show("test").await.expect_err("should fail");

    match err {
        CkanError::ApiError {
            status: 500,
            ref message,
        } => {
            assert!(message.contains("No result data"));
        }
        other => panic!("expected ApiError with 'No result data', got: {:?}", other),
    }
}

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

    // Return a result that's a string instead of a Package object
    Mock::given(method("GET"))
        .and(path("/action/package_show"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "help": "", "success": true,
            "result": "not a package object"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client.package_show("test").await.expect_err("should fail");

    assert!(
        matches!(err, CkanError::ParseError(_)),
        "expected ParseError, got: {:?}",
        err
    );
}

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

    Mock::given(method("GET"))
        .and(path("/action/package_search"))
        .respond_with(ResponseTemplate::new(200).set_body_string("not json at all"))
        .expect(1)
        .mount(&server)
        .await;

    let client = test_client(&server.uri());
    let err = client
        .package_search(Some("test"), None, None, None)
        .await
        .expect_err("should fail");

    assert!(
        matches!(err, CkanError::RequestError(_)),
        "expected RequestError, got: {:?}",
        err
    );
}

// ---------------------------------------------------------------------------
// Error trait and Display
// ---------------------------------------------------------------------------

#[test]
fn error_display_formats() {
    let api_err = CkanError::ApiError {
        status: 404,
        message: "Not Found".to_string(),
    };
    let display = format!("{}", api_err);
    assert!(display.contains("404"));
    assert!(display.contains("Not Found"));

    let parse_err =
        CkanError::ParseError(serde_json::from_str::<serde_json::Value>("invalid").unwrap_err());
    let display = format!("{}", parse_err);
    assert!(display.contains("Parse error"));

    let req_err = CkanError::RequestError(Box::new(std::io::Error::other("connection refused")));
    let display = format!("{}", req_err);
    assert!(display.contains("Request error"));
    assert!(display.contains("connection refused"));
}

#[test]
fn ckan_error_implements_std_error() {
    fn assert_error<T: std::error::Error>() {}
    assert_error::<CkanError>();
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

#[test]
fn default_configuration_has_expected_values() {
    let config = Configuration::default();
    assert_eq!(config.base_path, "https://catalog.data.gov/api/3");
    let expected_ua = concat!("data-gov-rs/", env!("CARGO_PKG_VERSION"));
    assert_eq!(config.user_agent.as_deref(), Some(expected_ua));
    assert!(config.api_key.is_none());
    assert!(config.basic_auth.is_none());
    assert!(config.oauth_access_token.is_none());
    assert!(config.bearer_access_token.is_none());
}

#[test]
fn client_debug_shows_base_path() {
    let config = Arc::new(Configuration {
        base_path: "https://example.com/api/3".to_string(),
        ..Configuration::default()
    });
    let client = CkanClient::new(config);
    let debug = format!("{:?}", client);
    assert!(debug.contains("example.com"));
}