-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add
.optional
proxy that may or may not return a fake value (#1867)
* PoC: a .optional proxy that may or may not return a fake value * add type annotations for the OptionalProxy * actually honour the probability :-) * blacken * add docstring to `OptionalProxy` class --------- Co-authored-by: Flavio Curella <89607+fcurella@users.noreply.github.com>
- Loading branch information
Showing
2 changed files
with
86 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import pytest | ||
|
||
from faker import Faker | ||
|
||
|
||
class TestOptionalClass: | ||
def test_optional(self) -> None: | ||
fake = Faker() | ||
|
||
assert {fake.optional.boolean() for _ in range(10)} == {True, False, None} | ||
|
||
def test_optional_probability(self) -> None: | ||
"""The probability is configurable.""" | ||
fake = Faker() | ||
|
||
fake.optional.name(prob=0.1) | ||
|
||
def test_optional_arguments(self) -> None: | ||
"""Other arguments are passed through to the function.""" | ||
fake = Faker() | ||
|
||
fake.optional.pyint(1, 2, prob=0.4) | ||
|
||
def test_optional_valid_range(self) -> None: | ||
"""Only probabilities in the range (0, 1].""" | ||
fake = Faker() | ||
|
||
with pytest.raises(ValueError, match=""): | ||
fake.optional.name(prob=0) | ||
|
||
with pytest.raises(ValueError, match=""): | ||
fake.optional.name(prob=1.1) | ||
|
||
with pytest.raises(ValueError, match=""): | ||
fake.optional.name(prob=-3) | ||
|
||
def test_functions_only(self): | ||
"""Accessing non-functions through the `.optional` attribute | ||
will throw a TypeError.""" | ||
|
||
fake = Faker() | ||
|
||
with pytest.raises(TypeError, match="Accessing non-functions through .optional is not supported."): | ||
fake.optional.locales |