Skip to content

Commit

Permalink
issue a warning instead of logging when elements don’t match word count
Browse files Browse the repository at this point in the history
  • Loading branch information
fcurella committed Jun 26, 2024
1 parent fb8b8a2 commit 39feef7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
9 changes: 4 additions & 5 deletions faker/providers/python/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import math
import string
import sys
Expand All @@ -17,8 +16,6 @@
TypesSpec = Union[List[Type], Tuple[Type, ...]]
TEnum = TypeVar("TEnum", bound=Enum)

logger = logging.getLogger(__name__)


class EmptyEnumException(BaseFakerException):
pass
Expand Down Expand Up @@ -476,8 +473,10 @@ def pydict(
nb_elements = self.randomize_nb_elements(nb_elements, min=1)

if nb_elements > words_list_count:
logger.warning(
f"Number of nb_elements is greater than the number of words in the list. {words_list_count} words will be used."
warnings.warn(
f"Number of nb_elements is greater than the number of words in the list."
f" {words_list_count} words will be used.",
RuntimeWarning,
)
nb_elements = words_list_count

Expand Down
32 changes: 20 additions & 12 deletions tests/providers/test_python.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import decimal
import logging
import sys
import unittest
import warnings

from typing import Iterable, Optional, Union
from typing import Iterable, Optional, Type, Union
from unittest.mock import patch

import pytest
Expand All @@ -14,8 +13,20 @@

@pytest.mark.parametrize("object_type", (None, bool, str, float, int, tuple, set, list, Iterable, dict))
def test_pyobject(
object_type: Optional[Union[bool, str, float, int, tuple, set, list, Iterable, dict]],
):
object_type: Optional[
Union[
Type[bool],
Type[str],
Type[float],
Type[int],
Type[tuple],
Type[set],
Type[list],
Type[Iterable],
Type[dict],
]
],
) -> None:
random_object = Faker().pyobject(object_type=object_type)
if object_type is None:
assert random_object is None
Expand Down Expand Up @@ -319,15 +330,12 @@ def test_pydict_with_invalid_number_of_nb_elements(self):
nb_elements = 10000

words_list_count = len(self.fake.get_words_list())

logger = logging.getLogger("faker.providers.python")

with patch.object(logger, "warning") as mock_warn:
warning_msg = (
f"Number of nb_elements is greater than the number of words in the list."
f" {words_list_count} words will be used."
)
with pytest.warns(RuntimeWarning, match=warning_msg):
result = self.fake.pydict(nb_elements=nb_elements)

mock_warn.assert_called_once_with(
f"Number of nb_elements is greater than the number of words in the list. {words_list_count} words will be used."
)
self.assertEqual(len(result), words_list_count)


Expand Down

0 comments on commit 39feef7

Please sign in to comment.