Skip to content

Commit

Permalink
Add pyobject generator
Browse files Browse the repository at this point in the history
  • Loading branch information
dariocurr committed Mar 20, 2023
1 parent d2ebcce commit 113d012
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
34 changes: 34 additions & 0 deletions faker/providers/python/__init__.py
Expand Up @@ -55,6 +55,40 @@ def _check_signature(self, value_types: Optional[TypesSpec], allowed_types: Opti
allowed_types = ()
return tuple(value_types) + tuple(allowed_types)

def pyobject(
self,
object_type: Optional[Type[Union[bool, str, float, int, tuple, set, list, Iterable, dict]]] = None,
) -> Optional[Union[bool, str, float, int, tuple, set, list, Iterable, dict]]:
"""
Generates a random object passing the type desired.
:object_type: the type of the object to generate.
:return: the random object generated.
:raises ValueError: if the object type passed is not supported
"""
if object_type is None:
return None
elif object_type == bool:
return self.pybool()
elif object_type == str:
return self.pystr()
elif object_type == float:
return self.pyfloat()
elif object_type == int:
return self.pyint()
elif object_type == tuple:
return self.pytuple()
elif object_type == set:
return self.pyset()
elif object_type == list:
return self.pylist()
elif object_type == Iterable:
return self.pyiterable()
elif object_type == dict:
return self.pydict()
else:
raise ValueError("Object type `{object_type}` is not supported by `pyobject` function")

def pybool(self, truth_probability: int = 50) -> bool:
"""
Generates a random boolean, optionally biased towards `True` or `False`.
Expand Down
18 changes: 18 additions & 0 deletions tests/providers/test_python.py
Expand Up @@ -3,13 +3,31 @@
import unittest
import warnings

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

import pytest

from faker import Faker


@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]],
):
random_object = Faker().pyobject(object_type=object_type)
if object_type is None:
assert random_object is None
else:
assert isinstance(random_object, object_type)


@pytest.mark.parametrize("object_type", (object, type, callable))
def test_pyobject_with_unknown_object_type(object_type):
with pytest.raises(ValueError):
assert Faker().pyobject(object_type=object_type)


@pytest.mark.parametrize(
"mock_random_number_source, right_digits, expected_decimal_part",
(
Expand Down

0 comments on commit 113d012

Please sign in to comment.