|
| 1 | +"""A CrawlResult built without links/media must still have their keys. |
| 2 | +
|
| 3 | +Successful crawls fill `links` and `media` from the scraper's result (arun moves |
| 4 | +media's "tables" to CrawlResult.tables). Results built without them -- the |
| 5 | +robots.txt refusal, the "all proxies failed" and exception paths in |
| 6 | +AsyncWebCrawler.arun -- used to default to `{}`, so `result.links["internal"]` |
| 7 | +raised KeyError on exactly the results a batch caller has to handle, and the |
| 8 | +Docker API returned `"links": {}` / `"media": {}` for them. |
| 9 | +""" |
| 10 | + |
| 11 | +from crawl4ai.models import CrawlResult |
| 12 | + |
| 13 | + |
| 14 | +def links_shape(): |
| 15 | + return {"internal": [], "external": []} |
| 16 | + |
| 17 | + |
| 18 | +def media_shape(): |
| 19 | + return {"images": [], "videos": [], "audios": []} |
| 20 | + |
| 21 | + |
| 22 | +def _refused(url="https://example.com/private"): |
| 23 | + # The shape AsyncWebCrawler.arun returns when robots.txt disallows a URL. |
| 24 | + return CrawlResult( |
| 25 | + url=url, |
| 26 | + html="", |
| 27 | + success=False, |
| 28 | + status_code=403, |
| 29 | + error_message="Access denied by robots.txt", |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +def test_result_without_links_or_media_has_the_scraped_shape(): |
| 34 | + result = _refused() |
| 35 | + |
| 36 | + assert result.links == links_shape() |
| 37 | + assert result.media == media_shape() |
| 38 | + |
| 39 | + |
| 40 | +def test_default_is_not_shared_between_results(): |
| 41 | + first, second = _refused(), _refused("https://example.com/other") |
| 42 | + |
| 43 | + assert first.links["internal"] is not second.links["internal"] |
| 44 | + assert first.media["images"] is not second.media["images"] |
| 45 | + |
| 46 | + first.links["internal"].append({"href": "https://example.com/a"}) |
| 47 | + first.media["images"].append({"src": "https://example.com/a.png"}) |
| 48 | + |
| 49 | + assert second.links == links_shape() |
| 50 | + assert second.media == media_shape() |
| 51 | + |
| 52 | + |
| 53 | +def test_serialized_result_keeps_the_keys(): |
| 54 | + dumped = _refused().model_dump() |
| 55 | + |
| 56 | + assert dumped["links"] == links_shape() |
| 57 | + assert dumped["media"] == media_shape() |
| 58 | + |
| 59 | + |
| 60 | +def test_explicit_values_are_kept(): |
| 61 | + links = {"internal": [{"href": "https://example.com/a"}], "external": []} |
| 62 | + result = CrawlResult( |
| 63 | + url="https://example.com/", html="<p></p>", success=True, links=links |
| 64 | + ) |
| 65 | + |
| 66 | + assert result.links == links |
0 commit comments