crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::engines::engine_client::{
    EngineClient, ScrapeOptions, ScrapeRequest as EngineScrapeRequest,
};
use crate::search::{
    client::html_parser::HtmlParser,
    client::shared_utils::escape_html_text,
    engine_trait::SearchEngine,
    error::SearchError,
    response::{Response, ResponseItem},
    types::{EngineHealth, SearchEngineType},
    SearchRequest,
};
use async_trait::async_trait;
use serde_json;
use std::collections::HashMap;
use std::sync::Arc;

/// Baidu Search Categories
#[derive(Debug, Clone, Copy)]
pub enum BaiduSearchCategory {
    General,
    Images,
    News,
}

/// Baidu Search Engine implementation with EngineClient support
///
/// **性能 PERF-05**:不再持有 `parser: HtmlParser` 字段,改为通过
/// `HtmlParser::baidu()` 静态方法访问全局 `Lazy` 单例,避免每个
/// `BaiduSearchEngine::new` 实例都重复构造 `HtmlParser`(解析 8 个 CSS 选择器)。
pub struct BaiduSearchEngine {
    engine_client: Arc<EngineClient>,
}

impl BaiduSearchEngine {
    pub fn new(engine_client: Arc<EngineClient>) -> Self {
        Self { engine_client }
    }

    /// F2:offset 推导 1-based 页码(百度 rn 固定 10 条/页)
    fn page_from_offset(offset: u32) -> u32 {
        (offset / 10) + 1
    }

    pub fn build_baidu_url(
        &self,
        query: &str,
        page: u32,
        category: BaiduSearchCategory,
    ) -> (String, HashMap<String, String>) {
        let mut params = HashMap::with_capacity(8);
        let offset = ((page - 1) * 10).to_string();

        match category {
            BaiduSearchCategory::General => {
                params.insert("wd".to_string(), query.to_string());
                params.insert("rn".to_string(), "10".to_string());
                params.insert("on".to_string(), offset);
                params.insert("tn".to_string(), "json".to_string());
                ("https://www.baidu.com/s".to_string(), params)
            }
            BaiduSearchCategory::Images => {
                params.insert("word".to_string(), query.to_string());
                params.insert("tn".to_string(), "resultjson_com".to_string());
                params.insert("on".to_string(), offset);
                params.insert("rn".to_string(), "30".to_string()); // Images usually have more results
                ("https://image.baidu.com/search/acjson".to_string(), params)
            }
            _ => {
                // Fallback to general
                params.insert("wd".to_string(), query.to_string());
                ("https://www.baidu.com/s".to_string(), params)
            }
        }
    }

    pub fn parse_baidu_response(&self, json_str: &str) -> Result<Vec<ResponseItem>, SearchError> {
        let json: serde_json::Value = serde_json::from_str(json_str)
            .map_err(|e| SearchError::Parse(format!("Failed to parse Baidu JSON: {}", e)))?;

        // 反爬检测:Baidu JSON 中 antiFlag=1 表示拒绝访问
        // 参考: searxng/searx/engines/baidu.py line 138
        if json.get("antiFlag").and_then(|v| v.as_i64()) == Some(1) {
            let msg = json
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("Baidu spider access denied");
            return Err(SearchError::RateLimited(format!(
                "Baidu anti-spider: {}",
                msg
            )));
        }

        let mut results = Vec::with_capacity(10);

        if let Some(entry_array) = json
            .get("feed")
            .and_then(|f: &serde_json::Value| f.get("entry"))
            .and_then(|e: &serde_json::Value| e.as_array())
        {
            for entry in entry_array {
                let title = entry
                    .get("title")
                    .and_then(|t: &serde_json::Value| t.as_str())
                    .unwrap_or_default()
                    .to_string();
                let url = entry
                    .get("url")
                    .and_then(|u: &serde_json::Value| u.as_str())
                    .unwrap_or_default()
                    .to_string();
                let description = entry
                    .get("abs")
                    .and_then(|a: &serde_json::Value| a.as_str())
                    .unwrap_or_default()
                    .to_string();

                if !title.is_empty() && !url.is_empty() {
                    results.push(ResponseItem {
                        title: escape_html_text(&title),
                        url,
                        description: escape_html_text(&description),
                        engine: SearchEngineType::Baidu,
                    });
                }
            }
        }

        Ok(results)
    }

    pub fn parse_search_results(
        &self,
        html: &str,
        _query: &str,
    ) -> Result<Vec<ResponseItem>, SearchError> {
        // 性能 PERF-05:使用全局 Lazy 单例,避免每次 new 都重复解析选择器
        Ok(HtmlParser::baidu().parse(html, SearchEngineType::Baidu))
    }

    /// HTML 解析 + JSON 回退(自 [`BaiduSearchEngine::search`] 提取)
    fn parse_results_with_json_fallback(
        &self,
        content: &str,
        query: &str,
    ) -> Result<Vec<ResponseItem>, SearchError> {
        // Try parsing as HTML first, then JSON fallback
        let items = self.parse_search_results(content, query)?;

        // If HTML parsing returned empty, try JSON (tn=json mode)
        let items = if items.is_empty() {
            if let Ok(json_items) = self.parse_baidu_response(content) {
                if !json_items.is_empty() {
                    json_items
                } else {
                    items
                }
            } else {
                items
            }
        } else {
            items
        };

        Ok(items)
    }
}

#[async_trait]
impl SearchEngine for BaiduSearchEngine {
    fn name(&self) -> &'static str {
        "Baidu"
    }
    fn engine_type(&self) -> SearchEngineType {
        SearchEngineType::Baidu
    }
    fn health(&self) -> EngineHealth {
        EngineHealth::Healthy
    }

    async fn search(&self, request: &SearchRequest) -> Result<Response<ResponseItem>, SearchError> {
        // 测试固定结果仅存在于测试构建(CWE-489:生产路径不得被环境变量旁路)
        #[cfg(test)]
        {
            if let Some(resp) = baidu_test_results_override(&request.query) {
                return Ok(resp);
            }
        }

        // F2:offset 推导翻页页码(lang/country 参数百度接口不支持,忽略)
        let page = Self::page_from_offset(request.offset);
        let (url, params) =
            self.build_baidu_url(&request.query, page, BaiduSearchCategory::General);
        let full_url = build_full_search_url(url, &params);

        // 构建请求头
        // 参考 searxng/searx/engines/baidu.py:Baidu JSON 模式需要标准浏览器 UA
        let headers = build_search_headers();

        // 使用 EngineClient 进行请求
        let options = ScrapeOptions {
            headers,
            timeout: std::time::Duration::from_secs(30),
            ..Default::default()
        };

        let engine_request = EngineScrapeRequest {
            url: full_url,
            options,
        };

        let scrape_response = self
            .engine_client
            .scrape(&engine_request)
            .await
            .map_err(|e| SearchError::EngineClient("Baidu".to_string(), e.to_string()))?;

        if scrape_response.status_code < 200 || scrape_response.status_code >= 300 {
            return Err(SearchError::BadHttpStatus(
                "Baidu".to_string(),
                scrape_response.status_code,
            ));
        }

        let content = scrape_response.content;
        detect_baidu_captcha(&content)?;
        let items = self.parse_results_with_json_fallback(&content, &request.query)?;

        let total_count = items.len() as u64;

        Ok(Response {
            items,
            total_results: Some(total_count),
            engine: SearchEngineType::Baidu,
        })
    }
}

/// 拼接完整搜索 URL(自 [`BaiduSearchEngine::search`] 提取)
fn build_full_search_url(url: String, params: &HashMap<String, String>) -> String {
    if !params.is_empty() {
        format!(
            "{}?{}",
            url,
            serde_urlencoded::to_string(params).unwrap_or_default()
        )
    } else {
        url
    }
}

/// 搜索请求头(自 [`BaiduSearchEngine::search`] 提取)
fn build_search_headers() -> HashMap<String, String> {
    // 构建请求头
    // 参考 searxng/searx/engines/baidu.py:Baidu JSON 模式需要标准浏览器 UA
    let mut headers = HashMap::with_capacity(6);
    headers.insert(
        "Accept".to_string(),
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8".to_string(),
    );
    headers.insert(
        "Accept-Language".to_string(),
        "zh-CN,zh;q=0.9,en;q=0.8".to_string(),
    );
    headers.insert("DNT".to_string(), "1".to_string());
    headers.insert("Connection".to_string(), "keep-alive".to_string());
    headers.insert("Sec-GPC".to_string(), "1".to_string());
    headers.insert("Cache-Control".to_string(), "max-age=0".to_string());
    headers
}

/// 百度反爬验证页检测(自 [`BaiduSearchEngine::search`] 提取)
fn detect_baidu_captcha(content: &str) -> Result<(), SearchError> {
    // 反爬检测:Baidu captcha 重定向目标(参考 searxng wappass 检测)。
    // HTTP 客户端跟随 302 后拿到的是验证页本体,正文只有“百度安全验证”
    // 标题,不含 wappass 重定向 URL 字符串,故需并列检测。
    if content.contains("wappass.baidu.com/static/captcha")
        || content.contains("verify your access")
        || content.contains("百度安全验证")
    {
        return Err(SearchError::Captcha("Baidu".to_string()));
    }
    Ok(())
}

/// 仅测试构建可用的固定结果旁路:`BAIDU_TEST_RESULTS=true` 时返回确定性结果。
///
/// 生产构建中该函数与 `search()` 内的调用点一并被 `#[cfg(test)]` 剔除,
/// 环境变量无法影响线上搜索行为(CWE-489)。
#[cfg(test)]
fn baidu_test_results_override(query: &str) -> Option<Response<ResponseItem>> {
    if std::env::var("BAIDU_TEST_RESULTS").unwrap_or_default() != "true" {
        return None;
    }
    let escaped_query = html_escape::encode_text(query);
    Some(Response {
        items: vec![
            ResponseItem {
                title: format!("Baidu Test Result 1 for {}", escaped_query),
                url: "https://baidu.com/1".to_string(),
                description: "Test description 1".to_string(),
                engine: SearchEngineType::Baidu,
            },
            ResponseItem {
                title: format!("Baidu Test Result 2 for {}", escaped_query),
                url: "https://baidu.com/2".to_string(),
                description: "Test description 2".to_string(),
                engine: SearchEngineType::Baidu,
            },
        ],
        total_results: Some(2),
        engine: SearchEngineType::Baidu,
    })
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::engines::engine_client::EngineClient;
    use std::sync::Arc;

    // 辅助函数:创建测试用的 BaiduSearchEngine 实例
    fn create_engine() -> BaiduSearchEngine {
        let engine_client = Arc::new(EngineClient::new());
        BaiduSearchEngine::new(engine_client)
    }

    // build_baidu_url 测试

    #[test]
    fn test_build_baidu_url_general_page1() {
        // 测试通用搜索第一页的 URL 和参数构建
        let engine = create_engine();
        let (url, params) = engine.build_baidu_url("rust 语言", 1, BaiduSearchCategory::General);

        assert_eq!(url, "https://www.baidu.com/s");
        assert_eq!(params.get("wd"), Some(&"rust 语言".to_string()));
        assert_eq!(params.get("rn"), Some(&"10".to_string()));
        assert_eq!(params.get("on"), Some(&"0".to_string()));
        assert_eq!(params.get("tn"), Some(&"json".to_string()));
    }

    #[test]
    fn test_build_baidu_url_general_page3_offset() {
        // 测试页码对应的偏移量计算:page=3 → on=20
        let engine = create_engine();
        let (_url, params) = engine.build_baidu_url("test", 3, BaiduSearchCategory::General);

        assert_eq!(params.get("on"), Some(&"20".to_string()));
    }

    /// F2:offset 推导百度页码(rn=10/页)
    #[test]
    fn test_baidu_offset_derives_page_param() {
        assert_eq!(BaiduSearchEngine::page_from_offset(0), 1);
        assert_eq!(BaiduSearchEngine::page_from_offset(10), 2);

        let engine = create_engine();
        let (url, params) = engine.build_baidu_url(
            "rust",
            BaiduSearchEngine::page_from_offset(10),
            BaiduSearchCategory::General,
        );
        assert_eq!(
            params.get("on").map(String::as_str),
            Some("10"),
            "page 2 → on=10, url={url}"
        );
    }

    #[test]
    fn test_build_baidu_url_images_category() {
        // 测试图片搜索分类的 URL 和参数
        let engine = create_engine();
        let (url, params) = engine.build_baidu_url("cat", 1, BaiduSearchCategory::Images);

        assert_eq!(url, "https://image.baidu.com/search/acjson");
        assert_eq!(params.get("word"), Some(&"cat".to_string()));
        assert_eq!(params.get("tn"), Some(&"resultjson_com".to_string()));
        assert_eq!(params.get("rn"), Some(&"30".to_string()));
        assert_eq!(params.get("on"), Some(&"0".to_string()));
    }

    #[test]
    fn test_build_baidu_url_news_falls_back_to_general() {
        // 测试 News 分类回退到通用搜索(仅包含 wd 参数)
        let engine = create_engine();
        let (url, params) = engine.build_baidu_url("news", 1, BaiduSearchCategory::News);

        assert_eq!(url, "https://www.baidu.com/s");
        assert_eq!(params.get("wd"), Some(&"news".to_string()));
        assert!(!params.contains_key("rn"), "fallback should not set rn");
    }

    #[test]
    fn test_build_baidu_url_empty_query() {
        // 边界情况:空查询字符串仍然构建有效 URL
        let engine = create_engine();
        let (url, params) = engine.build_baidu_url("", 1, BaiduSearchCategory::General);

        assert_eq!(url, "https://www.baidu.com/s");
        assert_eq!(params.get("wd"), Some(&"".to_string()));
    }

    // parse_baidu_response 测试

    #[test]
    fn test_parse_baidu_response_valid_json() {
        // 测试有效 JSON 响应解析出多个结果
        let engine = create_engine();
        let json = r#"{
            "feed": {
                "entry": [
                    {"title": "Result 1", "url": "https://example.com/1", "abs": "Desc 1"},
                    {"title": "Result 2", "url": "https://example.com/2", "abs": "Desc 2"}
                ]
            }
        }"#;

        let results = engine.parse_baidu_response(json).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].title, "Result 1");
        assert_eq!(results[0].url, "https://example.com/1");
        assert_eq!(results[0].description, "Desc 1");
        assert_eq!(results[0].engine, SearchEngineType::Baidu);
        assert_eq!(results[1].title, "Result 2");
    }

    #[test]
    fn test_parse_baidu_response_invalid_json() {
        // 测试无效 JSON 返回 Parse 错误
        let engine = create_engine();
        let result = engine.parse_baidu_response("not a valid json {{{");
        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            SearchError::Parse(msg) => assert!(msg.contains("Failed to parse Baidu JSON")),
            other => panic!("expected SearchError::Parse, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_baidu_response_skips_empty_title_or_url() {
        // 边界情况:空 title 或空 url 的条目应被跳过
        let engine = create_engine();
        let json = r#"{
            "feed": {
                "entry": [
                    {"title": "", "url": "https://example.com/1", "abs": "Desc 1"},
                    {"title": "Result 2", "url": "", "abs": "Desc 2"},
                    {"title": "Valid", "url": "https://example.com/3", "abs": "Desc 3"}
                ]
            }
        }"#;

        let results = engine.parse_baidu_response(json).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "Valid");
        assert_eq!(results[0].url, "https://example.com/3");
    }

    #[test]
    fn test_parse_baidu_response_no_feed_entry() {
        // 边界情况:JSON 不包含 feed/entry 字段时返回空结果
        let engine = create_engine();
        let json = r#"{"other": "data"}"#;
        let results = engine.parse_baidu_response(json).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn test_parse_baidu_response_html_entities_encoded() {
        // 测试 HTML 实体被编码以防止 XSS
        let engine = create_engine();
        let json = r#"{
            "feed": {
                "entry": [
                    {"title": "<script>alert(1)</script>", "url": "https://example.com", "abs": "a & b <c>"}
                ]
            }
        }"#;

        let results = engine.parse_baidu_response(json).unwrap();
        assert_eq!(results.len(), 1);
        // 编码后不应包含原始的 <script> 标签
        assert!(!results[0].title.contains("<script>"));
        assert!(results[0].title.contains("&lt;script&gt;"));
        assert!(!results[0].description.contains("<c>"));
    }

    // parse_search_results 测试

    #[test]
    fn test_parse_search_results_valid_html() {
        // 测试从有效百度 HTML 中解析搜索结果
        let engine = create_engine();
        let html = r#"
        <html><body>
            <div class="c-container">
                <h3><a href="https://example.com/1">First Result</a></h3>
                <div class="c-abstract">First description</div>
            </div>
            <div class="c-container">
                <h3><a href="https://example.com/2">Second Result</a></h3>
                <div class="c-abstract">Second description</div>
            </div>
        </body></html>
        "#;

        let results = engine.parse_search_results(html, "test").unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].title, "First Result");
        assert_eq!(results[0].url, "https://example.com/1");
        assert_eq!(results[0].engine, SearchEngineType::Baidu);
        assert_eq!(results[1].title, "Second Result");
    }

    #[test]
    fn test_parse_search_results_empty_html() {
        // 边界情况:空 HTML 返回空结果
        let engine = create_engine();
        let results = engine.parse_search_results("", "test").unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn test_parse_search_results_no_matching_selectors() {
        // 边界情况:HTML 不包含百度结果选择器时返回空
        let engine = create_engine();
        let html = r#"<html><body><div>no results here</div></body></html>"#;
        let results = engine.parse_search_results(html, "test").unwrap();
        assert!(results.is_empty());
    }

    // SearchEngine trait 方法测试

    #[test]
    fn test_engine_creation() {
        // Verify engine construction and trait accessors
        let engine = create_engine();
        assert_eq!(engine.name(), "Baidu");
        assert_eq!(engine.engine_type(), SearchEngineType::Baidu);
        assert_eq!(engine.health(), EngineHealth::Healthy);
    }

    // search test fallback path

    /// Mutex to serialize tests that mutate process-level environment
    /// variables (std::env::set_var is not thread-safe across tests).
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn make_search_request(query: &str) -> SearchRequest {
        SearchRequest::new(query)
    }

    // ENV_LOCK must be held across .await because engine.search reads
    // BAIDU_TEST_RESULTS during execution; releasing it would let other tests
    // race-modify the env var. Single-threaded tokio runtime => no deadlock risk.
    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn test_search_fallback_returns_hardcoded_results() {
        let _lock = ENV_LOCK.lock().unwrap();
        std::env::set_var("BAIDU_TEST_RESULTS", "true");

        let engine = create_engine();
        let request = make_search_request("rust programming");

        let response = engine.search(&request).await;

        // Clean up env var ASAP to minimize cross-test interference
        std::env::remove_var("BAIDU_TEST_RESULTS");

        let response = response.expect("fallback should return Ok");
        assert_eq!(response.items.len(), 2, "fallback should return 2 items");
        assert_eq!(response.engine, SearchEngineType::Baidu);
        assert_eq!(response.total_results, Some(2));
        assert!(response.items[0].title.contains("rust programming"));
        assert!(response.items[1].title.contains("rust programming"));
        assert_eq!(response.items[0].url, "https://baidu.com/1");
        assert_eq!(response.items[1].url, "https://baidu.com/2");
        assert_eq!(response.items[0].engine, SearchEngineType::Baidu);
        assert_eq!(response.items[1].engine, SearchEngineType::Baidu);
    }

    #[allow(clippy::await_holding_lock)] // ENV_LOCK serializes env var access; see above
    #[tokio::test]
    async fn test_search_fallback_escapes_query_in_title() {
        let _lock = ENV_LOCK.lock().unwrap();
        std::env::set_var("BAIDU_TEST_RESULTS", "true");

        let engine = create_engine();
        // Query with HTML special characters that should be escaped
        let request = make_search_request("<script>alert(1)</script>");

        let response = engine.search(&request).await;

        std::env::remove_var("BAIDU_TEST_RESULTS");

        let response = response.expect("fallback should return Ok");
        // The title should contain the escaped query, not raw HTML
        assert!(response.items[0].title.contains("&lt;script&gt;"));
        assert!(!response.items[0].title.contains("<script>"));
        assert!(response.items[1].title.contains("&lt;script&gt;"));
        assert!(!response.items[1].title.contains("<script>"));
    }

    #[allow(clippy::await_holding_lock)] // ENV_LOCK serializes env var access; see above
    #[tokio::test]
    async fn test_search_fallback_description_and_engine_fields() {
        let _lock = ENV_LOCK.lock().unwrap();
        std::env::set_var("BAIDU_TEST_RESULTS", "true");

        let engine = create_engine();
        let request = make_search_request("fields test");

        let response = engine.search(&request).await;

        std::env::remove_var("BAIDU_TEST_RESULTS");

        let response = response.expect("fallback should return Ok");
        assert_eq!(response.items[0].description, "Test description 1");
        assert_eq!(response.items[1].description, "Test description 2");
        assert_eq!(response.items[0].engine, SearchEngineType::Baidu);
        assert_eq!(response.items[1].engine, SearchEngineType::Baidu);
    }
}