"""Test dataloader util.""" from typing import Any, Dict, List from uuid import UUID import pytest from participant.utils.dataloader import format_for_dataloader @pytest.mark.parametrize( 'items, keys, expected, description', [ ( [], [], [], 'Empty still populates', ), ( [], [123, 456], [None, None], 'Empty items populates', ), ( [{'participant_id': 123}], [123, 456], [{'participant_id': 123}, None], 'Empty items populates', ), ( [{'participant_id': 789}], [123, 456], [None, None], 'Disregards irrelevant items', ), ( [{'participant_id': 456}, {'participant_id': 123}], [123, 456], [{'participant_id': 123}, {'participant_id': 456}], 'Orders items based on keys', ), ( [{'participant_id': 123}, {'participant_id': 123, 'something': 'else'}], [123, 456], [{'participant_id': 123, 'something': 'else'}, None], 'When duplicate key is present in list, uses the latter item', ), ( [{'participant_id': 123}, {'participant_id': 456}], [123, 456], [{'participant_id': 123}, {'participant_id': 456}], 'Returns items matching keys', ), ( [ {'participant_id': UUID('053a1a75-acc5-4cd8-9206-a194335d2afa')}, {'participant_id': UUID('bad45218-68d8-42b6-b4ee-730ef9e16309')}, ], [ '053a1a75-acc5-4cd8-9206-a194335d2afa', 'bad45218-68d8-42b6-b4ee-730ef9e16309', ], [ {'participant_id': UUID('053a1a75-acc5-4cd8-9206-a194335d2afa')}, {'participant_id': UUID('bad45218-68d8-42b6-b4ee-730ef9e16309')}, ], 'Item keys are converted to strings', ), ( [ {'participant_id': UUID('053a1a75-acc5-4cd8-9206-a194335d2afa')}, {'participant_id': UUID('bad45218-68d8-42b6-b4ee-730ef9e16309')}, ], [ UUID('053a1a75-acc5-4cd8-9206-a194335d2afa'), UUID('bad45218-68d8-42b6-b4ee-730ef9e16309'), ], [ {'participant_id': UUID('053a1a75-acc5-4cd8-9206-a194335d2afa')}, {'participant_id': UUID('bad45218-68d8-42b6-b4ee-730ef9e16309')}, ], 'Items and keys are converted to strings', ), ], ) def test_format_for_dataloader( items: List[Dict[str, Any]], keys: List[Any], expected: List[Any], description: str, ) -> None: """Test format_for_dataloader.""" result = format_for_dataloader(items, keys, 'participant_id') assert result == expected, description def test_format_for_dataloader_exceptions(): """Test format for dataloader raises when lookup key does not exist.""" with pytest.raises(Exception): format_for_dataloader( [{'participant_id': 123}], [123], 'lookup_key_does_not_exist', )