|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from crawlee._utils.ids import MAX_ID_LENGTH, validate_id |
| 8 | +from crawlee.crawlers._adaptive_playwright._rendering_type_predictor import DefaultRenderingTypePredictor |
| 9 | +from crawlee.sessions import SessionPool |
| 10 | +from crawlee.statistics import Statistics |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from collections.abc import Callable |
| 14 | + |
| 15 | + |
| 16 | +@pytest.mark.parametrize( |
| 17 | + 'value', |
| 18 | + [ |
| 19 | + pytest.param('my-id', id='hyphen'), |
| 20 | + pytest.param("a.b_c!(1)'", id='all allowed special characters'), |
| 21 | + pytest.param('x' * MAX_ID_LENGTH, id='max length'), |
| 22 | + ], |
| 23 | +) |
| 24 | +def test_validate_id_accepts_valid_id(value: str) -> None: |
| 25 | + """An ID that can be part of a key-value store key passes.""" |
| 26 | + validate_id(value, 'Owner') |
| 27 | + |
| 28 | + |
| 29 | +@pytest.mark.parametrize( |
| 30 | + 'value', |
| 31 | + [ |
| 32 | + pytest.param('a/b', id='slash'), |
| 33 | + pytest.param('', id='empty'), |
| 34 | + pytest.param('x' * (MAX_ID_LENGTH + 1), id='too long'), |
| 35 | + ], |
| 36 | +) |
| 37 | +def test_validate_id_rejects_invalid_id(value: str) -> None: |
| 38 | + """An ID that can't be part of a key-value store key raises `ValueError` naming the owner.""" |
| 39 | + with pytest.raises(ValueError, match='The `id` of `Owner` must'): |
| 40 | + validate_id(value, 'Owner') |
| 41 | + |
| 42 | + |
| 43 | +def test_validate_id_rejects_non_string() -> None: |
| 44 | + """An ID that isn't a string raises `TypeError` naming the owner and the type.""" |
| 45 | + with pytest.raises(TypeError, match='The `id` of `Owner` must be a string, got int'): |
| 46 | + validate_id(5, 'Owner') |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.parametrize( |
| 50 | + 'create_component', |
| 51 | + [ |
| 52 | + pytest.param(lambda id: SessionPool(id=id), id='session pool'), |
| 53 | + pytest.param(lambda id: Statistics.with_default_state(id=id), id='statistics'), |
| 54 | + pytest.param(lambda id: DefaultRenderingTypePredictor(id=id), id='rendering type predictor'), |
| 55 | + ], |
| 56 | +) |
| 57 | +def test_components_reject_invalid_id(create_component: Callable[[str], object]) -> None: |
| 58 | + """The components that use their ID in a key-value store key reject an invalid ID.""" |
| 59 | + with pytest.raises(ValueError, match='must be at most'): |
| 60 | + create_component('a/b') |
| 61 | + |
| 62 | + |
| 63 | +def test_longest_key_of_max_length_id_fits_key_limit() -> None: |
| 64 | + """The longest key built from an ID of the maximum length is a valid 256-character key.""" |
| 65 | + predictor = DefaultRenderingTypePredictor(id='x' * MAX_ID_LENGTH) |
| 66 | + assert len(predictor._state._persist_state_key) == 256 |
0 commit comments