instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
jd__tenacity-201
diff --git a/tenacity/_asyncio.py b/tenacity/_asyncio.py index f93bf0f..035699d 100644 --- a/tenacity/_asyncio.py +++ b/tenacity/_asyncio.py @@ -38,6 +38,12 @@ if asyncio: super(AsyncRetrying, self).__init__(**kwargs) self.sleep = sleep + def wraps(self, fn): + fn = super().wraps(fn) + # Ensure wrapper is recognized as a coroutine function. + fn._is_coroutine = asyncio.coroutines._is_coroutine + return fn + @asyncio.coroutine def call(self, fn, *args, **kwargs): self.begin(fn)
jd/tenacity
dcabb396a4b851da44d2fb6fed84d6540cc2d93c
diff --git a/tenacity/tests/test_asyncio.py b/tenacity/tests/test_asyncio.py index 6937511..8a8d3ce 100644 --- a/tenacity/tests/test_asyncio.py +++ b/tenacity/tests/test_asyncio.py @@ -36,9 +36,8 @@ def asynctest(callable_): @retry [email protected] -def _retryable_coroutine(thing): - yield from asyncio.sleep(0.00001) +async def _retryable_coroutine(thing): + await asyncio.sleep(0.00001) return thing.go()
Asyncio: iscoroutinefunction does not work with tenacity When decorating an `async` function with `@retry`, `asyncio.iscoroutinefunction(f)` unexpectedly returns `False`, because the wrapping function, in fact, is no coroutine. This is a problem in some libraries that are using this way of determining if they are handling an async function or not (in my case: trafaret).
0.0
dcabb396a4b851da44d2fb6fed84d6540cc2d93c
[ "tenacity/tests/test_asyncio.py::TestAsync::test_retry" ]
[ "tenacity/tests/test_asyncio.py::TestAsync::test_attempt_number_is_correct_for_interleaved_coroutines", "tenacity/tests/test_asyncio.py::TestAsync::test_repr", "tenacity/tests/test_asyncio.py::TestAsync::test_stop_after_attempt" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-11-05 13:34:40+00:00
apache-2.0
3,235
jd__tenacity-236
diff --git a/releasenotes/notes/allow-mocking-of-nap-sleep-6679c50e702446f1.yaml b/releasenotes/notes/allow-mocking-of-nap-sleep-6679c50e702446f1.yaml new file mode 100644 index 0000000..0a996e4 --- /dev/null +++ b/releasenotes/notes/allow-mocking-of-nap-sleep-6679c50e702446f1.yaml @@ -0,0 +1,3 @@ +--- +other: + - Unit tests can now mock ``nap.sleep()`` for testing in all tenacity usage styles \ No newline at end of file diff --git a/tenacity/nap.py b/tenacity/nap.py index e5bd8dc..83ff839 100644 --- a/tenacity/nap.py +++ b/tenacity/nap.py @@ -18,8 +18,14 @@ import time -#: Default sleep strategy. -sleep = time.sleep + +def sleep(seconds): + """ + Sleep strategy that delays execution for a given number of seconds. + + This is the default strategy, and may be mocked out for unit testing. + """ + time.sleep(seconds) class sleep_using_event(object):
jd/tenacity
d66af82a70dd9af24a7953c6ae5f02d8f198d10f
diff --git a/tenacity/tests/test_tenacity.py b/tenacity/tests/test_tenacity.py index 673541c..223b19a 100644 --- a/tenacity/tests/test_tenacity.py +++ b/tenacity/tests/test_tenacity.py @@ -1565,5 +1565,50 @@ def reports_deprecation_warning(): warnings.filters = oldfilters +class TestMockingSleep(): + RETRY_ARGS = dict( + wait=tenacity.wait_fixed(0.1), + stop=tenacity.stop_after_attempt(5), + ) + + def _fail(self): + raise NotImplementedError() + + @retry(**RETRY_ARGS) + def _decorated_fail(self): + self._fail() + + @pytest.fixture() + def mock_sleep(self, monkeypatch): + class MockSleep(object): + call_count = 0 + + def __call__(self, seconds): + self.call_count += 1 + + sleep = MockSleep() + monkeypatch.setattr(tenacity.nap.time, "sleep", sleep) + yield sleep + + def test_call(self, mock_sleep): + retrying = Retrying(**self.RETRY_ARGS) + with pytest.raises(RetryError): + retrying.call(self._fail) + assert mock_sleep.call_count == 4 + + def test_decorated(self, mock_sleep): + with pytest.raises(RetryError): + self._decorated_fail() + assert mock_sleep.call_count == 4 + + def test_decorated_retry_with(self, mock_sleep): + fail_faster = self._decorated_fail.retry_with( + stop=tenacity.stop_after_attempt(2), + ) + with pytest.raises(RetryError): + fail_faster() + assert mock_sleep.call_count == 1 + + if __name__ == '__main__': unittest.main()
Cannot easily mock out sleep function in order to simulate time in tests Given the level of flexibility of this library, and a slightly elaborate context which I am using it in, it is desirable to be able to write an integration test where the concepts of 'time' (i.e. `time.monotonic`) and 'sleep' (i.e. `tenacity.nap.sleep`) are mocked out so that we can simulate in full fidelity how a retry scenario plays out, without having to actually sleep. Using the [testfixtures](https://github.com/Simplistix/testfixtures) library and `mock.patch` I'm mocking out 'time' with an object that always returns the same 'virtual' time, and 'sleep' with a function that advances this 'virtual' time. This approach works pretty well, save for one complication... Since the signature of `BaseRetrying.__init__()` defaults the `sleep` argument to `tenacity.nap.sleep` this default is bound at import time, making it hard to mock out the sleep function after the fact. Options I can think of: 1. Reach in to the method signature and mock out the default value - seems a bit messy. 2. Pass in a sleep function in the code under test, then mock this out in the test - I don't like this because it involves modifying production code simply for the sake of the test, and also makes this mocking strategy less portable if I want to use it in other tests (because now I need to mock out sleep at my callsite, rather than inside tenacity). 3. Make a change to the signature of `BaseRetrying.__init__()` to default `sleep` to `None`, and then default this to `nap.sleep` inside the method: `self.sleep = sleep or nap.sleep`. Option 3 seems the neatest, because now I can just mock out `tenacity.nap.sleep` which is the most intuitive approach, but it does involve a change to the library which is why I wanted to solicit input first before preparing a PR. Thoughts?
0.0
d66af82a70dd9af24a7953c6ae5f02d8f198d10f
[ "tenacity/tests/test_tenacity.py::TestMockingSleep::test_call", "tenacity/tests/test_tenacity.py::TestMockingSleep::test_decorated", "tenacity/tests/test_tenacity.py::TestMockingSleep::test_decorated_retry_with" ]
[ "tenacity/tests/test_tenacity.py::TestBase::test_repr", "tenacity/tests/test_tenacity.py::TestStopConditions::test_legacy_explicit_stop_type", "tenacity/tests/test_tenacity.py::TestStopConditions::test_never_stop", "tenacity/tests/test_tenacity.py::TestStopConditions::test_retry_child_class_with_override_backward_compat", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_after_attempt", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_after_delay", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_all", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_and", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_any", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_backward_compat", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_func_with_retry_state", "tenacity/tests/test_tenacity.py::TestStopConditions::test_stop_or", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential_with_max_wait", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential_with_max_wait_and_multiplier", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait_and_max_wait", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait_and_multiplier", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_fixed_sleep", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_incrementing_sleep", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_legacy_explicit_wait_type", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_no_sleep", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_random_sleep", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_random_sleep_without_min", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_arbitrary_sum", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_backward_compat", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_backward_compat_with_result", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_chain", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_chain_multiple_invocations", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_class_backward_compatibility", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_combine", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_double_sum", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_func", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_random_exponential", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_random_exponential_statistically", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_retry_state_attributes", "tenacity/tests/test_tenacity.py::TestWaitConditions::test_wait_triple_sum", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_all", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_and", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_any", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_if_exception_message_negative_no_inputs", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_if_exception_message_negative_too_many_inputs", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_if_not_result", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_if_result", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_or", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_try_again", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_try_again_forever", "tenacity/tests/test_tenacity.py::TestRetryConditions::test_retry_try_again_forever_reraise", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_defaults", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_child_class_with_override_backward_compat", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_function_object", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_message", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_message_match", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_of_type", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message_delay", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message_match", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_attempt_number", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_no_type", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_wrong_exception", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_retry_with", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_with_stop_on_exception", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_with_stop_on_return_value", "tenacity/tests/test_tenacity.py::TestDecoratorWrapper::test_with_wait", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_after_attempts", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_attempts", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_backward_compat", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_backward_compat_method", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_raises", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_raises_deprecated_call", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_raises_with_exc_info", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_returns", "tenacity/tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_returns_with_exc_info", "tenacity/tests/test_tenacity.py::TestReraiseExceptions::test_reraise_by_default", "tenacity/tests/test_tenacity.py::TestReraiseExceptions::test_reraise_from_retry_error", "tenacity/tests/test_tenacity.py::TestReraiseExceptions::test_reraise_no_exception", "tenacity/tests/test_tenacity.py::TestReraiseExceptions::test_reraise_timeout_from_retry_error", "tenacity/tests/test_tenacity.py::TestStatistics::test_stats", "tenacity/tests/test_tenacity.py::TestStatistics::test_stats_failing", "tenacity/tests/test_tenacity.py::TestRetryErrorCallback::test_retry_error_callback", "tenacity/tests/test_tenacity.py::TestRetryErrorCallback::test_retry_error_callback_backward_compat", "tenacity/tests/test_tenacity.py::TestContextManager::test_context_manager_on_error", "tenacity/tests/test_tenacity.py::TestContextManager::test_context_manager_reraise", "tenacity/tests/test_tenacity.py::TestContextManager::test_context_manager_retry_error", "tenacity/tests/test_tenacity.py::TestContextManager::test_context_manager_retry_one", "tenacity/tests/test_tenacity.py::TestInvokeAsCallable::test_retry_one", "tenacity/tests/test_tenacity.py::TestInvokeAsCallable::test_on_error", "tenacity/tests/test_tenacity.py::TestInvokeAsCallable::test_retry_error", "tenacity/tests/test_tenacity.py::TestInvokeAsCallable::test_reraise", "tenacity/tests/test_tenacity.py::TestInvokeViaLegacyCallMethod::test_retry_one", "tenacity/tests/test_tenacity.py::TestInvokeViaLegacyCallMethod::test_on_error", "tenacity/tests/test_tenacity.py::TestInvokeViaLegacyCallMethod::test_retry_error", "tenacity/tests/test_tenacity.py::TestInvokeViaLegacyCallMethod::test_reraise", "tenacity/tests/test_tenacity.py::TestRetryException::test_retry_error_is_pickleable" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-06-07 15:53:19+00:00
apache-2.0
3,236
jd__tenacity-342
diff --git a/releasenotes/notes/support-timedelta-wait-unit-type-5ba1e9fc0fe45523.yaml b/releasenotes/notes/support-timedelta-wait-unit-type-5ba1e9fc0fe45523.yaml new file mode 100644 index 0000000..bc7e62d --- /dev/null +++ b/releasenotes/notes/support-timedelta-wait-unit-type-5ba1e9fc0fe45523.yaml @@ -0,0 +1,3 @@ +--- +features: + - Add ``datetime.timedelta`` as accepted wait unit type. diff --git a/tenacity/wait.py b/tenacity/wait.py index 289705c..1d87672 100644 --- a/tenacity/wait.py +++ b/tenacity/wait.py @@ -17,12 +17,19 @@ import abc import random import typing +from datetime import timedelta from tenacity import _utils if typing.TYPE_CHECKING: from tenacity import RetryCallState +wait_unit_type = typing.Union[int, float, timedelta] + + +def to_seconds(wait_unit: wait_unit_type) -> float: + return float(wait_unit.total_seconds() if isinstance(wait_unit, timedelta) else wait_unit) + class wait_base(abc.ABC): """Abstract base class for wait strategies.""" @@ -44,8 +51,8 @@ class wait_base(abc.ABC): class wait_fixed(wait_base): """Wait strategy that waits a fixed amount of time between each retry.""" - def __init__(self, wait: float) -> None: - self.wait_fixed = wait + def __init__(self, wait: wait_unit_type) -> None: + self.wait_fixed = to_seconds(wait) def __call__(self, retry_state: "RetryCallState") -> float: return self.wait_fixed @@ -61,9 +68,9 @@ class wait_none(wait_fixed): class wait_random(wait_base): """Wait strategy that waits a random amount of time between min/max.""" - def __init__(self, min: typing.Union[int, float] = 0, max: typing.Union[int, float] = 1) -> None: # noqa - self.wait_random_min = min - self.wait_random_max = max + def __init__(self, min: wait_unit_type = 0, max: wait_unit_type = 1) -> None: # noqa + self.wait_random_min = to_seconds(min) + self.wait_random_max = to_seconds(max) def __call__(self, retry_state: "RetryCallState") -> float: return self.wait_random_min + (random.random() * (self.wait_random_max - self.wait_random_min)) @@ -113,13 +120,13 @@ class wait_incrementing(wait_base): def __init__( self, - start: typing.Union[int, float] = 0, - increment: typing.Union[int, float] = 100, - max: typing.Union[int, float] = _utils.MAX_WAIT, # noqa + start: wait_unit_type = 0, + increment: wait_unit_type = 100, + max: wait_unit_type = _utils.MAX_WAIT, # noqa ) -> None: - self.start = start - self.increment = increment - self.max = max + self.start = to_seconds(start) + self.increment = to_seconds(increment) + self.max = to_seconds(max) def __call__(self, retry_state: "RetryCallState") -> float: result = self.start + (self.increment * (retry_state.attempt_number - 1)) @@ -142,13 +149,13 @@ class wait_exponential(wait_base): def __init__( self, multiplier: typing.Union[int, float] = 1, - max: typing.Union[int, float] = _utils.MAX_WAIT, # noqa + max: wait_unit_type = _utils.MAX_WAIT, # noqa exp_base: typing.Union[int, float] = 2, - min: typing.Union[int, float] = 0, # noqa + min: wait_unit_type = 0, # noqa ) -> None: self.multiplier = multiplier - self.min = min - self.max = max + self.min = to_seconds(min) + self.max = to_seconds(max) self.exp_base = exp_base def __call__(self, retry_state: "RetryCallState") -> float:
jd/tenacity
f6465c082fc153ec389b281aabc323f3c2d0ced9
diff --git a/tests/test_tenacity.py b/tests/test_tenacity.py index d9a4858..b6f6bbb 100644 --- a/tests/test_tenacity.py +++ b/tests/test_tenacity.py @@ -13,6 +13,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import datetime import logging import re import sys @@ -29,7 +30,6 @@ import pytest import tenacity from tenacity import RetryCallState, RetryError, Retrying, retry - _unset = object() @@ -180,28 +180,34 @@ class TestWaitConditions(unittest.TestCase): self.assertEqual(0, r.wait(make_retry_state(18, 9879))) def test_fixed_sleep(self): - r = Retrying(wait=tenacity.wait_fixed(1)) - self.assertEqual(1, r.wait(make_retry_state(12, 6546))) + for wait in (1, datetime.timedelta(seconds=1)): + with self.subTest(): + r = Retrying(wait=tenacity.wait_fixed(wait)) + self.assertEqual(1, r.wait(make_retry_state(12, 6546))) def test_incrementing_sleep(self): - r = Retrying(wait=tenacity.wait_incrementing(start=500, increment=100)) - self.assertEqual(500, r.wait(make_retry_state(1, 6546))) - self.assertEqual(600, r.wait(make_retry_state(2, 6546))) - self.assertEqual(700, r.wait(make_retry_state(3, 6546))) + for start, increment in ((500, 100), (datetime.timedelta(seconds=500), datetime.timedelta(seconds=100))): + with self.subTest(): + r = Retrying(wait=tenacity.wait_incrementing(start=start, increment=increment)) + self.assertEqual(500, r.wait(make_retry_state(1, 6546))) + self.assertEqual(600, r.wait(make_retry_state(2, 6546))) + self.assertEqual(700, r.wait(make_retry_state(3, 6546))) def test_random_sleep(self): - r = Retrying(wait=tenacity.wait_random(min=1, max=20)) - times = set() - for x in range(1000): - times.add(r.wait(make_retry_state(1, 6546))) - - # this is kind of non-deterministic... - self.assertTrue(len(times) > 1) - for t in times: - self.assertTrue(t >= 1) - self.assertTrue(t < 20) - - def test_random_sleep_without_min(self): + for min_, max_ in ((1, 20), (datetime.timedelta(seconds=1), datetime.timedelta(seconds=20))): + with self.subTest(): + r = Retrying(wait=tenacity.wait_random(min=min_, max=max_)) + times = set() + for _ in range(1000): + times.add(r.wait(make_retry_state(1, 6546))) + + # this is kind of non-deterministic... + self.assertTrue(len(times) > 1) + for t in times: + self.assertTrue(t >= 1) + self.assertTrue(t < 20) + + def test_random_sleep_withoutmin_(self): r = Retrying(wait=tenacity.wait_random(max=2)) times = set() times.add(r.wait(make_retry_state(1, 6546))) @@ -274,18 +280,20 @@ class TestWaitConditions(unittest.TestCase): self.assertEqual(r.wait(make_retry_state(8, 0)), 256) self.assertEqual(r.wait(make_retry_state(20, 0)), 1048576) - def test_exponential_with_min_wait_and_max_wait(self): - r = Retrying(wait=tenacity.wait_exponential(min=10, max=100)) - self.assertEqual(r.wait(make_retry_state(1, 0)), 10) - self.assertEqual(r.wait(make_retry_state(2, 0)), 10) - self.assertEqual(r.wait(make_retry_state(3, 0)), 10) - self.assertEqual(r.wait(make_retry_state(4, 0)), 10) - self.assertEqual(r.wait(make_retry_state(5, 0)), 16) - self.assertEqual(r.wait(make_retry_state(6, 0)), 32) - self.assertEqual(r.wait(make_retry_state(7, 0)), 64) - self.assertEqual(r.wait(make_retry_state(8, 0)), 100) - self.assertEqual(r.wait(make_retry_state(9, 0)), 100) - self.assertEqual(r.wait(make_retry_state(20, 0)), 100) + def test_exponential_with_min_wait_andmax__wait(self): + for min_, max_ in ((10, 100), (datetime.timedelta(seconds=10), datetime.timedelta(seconds=100))): + with self.subTest(): + r = Retrying(wait=tenacity.wait_exponential(min=min_, max=max_)) + self.assertEqual(r.wait(make_retry_state(1, 0)), 10) + self.assertEqual(r.wait(make_retry_state(2, 0)), 10) + self.assertEqual(r.wait(make_retry_state(3, 0)), 10) + self.assertEqual(r.wait(make_retry_state(4, 0)), 10) + self.assertEqual(r.wait(make_retry_state(5, 0)), 16) + self.assertEqual(r.wait(make_retry_state(6, 0)), 32) + self.assertEqual(r.wait(make_retry_state(7, 0)), 64) + self.assertEqual(r.wait(make_retry_state(8, 0)), 100) + self.assertEqual(r.wait(make_retry_state(9, 0)), 100) + self.assertEqual(r.wait(make_retry_state(20, 0)), 100) def test_legacy_explicit_wait_type(self): Retrying(wait="exponential_sleep") @@ -335,7 +343,7 @@ class TestWaitConditions(unittest.TestCase): ) ) # Test it a few time since it's random - for i in range(1000): + for _ in range(1000): w = r.wait(make_retry_state(1, 5)) self.assertLess(w, 9) self.assertGreaterEqual(w, 6)
Support timedelta as a valid type for `wait` classes Currently, the `wait`ing classes only take `int` or `float` as their wait unit types where they are representing seconds. It would make for a better, more readable code if I could simply pass in a `datetime.timedelta` instead and thus also avoid passing in `wait=60*5` for 5 minutes and instead could `wait=timedelta(minutes=5)`
0.0
f6465c082fc153ec389b281aabc323f3c2d0ced9
[ "tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait_andmax__wait", "tests/test_tenacity.py::TestWaitConditions::test_fixed_sleep", "tests/test_tenacity.py::TestWaitConditions::test_incrementing_sleep", "tests/test_tenacity.py::TestWaitConditions::test_random_sleep" ]
[ "tests/test_tenacity.py::TestBase::test_callstate_repr", "tests/test_tenacity.py::TestBase::test_retrying_repr", "tests/test_tenacity.py::TestStopConditions::test_legacy_explicit_stop_type", "tests/test_tenacity.py::TestStopConditions::test_never_stop", "tests/test_tenacity.py::TestStopConditions::test_stop_after_attempt", "tests/test_tenacity.py::TestStopConditions::test_stop_after_delay", "tests/test_tenacity.py::TestStopConditions::test_stop_all", "tests/test_tenacity.py::TestStopConditions::test_stop_and", "tests/test_tenacity.py::TestStopConditions::test_stop_any", "tests/test_tenacity.py::TestStopConditions::test_stop_func_with_retry_state", "tests/test_tenacity.py::TestStopConditions::test_stop_or", "tests/test_tenacity.py::TestWaitConditions::test_exponential", "tests/test_tenacity.py::TestWaitConditions::test_exponential_with_max_wait", "tests/test_tenacity.py::TestWaitConditions::test_exponential_with_max_wait_and_multiplier", "tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait", "tests/test_tenacity.py::TestWaitConditions::test_exponential_with_min_wait_and_multiplier", "tests/test_tenacity.py::TestWaitConditions::test_legacy_explicit_wait_type", "tests/test_tenacity.py::TestWaitConditions::test_no_sleep", "tests/test_tenacity.py::TestWaitConditions::test_random_sleep_withoutmin_", "tests/test_tenacity.py::TestWaitConditions::test_wait_arbitrary_sum", "tests/test_tenacity.py::TestWaitConditions::test_wait_chain", "tests/test_tenacity.py::TestWaitConditions::test_wait_chain_multiple_invocations", "tests/test_tenacity.py::TestWaitConditions::test_wait_combine", "tests/test_tenacity.py::TestWaitConditions::test_wait_double_sum", "tests/test_tenacity.py::TestWaitConditions::test_wait_exponential_jitter", "tests/test_tenacity.py::TestWaitConditions::test_wait_func", "tests/test_tenacity.py::TestWaitConditions::test_wait_random_exponential", "tests/test_tenacity.py::TestWaitConditions::test_wait_random_exponential_statistically", "tests/test_tenacity.py::TestWaitConditions::test_wait_retry_state_attributes", "tests/test_tenacity.py::TestWaitConditions::test_wait_triple_sum", "tests/test_tenacity.py::TestRetryConditions::test_retry_all", "tests/test_tenacity.py::TestRetryConditions::test_retry_and", "tests/test_tenacity.py::TestRetryConditions::test_retry_any", "tests/test_tenacity.py::TestRetryConditions::test_retry_if_exception_message_negative_no_inputs", "tests/test_tenacity.py::TestRetryConditions::test_retry_if_exception_message_negative_too_many_inputs", "tests/test_tenacity.py::TestRetryConditions::test_retry_if_not_result", "tests/test_tenacity.py::TestRetryConditions::test_retry_if_result", "tests/test_tenacity.py::TestRetryConditions::test_retry_or", "tests/test_tenacity.py::TestRetryConditions::test_retry_try_again", "tests/test_tenacity.py::TestRetryConditions::test_retry_try_again_forever", "tests/test_tenacity.py::TestRetryConditions::test_retry_try_again_forever_reraise", "tests/test_tenacity.py::TestDecoratorWrapper::test_defaults", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_except_exception_of_type", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_function_object", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_message", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_message_match", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_exception_of_type", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message_delay", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_if_not_exception_message_match", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_attempt_number", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_no_type", "tests/test_tenacity.py::TestDecoratorWrapper::test_retry_until_exception_of_type_wrong_exception", "tests/test_tenacity.py::TestDecoratorWrapper::test_with_stop_on_exception", "tests/test_tenacity.py::TestDecoratorWrapper::test_with_stop_on_return_value", "tests/test_tenacity.py::TestDecoratorWrapper::test_with_wait", "tests/test_tenacity.py::TestRetryWith::test_redefine_wait", "tests/test_tenacity.py::TestRetryWith::test_redefine_stop", "tests/test_tenacity.py::TestRetryWith::test_retry_error_cls_should_be_preserved", "tests/test_tenacity.py::TestRetryWith::test_retry_error_callback_should_be_preserved", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_after_attempts", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_attempts", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_raises", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_raises_with_exc_info", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_returns", "tests/test_tenacity.py::TestBeforeAfterAttempts::test_before_sleep_log_returns_with_exc_info", "tests/test_tenacity.py::TestReraiseExceptions::test_reraise_by_default", "tests/test_tenacity.py::TestReraiseExceptions::test_reraise_from_retry_error", "tests/test_tenacity.py::TestReraiseExceptions::test_reraise_no_exception", "tests/test_tenacity.py::TestReraiseExceptions::test_reraise_timeout_from_retry_error", "tests/test_tenacity.py::TestStatistics::test_stats", "tests/test_tenacity.py::TestStatistics::test_stats_failing", "tests/test_tenacity.py::TestRetryErrorCallback::test_retry_error_callback", "tests/test_tenacity.py::TestContextManager::test_context_manager_on_error", "tests/test_tenacity.py::TestContextManager::test_context_manager_reraise", "tests/test_tenacity.py::TestContextManager::test_context_manager_retry_error", "tests/test_tenacity.py::TestContextManager::test_context_manager_retry_one", "tests/test_tenacity.py::TestInvokeAsCallable::test_retry_one", "tests/test_tenacity.py::TestInvokeAsCallable::test_on_error", "tests/test_tenacity.py::TestInvokeAsCallable::test_retry_error", "tests/test_tenacity.py::TestInvokeAsCallable::test_reraise", "tests/test_tenacity.py::TestRetryException::test_retry_error_is_pickleable", "tests/test_tenacity.py::TestMockingSleep::test_decorated", "tests/test_tenacity.py::TestMockingSleep::test_decorated_retry_with" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-24 15:20:38+00:00
apache-2.0
3,237
jdkandersson__OpenAlchemy-108
diff --git a/CHANGELOG.md b/CHANGELOG.md index 311b4b60..baabd64f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Add support for remote references to a file at a URL. - Add support for default values. +- Add check for whether the value of an extension property is null. ## Version 0.14.0 - 2020-02-21 diff --git a/open_alchemy/helpers/get_ext_prop/__init__.py b/open_alchemy/helpers/get_ext_prop/__init__.py index 3b694993..d254a3c3 100644 --- a/open_alchemy/helpers/get_ext_prop/__init__.py +++ b/open_alchemy/helpers/get_ext_prop/__init__.py @@ -45,9 +45,16 @@ def get_ext_prop( The value of the property or the default value if it does not exist. """ + # Check for presence of name + if name not in source: + return default + + # Retrieve value value = source.get(name) if value is None: - return default + raise exceptions.MalformedExtensionPropertyError( + f"The value of the {name} extension property cannot be null." + ) schema = _SCHEMAS.get(name) try:
jdkandersson/OpenAlchemy
123cc73aecfe79cd6bc46d829d388917c9df9e43
diff --git a/tests/open_alchemy/helpers/test_get_ext_prop.py b/tests/open_alchemy/helpers/test_get_ext_prop.py index 6f78bf2d..c781c417 100644 --- a/tests/open_alchemy/helpers/test_get_ext_prop.py +++ b/tests/open_alchemy/helpers/test_get_ext_prop.py @@ -44,6 +44,7 @@ def test_miss_default(): ("x-foreign-key", "no column"), ("x-foreign-key-column", True), ("x-tablename", True), + ("x-tablename", None), ("x-de-$ref", True), ("x-dict-ignore", "True"), ("x-generated", "True"), @@ -60,6 +61,7 @@ def test_miss_default(): "x-foreign-key invalid format", "x-foreign-key-column", "x-tablename", + "x-tablename None", "x-de-$ref", "x-dict-ignore", "x-generated", diff --git a/tests/open_alchemy/test_model_factory.py b/tests/open_alchemy/test_model_factory.py index f9031c15..a0ef659e 100644 --- a/tests/open_alchemy/test_model_factory.py +++ b/tests/open_alchemy/test_model_factory.py @@ -36,6 +36,27 @@ def test_missing_tablename(): ) [email protected] +def test_tablename_none(): + """ + GIVEN schemas with schema that has None for the tablename + WHEN model_factory is called with the name of the schema + THEN MalformedExtensionPropertyError is raised. + """ + with pytest.raises(exceptions.MalformedExtensionPropertyError): + model_factory.model_factory( + name="SingleProperty", + base=mock.MagicMock, + schemas={ + "SingleProperty": { + "x-tablename": None, + "type": "object", + "properties": {"property_1": {"type": "integer"}}, + } + }, + ) + + @pytest.mark.model def test_not_object(): """
Examine nullability of extension properties Examine whether nullability of extension properties is a problem sine JSON schema does not support _nullable_.
0.0
123cc73aecfe79cd6bc46d829d388917c9df9e43
[ "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-tablename", "tests/open_alchemy/test_model_factory.py::test_tablename_none" ]
[ "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_valid[object", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-foreign-key-column]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-secondary]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-backref]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_invalid[empty", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_invalid[list", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-de-$ref]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_pop", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_valid[list", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_valid[list", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_miss", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_relationship_backrefs_invalid[object", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_invalid[list", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_valid[object]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_invalid[object", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_relationship_backrefs_valid[empty]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-foreign-key", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_relationship_backrefs_valid[single", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-unique]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-dict-ignore]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-generated]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-autoincrement]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_invalid[empty", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-uselist]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-tablename]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-unique]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-foreign-key-column]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-uselist]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_invalid[object", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-secondary]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_invalid[not", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-foreign-key]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-backref]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_unique_constraint_valid[object", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-primary-key]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_composite_index_invalid[not", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-primary-key]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_relationship_backrefs_invalid[not", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-tablename]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-generated]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_relationship_backrefs_valid[multiple]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-dict-ignore]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-index]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_invalid[x-autoincrement]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-index]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_valid[x-de-$ref]", "tests/open_alchemy/helpers/test_get_ext_prop.py::test_miss_default", "tests/open_alchemy/test_model_factory.py::test_schema[multiple", "tests/open_alchemy/test_model_factory.py::test_schema[single", "tests/open_alchemy/test_model_factory.py::test_all_of", "tests/open_alchemy/test_model_factory.py::test_tablename", "tests/open_alchemy/test_model_factory.py::test_single_property_required", "tests/open_alchemy/test_model_factory.py::test_single_property_required_missing", "tests/open_alchemy/test_model_factory.py::test_single_property", "tests/open_alchemy/test_model_factory.py::test_schema_relationship_invalid", "tests/open_alchemy/test_model_factory.py::test_not_object", "tests/open_alchemy/test_model_factory.py::test_table_args_unique", "tests/open_alchemy/test_model_factory.py::test_table_args_index", "tests/open_alchemy/test_model_factory.py::test_multiple_property", "tests/open_alchemy/test_model_factory.py::test_ref", "tests/open_alchemy/test_model_factory.py::test_properties_empty", "tests/open_alchemy/test_model_factory.py::test_missing_schema", "tests/open_alchemy/test_model_factory.py::test_single_property_not_required", "tests/open_alchemy/test_model_factory.py::test_properties_missing", "tests/open_alchemy/test_model_factory.py::test_missing_tablename", "tests/open_alchemy/helpers/test_get_ext_prop.py::flake-8::FLAKE8", "tests/open_alchemy/test_model_factory.py::flake-8::FLAKE8" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-03-21 07:48:40+00:00
apache-2.0
3,238
jdkandersson__OpenAlchemy-128
diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc8241c..adf69203 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Version _next_ - Add support for `readOnly`. +- Fix bug where TypedDIct types for `binary`, `date` and `date-time` string formats mapped to the incorrect python types. ## Version 1.1.0 - 2020-04-05 diff --git a/open_alchemy/models_file/model/type_.py b/open_alchemy/models_file/model/type_.py index 7bc55cd3..5b4b361d 100644 --- a/open_alchemy/models_file/model/type_.py +++ b/open_alchemy/models_file/model/type_.py @@ -72,6 +72,12 @@ def typed_dict(*, artifacts: types.ColumnSchemaArtifacts) -> str: model_type = model_type.replace( f"T{artifacts.de_ref}", f"{artifacts.de_ref}Dict" ) + if artifacts.format == "binary": + model_type = model_type.replace("bytes", "str") + if artifacts.format == "date": + model_type = model_type.replace("datetime.date", "str") + if artifacts.format == "date-time": + model_type = model_type.replace("datetime.datetime", "str") return model_type
jdkandersson/OpenAlchemy
4679055ab3ee068d8aa54f2a5f2c2104f9479505
diff --git a/tests/open_alchemy/models_file/model/test_type.py b/tests/open_alchemy/models_file/model/test_type.py index caa228af..1b2c0e13 100644 --- a/tests/open_alchemy/models_file/model/test_type.py +++ b/tests/open_alchemy/models_file/model/test_type.py @@ -106,23 +106,25 @@ def test_model( @pytest.mark.parametrize( - "type_, expected_type", + "type_, format_, expected_type", [ - ("integer", "int"), - ("object", '"RefModelDict"'), - ("array", 'typing.Sequence["RefModelDict"]'), + pytest.param("integer", None, "typing.Optional[int]", id="plain"), + pytest.param("string", "binary", "typing.Optional[str]", id="binary"), + pytest.param("string", "date", "typing.Optional[str]", id="date"), + pytest.param("string", "date-time", "typing.Optional[str]", id="date-time"), + pytest.param("object", None, 'typing.Optional["RefModelDict"]', id="object"), + pytest.param("array", None, 'typing.Sequence["RefModelDict"]', id="array"), ], - ids=["plain", "object", "array"], ) @pytest.mark.models_file -def test_dict(type_, expected_type): +def test_dict(type_, format_, expected_type): """ GIVEN None format and required, False nullable and de_ref and given type WHEN typed_dict is called with the type, format, nullable, required and de_ref THEN the given expected type is returned. """ artifacts = models_file.types.ColumnSchemaArtifacts( - type=type_, nullable=False, de_ref="RefModel" + type=type_, format=format_, nullable=True, de_ref="RefModel" ) returned_type = models_file._model._type.typed_dict(artifacts=artifacts)
The typed dict cannot have types such as datetime The typed dict of a models file should only have the basic OpenAPI types, it should not have python types such as `datetime` which currently is the case.
0.0
4679055ab3ee068d8aa54f2a5f2c2104f9479505
[ "tests/open_alchemy/models_file/model/test_type.py::test_dict[date]", "tests/open_alchemy/models_file/model/test_type.py::test_dict[binary]", "tests/open_alchemy/models_file/model/test_type.py::test_dict[date-time]" ]
[ "tests/open_alchemy/models_file/model/test_type.py::flake-8::FLAKE8", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_simple_nullable_fail[sqlite:///:memory:-required", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_many_to_many[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_arg_init[nullable", "tests/open_alchemy/models_file/model/test_type.py::test_model[string", "tests/open_alchemy/models_file/model/test_type.py::test_dict[array]", "tests/open_alchemy/models_file/model/test_type.py::test_arg_init[not", "tests/open_alchemy/models_file/model/test_type.py::test_arg_from_dict[array]", "tests/open_alchemy/models_file/model/test_type.py::test_model[nullable", "tests/open_alchemy/models_file/model/test_type.py::test_model[array]", "tests/open_alchemy/models_file/model/test_type.py::test_model[integer", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_simple_nullable_fail[sqlite:///:memory:-generated", "tests/open_alchemy/models_file/model/test_type.py::test_dict[object]", "tests/open_alchemy/models_file/model/test_type.py::test_arg_from_dict[object]", "tests/open_alchemy/models_file/model/test_type.py::test_model[object]", "tests/open_alchemy/models_file/model/test_type.py::test_dict[plain]", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_one_to_one[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_model[object", "tests/open_alchemy/models_file/model/test_type.py::test_model[number", "tests/open_alchemy/models_file/model/test_type.py::test_arg_from_dict[plain]", "tests/open_alchemy/models_file/model/test_type.py::test_dict_de_ref_none", "tests/open_alchemy/models_file/model/test_type.py::test_model[boolean", "tests/open_alchemy/models_file/model/test_type.py::test_model[array", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_many_to_one_not_nullable[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_many_to_one[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_simple_nullable_fail[sqlite:///:memory:-nullable", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_one_to_one_not_nullable[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_model_database_type_one_to_many[sqlite:///:memory:]", "tests/open_alchemy/models_file/model/test_type.py::test_arg_from_dict_de_ref_none" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-05-17 08:49:54+00:00
apache-2.0
3,239
jdkandersson__OpenAlchemy-130
diff --git a/CHANGELOG.md b/CHANGELOG.md index adf69203..71d90b35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Add support for `readOnly`. - Fix bug where TypedDIct types for `binary`, `date` and `date-time` string formats mapped to the incorrect python types. +- Fix bug where `to_dict` and `to_str` returned `null` for values that are not required and not nullable. ## Version 1.1.0 - 2020-04-05 diff --git a/open_alchemy/utility_base/__init__.py b/open_alchemy/utility_base/__init__.py index 70181b32..76846c7a 100644 --- a/open_alchemy/utility_base/__init__.py +++ b/open_alchemy/utility_base/__init__.py @@ -221,6 +221,15 @@ class UtilityBase: return_dict: typing.Dict[str, typing.Any] = {} for name, property_schema in properties.items(): value = getattr(instance, name, None) + + # Handle none value + if value is None: + return_none = to_dict.return_none(schema=schema, property_name=name) + if return_none is True: + return_dict[name] = None + # Don't consider for coverage due to coverage bug + continue # pragma: no cover + try: return_dict[name] = to_dict.convert(schema=property_schema, value=value) except exceptions.BaseError as exc: diff --git a/open_alchemy/utility_base/to_dict/__init__.py b/open_alchemy/utility_base/to_dict/__init__.py index 67079c56..41cd0680 100644 --- a/open_alchemy/utility_base/to_dict/__init__.py +++ b/open_alchemy/utility_base/to_dict/__init__.py @@ -31,3 +31,36 @@ def convert(*, schema: oa_types.Schema, value: typing.Any) -> types.TAnyDict: if type_ in {"integer", "number", "string", "boolean"}: return simple.convert(value, schema=schema) raise exceptions.FeatureNotImplementedError(f"Type {type_} is not supported.") + + +def return_none(*, schema: oa_types.Schema, property_name: str) -> bool: + """ + Check whether a null value for a property should be returned. + + Assume the schema has properties and that it has a schema for the property. + Assume that any $ref and allOf has already been resolved. + + The rules are: + 1. if the property is required, return it, + 2. if the property is nullable, return it and + 3. else, don't return it. + + Args: + schema: The schema for the model. + property_name: The name of the property to check for. + + Returns: + Whether the none value should be returned for the property. + + """ + # Retrieve input + required_array = schema.get("required", None) + property_schema = schema["properties"][property_name] + + # Check for required and nullable + if required_array is not None and property_name in set(required_array): + return True + nullable_value = helpers.peek.nullable(schema=property_schema, schemas={}) + if nullable_value is True: + return True + return False
jdkandersson/OpenAlchemy
30d50467bb784b87f98e9464f127012c9679d5b5
diff --git a/tests/open_alchemy/utility_base/test_to_dict.py b/tests/open_alchemy/utility_base/test_to_dict.py index eba6f58c..51713a44 100644 --- a/tests/open_alchemy/utility_base/test_to_dict.py +++ b/tests/open_alchemy/utility_base/test_to_dict.py @@ -41,14 +41,31 @@ def test_to_dict_no_properties(__init__): @pytest.mark.parametrize( "schema, value, expected_value", [ - ({"properties": {"key": {"type": "integer"}}}, {"key": 1}, {"key": 1}), - ( + pytest.param( + {"properties": {"key": {"type": "integer"}}}, + {"key": 1}, + {"key": 1}, + id="single", + ), + pytest.param( + {"properties": {"key": {"type": "integer"}}}, + {"key": None}, + {}, + id="single null value not return", + ), + pytest.param( + {"properties": {"key": {"type": "integer", "nullable": True}}}, + {"key": None}, + {"key": None}, + id="single null value return", + ), + pytest.param( {"properties": {"key_1": {"type": "integer"}, "key_2": {"type": "string"}}}, {"key_1": 1, "key_2": "value 2"}, {"key_1": 1, "key_2": "value 2"}, + id="multiple", ), ], - ids=["single", "multiple"], ) @pytest.mark.utility_base def test_valid(__init__, schema, value, expected_value): diff --git a/tests/open_alchemy/utility_base/to_dict/test_to_dict.py b/tests/open_alchemy/utility_base/to_dict/test_to_dict.py new file mode 100644 index 00000000..fe056fd8 --- /dev/null +++ b/tests/open_alchemy/utility_base/to_dict/test_to_dict.py @@ -0,0 +1,74 @@ +"""Tests for to_dict.""" + +import pytest + +from open_alchemy.utility_base import to_dict + + [email protected]( + "schema, expected_result", + [ + pytest.param( + {"properties": {"prop_1": {"key": "value"}}}, + False, + id="nullable not set required not set expect false", + ), + pytest.param( + {"properties": {"prop_1": {"key": "value"}}, "required": []}, + False, + id="nullable not set required empty expect false", + ), + pytest.param( + {"properties": {"prop_1": {"key": "value"}}, "required": ["prop_2"]}, + False, + id="nullable not set required different property expect false", + ), + pytest.param( + {"properties": {"prop_1": {"key": "value"}}, "required": ["prop_1"]}, + True, + id="nullable not set required has property expect true", + ), + pytest.param( + { + "properties": {"prop_1": {"key": "value", "nullable": False}}, + "required": [], + }, + False, + id="nullable false required empty expect false", + ), + pytest.param( + { + "properties": {"prop_1": {"key": "value", "nullable": False}}, + "required": ["prop_1"], + }, + True, + id="nullable false required has property expect true", + ), + pytest.param( + { + "properties": {"prop_1": {"key": "value", "nullable": True}}, + "required": [], + }, + True, + id="nullable true required empty expect true", + ), + pytest.param( + { + "properties": {"prop_1": {"key": "value", "nullable": True}}, + "required": ["prop_1"], + }, + True, + id="nullable true required has property expect true", + ), + ], +) [email protected]_base +def test_return_none(schema, expected_result): + """ + GIVEN schema with property and expected result + WHEN return_none is called with the schema and property name + THEN the expected result is returned. + """ + result = to_dict.return_none(schema=schema, property_name="prop_1") + + assert result == expected_result
Don't return null column values unless they are required for to_dict and to_str `null` values for non-required properties are not valid JSON schema dictionaries unless they are nullable. Change the rule for null values to: - [ ] If the value is required, return it. - [ ] If the value is nullable, return it. - [ ] If the value is not nullable and not required, don't return it.
0.0
30d50467bb784b87f98e9464f127012c9679d5b5
[ "tests/open_alchemy/utility_base/to_dict/test_to_dict.py::test_return_none[nullable", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[single" ]
[ "tests/open_alchemy/utility_base/test_to_dict.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/to_dict/test_to_dict.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_str", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_schema", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_backrefs_object", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_inheritance_call", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[single]", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[multiple]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_error", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_properties" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-05-17 09:40:08+00:00
apache-2.0
3,240
jdkandersson__OpenAlchemy-135
diff --git a/open_alchemy/facades/__init__.py b/open_alchemy/facades/__init__.py index 76fedf12..6b87c8e0 100644 --- a/open_alchemy/facades/__init__.py +++ b/open_alchemy/facades/__init__.py @@ -1,6 +1,7 @@ """Facades for ringfenced modules.""" # pylint: disable=useless-import-alias +from . import code_formatter as code_formatter from . import jsonschema as jsonschema from . import models as models from . import sqlalchemy as sqlalchemy diff --git a/open_alchemy/facades/code_formatter/__init__.py b/open_alchemy/facades/code_formatter/__init__.py new file mode 100644 index 00000000..bcb579d0 --- /dev/null +++ b/open_alchemy/facades/code_formatter/__init__.py @@ -0,0 +1,22 @@ +"""Apply automatic code formatting to source code.""" + +import black + + +def apply(*, source: str) -> str: + """ + Apply automatic code formatting to source code. + + Args: + source: The source code. + + Returns: + The formatted source code. + + """ + try: + return black.format_file_contents( + src_contents=source, fast=False, mode=black.FileMode() + ) + except black.NothingChanged: + return source diff --git a/open_alchemy/models_file/__init__.py b/open_alchemy/models_file/__init__.py index 6075191e..53a6ee33 100644 --- a/open_alchemy/models_file/__init__.py +++ b/open_alchemy/models_file/__init__.py @@ -4,8 +4,7 @@ import dataclasses import typing -import black - +from open_alchemy import facades from open_alchemy import types as oa_types from . import model as _model @@ -49,9 +48,4 @@ class ModelsFile: # Generate source code for models file raw_source = _models.generate(models=model_sources) - try: - return black.format_file_contents( - src_contents=raw_source, fast=False, mode=black.FileMode() - ) - except black.NothingChanged: - return raw_source + return facades.code_formatter.apply(source=raw_source) diff --git a/setup.cfg b/setup.cfg index ecfa1cad..9aeea833 100644 --- a/setup.cfg +++ b/setup.cfg @@ -19,6 +19,7 @@ markers = only_this example init + code_formatter python_functions = test_* mocked-sessions = examples.app.database.db.session
jdkandersson/OpenAlchemy
00725a51efdcfcb8297c66abfd12dbc6766a4b2e
diff --git a/tests/open_alchemy/facades/test_code_formatter.py b/tests/open_alchemy/facades/test_code_formatter.py new file mode 100644 index 00000000..e881ef8c --- /dev/null +++ b/tests/open_alchemy/facades/test_code_formatter.py @@ -0,0 +1,25 @@ +"""Tests for code formatting.""" + +import pytest + +from open_alchemy import facades + + [email protected]( + "source, expected_source", + [ + pytest.param("'test'\n", '"test"\n', id="apply formatting"), + pytest.param('"test"\n', '"test"\n', id="no formatting"), + ], +) [email protected] [email protected]_formatter +def test_apply(source, expected_source): + """ + GIVEN source code and expected source code + WHEN apply is called with the source code + THEN the expected source code is returned. + """ + returned_source = facades.code_formatter.apply(source=source) + + assert returned_source == expected_source diff --git a/tests/open_alchemy/models_file/test_integration.py b/tests/open_alchemy/models_file/test_integration.py index 976b440e..c131ca75 100644 --- a/tests/open_alchemy/models_file/test_integration.py +++ b/tests/open_alchemy/models_file/test_integration.py @@ -8,7 +8,6 @@ from mypy import api from open_alchemy import models_file _DOCSTRING = '"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""' -_LONG_NAME = "extremely_long_name_that_will_cause_wrapping_aaaaaaaaaaaaaaaaa" _EXPECTED_TD_BASE = "typing.TypedDict" if sys.version_info[1] < 8: _EXPECTED_TD_BASE = "typing_extensions.TypedDict" @@ -116,110 +115,6 @@ class TModel({_EXPECTED_MODEL_BASE}): ... -Model: typing.Type[TModel] = models.Model # type: ignore -''', - ), - ( - [ - ( - { - "properties": { - "ref_model": {"type": "object", "x-de-$ref": "RefModel"} - } - }, - "Model", - ) - ], - f'''{_DOCSTRING} -# pylint: disable=no-member,super-init-not-called,unused-argument - -import typing - -import sqlalchemy{_ADDITIONAL_IMPORT} -from sqlalchemy import orm - -from open_alchemy import models - - -class ModelDict({_EXPECTED_TD_BASE}, total=False): - """TypedDict for properties that are not required.""" - - ref_model: typing.Optional["RefModelDict"] - - -class TModel({_EXPECTED_MODEL_BASE}): - """ - SQLAlchemy model protocol. - - Attrs: - ref_model: The ref_model of the Model. - - """ - - # SQLAlchemy properties - __table__: sqlalchemy.Table - __tablename__: str - query: orm.Query - - # Model properties - ref_model: 'sqlalchemy.Column[typing.Optional["TRefModel"]]' - - def __init__(self, ref_model: typing.Optional["TRefModel"] = None) -> None: - """ - Construct. - - Args: - ref_model: The ref_model of the Model. - - """ - ... - - @classmethod - def from_dict(cls, ref_model: typing.Optional["RefModelDict"] = None) -> "TModel": - """ - Construct from a dictionary (eg. a POST payload). - - Args: - ref_model: The ref_model of the Model. - - Returns: - Model instance based on the dictionary. - - """ - ... - - @classmethod - def from_str(cls, value: str) -> "TModel": - """ - Construct from a JSON string (eg. a POST payload). - - Returns: - Model instance based on the JSON string. - - """ - ... - - def to_dict(self) -> ModelDict: - """ - Convert to a dictionary (eg. to send back for a GET request). - - Returns: - Dictionary based on the model instance. - - """ - ... - - def to_str(self) -> str: - """ - Convert to a JSON string (eg. to send back for a GET request). - - Returns: - JSON string based on the model instance. - - """ - ... - - Model: typing.Type[TModel] = models.Model # type: ignore ''', ), @@ -401,121 +296,10 @@ class TModel2({_EXPECTED_MODEL_BASE}): Model2: typing.Type[TModel2] = models.Model2 # type: ignore -''', - ), - ( - [({"properties": {_LONG_NAME: {"type": "integer"}}}, "Model")], - f'''{_DOCSTRING} -# pylint: disable=no-member,super-init-not-called,unused-argument - -import typing - -import sqlalchemy{_ADDITIONAL_IMPORT} -from sqlalchemy import orm - -from open_alchemy import models - - -class ModelDict({_EXPECTED_TD_BASE}, total=False): - """TypedDict for properties that are not required.""" - - {_LONG_NAME}: typing.Optional[int] - - -class TModel({_EXPECTED_MODEL_BASE}): - """ - SQLAlchemy model protocol. - - Attrs: - {_LONG_NAME}: The - {_LONG_NAME} of - the Model. - - """ - - # SQLAlchemy properties - __table__: sqlalchemy.Table - __tablename__: str - query: orm.Query - - # Model properties - {_LONG_NAME}: "sqlalchemy.Column[typing.Optional[int]]" - - def __init__( - self, - {_LONG_NAME}: typing.Optional[ - int - ] = None, - ) -> None: - """ - Construct. - - Args: - {_LONG_NAME}: The - {_LONG_NAME} - of the Model. - - """ - ... - - @classmethod - def from_dict( - cls, - {_LONG_NAME}: typing.Optional[ - int - ] = None, - ) -> "TModel": - """ - Construct from a dictionary (eg. a POST payload). - - Args: - {_LONG_NAME}: The - {_LONG_NAME} - of the Model. - - Returns: - Model instance based on the dictionary. - - """ - ... - - @classmethod - def from_str(cls, value: str) -> "TModel": - """ - Construct from a JSON string (eg. a POST payload). - - Returns: - Model instance based on the JSON string. - - """ - ... - - def to_dict(self) -> ModelDict: - """ - Convert to a dictionary (eg. to send back for a GET request). - - Returns: - Dictionary based on the model instance. - - """ - ... - - def to_str(self) -> str: - """ - Convert to a JSON string (eg. to send back for a GET request). - - Returns: - JSON string based on the model instance. - - """ - ... - - -Model: typing.Type[TModel] = models.Model # type: ignore ''', ), ], - ids=["single", "single object", "multiple", "black"], + ids=["single", "multiple"], ) @pytest.mark.models_file def test_integration(schemas, expected_source):
change black to be a facade As a developer I want to ring fence the black dependency so that it can be replaced easily in the future. - [x] Define facade interface - [x] Integrate with black - [x] move black dependencies
0.0
00725a51efdcfcb8297c66abfd12dbc6766a4b2e
[ "tests/open_alchemy/models_file/test_integration.py::test_generate_type_return[simple]", "tests/open_alchemy/models_file/test_integration.py::test_generate_type_return[object]", "tests/open_alchemy/facades/test_code_formatter.py::test_apply[apply", "tests/open_alchemy/facades/test_code_formatter.py::test_apply[no", "tests/open_alchemy/facades/test_code_formatter.py::flake-8::FLAKE8", "tests/open_alchemy/models_file/test_integration.py::flake-8::FLAKE8" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-08 01:31:42+00:00
apache-2.0
3,241
jdkandersson__OpenAlchemy-136
diff --git a/CHANGELOG.md b/CHANGELOG.md index 17d4c413..66b12700 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Remove several bugs from the generated models file and integrate with `sqlalchemy-stubs`. - Ring fence `black` dependency. +- add support for `__str__` and `__repr__` for model instances. ## Version 1.1.1 - 2020-05-17 diff --git a/README.md b/README.md index 8ed248d7..6fea1ef7 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,8 @@ An example API has been defined using connexion and Flask here: - `from_str` model methods to construct from JSON string, - `from_dict` model methods to construct from dictionaries, - `to_str` model methods to convert instances to JSON string, +- `__str__` model methods to support the python `str` function, +- `__repr__` model methods to support the python `repr` function, - `to_dict` model methods to convert instances to dictionaries and - exposing created models under `open_alchemy.models` removing the need for `models.py` files. diff --git a/docs/source/index.rst b/docs/source/index.rst index 9cd39ebc..26fe842a 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -21,15 +21,15 @@ If you have the following OpenAPI specification: :language: yaml :linenos: -To use SQLAlchemy to retrieve *Employees* from a database you need the -following *models.py* file: +To use SQLAlchemy to retrieve :samp:`Employees` from a database you need the +following :samp:`models.py` file: .. literalinclude:: ../../examples/simple/models.py :language: python :linenos: -The *Base* for the SQLAlchemy models and the *Employee* model is now available -from *open_alchemy.models*:: +The :samp:`Base` for the SQLAlchemy models and the :samp:`Employee` model is +now available from :samp:`open_alchemy.models`:: from open_alchemy.models import Base from open_alchemy.models import Employee @@ -44,83 +44,86 @@ friendly. .. _init-yaml: -*init_yaml* -^^^^^^^^^^^ +:samp:`init_yaml` +^^^^^^^^^^^^^^^^^ -The *init_yaml* interface requires the *PyYAML* library to be installed. The -*init_yaml* interface accepts the following arguments: +The :samp:`init_yaml` interface requires the :samp:`PyYAML` library to be +installed. The :samp:`init_yaml` interface accepts the following arguments: -* *spec_filename*: The name of the file as a positional argument. The file - must by a YAML file. -* *base*: The SQLAlchemy declarative base as an optional keyword only +* :samp:`spec_filename`: The name of the file as a positional argument. The + file must by a YAML file. +* :samp:`base`: The SQLAlchemy declarative base as an optional keyword only argument. It is used to as the base class for all SQLAlchemy models. If it is not passed in, a new declarative base is constructed. -* *define_all*: Whether to pre-define the SQLAlchemy models as an optional - keyword only argument. If it is *True*, all schemas with the *x-tablename* - property are constructed as a part of the initialization. Defaults to - *True*. -* *models_filename*: The name of the file where the SQLAlchemy models will be - written as an optional keyword only argument. -* *spec_path*: The path to the OpenAPI specification (what would need to be - passed to the *open* function to read the file) as an optional keyword only - argument. Used to support remote references. +* :samp:`define_all`: Whether to pre-define the SQLAlchemy models as an optional + keyword only argument. If it is :samp:`True`, all schemas with the + :samp:`x-tablename` property are constructed as a part of the initialization. + Defaults to :samp:`True`. +* :samp:`models_filename`: The name of the file where the SQLAlchemy models + will be written as an optional keyword only argument. +* :samp:`spec_path`: The path to the OpenAPI specification (what would need to + be passed to the :samp:`open` function to read the file) as an optional + keyword only argument. Used to support remote references. The return value is a tuple consisting of: -* *Base*: The SQLAlchemy declarative based used for the models. It is also - importable: :python:`from open_alchemy.models import Base`. -* *model_factory*: The factory that can be used to construct the SQLAlchemy - models using the name of the schema in the OpenAPI specification. All - constructed models are added to the *open_alchemy.models* module and are - importable. For example: :python:`from open_alchemy.models import Employee`. +* :samp:`Base`: The SQLAlchemy declarative based used for the models. It is + also importable: :python:`from open_alchemy.models import Base`. +* :samp:`model_factory`: The factory that can be used to construct the + SQLAlchemy models using the name of the schema in the OpenAPI specification. + All constructed models are added to the :samp:`open_alchemy.models` module + and are importable. For example: + :python:`from open_alchemy.models import Employee`. .. _init-json: -*init_json* -^^^^^^^^^^^ +:samp:`init_json` +^^^^^^^^^^^^^^^^^ -The *init_json* interface is similar to the :ref:`init-yaml` interface except -that *spec_filename* must be a JSON file and *PyYAML* is not a required -dependency. +The :samp:`init_json` interface is similar to the :ref:`init-yaml` interface +except that :samp:`spec_filename` must be a JSON file and :samp:`PyYAML` is not +a required dependency. .. _init-model-factory: -*init_model_factory* -^^^^^^^^^^^^^^^^^^^^ +:samp:`init_model_factory` +^^^^^^^^^^^^^^^^^^^^^^^^^^ -The *init_model_factory* interface is less user friendly but perhaps of +The :samp:`init_model_factory` interface is less user friendly but perhaps of interest to advanced users. It accepts the specification in dictionary format (so it has fewer dependencies than :ref:`init-yaml` and :ref:`init-json`) and does not construct a declarative base. It accepts the following parameters: -* *base*: The SQLAlchemy declarative base as a keyword only argument. It is - used to as the base class for all SQLAlchemy models. -* *spec*: The OpenAPI specification as a dictionary as a keyword only +* :samp:`base`: The SQLAlchemy declarative base as a keyword only argument. It + is used to as the base class for all SQLAlchemy models. +* :samp:`spec`: The OpenAPI specification as a dictionary as a keyword only argument. -* *define_all*: Whether to pre-define the SQLAlchemy models as an optional - keyword only argument. If it is *True*, all schemas with the *x-tablename* - property are constructed as a part of the initialization. Defaults to - *False*. -* *models_filename*: The name of the file where the SQLAlchemy models will be - written as an optional keyword only argument. +* :samp:`define_all`: Whether to pre-define the SQLAlchemy models as an + optional keyword only argument. If it is :samp:`True`, all schemas with the + :samp:`x-tablename` property are constructed as a part of the initialization. + Defaults to :samp:`False`. +* :samp:`models_filename`: The name of the file where the SQLAlchemy models + will be written as an optional keyword only argument. -The return value is the *model_factory* as defined as part of the return value -of :ref:`init-yaml`. +The return value is the :samp:`model_factory` as defined as part of the return +value of :ref:`init-yaml`. .. _models-file: Models File ----------- -*OpenAlchemy* can optionally generate a file with all the SQLAlchemy models. -Each model is constructed based on the *OpenApi* schema. The class inherits -from the SQLAlchemy model defined on *open_alchemy.models*. The generated -classes contain type information only, they do not provide any additional -functionality on top of what the SQLAlchemy model provides. They are primarily +:samp:`OpenAlchemy` can optionally generate a file with all the +:samp:`SQLAlchemy` models. Each model is constructed based on the +:samp:`OpenApi` schema. The class inherits from the :samp:`SQLAlchemy` model +defined on :samp:`open_alchemy.models`. The generated classes contain type +information only, they do not provide any additional functionality on top of +what the :samp:`SQLAlchemy` model provides. They are primarily used to enable IDE auto-complete and type hint support. The models can be used -in the same way as the models that can be imported from *open_alchemy.models* -and provide the full functionality of *SQLAlchemy* models. The following is a -sample file generated for the above example: +in the same way as the models that can be imported from +:samp:`open_alchemy.models` and provide the full functionality of +:samp:`SQLAlchemy` models. The following is a sample file generated for the +above example: .. literalinclude:: ../../examples/simple/models_auto.py :language: python @@ -140,13 +143,13 @@ The following information is recorded in the models file: .. _backrefs: -.. note:: To be able to add relationships created by *x-backrefs* to the type - annotations of the models file, the schema stored alongside a model, which - is accessible at the *_schema* class variable (not a public interface so it - should not be used or relied upon), will use the *x-backrefs* extension - property to record the schema for all back references for the model. - *x-backrefs* is not a public interface and should not be relied upon as it - is subject to change. +.. note:: To be able to add relationships created by :samp:`x-backrefs` to the + type annotations of the models file, the schema stored alongside a model, + which is accessible at the :samp:`_schema` class variable (not a public + interface so it should not be used or relied upon), will use the + :samp:`x-backrefs` extension property to record the schema for all back + references for the model. :samp:`x-backrefs` is not a public interface and + should not be relied upon as it is subject to change. .. _model-utilities: @@ -160,12 +163,12 @@ dictionary. .. _from-dict: -*from_dict* -^^^^^^^^^^^ +:samp:`from_dict` +^^^^^^^^^^^^^^^^^ -The *from_dict* function is available on all constructed models. It accepts a -dictionary and constructs a model instance based on the dictionary. It is -similar to :python:`Employee(**employee_dict)` with a few advantages: +The :samp:`from_dict` function is available on all constructed models. It +accepts a dictionary and constructs a model instance based on the dictionary. +It is similar to :python:`Employee(**employee_dict)` with a few advantages: * The dictionary based on which the model is constructed is checked against the schema used to define the model. @@ -187,20 +190,20 @@ For example:: .. _de-ref: .. note:: To be able to support relationships, the schema stored alongside a - model, which is accessible at the *_schema* class variable (not a public - interface so it should not be used or relied upon), won't store the actual - schema for the referenced object. Instead, the *object* type is noted for - the property alongside the *x-de-$ref* extension property which stores the - name of the referenced model. + model, which is accessible at the :samp:`_schema` class variable (not a + public interface so it should not be used or relied upon), won't store the + actual schema for the referenced object. Instead, the :samp:`object` type + is noted for the property alongside the :samp:`x-de-$ref` extension + property which stores the name of the referenced model. .. _from-str: -*from_str* -^^^^^^^^^^^ +:samp:`from_str` +^^^^^^^^^^^^^^^^ -The *from_str* function is available on all constructed models. It accepts a -JSON formatted string and constructs a model instance by de-serializing the -JSON string and then using :ref:`from-dict`. For example:: +The :samp:`from_str` function is available on all constructed models. It +accepts a JSON formatted string and constructs a model instance by +de-serializing the JSON string and then using :ref:`from-dict`. For example:: >>> employee_str = '''{ "id": 1, @@ -214,13 +217,13 @@ JSON string and then using :ref:`from-dict`. For example:: .. _to-dict: -*to_dict* -^^^^^^^^^ +:samp:`to_dict` +^^^^^^^^^^^^^^^ -The *to_dict* function is available on all constructed models. It converts a -model instance into a dictionary based on the schema that was used to define -the model. If the model includes a relationship, the *to_dict* function is -called recursively on the relationship. +The :samp:`to_dict` function is available on all constructed models. It +converts a model instance into a dictionary based on the schema that was used +to define the model. If the model includes a relationship, the :samp:`to_dict` +function is called recursively on the relationship. For example:: @@ -239,11 +242,11 @@ For example:: .. _to-str: -*to_str* -^^^^^^^^^ +:samp:`to_str` +^^^^^^^^^^^^^^ -The *to_str* function is available on all constructed models. It converts a -model instance into a JSON formatted string by serializing the output of +The :samp:`to_str` function is available on all constructed models. It converts +a model instance into a JSON formatted string by serializing the output of :ref:`to-dict`. For example:: @@ -258,6 +261,36 @@ For example:: >>> employee.to_str() '{"id": 1, "name": "David Andersson", "division": "engineering", "salary": 1000000}' +.. _str: + +:samp:`__str__` +^^^^^^^^^^^^^^^ + +It is possible to convert any model instance to a string using the +:python:`str` function. This is supported as there is a :samp:`__str__` alias +for the :ref:`to-str` function. + +.. _repr: + +:samp:`__repr__` +^^^^^^^^^^^^^^^^ + +Each model includes a :samp:`__repr__` implementation to support calling +:python:`repr` in any model instance. The returned string is the source code +required to construct an equivalent model instance. + +For example:: + + >>> employee_dict = { + "id": 1, + "name": "David Andersson", + "division": "engineering", + "salary": 1000000, + } + >>> employee = Employee.from_dict(**employee_dict) + >>> repr(employee) + "open_alchemy.models.Employee(id=1, name='David Andersson', division='engineering', salary=1000000)" + .. _alembic: Alembic @@ -274,11 +307,12 @@ alembic is supported. The following instructions show how to get started: How Does It Work? ----------------- -Given a name for a schema, *OpenAlchemy* looks for that schema in the -schemas section of the specification. The schema must have the *x-tablename* -property which defines the name of the table. The schema is required to be an -*object*. For each *property* of the schema, a column is generated for the -table mapping OpenAPI types to equivalent SQLAlchemy types. +Given a name for a schema, :samp:`OpenAlchemy` looks for that schema in the +schemas section of the specification. The schema must have the +:samp:`x-tablename` property which defines the name of the table. The schema is +required to be an :samp:`object`. For each :samp:`property` of the schema, a +column is generated for the table mapping OpenAPI types to equivalent +SQLAlchemy types. On top of the information in the OpenAPI specification, certain extension properties are used to define the database schema. The following specification @@ -336,8 +370,8 @@ the documentation: | :samp:`x-foreign-key-kwargs` | :ref:`Foreign Key kwargs <foreign-key-kwargs>` | +------------------------------+----------------------------------------------------+ -The SQLAlchemy *Base* and any constructed database models are dynamically added -to the *models* module that is available from OpenAlchemy. +The SQLAlchemy :samp:`Base` and any constructed database models are dynamically +added to the :samp:`models` module that is available from OpenAlchemy. Technical Details ----------------- diff --git a/open_alchemy/utility_base/__init__.py b/open_alchemy/utility_base/__init__.py index 76846c7a..ab196855 100644 --- a/open_alchemy/utility_base/__init__.py +++ b/open_alchemy/utility_base/__init__.py @@ -9,6 +9,7 @@ from .. import facades from .. import helpers from .. import types as oa_types from . import from_dict +from . import repr_ from . import to_dict TUtilityBase = typing.TypeVar("TUtilityBase", bound="UtilityBase") @@ -268,3 +269,10 @@ class UtilityBase: """ instance_dict = self.to_dict() return json.dumps(instance_dict) + + __str__ = to_str + + def __repr__(self) -> str: + """Calculate the repr for the model.""" + properties = self.get_properties() + return repr_.calculate(instance=self, properties=properties) diff --git a/open_alchemy/utility_base/repr_.py b/open_alchemy/utility_base/repr_.py new file mode 100644 index 00000000..66cb9585 --- /dev/null +++ b/open_alchemy/utility_base/repr_.py @@ -0,0 +1,34 @@ +"""Calculate the repr for the model.""" + +import typing + +from open_alchemy import types + + +def calculate(*, instance: typing.Any, properties: types.Schema) -> str: + """ + Calculate the repr for the model. + + The repr is the string that would be needed to create an equivalent instance of the + model. + + Args: + instance: The model instance to calculate the repr for. + properties: The properties of the model instance. + + Returns: + The string that would be needed to create an equivalent instance of the model. + + """ + # Calculate the name + name = type(instance).__name__ + + # Retrieve property values + prop_repr_gen = ( + (prop, repr(getattr(instance, prop, None))) for prop in properties.keys() + ) + prop_repr_str_gen = (f"{name}={value}" for name, value in prop_repr_gen) + prop_repr_str = ", ".join(prop_repr_str_gen) + + # Calculate repr + return f"open_alchemy.models.{name}({prop_repr_str})"
jdkandersson/OpenAlchemy
4f121c014f5864fb3affe839f3136d447839743a
diff --git a/tests/open_alchemy/utility_base/test_repr_.py b/tests/open_alchemy/utility_base/test_repr_.py new file mode 100644 index 00000000..1bf3ea7b --- /dev/null +++ b/tests/open_alchemy/utility_base/test_repr_.py @@ -0,0 +1,61 @@ +"""Test for the repr of the model.""" + +from unittest import mock + +import pytest + +from open_alchemy import utility_base + + +class Model: + """Model class for testing.""" + + def __init__(self): + """Construct.""" + self.property_int = 1 + self.property_str = "value 1" + self.property_repr = mock.MagicMock( + spec=["__repr__"], __repr__=lambda _: "open_alchemy.models.RefModel()" + ) + + [email protected]( + "properties, expected_repr", + [ + pytest.param({}, "open_alchemy.models.Model()", id="no properties",), + pytest.param( + {"property_not_def": {}}, + "open_alchemy.models.Model(property_not_def=None)", + id="single property property simple no value", + ), + pytest.param( + {"property_int": {}}, + "open_alchemy.models.Model(property_int=1)", + id="single property property simple value", + ), + pytest.param( + {"property_repr": {}}, + "open_alchemy.models.Model(property_repr=open_alchemy.models.RefModel())", + id="single property property repr", + ), + pytest.param( + {"property_int": {}, "property_str": {}}, + "open_alchemy.models.Model(property_int=1, property_str='value 1')", + id="multiple property property", + ), + ], +) [email protected]_base +def test_calculate(properties, expected_repr): + """ + GIVEN model instance, properties and expected repr result + WHEN calculate is called on the instance + THEN the expected repr is returned. + """ + instance = Model() + + returned_repr = utility_base.repr_.calculate( + instance=instance, properties=properties + ) + + assert returned_repr == expected_repr diff --git a/tests/open_alchemy/utility_base/test_to_dict.py b/tests/open_alchemy/utility_base/test_to_dict.py index 51713a44..da1e676b 100644 --- a/tests/open_alchemy/utility_base/test_to_dict.py +++ b/tests/open_alchemy/utility_base/test_to_dict.py @@ -172,7 +172,7 @@ def test_to_str(__init__): THEN the JSON representation of the properties is returned. """ model = type( - "model", + "Model", (utility_base.UtilityBase,), { "_schema": {"properties": {"key_1": {"type": "integer"}}}, @@ -184,3 +184,5 @@ def test_to_str(__init__): returned_str = instance.to_str() assert returned_str == '{"key_1": 1}' + assert str(instance) == '{"key_1": 1}' + assert repr(instance) == "open_alchemy.models.Model(key_1=1)"
Add good __str__ and __repr__ As a user when I print a model instance I want to see good information about the instance so that debugging is easier.
0.0
4f121c014f5864fb3affe839f3136d447839743a
[ "tests/open_alchemy/utility_base/test_to_dict.py::test_to_str", "tests/open_alchemy/utility_base/test_repr_.py::test_calculate[multiple", "tests/open_alchemy/utility_base/test_repr_.py::test_calculate[single", "tests/open_alchemy/utility_base/test_repr_.py::test_calculate[no" ]
[ "tests/open_alchemy/utility_base/test_repr_.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/test_to_dict.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[multiple]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_inheritance_call", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[single", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_properties", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_schema", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_backrefs_object", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_error", "tests/open_alchemy/utility_base/test_to_dict.py::test_valid[single]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-08 08:07:28+00:00
apache-2.0
3,242
jdkandersson__OpenAlchemy-63
diff --git a/CHANGELOG.md b/CHANGELOG.md index f0e38c7e..e44f4266 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Version _next_ +- Add support for _byte_ - Add support for _date_ - Move SQLAlchemy relationship construction behind facade - Move schema calculations into separate files diff --git a/README.md b/README.md index d92da4f9..4684c692 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,7 @@ An example API has been defined using connexion and Flask here: - `number` (float only), - `boolean`, - `string`, +- `byte`, - `date`, - `date-time`, - `$ref` references for columns and models, diff --git a/docs/source/technical_details/type_mapping.rst b/docs/source/technical_details/type_mapping.rst index 201d7faf..077313ac 100644 --- a/docs/source/technical_details/type_mapping.rst +++ b/docs/source/technical_details/type_mapping.rst @@ -19,6 +19,8 @@ following mappings: +--------------+----------------+-----------------+ | string | *undefined* | String | +--------------+----------------+-----------------+ +| | byte | String | ++--------------+----------------+-----------------+ | | date | Date | +--------------+----------------+-----------------+ | | date-time | DateTime | diff --git a/open_alchemy/column_factory/column.py b/open_alchemy/column_factory/column.py index 76987e22..7a2874aa 100644 --- a/open_alchemy/column_factory/column.py +++ b/open_alchemy/column_factory/column.py @@ -272,7 +272,7 @@ def _handle_string(*, artifacts: types.ColumnArtifacts) -> sqlalchemy.String: raise exceptions.MalformedSchemaError( "The string type does not support autoincrement." ) - if artifacts.format is None: + if artifacts.format in {None, "byte"}: if artifacts.max_length is None: return sqlalchemy.String return sqlalchemy.String(length=artifacts.max_length)
jdkandersson/OpenAlchemy
efb83519b59586ce725b34eeb345f22a53fb58c3
diff --git a/tests/open_alchemy/column_factory/test_column.py b/tests/open_alchemy/column_factory/test_column.py index 96309c35..d2a11fe6 100644 --- a/tests/open_alchemy/column_factory/test_column.py +++ b/tests/open_alchemy/column_factory/test_column.py @@ -521,8 +521,9 @@ def test_handle_string_invalid_format(): (None, sqlalchemy.String), ("date", sqlalchemy.Date), ("date-time", sqlalchemy.DateTime), + ("byte", sqlalchemy.String), ], - ids=["None", "date", "date-time"], + ids=["None", "date", "date-time", "byte"], ) @pytest.mark.column def test_handle_string(format_, expected_type):
Support byte As a user I want to define a byte format so that I can store and retrieve base64 encoded values from the database. Support byte as indicated by the appropriate format directive of a string.
0.0
efb83519b59586ce725b34eeb345f22a53fb58c3
[ "tests/open_alchemy/column_factory/test_column.py::test_handle_string[byte]" ]
[ "tests/open_alchemy/column_factory/test_column.py::flake-8::FLAKE8", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_artifacts[type", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[date]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[foreign", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[number]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_schema[type", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[none]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[integer]", "tests/open_alchemy/column_factory/test_column.py::test_calculate_nullable[required", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[integer]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[true]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[autoincrement", "tests/open_alchemy/column_factory/test_column.py::test_handle_number[float]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_schema_other", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[boolean]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[int64]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[false]", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[format]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_required", "tests/open_alchemy/column_factory/test_column.py::test_determine_type_unsupported", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[none]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[maxLength", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_foreign_key", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[x-dict-ignore", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[None]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[nullable", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[boolean]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_nullable[true]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[unique", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[none]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[true]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[true]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[index", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[number]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[false]", "tests/open_alchemy/column_factory/test_column.py::test_integration", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[primary", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[type", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[true]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[none]", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[string]", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[None]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[string]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[int32]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_max_length", "tests/open_alchemy/column_factory/test_column.py::test_handle_number[None]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[false]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[format", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[date-time]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_nullable[false]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[false]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-12-22 04:03:25+00:00
apache-2.0
3,243
jdkandersson__OpenAlchemy-64
diff --git a/CHANGELOG.md b/CHANGELOG.md index e44f4266..cc8553aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Version _next_ +- Add support for _password_ +- Add support for _binary_ - Add support for _byte_ - Add support for _date_ - Move SQLAlchemy relationship construction behind facade diff --git a/README.md b/README.md index 4684c692..87a5c8c1 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,9 @@ An example API has been defined using connexion and Flask here: - `number` (float only), - `boolean`, - `string`, +- `password`, - `byte`, +- `binary`, - `date`, - `date-time`, - `$ref` references for columns and models, diff --git a/docs/source/technical_details/type_mapping.rst b/docs/source/technical_details/type_mapping.rst index 077313ac..bf7406ba 100644 --- a/docs/source/technical_details/type_mapping.rst +++ b/docs/source/technical_details/type_mapping.rst @@ -19,8 +19,12 @@ following mappings: +--------------+----------------+-----------------+ | string | *undefined* | String | +--------------+----------------+-----------------+ +| | password | String | ++--------------+----------------+-----------------+ | | byte | String | +--------------+----------------+-----------------+ +| | binary | LargeBinary | ++--------------+----------------+-----------------+ | | date | Date | +--------------+----------------+-----------------+ | | date-time | DateTime | @@ -35,6 +39,26 @@ String translated to the *length* argument for the *SQLAlchemy* *String*, which is set to *None* if *maxLength* is *undefined*. +Password +-------- + +The same *maxLength* information as for *String* also applies. + +.. note:: The *password* format under the hood is the same as *String*. No + special protection (such as encryption) is added. + +Byte +------ + +This format is for *base64* encoded binary data. The same *maxLength* +information as for *String* also applies. + +Binary +------ + +The same *maxLength* information as for *String* also applies. The codec is +assumed to be *utf-8*. + DateTime -------- diff --git a/open_alchemy/column_factory/column.py b/open_alchemy/column_factory/column.py index 7a2874aa..395e470a 100644 --- a/open_alchemy/column_factory/column.py +++ b/open_alchemy/column_factory/column.py @@ -272,10 +272,14 @@ def _handle_string(*, artifacts: types.ColumnArtifacts) -> sqlalchemy.String: raise exceptions.MalformedSchemaError( "The string type does not support autoincrement." ) - if artifacts.format in {None, "byte"}: + if artifacts.format in {None, "byte", "password"}: if artifacts.max_length is None: return sqlalchemy.String return sqlalchemy.String(length=artifacts.max_length) + if artifacts.format == "binary": + if artifacts.max_length is None: + return sqlalchemy.LargeBinary + return sqlalchemy.LargeBinary(length=artifacts.max_length) if artifacts.format == "date": return sqlalchemy.Date if artifacts.format == "date-time": diff --git a/open_alchemy/utility_base.py b/open_alchemy/utility_base.py index dcdff3cc..042d8c20 100644 --- a/open_alchemy/utility_base.py +++ b/open_alchemy/utility_base.py @@ -99,12 +99,23 @@ class UtilityBase: return ref_model @staticmethod - def _from_dict( + def _model_from_dict( kwargs: typing.Dict[str, typing.Any], *, model: typing.Type[TUtilityBase] ) -> TUtilityBase: """Construct model from dictionary.""" return model.from_dict(**kwargs) + @staticmethod + def _simple_type_from_dict(format_: str, value: typing.Any) -> typing.Any: + """Construct dictionary key for simple types.""" + if format_ == "date": + return datetime.date.fromisoformat(value) + if format_ == "date-time": + return datetime.datetime.fromisoformat(value) + if format_ == "binary": + return value.encode() + return value + @classmethod def from_dict(cls: typing.Type[TUtilityBase], **kwargs: typing.Any) -> TUtilityBase: """ @@ -168,7 +179,7 @@ class UtilityBase: ref_model: typing.Type[TUtilityBase] if type_ == "object": ref_model = cls._get_model(spec=spec, name=name, schema=schema) - ref_model_instance = cls._from_dict(value, model=ref_model) + ref_model_instance = cls._model_from_dict(value, model=ref_model) model_dict[name] = ref_model_instance continue @@ -183,19 +194,15 @@ class UtilityBase: f"The model schema is {json.dumps(schema)}." ) ref_model = cls._get_model(spec=item_spec, name=name, schema=schema) - model_from_dict = functools.partial(cls._from_dict, model=ref_model) + model_from_dict = functools.partial( + cls._model_from_dict, model=ref_model + ) ref_model_instances = map(model_from_dict, value) model_dict[name] = list(ref_model_instances) continue # Handle other types - if format_ == "date": - model_dict[name] = datetime.date.fromisoformat(value) - continue - if format_ == "date-time": - model_dict[name] = datetime.datetime.fromisoformat(value) - continue - model_dict[name] = value + model_dict[name] = cls._simple_type_from_dict(format_=format_, value=value) return cls(**model_dict) @@ -265,6 +272,8 @@ class UtilityBase: return value.isoformat() if format_ == "date-time": return value.isoformat() + if format_ == "binary": + return value.decode() return value @classmethod
jdkandersson/OpenAlchemy
29c90022dce685c1f92fe5973784e0ea5035670b
diff --git a/tests/open_alchemy/column_factory/test_column.py b/tests/open_alchemy/column_factory/test_column.py index d2a11fe6..3e78874a 100644 --- a/tests/open_alchemy/column_factory/test_column.py +++ b/tests/open_alchemy/column_factory/test_column.py @@ -522,8 +522,10 @@ def test_handle_string_invalid_format(): ("date", sqlalchemy.Date), ("date-time", sqlalchemy.DateTime), ("byte", sqlalchemy.String), + ("password", sqlalchemy.String), + ("binary", sqlalchemy.LargeBinary), ], - ids=["None", "date", "date-time", "byte"], + ids=["None", "date", "date-time", "byte", "password", "binary"], ) @pytest.mark.column def test_handle_string(format_, expected_type): @@ -539,19 +541,24 @@ def test_handle_string(format_, expected_type): assert string == expected_type [email protected]( + "format_, expected_type", + [(None, sqlalchemy.String), ("binary", sqlalchemy.LargeBinary)], + ids=["string", "binary"], +) @pytest.mark.column -def test_handle_string_max_length(): +def test_handle_string_max_length(format_, expected_type): """ - GIVEN artifacts with max_length + GIVEN artifacts with max_length and given format WHEN _handle_string is called with the artifacts - THEN a string with a maximum length is returned. + THEN a given expected type column with a maximum length is returned. """ length = 1 - artifacts = types.ColumnArtifacts("string", max_length=length) + artifacts = types.ColumnArtifacts("string", max_length=length, format=format_) string = column._handle_string(artifacts=artifacts) - assert isinstance(string, sqlalchemy.String) + assert isinstance(string, expected_type) assert string.length == length diff --git a/tests/open_alchemy/test_integration/test_database.py b/tests/open_alchemy/test_integration/test_database.py index 5fe2482c..3e7f57f4 100644 --- a/tests/open_alchemy/test_integration/test_database.py +++ b/tests/open_alchemy/test_integration/test_database.py @@ -17,6 +17,9 @@ import open_alchemy ("integer", "int64", 1), ("number", None, 1.0), ("string", None, "some string"), + ("string", "password", "some password"), + ("string", "byte", "some string"), + ("string", "binary", b"some bytes"), ("string", "date", datetime.date(year=2000, month=1, day=1)), ( "string", @@ -25,7 +28,18 @@ import open_alchemy ), ("boolean", None, True), ], - ids=["integer", "int64", "number", "string", "date", "date-time", "boolean"], + ids=[ + "integer", + "int64", + "number", + "string", + "password", + "byte", + "binary", + "date", + "date-time", + "boolean", + ], ) @pytest.mark.integration def test_database_types( diff --git a/tests/open_alchemy/test_integration/test_to_from_dict.py b/tests/open_alchemy/test_integration/test_to_from_dict.py index 168e6b19..f1dc7ea3 100644 --- a/tests/open_alchemy/test_integration/test_to_from_dict.py +++ b/tests/open_alchemy/test_integration/test_to_from_dict.py @@ -10,13 +10,17 @@ import open_alchemy "column_schema, value", [ ({"type": "integer", "x-primary-key": True}, 1), + ( + {"type": "string", "format": "binary", "x-primary-key": True}, + "some binary files", + ), ({"type": "string", "format": "date", "x-primary-key": True}, "2000-01-01"), ( {"type": "string", "format": "date-time", "x-primary-key": True}, "2000-01-01T01:01:01", ), ], - ids=["integer", "date", "date-time"], + ids=["integer", "binary", "date", "date-time"], ) @pytest.mark.integration def test_basic_types(engine, sessionmaker, column_schema, value): diff --git a/tests/open_alchemy/utility_base/test_from_dict.py b/tests/open_alchemy/utility_base/test_from_dict.py index 049dba3f..9de3549c 100644 --- a/tests/open_alchemy/utility_base/test_from_dict.py +++ b/tests/open_alchemy/utility_base/test_from_dict.py @@ -150,6 +150,7 @@ def test_from_dict(schema, dictionary, __init__): @pytest.mark.parametrize( "format_, value, expected_value", [ + ("binary", "some binary file", b"some binary file"), ("date", "2000-01-01", datetime.date(year=2000, month=1, day=1)), ( "date-time", @@ -157,7 +158,7 @@ def test_from_dict(schema, dictionary, __init__): datetime.datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1), ), ], - ids=["date", "date-time"], + ids=["binary", "date", "date-time"], ) @pytest.mark.utility_base def test_from_dict_string_format(format_, value, expected_value, __init__): diff --git a/tests/open_alchemy/utility_base/test_to_dict.py b/tests/open_alchemy/utility_base/test_to_dict.py index a441bb53..89c39c82 100644 --- a/tests/open_alchemy/utility_base/test_to_dict.py +++ b/tests/open_alchemy/utility_base/test_to_dict.py @@ -439,6 +439,7 @@ class TestToDictProperty: @pytest.mark.parametrize( "format_, value, expected_value", [ + ("binary", b"some binary file", "some binary file"), ("date", datetime.date(year=2000, month=1, day=1), "2000-01-01"), ( "date-time", @@ -448,7 +449,7 @@ class TestToDictProperty: "2000-01-01T01:01:01", ), ], - ids=["date", "date-time"], + ids=["binary", "date", "date-time"], ) @pytest.mark.utility_base def test_string_format(format_, value, expected_value):
Support byte As a user I want to define a byte format so that I can store and retrieve base64 encoded values from the database. Support byte as indicated by the appropriate format directive of a string.
0.0
29c90022dce685c1f92fe5973784e0ea5035670b
[ "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-password]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-binary]", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_string_format[binary]", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_string_format[binary]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_basic_types[sqlite:///:memory:-binary]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[binary]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[password]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_max_length[binary]" ]
[ "tests/open_alchemy/test_integration/test_database.py::test_database_indexes[sqlite:///:memory:-x-index]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-date]", "tests/open_alchemy/test_integration/test_database.py::test_database_autoincrement[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_one_to_many_relationship[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_ref_all_of[sqlite:///:memory:-ref", "tests/open_alchemy/test_integration/test_database.py::test_database_indexes[sqlite:///:memory:-x-unique]", "tests/open_alchemy/test_integration/test_database.py::test_database_one_to_many_relationship_other_order[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-date-time]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-number]", "tests/open_alchemy/test_integration/test_database.py::test_database_one_to_one_relationship[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_ref_all_of[sqlite:///:memory:-allOf", "tests/open_alchemy/test_integration/test_database.py::test_database_many_to_many_relationship[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-integer]", "tests/open_alchemy/test_integration/test_database.py::test_database_many_to_one_relationship[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_many_to_one_relationship_fk[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-int64]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-boolean]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-string]", "tests/open_alchemy/test_integration/test_database.py::test_database_not_autoincrement[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_database.py::test_database_indexes[sqlite:///:memory:-x-primary-key]", "tests/open_alchemy/test_integration/test_database.py::test_database_types[sqlite:///:memory:-byte]", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_string_format[date]", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict[multiple]", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict[single", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_array_no_items", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_object_from_dict_call", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_read_only", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_array_multiple_from_dict", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_array_empty_from_dict", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_string_format[date-time]", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_malformed_dictionary", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_no_type_schema", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_read_only_false", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_object_model_undefined", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_array_single_from_dict", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_argument_not_in_properties", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_object_return", "tests/open_alchemy/utility_base/test_from_dict.py::test_from_dict_object_de_ref_missing", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictReadOnly::test_spec_invalid[properties", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictReadOnly::test_multiple", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictReadOnly::test_missing", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictReadOnly::test_single", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_string_format[date]", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_read_only", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_array_none", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_invalid_spec[array", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_read_only_array", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_simple_value[none]", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_object_value", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_array_multiple", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_object_none", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_string_format[date-time]", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_array_single", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_simple_value[value]", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_array_empty", "tests/open_alchemy/utility_base/test_to_dict.py::TestToDictProperty::test_invalid_spec[no", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictRelationship::test_object_to_dict_relationship_object_no_to_dict", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictRelationship::test_object_to_dict_relationship_object_to_dict_relationship_different_func", "tests/open_alchemy/utility_base/test_to_dict.py::TestObjectToDictRelationship::test_object_to_dict_relationship_object_to_dict_relationship", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_simple_type[multiple]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_simple_type[single", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_object", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_array_none[undefined]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_properties", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_object_none[none]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_array_empty", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_array_multiple", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_simple_type[empty]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_type", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_object_none[undefined]", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_no_schema", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_array_single", "tests/open_alchemy/utility_base/test_to_dict.py::test_to_dict_array_none[none]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_many_to_many_read_only[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_one_to_many[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_one_to_one_read_only[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_one_to_many_fk_def[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_many_to_one[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_many_to_one_read_only[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_one_to_many_read_only[sqlite:///:memory:]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_basic_types[sqlite:///:memory:-date]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_basic_types[sqlite:///:memory:-integer]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_basic_types[sqlite:///:memory:-date-time]", "tests/open_alchemy/test_integration/test_to_from_dict.py::test_to_from_dict_many_to_many[sqlite:///:memory:]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[byte]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[index", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[type", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[none]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_max_length[string]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[int64]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_artifacts[type", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[true]", "tests/open_alchemy/column_factory/test_column.py::test_calculate_nullable[required", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[foreign", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[string]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[true]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[false]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_required", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[autoincrement", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[None]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_schema[type", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[x-dict-ignore", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_handle_number[float]", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[date-time]", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid[max_length]", "tests/open_alchemy/column_factory/test_column.py::test_integration", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_nullable[false]", "tests/open_alchemy/column_factory/test_column.py::test_handle_number_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[boolean]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[none]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_foreign_key", "tests/open_alchemy/column_factory/test_column.py::test_handle_number[None]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[maxLength", "tests/open_alchemy/column_factory/test_column.py::test_determine_type_unsupported", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[primary", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[false]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[false]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[none]", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[number]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_primary_key[false]", "tests/open_alchemy/column_factory/test_column.py::test_handle_boolean_invalid[format]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_unique[true]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[number]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[nullable", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_invalid[autoincrement]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_nullable[true]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_schema_other", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[boolean]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_index[none]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column_autoincrement[true]", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[integer]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string_invalid_format", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[None]", "tests/open_alchemy/column_factory/test_column.py::test_handle_string[date]", "tests/open_alchemy/column_factory/test_column.py::test_determine_type[integer]", "tests/open_alchemy/column_factory/test_column.py::test_handle_integer[int32]", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[unique", "tests/open_alchemy/column_factory/test_column.py::test_check_schema_invalid[format", "tests/open_alchemy/column_factory/test_column.py::test_construct_column[string]", "tests/open_alchemy/column_factory/test_column.py::flake-8::FLAKE8", "tests/open_alchemy/test_integration/test_database.py::flake-8::FLAKE8", "tests/open_alchemy/test_integration/test_to_from_dict.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/test_from_dict.py::flake-8::FLAKE8", "tests/open_alchemy/utility_base/test_to_dict.py::flake-8::FLAKE8" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-12-22 04:46:27+00:00
apache-2.0
3,244
jdkandersson__OpenAlchemy-97
diff --git a/CHANGELOG.md b/CHANGELOG.md index b35ad65e..4f4c40a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Ring fence SQLAlchemy dependency to a facade and integration tests. - Add tests for examples. - Add _from_str_ and _to_str_ to complement _from_dict_ and _to_dict_ for de-serializing and serializing from JSON. +- Ring fence jsonschema dependency into a facade. ## Version 0.12.1 - 2020-01-12 diff --git a/open_alchemy/facades/__init__.py b/open_alchemy/facades/__init__.py index 2f7710ef..76fedf12 100644 --- a/open_alchemy/facades/__init__.py +++ b/open_alchemy/facades/__init__.py @@ -1,5 +1,6 @@ """Facades for ringfenced modules.""" # pylint: disable=useless-import-alias +from . import jsonschema as jsonschema from . import models as models from . import sqlalchemy as sqlalchemy diff --git a/open_alchemy/facades/jsonschema/__init__.py b/open_alchemy/facades/jsonschema/__init__.py new file mode 100644 index 00000000..b1ac6e30 --- /dev/null +++ b/open_alchemy/facades/jsonschema/__init__.py @@ -0,0 +1,48 @@ +"""Facade for jsonschema.""" + +import functools +import json +import typing + +import jsonschema + +# Re mapping values +ValidationError = jsonschema.ValidationError +validate = jsonschema.validate # pylint: disable=invalid-name + + +def _filename_to_dict(filename: str) -> typing.Dict: + """ + Map filename for a JSON file to the de-serialized dictionary. + + Args: + filename: The name of the JSON file. + + Returns: + The de-serialized contents of the file as a dictionary. + + """ + with open(filename) as in_file: + json_dict = json.loads(in_file.read()) + return json_dict + + +def resolver( + *filenames: str, +) -> typing.Tuple[ + jsonschema.RefResolver, typing.Tuple[typing.Dict[str, typing.Any], ...] +]: + """ + Create resolver for references to schemas in another file. + + Args: + filenames: The names for the files to add to the resolver. + + Returns: + The resolver and the underlying schemas as a dictionary. + + """ + schema_dicts = tuple(map(_filename_to_dict, filenames)) + initial: typing.Dict[str, typing.Any] = {} + merged_schema = functools.reduce(lambda x, y: {**x, **y}, schema_dicts, initial) + return jsonschema.RefResolver.from_schema(merged_schema), schema_dicts diff --git a/open_alchemy/helpers/get_ext_prop/__init__.py b/open_alchemy/helpers/get_ext_prop/__init__.py index 4ebb4523..382f678b 100644 --- a/open_alchemy/helpers/get_ext_prop/__init__.py +++ b/open_alchemy/helpers/get_ext_prop/__init__.py @@ -4,19 +4,14 @@ import json import os import typing -import jsonschema - from open_alchemy import exceptions +from open_alchemy import facades _DIRECTORY = os.path.dirname(__file__) _SCHEMAS_FILE = os.path.join(_DIRECTORY, "extension-schemas.json") -with open(_SCHEMAS_FILE) as in_file: - _SCHEMAS = json.load(in_file) _COMMON_SCHEMAS_FILE = os.path.join(_DIRECTORY, "common-schemas.json") -with open(_COMMON_SCHEMAS_FILE) as in_file: - _COMMON_SCHEMAS = json.load(in_file) -_resolver = jsonschema.RefResolver.from_schema( # pylint: disable=invalid-name - {**_COMMON_SCHEMAS, **_SCHEMAS} +_resolver, (_SCHEMAS, _) = facades.jsonschema.resolver( # pylint: disable=invalid-name + _SCHEMAS_FILE, _COMMON_SCHEMAS_FILE ) @@ -49,8 +44,8 @@ def get_ext_prop( schema = _SCHEMAS.get(name) try: - jsonschema.validate(instance=value, schema=schema, resolver=_resolver) - except jsonschema.ValidationError: + facades.jsonschema.validate(instance=value, schema=schema, resolver=_resolver) + except facades.jsonschema.ValidationError: raise exceptions.MalformedExtensionPropertyError( f"The value of the {json.dumps(name)} extension property is not " "valid. " diff --git a/open_alchemy/table_args/factory.py b/open_alchemy/table_args/factory.py index 19703d6b..eaef2338 100644 --- a/open_alchemy/table_args/factory.py +++ b/open_alchemy/table_args/factory.py @@ -5,20 +5,19 @@ import json import os import typing -import jsonschema from sqlalchemy import schema from open_alchemy import exceptions +from open_alchemy import facades from open_alchemy import types _DIRECTORY = os.path.dirname(__file__) _PATHS = ("..", "helpers", "get_ext_prop") _COMMON_SCHEMAS_FILE = os.path.join(_DIRECTORY, *_PATHS, "common-schemas.json") -with open(_COMMON_SCHEMAS_FILE) as in_file: - _COMMON_SCHEMAS = json.load(in_file) -_resolver = jsonschema.RefResolver.from_schema( # pylint: disable=invalid-name - _COMMON_SCHEMAS -) +( + _resolver, # pylint: disable=invalid-name + (_COMMON_SCHEMAS,), +) = facades.jsonschema.resolver(_COMMON_SCHEMAS_FILE) def _spec_to_schema_name( @@ -39,15 +38,15 @@ def _spec_to_schema_name( """ if schema_names is None: - schema_names = _COMMON_SCHEMAS.keys() + schema_names = list(_COMMON_SCHEMAS.keys()) for name in schema_names: try: - jsonschema.validate( + facades.jsonschema.validate( instance=spec, schema=_COMMON_SCHEMAS[name], resolver=_resolver ) return name - except jsonschema.ValidationError: + except facades.jsonschema.ValidationError: continue raise exceptions.SchemaNotFoundError("Specification did not match any schemas.") diff --git a/open_alchemy/utility_base.py b/open_alchemy/utility_base.py index adaadc52..afa5552e 100644 --- a/open_alchemy/utility_base.py +++ b/open_alchemy/utility_base.py @@ -6,8 +6,6 @@ import json import sys import typing -import jsonschema - from . import exceptions from . import facades from . import helpers @@ -134,8 +132,8 @@ class UtilityBase: # Check dictionary schema = cls._get_schema() try: - jsonschema.validate(instance=kwargs, schema=schema) - except jsonschema.ValidationError: + facades.jsonschema.validate(instance=kwargs, schema=schema) + except facades.jsonschema.ValidationError: raise exceptions.MalformedModelDictionaryError( "The dictionary passed to from_dict is not a valid instance of the " "model schema. "
jdkandersson/OpenAlchemy
1172530614fe0c92ffb350d7ea6773b46057b4b8
diff --git a/tests/open_alchemy/facades/test_jsonschema.py b/tests/open_alchemy/facades/test_jsonschema.py new file mode 100644 index 00000000..93b1fd0e --- /dev/null +++ b/tests/open_alchemy/facades/test_jsonschema.py @@ -0,0 +1,79 @@ +"""Tests for jsonschema facade.""" + +import jsonschema +import pytest + +from open_alchemy import facades + + [email protected] +def test_filename_to_dict(tmp_path): + """ + GIVEN file with JSON contents + WHEN _filename_to_dict is called with the name of the file + THEN the dictionary contents of the file are returned. + """ + # pylint: disable=protected-access + # Create file + directory = tmp_path / "json" + directory.mkdir() + json_file = directory / "dict.json" + json_file.write_text('{"key": "value"}') + + returned_dict = facades.jsonschema._filename_to_dict(str(json_file)) + + assert returned_dict == {"key": "value"} + + [email protected] +def test_resolver_single(tmp_path): + """ + GIVEN single file with schema, schema that references that schema and instance of + the schema + WHEN resolver is created and used to validate the instance + THEN no exceptions are raised and the referenced schema is returned as a dictionary. + """ + # Create file + directory = tmp_path / "json" + directory.mkdir() + json_file = directory / "dict.json" + json_file.write_text('{"RefSchema": {"type": "string"}}') + schema = {"$ref": "#/RefSchema"} + instance = "test" + + resolver, (schema_dict,) = facades.jsonschema.resolver(str(json_file)) + jsonschema.validate(instance, schema, resolver=resolver) + assert schema_dict == {"RefSchema": {"type": "string"}} + + [email protected] +def test_resolver_multiple(tmp_path): + """ + GIVEN multiple files with schema, schema that references those schemas and instance + of the schema + WHEN resolver is created and used to validate the instance + THEN no exceptions are raised and the referenced schemas are returned as + dictionaries. + """ + # Create file + directory = tmp_path / "json" + directory.mkdir() + json_file1 = directory / "dict1.json" + json_file1.write_text('{"RefSchema1": {"type": "string"}}') + json_file2 = directory / "dict2.json" + json_file2.write_text('{"RefSchema2": {"type": "integer"}}') + schema = { + "type": "object", + "properties": { + "key1": {"$ref": "#/RefSchema1"}, + "key2": {"$ref": "#/RefSchema2"}, + }, + } + instance = {"key1": "value 1", "key2": 1} + + resolver, (schema1_dict, schema2_dict) = facades.jsonschema.resolver( + str(json_file1), str(json_file2) + ) + jsonschema.validate(instance, schema, resolver=resolver) + assert schema1_dict == {"RefSchema1": {"type": "string"}} + assert schema2_dict == {"RefSchema2": {"type": "integer"}}
Ring fence jsonschema As a developer I want to have a shallow dependency on jsonschema so that it can be switched out for something else in the future. At the moment jsonschema is deep linked into the code. There should be a module with an interface that abstracts away jasonschema behind an interface so that something else could be used in the future.
0.0
1172530614fe0c92ffb350d7ea6773b46057b4b8
[ "tests/open_alchemy/facades/test_jsonschema.py::test_filename_to_dict", "tests/open_alchemy/facades/test_jsonschema.py::test_resolver_multiple", "tests/open_alchemy/facades/test_jsonschema.py::test_resolver_single" ]
[ "tests/open_alchemy/facades/test_jsonschema.py::flake-8::FLAKE8" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-26 02:42:05+00:00
apache-2.0
3,245
jendrikseipp__vulture-220
diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bae76c..deb0d13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * Consider all files under `test` or `tests` directories test files (Jendrik Seipp). * Ignore `logging.Logger.propagate` attribute (Jendrik Seipp). +* Parse mypy / PEP 484 / PEP 526 `# type: ...` comments if on Python 3.8+. + (jingw, #220) # 1.6 (2020-07-28) diff --git a/vulture/core.py b/vulture/core.py index bb5925f..b53c065 100644 --- a/vulture/core.py +++ b/vulture/core.py @@ -203,15 +203,23 @@ class Vulture(ast.NodeVisitor): self.code = code.splitlines() self.noqa_lines = noqa.parse_noqa(self.code) self.filename = filename - try: - node = ast.parse(code, filename=self.filename) - except SyntaxError as err: - text = f' at "{err.text.strip()}"' if err.text else "" + + def handle_syntax_error(e): + text = f' at "{e.text.strip()}"' if e.text else "" print( - f"{utils.format_path(filename)}:{err.lineno}: {err.msg}{text}", + f"{utils.format_path(filename)}:{e.lineno}: {e.msg}{text}", file=sys.stderr, ) self.found_dead_code_or_error = True + + try: + node = ( + ast.parse(code, filename=self.filename, type_comments=True) + if sys.version_info >= (3, 8) # type_comments requires 3.8+ + else ast.parse(code, filename=self.filename) + ) + except SyntaxError as err: + handle_syntax_error(err) except ValueError as err: # ValueError is raised if source contains null bytes. print( @@ -220,7 +228,11 @@ class Vulture(ast.NodeVisitor): ) self.found_dead_code_or_error = True else: - self.visit(node) + # When parsing type comments, visiting can throw SyntaxError. + try: + self.visit(node) + except SyntaxError as err: + handle_syntax_error(err) def scavenge(self, paths, exclude=None): def prepare_pattern(pattern): @@ -603,6 +615,20 @@ class Vulture(ast.NodeVisitor): self._log(lineno, ast.dump(node), line) if visitor: visitor(node) + + # There isn't a clean subset of node types that might have type + # comments, so just check all of them. + type_comment = getattr(node, "type_comment", None) + if type_comment is not None: + mode = ( + "func_type" + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + else "eval" + ) + self.visit( + ast.parse(type_comment, filename="<type_comment>", mode=mode) + ) + return self.generic_visit(node) def _handle_ast_list(self, ast_list):
jendrikseipp/vulture
899a49e6f08e628caf47e886c5d9917374e522c2
diff --git a/tests/test_scavenging.py b/tests/test_scavenging.py index 86f4558..22a4a88 100644 --- a/tests/test_scavenging.py +++ b/tests/test_scavenging.py @@ -1,3 +1,5 @@ +import sys + from . import check, v assert v # Silence pyflakes. @@ -644,16 +646,46 @@ x: List[int] = [1] def test_type_hint_comments(v): v.scan( """\ -import typing +from typing import Any, Dict, List, Text, Tuple + + +def plain_function(arg): + # type: (Text) -> None + pass + +async def async_function(arg): + # type: (List[int]) -> None + pass + +some_var = {} # type: Dict[str, str] + +class Thing: + def __init__(self): + self.some_attr = (1, 2) # type: Tuple[int, int] + +for x in []: # type: Any + print(x) +""" + ) -if typing.TYPE_CHECKING: - from typing import List, Text + if sys.version_info < (3, 8): + check(v.unused_imports, ["Any", "Dict", "List", "Text", "Tuple"]) + else: + check(v.unused_imports, []) + assert not v.found_dead_code_or_error -def foo(foo_li): - # type: (List[Text]) -> None - for bar in foo_li: - bar.xyz() + +def test_invalid_type_comment(v): + v.scan( + """\ +def bad(): + # type: bogus + pass +bad() """ ) - check(v.unused_imports, ["List", "Text"]) + if sys.version_info < (3, 8): + assert not v.found_dead_code_or_error + else: + assert v.found_dead_code_or_error
Ignore type checking imports Code like this is common when type annotations in comments are used in Python: ``` from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Optional, Iterator from abc import xyz ``` These will usually show up as `unused import` as they are only referenced from comments. The code should probably be parsed with a `TYPE_CHECKING=False` in mind.
0.0
899a49e6f08e628caf47e886c5d9917374e522c2
[ "tests/test_scavenging.py::test_type_hint_comments", "tests/test_scavenging.py::test_invalid_type_comment" ]
[ "tests/test_scavenging.py::test_function_object1", "tests/test_scavenging.py::test_function_object2", "tests/test_scavenging.py::test_function1", "tests/test_scavenging.py::test_function2", "tests/test_scavenging.py::test_function3", "tests/test_scavenging.py::test_async_function", "tests/test_scavenging.py::test_async_method", "tests/test_scavenging.py::test_function_and_method1", "tests/test_scavenging.py::test_attribute1", "tests/test_scavenging.py::test_ignored_attributes", "tests/test_scavenging.py::test_callback1", "tests/test_scavenging.py::test_class1", "tests/test_scavenging.py::test_class2", "tests/test_scavenging.py::test_class3", "tests/test_scavenging.py::test_class4", "tests/test_scavenging.py::test_class5", "tests/test_scavenging.py::test_class6", "tests/test_scavenging.py::test_class7", "tests/test_scavenging.py::test_method1", "tests/test_scavenging.py::test_token_types", "tests/test_scavenging.py::test_variable1", "tests/test_scavenging.py::test_variable2", "tests/test_scavenging.py::test_variable3", "tests/test_scavenging.py::test_variable4", "tests/test_scavenging.py::test_variable5", "tests/test_scavenging.py::test_ignored_variables", "tests/test_scavenging.py::test_prop1", "tests/test_scavenging.py::test_prop2", "tests/test_scavenging.py::test_object_attribute", "tests/test_scavenging.py::test_function_names_in_test_file", "tests/test_scavenging.py::test_async_function_name_in_test_file", "tests/test_scavenging.py::test_async_function_name_in_normal_file", "tests/test_scavenging.py::test_function_names_in_normal_file", "tests/test_scavenging.py::test_global_attribute", "tests/test_scavenging.py::test_boolean", "tests/test_scavenging.py::test_builtin_types", "tests/test_scavenging.py::test_unused_args", "tests/test_scavenging.py::test_unused_kwargs", "tests/test_scavenging.py::test_unused_kwargs_with_odd_name", "tests/test_scavenging.py::test_unused_vararg", "tests/test_scavenging.py::test_multiple_definition", "tests/test_scavenging.py::test_arg_type_annotation", "tests/test_scavenging.py::test_var_type_annotation" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-08 18:11:34+00:00
mit
3,246
jendrikseipp__vulture-30
diff --git a/whitelist_python.py b/whitelist_python.py new file mode 100644 index 0000000..8e459e6 --- /dev/null +++ b/whitelist_python.py @@ -0,0 +1,4 @@ +import collections + +collections.defaultdict(list).default_factory = None +collections.defaultdict(list).default_factory
jendrikseipp/vulture
bae51858abe19f3337e5e17cbb170533161d634a
diff --git a/tests/test_whitelist_python.py b/tests/test_whitelist_python.py new file mode 100644 index 0000000..3529af0 --- /dev/null +++ b/tests/test_whitelist_python.py @@ -0,0 +1,15 @@ +import subprocess +import sys + +from .test_script import call_vulture, REPO + +whitelist_file = 'whitelist_python.py' + + +def test_whitelist_python_with_python(): + assert subprocess.call( + [sys.executable, whitelist_file], cwd=REPO) == 0 + + +def test_whitelist_python_with_vulture(): + assert call_vulture([whitelist_file]) == 0
Whitelist defaultdict.default_factory Originally reported by: **bitserver (Bitbucket: [bitserver](https://bitbucket.org/bitserver), GitHub: [bitserver](https://github.com/bitserver))** ---------------------------------------- I have a collections.defaultdict(). After I have finished populating it, I have to set its default_factory attribute to None. vulture then tells me that default_factory is an unused attribute, but I can't help it, as that's how defaultdict works. ---------------------------------------- - Bitbucket: https://bitbucket.org/jendrikseipp/vulture/issue/21
0.0
bae51858abe19f3337e5e17cbb170533161d634a
[ "tests/test_whitelist_python.py::test_whitelist_python_with_python", "tests/test_whitelist_python.py::test_whitelist_python_with_vulture" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2017-03-28 04:49:05+00:00
mit
3,247
jendrikseipp__vulture-340
diff --git a/.gitignore b/.gitignore index df19119..0ec272f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ vulture.egg-info/ .pytest_cache/ .tox/ .venv/ +.vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md index c793814..660b0d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +# next (unreleased) +* Switch to tomllib/tomli to support heterogeneous arrays (Sebastian Csar, #340). + # 2.10 (2023-10-06) * Drop support for Python 3.7 (Jendrik Seipp, #323). diff --git a/setup.py b/setup.py index 3914be9..4854941 100644 --- a/setup.py +++ b/setup.py @@ -47,7 +47,7 @@ setuptools.setup( "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Quality Assurance", ], - install_requires=["toml"], + install_requires=["tomli >= 1.1.0; python_version < '3.11'"], entry_points={"console_scripts": ["vulture = vulture.core:main"]}, python_requires=">=3.8", packages=setuptools.find_packages(exclude=["tests"]), diff --git a/vulture/config.py b/vulture/config.py index 4aa0d2d..4e193fe 100644 --- a/vulture/config.py +++ b/vulture/config.py @@ -5,7 +5,10 @@ command-line arguments or the pyproject.toml file. import argparse import pathlib -import toml +try: + import tomllib +except ModuleNotFoundError: + import tomli as tomllib from .version import __version__ @@ -76,7 +79,7 @@ def _parse_toml(infile): verbose = true paths = ["path1", "path2"] """ - data = toml.load(infile) + data = tomllib.load(infile) settings = data.get("tool", {}).get("vulture", {}) _check_input_config(settings) return settings @@ -194,7 +197,7 @@ def make_config(argv=None, tomlfile=None): else: toml_path = pathlib.Path("pyproject.toml").resolve() if toml_path.is_file(): - with open(toml_path) as fconfig: + with open(toml_path, "rb") as fconfig: config = _parse_toml(fconfig) detected_toml_path = str(toml_path) else:
jendrikseipp/vulture
b6fae7161611e0b820231d1e80432ee746adee50
diff --git a/tests/test_config.py b/tests/test_config.py index 494433d..04ce725 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -2,7 +2,7 @@ Unit tests for config file and CLI argument parsing. """ -from io import StringIO +from io import BytesIO from textwrap import dedent import pytest @@ -17,6 +17,13 @@ from vulture.config import ( ) +def get_toml_bytes(toml_str: str) -> BytesIO: + """ + Wrap a string in BytesIO to play the role of the incoming config stream. + """ + return BytesIO(bytes(toml_str, "utf-8")) + + def test_cli_args(): """ Ensure that CLI arguments are converted to a config object. @@ -62,9 +69,48 @@ def test_toml_config(): sort_by_size=True, verbose=True, ) - data = StringIO( + data = get_toml_bytes( + dedent( + """\ + [tool.vulture] + exclude = ["file*.py", "dir/"] + ignore_decorators = ["deco1", "deco2"] + ignore_names = ["name1", "name2"] + make_whitelist = true + min_confidence = 10 + sort_by_size = true + verbose = true + paths = ["path1", "path2"] + """ + ) + ) + result = _parse_toml(data) + assert isinstance(result, dict) + assert result == expected + + +def test_toml_config_with_heterogenous_array(): + """ + Ensure parsing of TOML files results in a valid config object, even if some + other part of the file contains an array of mixed types. + """ + expected = dict( + paths=["path1", "path2"], + exclude=["file*.py", "dir/"], + ignore_decorators=["deco1", "deco2"], + ignore_names=["name1", "name2"], + make_whitelist=True, + min_confidence=10, + sort_by_size=True, + verbose=True, + ) + data = get_toml_bytes( dedent( """\ + [tool.foo] + # comment for good measure + problem_array = [{a = 1}, [2,3,4], "foo"] + [tool.vulture] exclude = ["file*.py", "dir/"] ignore_decorators = ["deco1", "deco2"] @@ -87,7 +133,7 @@ def test_config_merging(): If we have both CLI args and a ``pyproject.toml`` file, the CLI args should have precedence. """ - toml = StringIO( + toml = get_toml_bytes( dedent( """\ [tool.vulture] @@ -131,7 +177,7 @@ def test_config_merging_missing(): If we have set a boolean value in the TOML file, but not on the CLI, we want the TOML value to be taken. """ - toml = StringIO( + toml = get_toml_bytes( dedent( """\ [tool.vulture] @@ -153,7 +199,7 @@ def test_config_merging_toml_paths_only(): If we have paths in the TOML but not on the CLI, the TOML paths should be used. """ - toml = StringIO( + toml = get_toml_bytes( dedent( """\ [tool.vulture]
Switch to tomli/tomllib for toml parsing Due to https://github.com/uiri/toml/issues/270, vulture won't run for projects with a `pyproject.toml` that contain an array with mixed types. According to https://github.com/python-poetry/poetry/issues/7094#issuecomment-1328127456, this is not an issue in the `tomllib` in Python 3.11+ or its backport (https://github.com/hukkin/tomli). It looks like this should be a quick swap. I'll send a PR along when I have a moment.
0.0
b6fae7161611e0b820231d1e80432ee746adee50
[ "tests/test_config.py::test_toml_config", "tests/test_config.py::test_toml_config_with_heterogenous_array", "tests/test_config.py::test_config_merging", "tests/test_config.py::test_config_merging_missing", "tests/test_config.py::test_config_merging_toml_paths_only" ]
[ "tests/test_config.py::test_cli_args", "tests/test_config.py::test_invalid_config_options_output", "tests/test_config.py::test_incompatible_option_type[min_confidence-0]", "tests/test_config.py::test_incompatible_option_type[paths-value1]", "tests/test_config.py::test_incompatible_option_type[exclude-value2]", "tests/test_config.py::test_incompatible_option_type[ignore_decorators-value3]", "tests/test_config.py::test_incompatible_option_type[ignore_names-value4]", "tests/test_config.py::test_incompatible_option_type[make_whitelist-False]", "tests/test_config.py::test_incompatible_option_type[sort_by_size-False]", "tests/test_config.py::test_incompatible_option_type[verbose-False]", "tests/test_config.py::test_missing_paths" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-23 20:26:37+00:00
mit
3,248
jerry-git__logplot-11
diff --git a/src/logplot/conf.py b/src/logplot/conf.py index 462fb25..4dd6e2a 100644 --- a/src/logplot/conf.py +++ b/src/logplot/conf.py @@ -4,7 +4,16 @@ import yaml General = namedtuple( - "General", ["log_open_cmd", "default_entry_style", "click_hit_tolerance", "shell"] + "General", + [ + "log_open_cmd", + "default_entry_style", + "click_hit_tolerance", + "shell", + "plot_title", + "x_axis_name", + "y_axis_name", + ], ) General.__new__.__defaults__ = (None,) * len(General._fields) diff --git a/src/logplot/default_conf.yaml b/src/logplot/default_conf.yaml index 9805959..cf8e225 100644 --- a/src/logplot/default_conf.yaml +++ b/src/logplot/default_conf.yaml @@ -3,3 +3,7 @@ general: shell: false # boolean given to as shell argument to subprocess function calls (e.g Popen) default_entry_style: '-o' click_hit_tolerance: 5 + + plot_title: 'Magical Log Plot' + x_axis_name: 'value' + y_axis_name: 'line number' diff --git a/src/logplot/plot.py b/src/logplot/plot.py index a77cbe4..422994a 100644 --- a/src/logplot/plot.py +++ b/src/logplot/plot.py @@ -1,44 +1,111 @@ +from collections import defaultdict import os import subprocess import sys import shlex import matplotlib.pyplot as plt +from matplotlib.lines import Line2D import numpy as np +TEMP_COLOR = "black" + + class Plot: def __init__(self, entries, special_entries, log_path, conf): self._entries = entries self._special_entries = special_entries self._log_path = log_path self._conf = conf + self._legend_mapping = {} self._initialise() plt.show() def _initialise(self): - fig, ax = plt.subplots() - fig.canvas.callbacks.connect("pick_event", self._data_point_click_callback) + self._fig, self._ax = plt.subplots() + self._fig.canvas.callbacks.connect("pick_event", self._click_callback) x, y = [], [] - default_style = self._conf.general.default_entry_style - pick = self._conf.general.click_hit_tolerance + trend_mapping = defaultdict(list) + + def add_line(): + nonlocal x, y + if x and y: + line = self._ax.plot( + x, + y, + self._conf.general.default_entry_style, + picker=self._conf.general.click_hit_tolerance, + zorder=-32, + color=TEMP_COLOR, + )[0] + trend_mapping[str(y)].append(line) + x, y = [], [] for entry in self._entries: if entry.conf_entry.initial_state: - ax.plot(x, y, default_style, picker=pick) - x, y = [], [] + add_line() x.append(entry.line_number) y.append(entry.conf_entry.value) - ax.plot(x, y, default_style, picker=pick) + # last line + add_line() + + self._add_special_entries() + self._create_legend(trend_mapping) + self._add_naming() + + def _add_special_entries(self): for entry in self._special_entries: - style = entry.conf_entry.style or default_style - ax.plot(entry.line_number, entry.conf_entry.value, style, picker=pick) + style = entry.conf_entry.style or self._conf.general.default_entry_style + self._ax.plot( + entry.line_number, + entry.conf_entry.value, + style, + picker=self._conf.general.click_hit_tolerance, + ) + + def _create_legend(self, trend_mapping): + # shrink the plot area a bit to fit the legend outside + box = self._ax.get_position() + self._ax.set_position([box.x0, box.y0, box.width * 0.95, box.height]) + + legend_dummy_lines, lines_list = [], [] + for lines in trend_mapping.values(): + color = next(self._ax._get_lines.prop_cycler)["color"] + for line in lines: + line.set_color(color) + + legend_line = Line2D([0], [0], color=color, lw=4) + legend_dummy_lines.append(legend_line) + lines_list.append(lines) + + self._legend = self._ax.legend( + legend_dummy_lines, + [""] * len(legend_dummy_lines), + loc="center left", + bbox_to_anchor=(1, 0.5), + ) + for idx, legend_line in enumerate(self._legend.get_lines()): + legend_line.set_picker(5) + self._legend_mapping[legend_line] = lines_list[idx] + + def _add_naming(self): + self._fig.suptitle(self._conf.general.plot_title) + plt.xlabel(self._conf.general.y_axis_name) + plt.ylabel(self._conf.general.x_axis_name) - def _data_point_click_callback(self, event): - x_data, y_data = event.artist.get_data() - x_val = np.take(x_data, event.ind)[0] - self._open_log_viewer(line_number=x_val) + def _click_callback(self, event): + if event.artist in self._legend_mapping: # click in legend + for line in self._legend_mapping[event.artist]: + # toggle visibility + line.set_visible(not line.get_visible()) + self._fig.canvas.draw() + elif event.artist.get_visible(): # click in plot + x_data, y_data = event.artist.get_data() + x_val = np.take(x_data, event.ind)[0] + # y_val = np.take(y_data, event.ind)[0] + self._open_log_viewer(line_number=x_val) def _open_log_viewer(self, line_number=None): cmd = self._conf.general.log_open_cmd
jerry-git/logplot
ed54bd9162bd7bc901c1f448f7ac25cd5d49feaa
diff --git a/tests/data/conf/expected_json_1_1.txt b/tests/data/conf/expected_json_1_1.txt index 28b9625..efdb69c 100644 --- a/tests/data/conf/expected_json_1_1.txt +++ b/tests/data/conf/expected_json_1_1.txt @@ -1,1 +1,1 @@ -[["default-command", null, null, null], [["ID1", 1, null, true], ["ID2", 2, null, null], ["ID3", 3, null, null]], []] \ No newline at end of file +[["default-command", null, null, null, null, null, null], [["ID1", 1, null, true], ["ID2", 2, null, null], ["ID3", 3, null, null]], []] \ No newline at end of file diff --git a/tests/data/conf/expected_json_1_2.txt b/tests/data/conf/expected_json_1_2.txt index 52a6be7..14a9cd3 100644 --- a/tests/data/conf/expected_json_1_2.txt +++ b/tests/data/conf/expected_json_1_2.txt @@ -1,1 +1,1 @@ -[["overridden command {line_number}", null, null, null], [["ID1", 1, null, null], ["ID2", 2, null, null], ["ID3", 3, null, null]], []] \ No newline at end of file +[["overridden command {line_number}", null, null, null, null, null, null], [["ID1", 1, null, null], ["ID2", 2, null, null], ["ID3", 3, null, null]], []] \ No newline at end of file
Add feature for selecting which series are visible in the plot It'd be nice to be able to filter out certain series to have less noise in the plot. Potential UX: * Similar series are grouped under one toggle (e.g. legend) * User can click the toggle to hide/show the series belonging to that group * Naming of these groups?
0.0
ed54bd9162bd7bc901c1f448f7ac25cd5d49feaa
[ "tests/test_conf.py::TestRead::test_it_reads[1-1]", "tests/test_conf.py::TestRead::test_it_reads[1-2]" ]
[ "tests/test_log.py::TestParse::test_it_parses[1-1]", "tests/test_plot.py::TestOpenLogViewer::test_it_passes_correct_params_to_popen[-False-linux-foo/bar/log.txt-expected0]", "tests/test_plot.py::TestOpenLogViewer::test_it_passes_correct_params_to_popen[-False-darwin-foo/bar/log.txt-expected1]", "tests/test_plot.py::TestOpenLogViewer::test_it_passes_correct_params_to_popen[custom_cmd", "tests/test_plot.py::TestOpenLogViewer::test_it_calls_startfile_on_windows_as_default" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-10-06 21:08:35+00:00
mit
3,249
jitsi__jiwer-63
diff --git a/README.md b/README.md index 0b1633b..abf8839 100644 --- a/README.md +++ b/README.md @@ -211,9 +211,8 @@ print(jiwer.RemoveWhiteSpace(replace_by_space=True)(sentences)) #### RemovePunctuation -`jiwer.RemovePunctuation()` can be used to filter out punctuation. The punctuation characters are: - -``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'`` +`jiwer.RemovePunctuation()` can be used to filter out punctuation. The punctuation characters are defined as +all unicode characters whose catogary name starts with `P`. See https://www.unicode.org/reports/tr44/#General_Category_Values. Example: ```python diff --git a/jiwer/transforms.py b/jiwer/transforms.py index 1f717bb..024f82e 100644 --- a/jiwer/transforms.py +++ b/jiwer/transforms.py @@ -21,8 +21,10 @@ This file implements the building blocks for transforming a collection of input strings to the desired format in order to calculate the WER. """ +import sys import re import string +import unicodedata from typing import Union, List, Mapping @@ -189,9 +191,12 @@ class RemoveWhiteSpace(BaseRemoveTransform): class RemovePunctuation(BaseRemoveTransform): def __init__(self): - characters = [c for c in string.punctuation] + codepoints = range(sys.maxunicode + 1) + punctuation = set( + chr(i) for i in codepoints if unicodedata.category(chr(i)).startswith("P") + ) - super().__init__(characters) + super().__init__(list(punctuation)) class RemoveMultipleSpaces(AbstractTransform):
jitsi/jiwer
332e6a14840b989942cf3467e4003f2b7d0c24ed
diff --git a/tests/test_transforms.py b/tests/test_transforms.py index 834c455..552e599 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -205,6 +205,16 @@ class TestRemovePunctuation(unittest.TestCase): cases = [ (["this is an example!", "this is an example"]), (["hello. goodbye", "hello goodbye"]), + (["this sentence has no punctuation", "this sentence has no punctuation"]), + ] + + _apply_test_on(self, RemovePunctuation(), cases) + + def test_non_ascii_punctuation(self): + cases = [ + (["word༆’'", "word"]), + (["‘no’", "no"]), + (["“yes”", "yes"]), ] _apply_test_on(self, RemovePunctuation(), cases)
RemovePunctuation does not remove smart/curly quotes RemovePunctuation does not remove the following: ‘ ’ “ ”
0.0
332e6a14840b989942cf3467e4003f2b7d0c24ed
[ "tests/test_transforms.py::TestRemovePunctuation::test_non_ascii_punctuation" ]
[ "tests/test_transforms.py::TestReduceToSingleSentence::test_delimiter", "tests/test_transforms.py::TestReduceToSingleSentence::test_normal", "tests/test_transforms.py::TestReduceToListOfListOfWords::test_delimiter", "tests/test_transforms.py::TestReduceToListOfListOfWords::test_normal", "tests/test_transforms.py::TestReduceToListOfListOfChars::test_delimiter", "tests/test_transforms.py::TestReduceToListOfListOfChars::test_normal", "tests/test_transforms.py::TestRemoveSpecificWords::test_normal", "tests/test_transforms.py::TestRemoveWhiteSpace::test_normal", "tests/test_transforms.py::TestRemoveWhiteSpace::test_replace_by_space", "tests/test_transforms.py::TestRemovePunctuation::test_normal", "tests/test_transforms.py::TestRemoveMultipleSpaces::test_normal", "tests/test_transforms.py::TestSubstituteWords::test_normal", "tests/test_transforms.py::TestSubstituteRegexes::test_normal", "tests/test_transforms.py::TestStrip::test_normal", "tests/test_transforms.py::TestRemoveEmptyStrings::test_normal", "tests/test_transforms.py::TestExpandCommonEnglishContractions::test_normal", "tests/test_transforms.py::TestToLowerCase::test_normal", "tests/test_transforms.py::TestToUpperCase::test_normal", "tests/test_transforms.py::TestRemoveKaldiNonWords::test_normal" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-03 08:42:39+00:00
apache-2.0
3,250
jitsi__jiwer-64
diff --git a/README.md b/README.md index 0b1633b..c2ccc60 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,8 @@ print(jiwer.ReduceToSingleSentence()(sentences)) #### RemoveSpecificWords `jiwer.RemoveSpecificWords(words_to_remove: List[str])` can be used to filter out certain words. +As words are replaced with a ` ` character, make sure to that `jiwer.RemoveMultipleSpaces`, +`jiwer.Strip()` and `jiwer.RemoveEmptyStrings` are present in the composition _after_ `jiwer.RemoveSpecificWords`. Example: ```python @@ -184,7 +186,8 @@ import jiwer sentences = ["yhe awesome", "the apple is not a pear", "yhe"] print(jiwer.RemoveSpecificWords(["yhe", "the", "a"])(sentences)) -# prints: ["awesome", "apple is pear", ""] +# prints: [' awesome', ' apple is not pear', ' '] +# note the extra spaces ``` #### RemoveWhiteSpace @@ -194,6 +197,9 @@ The whitespace characters are ` `, `\t`, `\n`, `\r`, `\x0b` and `\x0c`. Note that by default space (` `) is also removed, which will make it impossible to split a sentence into a list of words by using `ReduceToListOfListOfWords` or `ReduceToSingleSentence`. This can be prevented by replacing all whitespace with the space character. +If so, make sure that `jiwer.RemoveMultipleSpaces`, +`jiwer.Strip()` and `jiwer.RemoveEmptyStrings` are present in the composition _after_ `jiwer.RemoveWhiteSpace`. + Example: ```python @@ -211,9 +217,8 @@ print(jiwer.RemoveWhiteSpace(replace_by_space=True)(sentences)) #### RemovePunctuation -`jiwer.RemovePunctuation()` can be used to filter out punctuation. The punctuation characters are: - -``'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'`` +`jiwer.RemovePunctuation()` can be used to filter out punctuation. The punctuation characters are defined as +all unicode characters whose catogary name starts with `P`. See https://www.unicode.org/reports/tr44/#General_Category_Values. Example: ```python diff --git a/jiwer/transforms.py b/jiwer/transforms.py index 1f717bb..e00abfe 100644 --- a/jiwer/transforms.py +++ b/jiwer/transforms.py @@ -21,8 +21,10 @@ This file implements the building blocks for transforming a collection of input strings to the desired format in order to calculate the WER. """ +import sys import re import string +import unicodedata from typing import Union, List, Mapping @@ -170,9 +172,33 @@ class ReduceToSingleSentence(AbstractTransform): return ["{}".format(self.word_delimiter).join(filtered_inp)] -class RemoveSpecificWords(BaseRemoveTransform): +class SubstituteRegexes(AbstractTransform): + def __init__(self, substitutions: Mapping[str, str]): + self.substitutions = substitutions + + def process_string(self, s: str): + for key, value in self.substitutions.items(): + s = re.sub(key, value, s) + + return s + + +class SubstituteWords(AbstractTransform): + def __init__(self, substitutions: Mapping[str, str]): + self.substitutions = substitutions + + def process_string(self, s: str): + for key, value in self.substitutions.items(): + s = re.sub(r"\b{}\b".format(re.escape(key)), value, s) + + return s + + +class RemoveSpecificWords(SubstituteWords): def __init__(self, words_to_remove: List[str]): - super().__init__(words_to_remove) + mapping = {word: " " for word in words_to_remove} + + super().__init__(mapping) class RemoveWhiteSpace(BaseRemoveTransform): @@ -189,9 +215,12 @@ class RemoveWhiteSpace(BaseRemoveTransform): class RemovePunctuation(BaseRemoveTransform): def __init__(self): - characters = [c for c in string.punctuation] + codepoints = range(sys.maxunicode + 1) + punctuation = set( + chr(i) for i in codepoints if unicodedata.category(chr(i)).startswith("P") + ) - super().__init__(characters) + super().__init__(list(punctuation)) class RemoveMultipleSpaces(AbstractTransform): @@ -237,28 +266,6 @@ class ExpandCommonEnglishContractions(AbstractTransform): return s -class SubstituteWords(AbstractTransform): - def __init__(self, substitutions: Mapping[str, str]): - self.substitutions = substitutions - - def process_string(self, s: str): - for key, value in self.substitutions.items(): - s = re.sub(r"\b{}\b".format(re.escape(key)), value, s) - - return s - - -class SubstituteRegexes(AbstractTransform): - def __init__(self, substitutions: Mapping[str, str]): - self.substitutions = substitutions - - def process_string(self, s: str): - for key, value in self.substitutions.items(): - s = re.sub(key, value, s) - - return s - - class ToLowerCase(AbstractTransform): def process_string(self, s: str): return s.lower()
jitsi/jiwer
332e6a14840b989942cf3467e4003f2b7d0c24ed
diff --git a/tests/test_transforms.py b/tests/test_transforms.py index 834c455..62be954 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -168,18 +168,26 @@ class TestReduceToListOfListOfChars(unittest.TestCase): class TestRemoveSpecificWords(unittest.TestCase): def test_normal(self): cases = [ - ("yhe about that bug", " about that bug"), - ("yeah about that bug", " about that bug"), - ("one bug", "one bug"), - (["yhe", "about", "bug"], ["", "about", "bug"]), - (["yeah", "about", "bug"], ["", "about", "bug"]), + (["yhe about that bug"], [" about that bug"]), + (["yeah about that bug"], [" about that bug"]), + (["one bug"], ["one bug"]), + (["yhe", "about", "bug"], [" ", "about", "bug"]), + (["yeah", "about", "bug"], [" ", "about", "bug"]), (["one", "bug"], ["one", "bug"]), - (["yhe about bug"], [" about bug"]), - (["yeah about bug"], [" about bug"]), + (["yhe about bug"], [" about bug"]), + (["yeah about bug"], [" about bug"]), + (["about bug yhe"], ["about bug "]), (["one bug"], ["one bug"]), + (["he asked a helpful question"], [" asked helpful question"]), + (["normal sentence"], ["normal sentence"]), + (["yhe awesome", " awesome"]), + (["the apple is not a pear", " apple is not pear"]), + (["yhe", " "]), ] - _apply_test_on(self, RemoveSpecificWords(["yhe", "yeah"]), cases) + _apply_test_on( + self, RemoveSpecificWords(["yhe", "yeah", "a", "he", "the"]), cases + ) class TestRemoveWhiteSpace(unittest.TestCase): @@ -205,6 +213,16 @@ class TestRemovePunctuation(unittest.TestCase): cases = [ (["this is an example!", "this is an example"]), (["hello. goodbye", "hello goodbye"]), + (["this sentence has no punctuation", "this sentence has no punctuation"]), + ] + + _apply_test_on(self, RemovePunctuation(), cases) + + def test_non_ascii_punctuation(self): + cases = [ + (["word༆’'", "word"]), + (["‘no’", "no"]), + (["“yes”", "yes"]), ] _apply_test_on(self, RemovePunctuation(), cases)
RemoveSpecificWords is not functioning as expected Hi! As the title says, the `RemoveSpecificWords` function does not work as I would expect it to. As an example, the following code ``` text = "he asked a helpful question" stop_words = ['a', 'he'] print(jiwer.Compose([ jiwer.ToLowerCase(), jiwer.RemoveMultipleSpaces(), jiwer.Strip(), jiwer.SentencesToListOfWords(), jiwer.RemoveEmptyStrings(), jiwer.RemovePunctuation(), jiwer.RemoveSpecificWords(stop_words), ])(text)) ``` returns `['', 'sked', '', 'lpful', 'question']` Is there a way to get this function recognize word boundaries? Thank you!
0.0
332e6a14840b989942cf3467e4003f2b7d0c24ed
[ "tests/test_transforms.py::TestRemoveSpecificWords::test_normal", "tests/test_transforms.py::TestRemovePunctuation::test_non_ascii_punctuation" ]
[ "tests/test_transforms.py::TestReduceToSingleSentence::test_delimiter", "tests/test_transforms.py::TestReduceToSingleSentence::test_normal", "tests/test_transforms.py::TestReduceToListOfListOfWords::test_delimiter", "tests/test_transforms.py::TestReduceToListOfListOfWords::test_normal", "tests/test_transforms.py::TestReduceToListOfListOfChars::test_delimiter", "tests/test_transforms.py::TestReduceToListOfListOfChars::test_normal", "tests/test_transforms.py::TestRemoveWhiteSpace::test_normal", "tests/test_transforms.py::TestRemoveWhiteSpace::test_replace_by_space", "tests/test_transforms.py::TestRemovePunctuation::test_normal", "tests/test_transforms.py::TestRemoveMultipleSpaces::test_normal", "tests/test_transforms.py::TestSubstituteWords::test_normal", "tests/test_transforms.py::TestSubstituteRegexes::test_normal", "tests/test_transforms.py::TestStrip::test_normal", "tests/test_transforms.py::TestRemoveEmptyStrings::test_normal", "tests/test_transforms.py::TestExpandCommonEnglishContractions::test_normal", "tests/test_transforms.py::TestToLowerCase::test_normal", "tests/test_transforms.py::TestToUpperCase::test_normal", "tests/test_transforms.py::TestRemoveKaldiNonWords::test_normal" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-03 09:50:05+00:00
apache-2.0
3,251
jitsi__jiwer-77
diff --git a/jiwer/measures.py b/jiwer/measures.py index 29ba0b9..ba55a6f 100644 --- a/jiwer/measures.py +++ b/jiwer/measures.py @@ -69,7 +69,7 @@ def wer( reference_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, hypothesis_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, truth: Union[str, List[str]] = None, - truth_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, + truth_transform: Union[tr.Compose, tr.AbstractTransform] = None, ) -> float: """ Calculate the word error rate (WER) between one or more reference and @@ -100,18 +100,17 @@ def wer( reference_transform, hypothesis_transform, ) = _deprecate_truth( - reference, - hypothesis, - truth, - reference_transform, - truth_transform, - hypothesis_transform, + reference=reference, + hypothesis=hypothesis, + truth=truth, + reference_transform=reference_transform, + truth_transform=truth_transform, + hypothesis_transform=hypothesis_transform, ) output = process_words( reference, hypothesis, reference_transform, hypothesis_transform ) - return output.wer @@ -121,7 +120,7 @@ def mer( reference_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, hypothesis_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, truth: Union[str, List[str]] = None, - truth_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, + truth_transform: Union[tr.Compose, tr.AbstractTransform] = None, ) -> float: """ Calculate the match error rate (MER) between one or more reference and @@ -152,12 +151,12 @@ def mer( reference_transform, hypothesis_transform, ) = _deprecate_truth( - reference, - hypothesis, - truth, - reference_transform, - truth_transform, - hypothesis_transform, + reference=reference, + hypothesis=hypothesis, + truth=truth, + reference_transform=reference_transform, + truth_transform=truth_transform, + hypothesis_transform=hypothesis_transform, ) output = process_words( @@ -173,7 +172,7 @@ def wip( reference_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, hypothesis_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, truth: Union[str, List[str]] = None, - truth_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, + truth_transform: Union[tr.Compose, tr.AbstractTransform] = None, ) -> float: """ Calculate the word information preserved (WIP) between one or more reference and @@ -204,12 +203,12 @@ def wip( reference_transform, hypothesis_transform, ) = _deprecate_truth( - reference, - hypothesis, - truth, - reference_transform, - truth_transform, - hypothesis_transform, + reference=reference, + hypothesis=hypothesis, + truth=truth, + reference_transform=reference_transform, + truth_transform=truth_transform, + hypothesis_transform=hypothesis_transform, ) output = process_words( @@ -225,7 +224,7 @@ def wil( reference_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, hypothesis_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, truth: Union[str, List[str]] = None, - truth_transform: Union[tr.Compose, tr.AbstractTransform] = wer_default, + truth_transform: Union[tr.Compose, tr.AbstractTransform] = None, ) -> float: """ Calculate the word information lost (WIL) between one or more reference and @@ -256,12 +255,12 @@ def wil( reference_transform, hypothesis_transform, ) = _deprecate_truth( - reference, - hypothesis, - truth, - reference_transform, - truth_transform, - hypothesis_transform, + reference=reference, + hypothesis=hypothesis, + truth=truth, + reference_transform=reference_transform, + truth_transform=truth_transform, + hypothesis_transform=hypothesis_transform, ) output = process_words( @@ -337,7 +336,7 @@ def cer( hypothesis_transform: Union[tr.Compose, tr.AbstractTransform] = cer_default, return_dict: bool = False, truth: Union[str, List[str]] = None, - truth_transform: Union[tr.Compose, tr.AbstractTransform] = cer_default, + truth_transform: Union[tr.Compose, tr.AbstractTransform] = None, ) -> Union[float, Dict[str, Any]]: """ Calculate the character error rate (CER) between one or more reference and @@ -373,12 +372,12 @@ def cer( reference_transform, hypothesis_transform, ) = _deprecate_truth( - reference, - hypothesis, - truth, - reference_transform, - truth_transform, - hypothesis_transform, + reference=reference, + hypothesis=hypothesis, + truth=truth, + reference_transform=reference_transform, + truth_transform=truth_transform, + hypothesis_transform=hypothesis_transform, ) output = process_characters(
jitsi/jiwer
6e620ab7ab658955dafef55300a160fd7a636ea8
diff --git a/tests/test_measures.py b/tests/test_measures.py index 88677ed..50fc744 100644 --- a/tests/test_measures.py +++ b/tests/test_measures.py @@ -359,6 +359,50 @@ class TestMeasuresDefaultTransform(unittest.TestCase): method(reference="only ref") method(hypothesis="only hypothesis") + def test_deprecated_truth_and_ref_with_transform(self): + wer_transform = jiwer.Compose( + [ + jiwer.ToLowerCase(), + jiwer.RemoveMultipleSpaces(), + jiwer.Strip(), + jiwer.ReduceToListOfListOfWords(), + ] + ) + cer_transform = jiwer.Compose( + [ + jiwer.ToLowerCase(), + jiwer.RemoveMultipleSpaces(), + jiwer.Strip(), + jiwer.ReduceToListOfListOfChars(), + ] + ) + + for key, method in [ + ("wer", jiwer.wer), + ("mer", jiwer.mer), + ("wil", jiwer.wil), + ("wip", jiwer.wip), + ("cer", jiwer.cer), + ]: + if key == "cer": + tr = cer_transform + else: + tr = wer_transform + + result = method( + truth="This is a short Sentence with a few Words with upper and Lower cases", + hypothesis="His is a short Sentence with a few Words with upper and Lower cases", + truth_transform=tr, + hypothesis_transform=tr, + ) + result_same = method( + reference="This is a short Sentence with a few Words with upper and Lower cases", + hypothesis="His is a short Sentence with a few Words with upper and Lower cases", + reference_transform=tr, + hypothesis_transform=tr, + ) + self.assertAlmostEqual(result, result_same) + def test_deprecate_compute_measures(): # TODO: remove once deprecated
Version 3.0.0 can produce wrong results Hi, when I use jiwer version 3.0.0 with the following commands: ```python wer_transform = jiwer.Compose( [ jiwer.ToLowerCase(), jiwer.RemoveMultipleSpaces(), jiwer.Strip(), jiwer.ReduceToListOfListOfWords(), ] ) wer = jiwer.wer( truth = 'This is a short Sentence with a few Words with upper and Lower cases', hypothesis = 'His is a short Sentence with a few Words with upper and Lower cases', truth_transform = wer_transform, hypothesis_transform = wer_transform, ) ``` I get wer=0.0714, which is the expected result based on the WER formula. But when I use the non-deprecated keywords 'reference' and 'reference_transform' instead of 'truth' and 'truth_transform': ```python wer = jiwer.wer( reference = 'This is a short Sentence with a few Words with upper and Lower cases', hypothesis = 'His is a short Sentence with a few Words with upper and Lower cases', reference_transform = wer_transform, hypothesis_transform = wer_transform, ) ``` I get wer=0.2857, which is clearly wrong. This does not happen if the 'jiwer.ToLowerCase()' transform is removed from the transformation, thus I expect the bug to be related to that. Cheers, Paul
0.0
6e620ab7ab658955dafef55300a160fd7a636ea8
[ "tests/test_measures.py::TestMeasuresDefaultTransform::test_deprecated_truth_and_ref_with_transform" ]
[ "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_different_sentence_length_equal_type", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_different_sentence_length_unequaL_type", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_fail_on_empty_reference", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_input_ref_list_hyp_list", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_input_ref_list_hyp_string", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_input_ref_string_hyp_list", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_input_ref_string_hyp_string", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_known_values", "tests/test_measures.py::TestMeasuresContiguousSentencesTransform::test_permutations_variance", "tests/test_measures.py::TestMeasuresDefaultTransform::test_deprecated_truth_and_ref", "tests/test_measures.py::TestMeasuresDefaultTransform::test_fail_on_different_sentence_length", "tests/test_measures.py::TestMeasuresDefaultTransform::test_fail_on_empty_reference", "tests/test_measures.py::TestMeasuresDefaultTransform::test_input_gt_list_h_list", "tests/test_measures.py::TestMeasuresDefaultTransform::test_input_gt_list_h_string", "tests/test_measures.py::TestMeasuresDefaultTransform::test_input_gt_string_h_list", "tests/test_measures.py::TestMeasuresDefaultTransform::test_input_gt_string_h_string", "tests/test_measures.py::TestMeasuresDefaultTransform::test_known_values", "tests/test_measures.py::TestMeasuresDefaultTransform::test_permutations_invariance", "tests/test_measures.py::test_deprecate_compute_measures" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-28 18:30:57+00:00
apache-2.0
3,252
jjhelmus__nmrglue-216
diff --git a/nmrglue/analysis/peakpick.py b/nmrglue/analysis/peakpick.py index 8eeda0d..17e46f5 100644 --- a/nmrglue/analysis/peakpick.py +++ b/nmrglue/analysis/peakpick.py @@ -535,7 +535,7 @@ def find_pseg_slice(data, location, thres): stop = stop + 1 al[dim] = stop seg_slice.append(slice(start + 1, stop)) - return seg_slice + return tuple(seg_slice) def find_nseg_slice(data, location, thres): @@ -558,4 +558,4 @@ def find_nseg_slice(data, location, thres): stop = stop + 1 al[dim] = stop seg_slice.append(slice(start + 1, stop)) - return seg_slice + return tuple(seg_slice)
jjhelmus/nmrglue
f17caaf98e315dde63d4c4e0bea127b247d9f70d
diff --git a/tests/test_peakpick.py b/tests/test_peakpick.py new file mode 100644 index 0000000..5895715 --- /dev/null +++ b/tests/test_peakpick.py @@ -0,0 +1,245 @@ +import nmrglue as ng +import numpy as np +import pytest + + +_ONE_D_PEAKS = { + "shape": (1024,), + "positions": [100, 200, 300, 400, 500], + "lws": [10, 20, 10, 20, 10], + "amps": [100, 200, 300, 300, 150], + "vparams": [0.2, 0.4, 0.2, 0.5, 1.0], +} + +_TWO_D_PEAKS = { + "shape": (512, 128), + "positions": [(100, 100), (200, 53), (300, 110), (400, 75)], + "lws": [(10, 5), (20, 5), (10, 5), (20, 5)], + "amps": [100, 200, 300, 300], + "vparams": [(0.2, 0.2), (0.4, 0.4), (0.2, 0.2), (0.5, 0.4)], +} + + +_THREE_D_PEAKS = { + "shape": (256, 64, 64), + "positions": [(150, 24, 22), (200, 10, 50), (210, 50, 10), (77, 30, 15)], + "lws": [(5, 5, 5), (3, 8, 5), (7, 5, 5), (7, 6, 5)], + "amps": [100, 200, 300, 300], + "vparams": [(0.2, 0.2, 0.3), (0.5, 0.4, 0.4), (0.1, 0.2, 0.2), (0.3, 0.5, 0.4)], +} + + +def _generate_1d_data(shape, positions, lws, amps, vparams): + """ + Generates a test 1d dataset with multiple peaks + + Parameters + ---------- + shape : Iterable[int] + shape of the numpy array to be created + positions : Iterable[int] + a list of the positions of the peaks + lws : Iterable[float|int] + a list of linewidths for each peak + amps : Iterable[float|int] + a list of amplitudes for each peak + vparams : Iterable[float|int] + a list of list containing the eta parameter + for the pseudo voigt lineshape + + Returns + ------- + numpy.ndarray + simulated one-d dataset + + """ + data = ng.linesh.sim_NDregion( + shape=shape, + lineshapes=["pv"], + params=[[(pos, lws, vp)] for pos, lws, vp in zip(positions, lws, vparams)], + amps=amps, + ) + return data + + +def _generate_2d_data(dataset): + """ + Generates a test 2d dataset with multiple peaks + + Parameters + ---------- + shape : Iterable[Iterable[int, int]] + shape of the numpy array to be created + positions : Iterable[Iterable[int, int]] + a list of list of two positions for each peak + lws : Iterable[Iterable[float, float]] + a list of list of two linewidths for each peak + amps : Iterable[Iterable[float, float]] + a list of list of two amplitudes for each peak + vparams : Iterable[Iterable[float, float]] + a list of list containing 2 values for the + eta parameter for the pseud-voigt lineshape + + Returns + ------- + numpy.ndarray + simulated two-d dataset + + """ + params = [] + for i in range(len(dataset["positions"])): + d = [[], []] + for j in range(2): + d[j] = ( + dataset["positions"][i][j], + dataset["lws"][i][j], + dataset["vparams"][i][j], + ) + + params.append(d) + + data = ng.linesh.sim_NDregion( + shape=(512, 128), lineshapes=["pv", "pv"], params=params, amps=dataset["amps"] + ) + + return data + + +def _generate_3d_data(dataset): + """ + Generates a test 3d dataset with multiple peaks + + Parameters + ---------- + shape : Iterable[Iterable[int, int, int]] + shape of the numpy array to be created + positions : Iterable[Iterable[int, int, int]] + a list of list of three positions for each peak + lws : Iterable[Iterable[float, float, float]] + a list of list of three linewidths for each peak + amps : Iterable[Iterable[float, float, float]] + a list of list of three amplitudes for each peak + vparams : Iterable[Iterable[float, float, float]] + a list of list containing three values for the + eta parameter for the pseud-voigt lineshape + + Returns + ------- + numpy.ndarray + simulated three-d dataset + + """ + params = [] + for i in range(len(dataset["positions"])): + d = [[], [], []] + for j in range(3): + d[j] = ( + dataset["positions"][i][j], + dataset["lws"][i][j], + dataset["vparams"][i][j], + ) + + params.append(d) + + data = ng.linesh.sim_NDregion( + shape=(256, 64, 64), + lineshapes=["pv", "pv", "pv"], + params=params, + amps=dataset["amps"], + ) + + return data + + +def _test_1d(dataset, algorithm, msep=None, rtol=1): + """test 1d peak picking""" + + data = _generate_1d_data(**dataset) + peaks = ng.peakpick.pick(data, pthres=50, algorithm=algorithm, msep=msep) + assert np.allclose(peaks.X_AXIS, dataset["positions"], rtol=1) + + +def _test_2d(dataset, algorithm, msep=None, rtol=1): + """test 2d peak picking""" + + data = _generate_2d_data(dataset) + peaks = ng.peakpick.pick(data, pthres=50, algorithm=algorithm, msep=msep) + assert np.allclose(peaks.X_AXIS, [i[1] for i in dataset["positions"]], rtol=1) + assert np.allclose(peaks.Y_AXIS, [i[0] for i in dataset["positions"]], rtol=1) + + +def _test_3d(dataset, algorithm, msep=None, rtol=1): + """test 3d peak picking""" + + data = _generate_3d_data(dataset) + peaks = ng.peakpick.pick(data, pthres=50, algorithm=algorithm, msep=msep) + + assert np.allclose( + sorted(peaks.X_AXIS), sorted([i[2] for i in dataset["positions"]]), rtol=rtol + ) + assert np.allclose( + sorted(peaks.Y_AXIS), sorted([i[1] for i in dataset["positions"]]), rtol=rtol + ) + assert np.allclose( + sorted(peaks.Z_AXIS), sorted([i[0] for i in dataset["positions"]]), rtol=rtol + ) + + [email protected] +def test_1d_connected(): + _test_1d(dataset=_ONE_D_PEAKS, algorithm="connected") + + [email protected] +def test_1d_downward(): + _test_1d(dataset=_ONE_D_PEAKS, algorithm="downward") + + [email protected] +def test_1d_thres(): + _test_1d(dataset=_ONE_D_PEAKS, algorithm="thres", msep=(5,)) + + [email protected] +def test_1d_thres_fast(): + _test_1d(dataset=_ONE_D_PEAKS, algorithm="thres-fast", msep=(5,)) + + [email protected] +def test_2d_connected(): + _test_2d(dataset=_TWO_D_PEAKS, algorithm="connected") + + [email protected] +def test_2d_downward(): + _test_2d(dataset=_TWO_D_PEAKS, algorithm="downward") + + [email protected] +def test_2d_thres(): + _test_2d(dataset=_TWO_D_PEAKS, algorithm="thres", msep=(5, 5)) + + [email protected] +def test_2d_thres_fast(): + _test_2d(dataset=_TWO_D_PEAKS, algorithm="thres-fast", msep=(5, 5)) + + [email protected] +def test_3d_connected(): + _test_3d(dataset=_THREE_D_PEAKS, algorithm="connected") + + [email protected] +def test_3d_downward(): + _test_3d(dataset=_THREE_D_PEAKS, algorithm="downward") + + [email protected] +def test_3d_thres(): + _test_3d(dataset=_THREE_D_PEAKS, algorithm="thres", msep=(2, 2, 2)) + + [email protected] +def test_3d_thres_fast(): + _test_3d(dataset=_THREE_D_PEAKS, algorithm="thres-fast", msep=(2, 2, 2))
Issue with ng.peakpick.pick for "thres" and "thres-fast" algorithms with Numpy ^v1.22 **Problem:** When using `ng.peakpick.pick` with the algorithms "thres" and "thres-fast" and the Numpy version ^1.22, the following error occurs: ``` Error: peakpick.py:369 # find the rectangular region around the segment peakpick.py:370 region = data[seg_slice] peakpick.py:371 edge = [s.start for s in seg_slice] peakpick.py:372 rlocation = [l - s.start for l, s in zip(location, seg_slice)] IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`), and integer or boolean arrays are valid indices. ``` It appears to be related to the function call `find_all_thres_fast(data, pthres, msep, True)` since it returns a list for `seg_slice`. **Potential Fix:** Modifying line 370 in peakpick.py to: ```python peakpick.py:370 region = data[seg_slice[0]] ``` or adjusting the return of the find_all_thres_fast function accordingly. Somehow this is not needed for numpy versions below 1.22 but for above versions it becomes a problem.
0.0
f17caaf98e315dde63d4c4e0bea127b247d9f70d
[ "tests/test_peakpick.py::test_1d_thres", "tests/test_peakpick.py::test_1d_thres_fast", "tests/test_peakpick.py::test_2d_thres", "tests/test_peakpick.py::test_2d_thres_fast", "tests/test_peakpick.py::test_3d_thres", "tests/test_peakpick.py::test_3d_thres_fast" ]
[ "tests/test_peakpick.py::test_1d_connected", "tests/test_peakpick.py::test_1d_downward", "tests/test_peakpick.py::test_2d_connected", "tests/test_peakpick.py::test_2d_downward", "tests/test_peakpick.py::test_3d_connected", "tests/test_peakpick.py::test_3d_downward" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2024-01-25 04:03:35+00:00
bsd-3-clause
3,253
jjmccollum__teiphy-49
diff --git a/.github/workflows/raxml.yml b/.github/workflows/raxml.yml new file mode 100644 index 0000000..a93dda3 --- /dev/null +++ b/.github/workflows/raxml.yml @@ -0,0 +1,36 @@ +name: raxml + +on: [push] +jobs: + build: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.10"] + steps: + - uses: actions/checkout@v3 + - name: Install poetry + run: pipx install poetry + - name: Install dependencies for Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + cache: 'poetry' + - run: poetry install + - name: Testing + run: | + poetry run teiphy -t reconstructed -t defective -t orthographic -m overlap -m lac -s"*" -s T --fill-correctors --no-labels --states-present example/ubs_ephesians.xml raxml_example.phy + poetry run teiphy -t reconstructed -t defective -t orthographic -m overlap -m lac -s"*" -s T --fill-correctors --no-labels --states-present example/ubs_ephesians.xml raxml_example.fasta + - name: Install Phylogenetics Package + run: | + git clone https://github.com/stamatak/standard-RAxML + cd standard-RAxML + make -f Makefile.gcc + rm *.o + - name: Phylogenetics Run + run: | + cd standard-RAxML + ./raxmlHPC -p 12345 -m MULTIGAMMA -s ../raxml_example.phy -K MK -n T1 + ./raxmlHPC -p 12345 -m MULTIGAMMA -s ../raxml_example.fasta -K MK -n T2 + diff --git a/poetry.lock b/poetry.lock index 7a46a65..0f5e5ed 100644 --- a/poetry.lock +++ b/poetry.lock @@ -150,7 +150,7 @@ optional = false python-versions = "*" [package.extras] -test = ["flake8 (==3.7.8)", "hypothesis (==3.55.3)"] +test = ["hypothesis (==3.55.3)", "flake8 (==3.7.8)"] [[package]] name = "coverage" @@ -205,7 +205,7 @@ python-versions = ">=3.6" [[package]] name = "exceptiongroup" -version = "1.0.0rc9" +version = "1.0.0" description = "Backport of PEP 654 (exception groups)" category = "dev" optional = false @@ -239,7 +239,7 @@ testing = ["covdefaults (>=2.2)", "coverage (>=6.4.2)", "pytest (>=7.1.2)", "pyt [[package]] name = "identify" -version = "2.5.7" +version = "2.5.8" description = "File identification library for Python" category = "dev" optional = false @@ -460,7 +460,7 @@ sphinx = ["sphinx-book-theme", "Sphinx (>=1.7)", "myst-parser", "moto", "mock", [[package]] name = "nbconvert" -version = "7.2.2" +version = "7.2.3" description = "Converting Jupyter Notebooks" category = "dev" optional = false @@ -636,8 +636,8 @@ optional = false python-versions = ">=3.6" [package.extras] -dev = ["pre-commit", "tox"] -testing = ["pytest", "pytest-benchmark"] +testing = ["pytest-benchmark", "pytest"] +dev = ["tox", "pre-commit"] [[package]] name = "pre-commit" @@ -976,8 +976,8 @@ optional = false python-versions = ">=3.5" [package.extras] -lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] +lint = ["docutils-stubs", "mypy", "flake8"] [[package]] name = "sphinxcontrib-bibtex" @@ -1003,8 +1003,8 @@ optional = false python-versions = ">=3.5" [package.extras] -lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] +lint = ["docutils-stubs", "mypy", "flake8"] [[package]] name = "sphinxcontrib-htmlhelp" @@ -1015,8 +1015,8 @@ optional = false python-versions = ">=3.6" [package.extras] -lint = ["flake8", "mypy", "docutils-stubs"] -test = ["pytest", "html5lib"] +test = ["html5lib", "pytest"] +lint = ["docutils-stubs", "mypy", "flake8"] [[package]] name = "sphinxcontrib-jsmath" @@ -1027,7 +1027,7 @@ optional = false python-versions = ">=3.5" [package.extras] -test = ["pytest", "flake8", "mypy"] +test = ["mypy", "flake8", "pytest"] [[package]] name = "sphinxcontrib-qthelp" @@ -1038,8 +1038,8 @@ optional = false python-versions = ">=3.5" [package.extras] -lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] +lint = ["docutils-stubs", "mypy", "flake8"] [[package]] name = "sphinxcontrib-serializinghtml" @@ -1205,10 +1205,7 @@ cfgv = [] charset-normalizer = [] click = [] colorama = [] -commonmark = [ - {file = "commonmark-0.9.1-py2.py3-none-any.whl", hash = "sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9"}, - {file = "commonmark-0.9.1.tar.gz", hash = "sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60"}, -] +commonmark = [] coverage = [] defusedxml = [] distlib = [] @@ -1284,10 +1281,7 @@ sphinxcontrib-qthelp = [] sphinxcontrib-serializinghtml = [] text-unidecode = [] tinycss2 = [] -toml = [ - {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, - {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, -] +toml = [] tomli = [] tornado = [] traitlets = [] diff --git a/pyproject.toml b/pyproject.toml index 78e8b2a..c3148e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,11 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Intended Audience :: Science/Research", "Topic :: Software Development :: Libraries :: Python Modules", + "Programming Language :: Python :: 3", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", ] diff --git a/teiphy/collation.py b/teiphy/collation.py index f615e01..2bd3ad3 100644 --- a/teiphy/collation.py +++ b/teiphy/collation.py @@ -324,28 +324,6 @@ class Collation: # nexus_equate_mapping = {t: possible_symbols[i] for i, t in enumerate(reading_ind_tuples)} # return nexus_equates, nexus_equate_mapping - def get_hennig86_symbols(self): - """Returns a list of one-character symbols needed to represent the states of all substantive readings in Hennig86 format. - - The number of symbols equals the maximum number of substantive readings at any variation unit. - - Returns: - A list of individual characters representing states in readings. - """ - possible_symbols = ( - list(string.digits) + list(string.ascii_uppercase)[:22] - ) # NOTE: the maximum number of symbols allowed in Hennig86 format is 32 - # The number of symbols needed is equal to the length of the longest substantive reading vector: - nsymbols = 0 - # If there are no witnesses, then no symbols are needed at all: - if len(self.witnesses) == 0: - return [] - wit_id = self.witnesses[0].id - for rdg_support in self.readings_by_witness[wit_id]: - nsymbols = max(nsymbols, len(rdg_support)) - hennig86_symbols = possible_symbols[:nsymbols] - return hennig86_symbols - def to_nexus( self, file_addr: Union[Path, str], @@ -485,6 +463,28 @@ class Collation: f.write("End;") return + def get_hennig86_symbols(self): + """Returns a list of one-character symbols needed to represent the states of all substantive readings in Hennig86 format. + + The number of symbols equals the maximum number of substantive readings at any variation unit. + + Returns: + A list of individual characters representing states in readings. + """ + possible_symbols = ( + list(string.digits) + list(string.ascii_uppercase)[:22] + ) # NOTE: the maximum number of symbols allowed in Hennig86 format is 32 + # The number of symbols needed is equal to the length of the longest substantive reading vector: + nsymbols = 0 + # If there are no witnesses, then no symbols are needed at all: + if len(self.witnesses) == 0: + return [] + wit_id = self.witnesses[0].id + for rdg_support in self.readings_by_witness[wit_id]: + nsymbols = max(nsymbols, len(rdg_support)) + hennig86_symbols = possible_symbols[:nsymbols] + return hennig86_symbols + def to_hennig86(self, file_addr: Union[Path, str]): """Writes this Collation to a file in Hennig86 format with the given address. Note that because Hennig86 format does not support NEXUS-style ambiguities, such ambiguities will be treated as missing data. @@ -541,6 +541,144 @@ class Collation: f.write(";") return + def get_phylip_symbols(self): + """Returns a list of one-character symbols needed to represent the states of all substantive readings in PHYLIP format. + + The number of symbols equals the maximum number of substantive readings at any variation unit. + + Returns: + A list of individual characters representing states in readings. + """ + possible_symbols = ( + list(string.digits) + list(string.ascii_lowercase)[:22] + ) # NOTE: for RAxML, multistate characters with an alphabet sizes up to 32 are supported + # The number of symbols needed is equal to the length of the longest substantive reading vector: + nsymbols = 0 + # If there are no witnesses, then no symbols are needed at all: + if len(self.witnesses) == 0: + return [] + wit_id = self.witnesses[0].id + for rdg_support in self.readings_by_witness[wit_id]: + nsymbols = max(nsymbols, len(rdg_support)) + phylip_symbols = possible_symbols[:nsymbols] + return phylip_symbols + + def to_phylip(self, file_addr: Union[Path, str]): + """Writes this Collation to a file in PHYLIP format with the given address. + Note that because PHYLIP format does not support NEXUS-style ambiguities, such ambiguities will be treated as missing data. + + Args: + file_addr: A string representing the path to an output file. + """ + # Start by calculating the values we will be using here: + ntax = len(self.witnesses) + nchar = ( + len(self.readings_by_witness[self.witnesses[0].id]) if ntax > 0 else 0 + ) # if the number of taxa is 0, then the number of characters is irrelevant + taxlabels = [] + for wit in self.witnesses: + taxlabel = wit.id + # Then replace any disallowed characters in the string with an underscore: + taxlabel = slugify(taxlabel, lowercase=False, separator='_') + taxlabels.append(taxlabel) + max_taxlabel_length = max( + [len(taxlabel) for taxlabel in taxlabels] + ) # keep track of the longest taxon label for tabular alignment purposes + missing_symbol = '?' + symbols = self.get_phylip_symbols() + with open(file_addr, "w", encoding="ascii") as f: + # Write the dimensions: + f.write("%d %d\n" % (ntax, nchar)) + # Now write the matrix: + for i, wit in enumerate(self.witnesses): + taxlabel = taxlabels[i] + # Add enough space after this label ensure that all sequences are nicely aligned: + sequence = taxlabel + (" " * (max_taxlabel_length - len(taxlabel))) + "\t" + for rdg_support in self.readings_by_witness[wit.id]: + # If this reading is lacunose in this witness, then use the missing character: + if sum(rdg_support) == 0: + sequence += missing_symbol + continue + rdg_inds = [ + i for i, w in enumerate(rdg_support) if w > 0 + ] # the index list consists of the indices of all readings with any degree of certainty assigned to them + # For singleton readings, just print the symbol: + if len(rdg_inds) == 1: + sequence += symbols[rdg_inds[0]] + continue + # For multiple readings, print the missing symbol: + sequence += missing_symbol + f.write("%s\n" % (sequence)) + return + + def get_fasta_symbols(self): + """Returns a list of one-character symbols needed to represent the states of all substantive readings in FASTA format. + + The number of symbols equals the maximum number of substantive readings at any variation unit. + + Returns: + A list of individual characters representing states in readings. + """ + possible_symbols = ( + list(string.digits) + list(string.ascii_lowercase)[:22] + ) # NOTE: for RAxML, multistate characters with an alphabet sizes up to 32 are supported + # The number of symbols needed is equal to the length of the longest substantive reading vector: + nsymbols = 0 + # If there are no witnesses, then no symbols are needed at all: + if len(self.witnesses) == 0: + return [] + wit_id = self.witnesses[0].id + for rdg_support in self.readings_by_witness[wit_id]: + nsymbols = max(nsymbols, len(rdg_support)) + fasta_symbols = possible_symbols[:nsymbols] + return fasta_symbols + + def to_fasta(self, file_addr: Union[Path, str]): + """Writes this Collation to a file in FASTA format with the given address. + Note that because FASTA format does not support NEXUS-style ambiguities, such ambiguities will be treated as missing data. + + Args: + file_addr: A string representing the path to an output file. + """ + # Start by calculating the values we will be using here: + ntax = len(self.witnesses) + nchar = ( + len(self.readings_by_witness[self.witnesses[0].id]) if ntax > 0 else 0 + ) # if the number of taxa is 0, then the number of characters is irrelevant + taxlabels = [] + for wit in self.witnesses: + taxlabel = wit.id + # Then replace any disallowed characters in the string with an underscore: + taxlabel = slugify(taxlabel, lowercase=False, separator='_') + taxlabels.append(taxlabel) + max_taxlabel_length = max( + [len(taxlabel) for taxlabel in taxlabels] + ) # keep track of the longest taxon label for tabular alignment purposes + missing_symbol = '?' + symbols = self.get_fasta_symbols() + with open(file_addr, "w", encoding="ascii") as f: + # Now write the matrix: + for i, wit in enumerate(self.witnesses): + taxlabel = taxlabels[i] + # Add enough space after this label ensure that all sequences are nicely aligned: + sequence = ">%s\n" % taxlabel + for rdg_support in self.readings_by_witness[wit.id]: + # If this reading is lacunose in this witness, then use the missing character: + if sum(rdg_support) == 0: + sequence += missing_symbol + continue + rdg_inds = [ + i for i, w in enumerate(rdg_support) if w > 0 + ] # the index list consists of the indices of all readings with any degree of certainty assigned to them + # For singleton readings, just print the symbol: + if len(rdg_inds) == 1: + sequence += symbols[rdg_inds[0]] + continue + # For multiple readings, print the missing symbol: + sequence += missing_symbol + f.write("%s\n" % (sequence)) + return + def to_numpy(self, split_missing: bool = True): """Returns this Collation in the form of a NumPy array, along with arrays of its row and column labels. @@ -820,7 +958,7 @@ class Collation: split_missing (bool, optional): An optional flag indicating whether to treat missing characters/variation units as having a contribution of 1 split over all states/readings; if False, then missing data is ignored (i.e., all states are 0). - Not applicable for NEXUS, HENNIG86, or STEMMA format. + Not applicable for NEXUS, HENNIG86, PHYLIP, FASTA, or STEMMA format. Default value is True. char_state_labels (bool, optional): An optional flag indicating whether to print the CharStateLabels block in NEXUS output. @@ -851,6 +989,12 @@ class Collation: if format == format.HENNIG86: return self.to_hennig86(file_addr) + if format == format.PHYLIP: + return self.to_phylip(file_addr) + + if format == format.FASTA: + return self.to_fasta(file_addr) + if format == Format.CSV: return self.to_csv(file_addr, split_missing=split_missing) diff --git a/teiphy/format.py b/teiphy/format.py index fd6654d..d122a24 100644 --- a/teiphy/format.py +++ b/teiphy/format.py @@ -8,6 +8,8 @@ class FormatUnknownException(Exception): class Format(Enum): NEXUS = 'NEXUS' HENNIG86 = 'HENNIG86' + PHYLIP = 'PHYLIP' + FASTA = 'FASTA' CSV = 'CSV' TSV = 'TSV' EXCEL = 'EXCEL' @@ -19,6 +21,10 @@ class Format(Enum): ".nex": cls.NEXUS, ".nexus": cls.NEXUS, ".nxs": cls.NEXUS, + ".ph": cls.PHYLIP, + ".phy": cls.PHYLIP, + ".fa": cls.FASTA, + ".fasta": cls.FASTA, ".tnt": cls.HENNIG86, ".csv": cls.CSV, ".tsv": cls.TSV, diff --git a/teiphy/main.py b/teiphy/main.py index 8d25a32..a8fec14 100644 --- a/teiphy/main.py +++ b/teiphy/main.py @@ -1,4 +1,5 @@ from typing import List # for list-like inputs +from importlib.metadata import version # for checking package version from pathlib import Path # for validating file address inputs from lxml import etree as et # for parsing XML input import typer @@ -9,6 +10,11 @@ from .collation import Collation app = typer.Typer(rich_markup_mode="rich") +def version_callback(value: bool): + if value: + teiphy_version = version("teiphy") + typer.echo(teiphy_version) + raise typer.Exit() @app.command() def to_file( @@ -44,6 +50,12 @@ def to_file( help="Use the missing symbol instead of Equate symbols (and thus treat all ambiguities as missing data) in NEXUS output; this option is only applied if the --states-present option is also set.", ), verbose: bool = typer.Option(False, help="Enable verbose logging (mostly for debugging purposes)."), + version: bool = typer.Option( + False, + callback=version_callback, + is_eager=True, + help="Print the current version.", + ), format: Format = typer.Option(None, case_sensitive=False, help="The output format."), input: Path = typer.Argument( ...,
jjmccollum/teiphy
ae7fa324ecc6bc597ecb425b30fdcc41b5be35c0
diff --git a/tests/test_collation.py b/tests/test_collation.py index 251aab4..484be1f 100644 --- a/tests/test_collation.py +++ b/tests/test_collation.py @@ -248,6 +248,26 @@ class CollationOutputTestCase(unittest.TestCase): hennig86_symbols = empty_collation.get_hennig86_symbols() self.assertEqual(hennig86_symbols, []) + def test_get_phylip_symbols(self): + phylip_symbols = self.collation.get_phylip_symbols() + self.assertEqual(phylip_symbols, ["0", "1", "2", "3", "4", "5"]) + + def test_get_phylip_symbols_empty(self): + empty_xml = et.fromstring("<TEI/>") + empty_collation = Collation(empty_xml) + phylip_symbols = empty_collation.get_phylip_symbols() + self.assertEqual(phylip_symbols, []) + + def test_get_fasta_symbols(self): + fasta_symbols = self.collation.get_fasta_symbols() + self.assertEqual(fasta_symbols, ["0", "1", "2", "3", "4", "5"]) + + def test_get_fasta_symbols_empty(self): + empty_xml = et.fromstring("<TEI/>") + empty_collation = Collation(empty_xml) + fasta_symbols = empty_collation.get_fasta_symbols() + self.assertEqual(fasta_symbols, []) + def test_to_numpy_ignore_missing(self): matrix, reading_labels, witness_labels = self.collation.to_numpy(split_missing=False) self.assertTrue( diff --git a/tests/test_format.py b/tests/test_format.py index 77845fb..9fd0611 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -8,6 +8,10 @@ class FormatTestCase(unittest.TestCase): self.assertEqual(Format.infer(".nex"), Format.NEXUS) self.assertEqual(Format.infer(".nxs"), Format.NEXUS) self.assertEqual(Format.infer(".nexus"), Format.NEXUS) + self.assertEqual(Format.infer(".ph"), Format.PHYLIP) + self.assertEqual(Format.infer(".phy"), Format.PHYLIP) + self.assertEqual(Format.infer(".fa"), Format.FASTA) + self.assertEqual(Format.infer(".fasta"), Format.FASTA) self.assertEqual(Format.infer(".tnt"), Format.HENNIG86) self.assertEqual(Format.infer(".csv"), Format.CSV) self.assertEqual(Format.infer(".tsv"), Format.TSV) diff --git a/tests/test_main.py b/tests/test_main.py index 27adc3c..51a2cb2 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -16,6 +16,12 @@ no_dates_example = test_dir / "no_dates_example.xml" some_dates_example = test_dir / "some_dates_example.xml" +def test_version(): + with tempfile.TemporaryDirectory() as tmp_dir: + result = runner.invoke(app, ["--version"]) + assert result.stdout != "" + + def test_non_xml_input(): with tempfile.TemporaryDirectory() as tmp_dir: output = Path(tmp_dir) / "test.nexus" @@ -104,6 +110,54 @@ def test_to_hennig86(): assert "xread" in text +def test_to_phylip(): + with tempfile.TemporaryDirectory() as tmp_dir: + output = Path(tmp_dir) / "test.phy" + result = runner.invoke( + app, + [ + "-t reconstructed", + "-t defective", + "-t orthographic", + "-m lac", + "-m overlap", + "-s *", + "-s T", + "--fill-correctors", + str(input_example), + str(output), + ], + ) + assert result.exit_code == 0 + assert output.exists() + text = output.read_text(encoding="ascii") + assert text.startswith("38 40") + + +def test_to_fasta(): + with tempfile.TemporaryDirectory() as tmp_dir: + output = Path(tmp_dir) / "test.fa" + result = runner.invoke( + app, + [ + "-t reconstructed", + "-t defective", + "-t orthographic", + "-m lac", + "-m overlap", + "-s *", + "-s T", + "--fill-correctors", + str(input_example), + str(output), + ], + ) + assert result.exit_code == 0 + assert output.exists() + text = output.read_text(encoding="ascii") + assert text.startswith(">UBS") + + def test_to_csv(): with tempfile.TemporaryDirectory() as tmp_dir: output = Path(tmp_dir) / "test.csv"
Add --version argument to app Per the first round of reviewer comments on the paper (https://github.com/openjournals/joss-reviews/issues/4879), it would be convenient to support a `--version` argument for the command-line interface that returns the current version of the code. This should be straightforward, but in the interest of preventing oversight in future updates, it would be nice if we only had to update the version number of the project in one place (specifically, in `pyproject.toml`). @rbturnbull, do you know if there's a preferred way of reading a package's version number within Python for this purpose? I'm seeing several suggestions in the thread at https://github.com/python-poetry/poetry/issues/273, so I wanted to see how you approach this problem. I've opened a `code-revision` branch where we can make this change.
0.0
ae7fa324ecc6bc597ecb425b30fdcc41b5be35c0
[ "tests/test_collation.py::CollationOutputTestCase::test_get_fasta_symbols", "tests/test_collation.py::CollationOutputTestCase::test_get_fasta_symbols_empty", "tests/test_collation.py::CollationOutputTestCase::test_get_phylip_symbols", "tests/test_collation.py::CollationOutputTestCase::test_get_phylip_symbols_empty", "tests/test_format.py::FormatTestCase::test_infer_success", "tests/test_main.py::test_to_phylip", "tests/test_main.py::test_to_fasta" ]
[ "tests/test_collation.py::CollationDefaultTestCase::test_readings_by_witness", "tests/test_collation.py::CollationDefaultTestCase::test_substantive_reading_ids", "tests/test_collation.py::CollationDefaultTestCase::test_substantive_variation_unit_ids", "tests/test_collation.py::CollationDefaultTestCase::test_variation_units", "tests/test_collation.py::CollationDefaultTestCase::test_witness_index_by_id", "tests/test_collation.py::CollationDefaultTestCase::test_witnesses", "tests/test_collation.py::CollationTrivialReconstructedTestCase::test_substantive_reading_ids", "tests/test_collation.py::CollationTrivialReconstructedTestCase::test_substantive_variation_unit_ids", "tests/test_collation.py::CollationTrivialDefectiveTestCase::test_substantive_reading_ids", "tests/test_collation.py::CollationTrivialDefectiveTestCase::test_substantive_variation_unit_ids", "tests/test_collation.py::CollationTrivialOrthographicTestCase::test_substantive_reading_ids", "tests/test_collation.py::CollationTrivialOrthographicTestCase::test_substantive_variation_unit_ids", "tests/test_collation.py::CollationTrivialSubreadingTestCase::test_substantive_reading_ids", "tests/test_collation.py::CollationTrivialSubreadingTestCase::test_substantive_variation_unit_ids", "tests/test_collation.py::CollationMissingTestCase::test_missing_get_readings_by_witness_for_unit", "tests/test_collation.py::CollationMissingTestCase::test_missing_lac", "tests/test_collation.py::CollationMissingTestCase::test_missing_overlap", "tests/test_collation.py::CollationManuscriptSuffixesTestCase::test_get_base_wit_apparent_suffix", "tests/test_collation.py::CollationManuscriptSuffixesTestCase::test_get_base_wit_multiple_suffixes", "tests/test_collation.py::CollationManuscriptSuffixesTestCase::test_get_base_wit_no_suffix", "tests/test_collation.py::CollationManuscriptSuffixesTestCase::test_get_base_wit_one_suffix", "tests/test_collation.py::CollationManuscriptSuffixesTestCase::test_merged_attestations", "tests/test_collation.py::CollationFillCorrectorLacunaeTestCase::test_active_corrector", "tests/test_collation.py::CollationFillCorrectorLacunaeTestCase::test_inactive_corrector", "tests/test_collation.py::CollationVerboseTestCase::test_verbose", "tests/test_collation.py::CollationOutputTestCase::test_get_hennig86_symbols", "tests/test_collation.py::CollationOutputTestCase::test_get_hennig86_symbols_empty", "tests/test_collation.py::CollationOutputTestCase::test_get_nexus_symbols", "tests/test_collation.py::CollationOutputTestCase::test_get_nexus_symbols_empty", "tests/test_collation.py::CollationOutputTestCase::test_to_distance_matrix", "tests/test_collation.py::CollationOutputTestCase::test_to_distance_matrix_proportion", "tests/test_collation.py::CollationOutputTestCase::test_to_numpy_ignore_missing", "tests/test_collation.py::CollationOutputTestCase::test_to_numpy_split_missing", "tests/test_format.py::FormatTestCase::test_infer_failure", "tests/test_main.py::test_version", "tests/test_main.py::test_non_xml_input", "tests/test_main.py::test_malformed_input", "tests/test_main.py::test_to_nexus", "tests/test_main.py::test_to_nexus_no_labels", "tests/test_main.py::test_to_nexus_states_present", "tests/test_main.py::test_to_nexus_states_present_ambiguous_as_missing", "tests/test_main.py::test_to_hennig86", "tests/test_main.py::test_to_csv", "tests/test_main.py::test_to_tsv", "tests/test_main.py::test_to_excel", "tests/test_main.py::test_to_stemma", "tests/test_main.py::test_to_stemma_no_dates", "tests/test_main.py::test_to_stemma_some_dates", "tests/test_main.py::test_to_file_bad_format" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-28 12:15:32+00:00
mit
3,254
jjmccollum__teiphy-76
diff --git a/.github/workflows/beast.yml b/.github/workflows/beast.yml index bfcf37c..118ece7 100644 --- a/.github/workflows/beast.yml +++ b/.github/workflows/beast.yml @@ -26,9 +26,9 @@ jobs: - run: poetry install - name: Testing run: | - poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock strict example/ubs_ephesians.xml beast_strict_example.xml - poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock uncorrelated example/ubs_ephesians.xml beast_uncorrelated_example.xml - poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock local example/ubs_ephesians.xml beast_local_example.xml + poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock strict --seed 1337 example/ubs_ephesians.xml beast_strict_example.xml + poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock uncorrelated --seed 1337 example/ubs_ephesians.xml beast_uncorrelated_example.xml + poetry run teiphy -t reconstructed -t defective -t orthographic -t subreading -m overlap -m lac -s"*" -s T --fill-correctors --clock local --seed 1337 example/ubs_ephesians.xml beast_local_example.xml - name: Install Phylogenetics Package run: | export JAVA_HOME=/opt/hostedtoolcache/Java_Zulu_jdk+fx/17.0.6-10/x64 diff --git a/teiphy/collation.py b/teiphy/collation.py index 0dd9f83..a87f297 100644 --- a/teiphy/collation.py +++ b/teiphy/collation.py @@ -7,7 +7,7 @@ from datetime import datetime # for calculating the current year (for dating an import time # to time calculations for users import string # for easy retrieval of character ranges from lxml import etree as et # for reading TEI XML inputs -import numpy as np # for collation matrix outputs +import numpy as np # for random number sampling and collation matrix outputs import pandas as pd # for writing to DataFrames, CSV, Excel, etc. from slugify import slugify # for converting Unicode text from readings to ASCII for NEXUS from jinja2 import Environment, PackageLoader, select_autoescape # for filling output XML templates @@ -1291,7 +1291,11 @@ class Collation: return root_frequencies_string def to_beast( - self, file_addr: Union[Path, str], drop_constant: bool = False, clock_model: ClockModel = ClockModel.strict + self, + file_addr: Union[Path, str], + drop_constant: bool = False, + clock_model: ClockModel = ClockModel.strict, + seed: int = None, ): """Writes this Collation to a file in BEAST format with the given address. @@ -1299,6 +1303,7 @@ class Collation: file_addr: A string representing the path to an output file. drop_constant (bool, optional): An optional flag indicating whether to ignore variation units with one substantive reading. clock_model: A ClockModel option indicating which clock model to use. + seed: A seed for random number generation (for setting initial values of unspecified transcriptional rates). """ # Populate a list of sites that will correspond to columns of the sequence alignment: substantive_variation_unit_ids = self.variation_unit_ids @@ -1453,15 +1458,16 @@ class Collation: intrinsic_category_object["odds"] = odds if odds is not None else 1.0 intrinsic_category_object["estimate"] = "false" if odds is not None else "true" intrinsic_category_objects.append(intrinsic_category_object) - # The proceed to transcriptional rate categories: + # Then proceed to transcriptional rate categories: + rng = np.random.default_rng(seed) for transcriptional_category in self.transcriptional_categories: transcriptional_category_object = {} # Copy the ID of this transcriptional category: transcriptional_category_object["id"] = transcriptional_category # Then copy the rate of this transcriptional category, - # setting it to 2.0 if it is not specified and setting the estimate attribute accordingly: + # setting it to a random number sampled from a Gamma distribution if it is not specified and setting the estimate attribute accordingly: rate = self.transcriptional_rates_by_id[transcriptional_category] - transcriptional_category_object["rate"] = rate if rate is not None else 2.0 + transcriptional_category_object["rate"] = rate if rate is not None else rng.gamma(5.0, 2.0) transcriptional_category_object["estimate"] = "false" if rate is not None else "true" transcriptional_category_objects.append(transcriptional_category_object) # Now render the output XML file using the Jinja template: @@ -1893,6 +1899,7 @@ class Collation: calibrate_dates: bool = False, mrbayes: bool = False, clock_model: ClockModel = ClockModel.strict, + seed: int = None, ): """Writes this Collation to the file with the given address. @@ -1933,6 +1940,7 @@ class Collation: clock_model: A ClockModel option indicating which type of clock model to use. This option is intended for inputs to MrBayes and BEAST 2. MrBayes does not presently support a local clock model, so it will default to a strict clock model if a local clock model is specified. + seed: A seed for random number generation (for setting initial values of unspecified transcriptional rates in BEAST 2 XML output). """ file_addr = Path(file_addr) format = format or Format.infer( @@ -1961,7 +1969,7 @@ class Collation: return self.to_fasta(file_addr, drop_constant=drop_constant) if format == format.BEAST: - return self.to_beast(file_addr, drop_constant=drop_constant, clock_model=clock_model) + return self.to_beast(file_addr, drop_constant=drop_constant, clock_model=clock_model, seed=seed) if format == Format.CSV: return self.to_csv( diff --git a/teiphy/main.py b/teiphy/main.py index 766b1f9..be29648 100644 --- a/teiphy/main.py +++ b/teiphy/main.py @@ -75,6 +75,10 @@ def to_file( False, help="Treat missing characters/variation units as having a contribution of 1 split over all states/readings; if False, then missing data is ignored (i.e., all states are 0). Not applicable for non-tabular formats.", ), + seed: int = typer.Option( + None, + help="Seed for random number generation (used for setting default initial values of transcriptional rate parameters for BEAST 2 XML output); if not specified, then the default seeding of the numpy.random.default_rng class will be used.", + ), verbose: bool = typer.Option(False, help="Enable verbose logging (mostly for debugging purposes)."), version: bool = typer.Option( False, @@ -128,4 +132,5 @@ def to_file( clock_model=clock, long_table=long_table, split_missing=split_missing, + seed=seed, ) diff --git a/teiphy/templates/beast_template.xml b/teiphy/templates/beast_template.xml index 59231f3..e0625bc 100644 --- a/teiphy/templates/beast_template.xml +++ b/teiphy/templates/beast_template.xml @@ -62,7 +62,7 @@ <!-- Start transcriptional rate parameters --> {%- for tc in transcriptional_categories %} - <stateNode spec="parameter.RealParameter" id="{{ tc.id }}_rate" lower="1.0" upper="Infinity" value="{{ tc.rate }}" estimate="{{ tc.estimate }}"/> + <stateNode spec="parameter.RealParameter" id="{{ tc.id }}_rate" lower="0.0" upper="Infinity" value="{{ tc.rate }}" estimate="{{ tc.estimate }}"/> {%- endfor %} <!-- We include a "default" rate fixed at 1 that corresponds to (unlikely) transitions with no transcriptional explanation. All other rates in the substitution matrices will be estimated relative to this. @@ -115,7 +115,7 @@ {%- for tc in transcriptional_categories %} {%- if tc.estimate == "true" %} <distribution spec="Prior" id="{{ tc.id }}_ratePrior" x="@{{ tc.id }}_rate"> - <distr spec="LogNormalDistributionModel" offset="1.0" M="1.0" S="1.0"/> + <distr spec="Gamma" alpha="5.0" beta="2.0"/> </distribution> {%- endif %} {%- endfor %}
jjmccollum/teiphy
17ef606cb2502cfa23c929f2c3a52c758982905b
diff --git a/tests/test_main.py b/tests/test_main.py index 6b46abc..dbd89a0 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -696,6 +696,8 @@ def test_to_beast_variable_rates(): "-s*", "-sT", "--fill-correctors", + "--seed", + "1337", str(input_example), str(output), ], @@ -703,13 +705,21 @@ def test_to_beast_variable_rates(): assert result.exit_code == 0 assert output.exists() beast_xml = et.parse(output, parser=parser) - for xml_transcriptional_category in xml_transcriptional_categories: + expected_rates = [ + 9.499649179019467, + 8.750762619939191, + 25.00430409157674, + 19.873724085272503, + 9.988999535304949, + 21.828078913817116, + ] # Gamma(5,2)-distributed numbers generated with seed 1337 + for i, xml_transcriptional_category in enumerate(xml_transcriptional_categories): transcriptional_category = xml_transcriptional_category.get("{%s}id" % xml_ns) beast_xml_transcriptional_rate_categories = beast_xml.xpath( "//stateNode[@id=\"%s_rate\"]" % transcriptional_category ) assert len(beast_xml_transcriptional_rate_categories) == 1 - assert float(beast_xml_transcriptional_rate_categories[0].get("value")) == 2.0 + assert float(beast_xml_transcriptional_rate_categories[0].get("value")) == expected_rates[i] assert beast_xml_transcriptional_rate_categories[0].get("estimate") == "true"
Assignment of random starting rate parameter values, new prior distributions, and support for `--seed` option For larger collations with increasingly varied substitution matrices at different sites/variation units, it becomes increasingly likely that at least one of the substitution matrices will be singular under the initial assignments of transcriptional rate parameters (which presently all default to 2.0). This ceases to be a problem after BEAST 2's first evaluation of the site likelihoods, because in subsequent likelihood calculations, it samples these rate parameter values randomly according to a prior distribution, and the resulting substitution matrices will almost never be singular. Since BEAST 2 XML inputs require that every `RealParameter` element have an initial `@value` attribute specified, we need to supply these values, but we should be able to avoid singular matrices if we set these values randomly in `to_beast`. This can be done by using distributions available in `numpy`, which is already a dependency of `teiphy`. I suggest replacing the current offset log-normal prior distribution assumed for transcriptional rate parameters with a simple gamma distribution (perhaps with `alpha="5"` and `beta="2"` as default values). Then we can sample random initial values for the rate parameters from this distribution using something like ```python rng = np.random.default_rng(seed) sample = rng.gamma(5.0, 2.0) ``` To ensure replicability for generated outputs, we will need to add support for a `--seed` command-line argument.
0.0
17ef606cb2502cfa23c929f2c3a52c758982905b
[ "tests/test_main.py::test_to_beast_variable_rates" ]
[ "tests/test_main.py::test_version", "tests/test_main.py::test_non_xml_input", "tests/test_main.py::test_malformed_input", "tests/test_main.py::test_no_listwit_input", "tests/test_main.py::test_extra_sigla_input", "tests/test_main.py::test_bad_date_witness_input", "tests/test_main.py::test_to_nexus", "tests/test_main.py::test_to_nexus_drop_constant", "tests/test_main.py::test_to_nexus_no_labels", "tests/test_main.py::test_to_nexus_frequency", "tests/test_main.py::test_to_nexus_drop_constant_frequency", "tests/test_main.py::test_to_nexus_ambiguous_as_missing", "tests/test_main.py::test_to_nexus_calibrate_dates", "tests/test_main.py::test_to_nexus_calibrate_dates_no_dates", "tests/test_main.py::test_to_nexus_calibrate_dates_some_dates", "tests/test_main.py::test_to_nexus_mrbayes", "tests/test_main.py::test_to_nexus_mrbayes_no_dates", "tests/test_main.py::test_to_nexus_mrbayes_some_dates", "tests/test_main.py::test_to_nexus_mrbayes_strict_clock", "tests/test_main.py::test_to_nexus_mrbayes_uncorrelated_clock", "tests/test_main.py::test_to_nexus_mrbayes_local_clock", "tests/test_main.py::test_to_hennig86", "tests/test_main.py::test_to_hennig86_drop_constant", "tests/test_main.py::test_to_phylip", "tests/test_main.py::test_to_phylip_drop_constant", "tests/test_main.py::test_to_fasta", "tests/test_main.py::test_to_fasta_drop_constant", "tests/test_main.py::test_to_beast", "tests/test_main.py::test_to_beast_drop_constant", "tests/test_main.py::test_to_beast_no_dates", "tests/test_main.py::test_to_beast_some_dates", "tests/test_main.py::test_to_beast_fixed_rates", "tests/test_main.py::test_to_beast_intrinsic_odds_excess_indegree", "tests/test_main.py::test_to_beast_intrinsic_odds_cycle", "tests/test_main.py::test_to_beast_intrinsic_odds_no_relations", "tests/test_main.py::test_to_beast_strict_clock", "tests/test_main.py::test_to_beast_uncorrelated_clock", "tests/test_main.py::test_to_beast_local_clock", "tests/test_main.py::test_to_csv", "tests/test_main.py::test_to_csv_drop_constant", "tests/test_main.py::test_to_csv_long_table", "tests/test_main.py::test_to_csv_drop_constant_long_table", "tests/test_main.py::test_to_tsv", "tests/test_main.py::test_to_tsv_long_table", "tests/test_main.py::test_to_excel", "tests/test_main.py::test_to_excel_long_table", "tests/test_main.py::test_to_stemma", "tests/test_main.py::test_to_stemma_no_dates", "tests/test_main.py::test_to_stemma_some_dates", "tests/test_main.py::test_to_file_bad_format" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-12 05:56:16+00:00
mit
3,255
jlusiardi__tlv8_python-14
diff --git a/CHANGES.md b/CHANGES.md index eaf351e..e1f512c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,13 @@ # Changes +## Version 0.9.0 + +Bug Fix: + +- Fix for https://github.com/jlusiardi/tlv8_python/issues/13 (and https://github.com/jlusiardi/homekit_python/issues/194) + which broke pairing with BLE devices. + ## Version 0.8.0 New Features: diff --git a/setup.py b/setup.py index 8559fc7..c8ba91c 100644 --- a/setup.py +++ b/setup.py @@ -23,14 +23,14 @@ with open("README.md", "r", encoding="utf-8") as fh: setuptools.setup( name='tlv8', packages=setuptools.find_packages(exclude=['tests']), - version='0.8.0', + version='0.9.0', description='Python module to handle type-length-value (TLV) encoded data 8-bit type, 8-bit length, and N-byte ' 'value as described within the Apple HomeKit Accessory Protocol Specification Non-Commercial Version ' 'Release R2.', author='Joachim Lusiardi', author_email='[email protected]', url='https://github.com/jlusiardi/tlv8_python', - download_url='https://github.com/jlusiardi/tlv8_python/archive/0.8.0.tar.gz', + download_url='https://github.com/jlusiardi/tlv8_python/archive/0.9.0.tar.gz', keywords=['TLV', 'Type-Length-Value', 'tlv8'], classifiers=[ 'License :: OSI Approved :: Apache Software License', diff --git a/tlv8/__init__.py b/tlv8/__init__.py index bb5ea98..bb1aea7 100644 --- a/tlv8/__init__.py +++ b/tlv8/__init__.py @@ -197,7 +197,7 @@ def encode(entries: list, separator_type_id=0xff) -> bytes: return result -def _internal_decode(data, strict_mode=False) -> EntryList: +def _internal_decode(data, expected=None, strict_mode=False) -> EntryList: if isinstance(data, bytearray): data = bytes(data) if not isinstance(data, bytes): @@ -214,6 +214,8 @@ def _internal_decode(data, strict_mode=False) -> EntryList: tlv_id = unpack('<B', remaining_data[0:1])[0] tlv_len = unpack('<B', remaining_data[1:2])[0] + if expected and tlv_id not in expected and tlv_len > 0: + break if len(remaining_data[2:]) < tlv_len: # the remaining data is less than the encoded length raise ValueError('Not enough data left. {} vs {}'.format(len(remaining_data[2:]), tlv_len)) @@ -248,7 +250,7 @@ def deep_decode(data, strict_mode=False) -> EntryList: :raises: ValueError on failures during decoding """ - tmp = _internal_decode(data, strict_mode) + tmp = _internal_decode(data, None, strict_mode) for entry in tmp: try: r = deep_decode(entry.data) @@ -270,7 +272,7 @@ def decode(data, expected=None, strict_mode=False) -> EntryList: :return: a list of tlv8.Entry objects :raises: ValueError on failures during decoding """ - tmp = _internal_decode(data, strict_mode) + tmp = _internal_decode(data, expected, strict_mode) # if we do not know what is expected, we just return the unfiltered, uninterpreted but parsed list of entries if not expected:
jlusiardi/tlv8_python
55cdbf71d41d25c24ba5b05e3f43a4d5e1d32274
diff --git a/tests/tlv8_real_world_test.py b/tests/tlv8_real_world_test.py index 6152289..c59bb1e 100644 --- a/tests/tlv8_real_world_test.py +++ b/tests/tlv8_real_world_test.py @@ -16,6 +16,7 @@ import unittest import enum +import binascii import tlv8 @@ -70,3 +71,44 @@ class TestTLV8RealWorld(unittest.TestCase): self.assertEqual(data, decoded) encoded_2 = tlv8.encode(decoded) self.assertEqual(encoded, encoded_2) + + def test_3(self): + """ + Example for a broken decode from https://github.com/jlusiardi/homekit_python/issues/194. + """ + data = '01ff0601040440371bf8c6cd6a7fb85e77a7b436a1b5300ed2023ca7e23f61303856a57358fd8ac03f288472776854765eb3' \ + 'a2fcb4497c8b5497c29c88a574479030ec36b176ae05ff85c337879f0a4146a9cc089e0cb48ba3c9c21af0b206d493b224de' \ + 'ee52ff0f9b1d8710db6531748ee6d1d66b8b4a6d0690670fb8f1233010d190c4ede1776cb10806eae66c78881647e82e9ba7' \ + 'c806f52184c6f108275719cf425c4f8ea0e86c6534712343f88a1482c986e3dd252715872dee506520903c17d27f02ea8957' \ + '719c255631b78a9f2ecb7af0dc245b370cefef28f4652eebbe34afda0138039714665dd880559d1f2667294207892137820c' \ + 'd80533d8c0b22601ffa49d1bdc1b641a33297fe59672a89d69391417c77e31283cd7f0d40920004d1bf1fc38357d9599ac2b' \ + '4d8ce3ac7ab8725a01500d198e94b00da80aac64ead393b266dcf9d4a07c05ff34548f7ebebd63f8a00ae2c82f6ee8ac6bcc' \ + 'e0ab1030e9268c36714e2ec11c3bf21331129d62978e069dd087cbbdc31bdd6e0cf4ca825b91ab3c8b240de19aa097fc01cd' \ + '471e8c1b5598044d21be12b84c97a1d70e46681e5ecebbde1c33bae9bbd9b3ad41ba2aff8f1f952d0ef0cfcb8a674d5b4c7f' \ + '515ba94341334e86aac277920bd9080b9bf702e16671a3e41c0930beb8a552aefc28a3a9a7f2818e8fbb84c37ae10fb6c5d2' \ + '2e6ba9899e01f082381c9a3344ecbaf801ff85e33306ec9823e72ec4c93f9a45aa657b16f46757aaaf7c74daf35840e68749' \ + '42c132f4a639562920318b9f9867d8e5b0d50deac48c4e14842c91d565b0dd1fec667d092d123a4e1a05fff0b7070f184b4f' \ + '399532c0d1cc0aaea326efea765bc88ace048040a3e07a741e26ef55203bb3f76c075e3b6d20ede89a2eaa63e23376b0dff4' \ + 'ef3a797df34a39d8130f60316e86cafcb264b0b570376ba911dc2bda031328ea1c915a724bc69ad2700623ed19c3ae75f946' \ + '4e3b1669adb916ad58e3252580911db2b535af3f2b2207aea880a0d24f1f759888bd5e25b6cf7b2e5ce825ab0fd943a8378a' \ + 'eb12906e0965540af14dc0bfa3fae2eb5361992efaf56501ff6ed5c6e686a4af3c2fa121c810cb84cd5abac94f6d618af493' \ + '29e34fa613d2b758e3bc79eb03cb78328f9cd34df43566589615e42088681b4f69775350c9abf68c107d312b0f2421bb53cf' \ + '05ff50c14d6ff0da74b50d9b080c5c06175d66b24b35eb1e25f940170c0815a0ead23703b86da2103cd1b33021fd981d95c6' \ + 'a32a3752dc903b0acba949d7d51a1bcabaebc52941bb25d558132feb1794481c0a5911e53553407a8771503d7673d4c3061a' \ + '4d2d41a2897fe507423509760fbe4847423a51155b99b67bf43c72958ce9409a459b5ce42e61309e96091411b256ec294fb0' \ + 'f32782efc80d9d548f3cee4fdb21babd011e118238ec7545b24e5af74317a2670179930156512875653dce4e957e94a7596f' \ + 'a7e2b533a3eacb9781634c79c094e2cbfcfc62128a25431f9b56cc40b6097614e7a4b08c32b3a7f2e471f55a295a9a06e5b0' \ + 'e07dec2ad282842aa6f176052acd544cb5d67c206a3e38e80e32f560a57edda173892a39b021d616d8f2862a5d111e6610c1e7' + data = binascii.unhexlify(data) + resp_data = tlv8.decode(data, {1: tlv8.DataType.BYTES}) + self.assertIsNotNone(resp_data.first_by_id(1)) + self.assertEqual(len(resp_data.first_by_id(1).data), 510) + + resp_data = tlv8.decode(resp_data.first_by_id(1).data, {4: tlv8.DataType.BYTES, 6: tlv8.DataType.BYTES}) + self.assertIsNotNone(resp_data.first_by_id(4)) + print(resp_data.first_by_id(4).data) + self.assertEqual(resp_data.first_by_id(4).data, + b'7\x1b\xf8\xc6\xcdj\x7f\xb8^w\xa7\xb46\xa1\xb50\x0e\xd2\x02<\xa7\xe2?a08V\xa5sX\xfd\x8a' + b'\xc0?(\x84rwhTv^\xb3\xa2\xfc\xb4I|\x8bT\x97\xc2\x9c\x88\xa5tG\x900\xec6\xb1v\xae') + self.assertIsNotNone(resp_data.first_by_id(6)) + self.assertEqual(resp_data.first_by_id(6).data, b'\x04')
Oversized TLV8 might be parsed properly. ``` data = '01ff0601040440371bf8c6cd6a7fb85e77a7b436a1b5300ed2023ca7e23f61303856a57358fd8ac03f288472776854765eb3' \ 'a2fcb4497c8b5497c29c88a574479030ec36b176ae05ff85c337879f0a4146a9cc089e0cb48ba3c9c21af0b206d493b224de' \ 'ee52ff0f9b1d8710db6531748ee6d1d66b8b4a6d0690670fb8f1233010d190c4ede1776cb10806eae66c78881647e82e9ba7' \ 'c806f52184c6f108275719cf425c4f8ea0e86c6534712343f88a1482c986e3dd252715872dee506520903c17d27f02ea8957' \ '719c255631b78a9f2ecb7af0dc245b370cefef28f4652eebbe34afda0138039714665dd880559d1f2667294207892137820c' \ 'd80533d8c0b22601ffa49d1bdc1b641a33297fe59672a89d69391417c77e31283cd7f0d40920004d1bf1fc38357d9599ac2b' \ '4d8ce3ac7ab8725a01500d198e94b00da80aac64ead393b266dcf9d4a07c05ff34548f7ebebd63f8a00ae2c82f6ee8ac6bcc' \ 'e0ab1030e9268c36714e2ec11c3bf21331129d62978e069dd087cbbdc31bdd6e0cf4ca825b91ab3c8b240de19aa097fc01cd' \ '471e8c1b5598044d21be12b84c97a1d70e46681e5ecebbde1c33bae9bbd9b3ad41ba2aff8f1f952d0ef0cfcb8a674d5b4c7f' \ '515ba94341334e86aac277920bd9080b9bf702e16671a3e41c0930beb8a552aefc28a3a9a7f2818e8fbb84c37ae10fb6c5d2' \ '2e6ba9899e01f082381c9a3344ecbaf801ff85e33306ec9823e72ec4c93f9a45aa657b16f46757aaaf7c74daf35840e68749' \ '42c132f4a639562920318b9f9867d8e5b0d50deac48c4e14842c91d565b0dd1fec667d092d123a4e1a05fff0b7070f184b4f' \ '399532c0d1cc0aaea326efea765bc88ace048040a3e07a741e26ef55203bb3f76c075e3b6d20ede89a2eaa63e23376b0dff4' \ 'ef3a797df34a39d8130f60316e86cafcb264b0b570376ba911dc2bda031328ea1c915a724bc69ad2700623ed19c3ae75f946' \ '4e3b1669adb916ad58e3252580911db2b535af3f2b2207aea880a0d24f1f759888bd5e25b6cf7b2e5ce825ab0fd943a8378a' \ 'eb12906e0965540af14dc0bfa3fae2eb5361992efaf56501ff6ed5c6e686a4af3c2fa121c810cb84cd5abac94f6d618af493' \ '29e34fa613d2b758e3bc79eb03cb78328f9cd34df43566589615e42088681b4f69775350c9abf68c107d312b0f2421bb53cf' \ '05ff50c14d6ff0da74b50d9b080c5c06175d66b24b35eb1e25f940170c0815a0ead23703b86da2103cd1b33021fd981d95c6' \ 'a32a3752dc903b0acba949d7d51a1bcabaebc52941bb25d558132feb1794481c0a5911e53553407a8771503d7673d4c3061a' \ '4d2d41a2897fe507423509760fbe4847423a51155b99b67bf43c72958ce9409a459b5ce42e61309e96091411b256ec294fb0' \ 'f32782efc80d9d548f3cee4fdb21babd011e118238ec7545b24e5af74317a2670179930156512875653dce4e957e94a7596f' \ 'a7e2b533a3eacb9781634c79c094e2cbfcfc62128a25431f9b56cc40b6097614e7a4b08c32b3a7f2e471f55a295a9a06e5b0' \ 'e07dec2ad282842aa6f176052acd544cb5d67c206a3e38e80e32f560a57edda173892a39b021d616d8f2862a5d111e6610c1e7' data = binascii.unhexlify(data) resp_data = tlv8.decode(data, {1: tlv8.DataType.BYTES}) ``` Failed with > 2020-05-12 19:56:52,627 pair_ble.py:0075 DEBUG Not enough data left. 45 vs 194 Traceback (most recent call last): File "homekit/pair_ble.py", line 68, in <module> finish_pairing(pin_function()) File "/home/jlusiardi/Dokumente/src/homekit_python/homekit/controller/controller.py", line 505, in finish_pairing response = write_fun(request, expected) File "/home/jlusiardi/Dokumente/src/homekit_python/homekit/controller/ble_impl/__init__.py", line 671, in write expected={AdditionalParameterTypes.Value: tlv8.DataType.BYTES}) File "/home/jlusiardi/Dokumente/src/homekit_python/venv/lib/python3.7/site-packages/tlv8/__init__.py", line 273, in decode tmp = _internal_decode(data, strict_mode) File "/home/jlusiardi/Dokumente/src/homekit_python/venv/lib/python3.7/site-packages/tlv8/__init__.py", line 219, in _internal_decode raise ValueError('Not enough data left. {} vs {}'.format(len(remaining_data[2:]), tlv_len)) ValueError: Not enough data left. 45 vs 194
0.0
55cdbf71d41d25c24ba5b05e3f43a4d5e1d32274
[ "tests/tlv8_real_world_test.py::TestTLV8RealWorld::test_3" ]
[ "tests/tlv8_real_world_test.py::TestTLV8RealWorld::test_1", "tests/tlv8_real_world_test.py::TestTLV8RealWorld::test_2" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-05-13 17:01:15+00:00
apache-2.0
3,256
jmcnamara__XlsxWriter-396
diff --git a/xlsxwriter/worksheet.py b/xlsxwriter/worksheet.py index 3e63ea53..dbe8e63e 100644 --- a/xlsxwriter/worksheet.py +++ b/xlsxwriter/worksheet.py @@ -1880,6 +1880,8 @@ class Worksheet(xmlwriter.XMLwriter): 'min_color': True, 'mid_color': True, 'max_color': True, + 'min_length': True, + 'max_length': True, 'multi_range': True, 'bar_color': 1} @@ -6026,7 +6028,15 @@ class Worksheet(xmlwriter.XMLwriter): def _write_data_bar(self, param): # Write the <dataBar> element. - self._xml_start_tag('dataBar') + attributes = [] + + if 'min_length' in param: + attributes.append(('minLength', param['min_length'])) + + if 'max_length' in param: + attributes.append(('maxLength', param['max_length'])) + + self._xml_start_tag('dataBar', attributes) self._write_cfvo(param['min_type'], param['min_value']) self._write_cfvo(param['max_type'], param['max_value'])
jmcnamara/XlsxWriter
7a48769abe7e68c0f3729c4f7c951ad5ca9a0bf8
diff --git a/xlsxwriter/test/worksheet/test_cond_format21.py b/xlsxwriter/test/worksheet/test_cond_format21.py new file mode 100644 index 00000000..4428b18e --- /dev/null +++ b/xlsxwriter/test/worksheet/test_cond_format21.py @@ -0,0 +1,141 @@ +############################################################################### +# +# Tests for XlsxWriter. +# +# Copyright (c), 2013-2016, John McNamara, [email protected] +# + +import unittest +from ...compatibility import StringIO +from ..helperfunctions import _xml_to_list +from ...worksheet import Worksheet + + +class TestAssembleWorksheet(unittest.TestCase): + """ + Test assembling a complete Worksheet file. + + """ + def test_assemble_xml_file(self): + """Test writing a worksheet with conditional formatting.""" + self.maxDiff = None + + fh = StringIO() + worksheet = Worksheet() + worksheet._set_filehandle(fh) + worksheet.select() + + worksheet.write('A1', 1) + worksheet.write('A2', 2) + worksheet.write('A3', 3) + worksheet.write('A4', 4) + worksheet.write('A5', 5) + worksheet.write('A6', 6) + worksheet.write('A7', 7) + worksheet.write('A8', 8) + worksheet.write('A9', 9) + worksheet.write('A10', 10) + worksheet.write('A11', 11) + worksheet.write('A12', 12) + + worksheet.conditional_format('A1:A12', + {'type': 'data_bar', + 'min_value': 5, + 'mid_value': 52, # Should be ignored. + 'max_value': 90, + 'min_length': 5, + 'max_length': 95, + 'min_type': 'num', + 'mid_type': 'percentile', # Should be ignored. + 'max_type': 'percent', + 'bar_color': '#8DB4E3', + }) + + worksheet._assemble_xml_file() + + exp = _xml_to_list(""" + <?xml version="1.0" encoding="UTF-8" standalone="yes"?> + <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> + <dimension ref="A1:A12"/> + <sheetViews> + <sheetView tabSelected="1" workbookViewId="0"/> + </sheetViews> + <sheetFormatPr defaultRowHeight="15"/> + <sheetData> + <row r="1" spans="1:1"> + <c r="A1"> + <v>1</v> + </c> + </row> + <row r="2" spans="1:1"> + <c r="A2"> + <v>2</v> + </c> + </row> + <row r="3" spans="1:1"> + <c r="A3"> + <v>3</v> + </c> + </row> + <row r="4" spans="1:1"> + <c r="A4"> + <v>4</v> + </c> + </row> + <row r="5" spans="1:1"> + <c r="A5"> + <v>5</v> + </c> + </row> + <row r="6" spans="1:1"> + <c r="A6"> + <v>6</v> + </c> + </row> + <row r="7" spans="1:1"> + <c r="A7"> + <v>7</v> + </c> + </row> + <row r="8" spans="1:1"> + <c r="A8"> + <v>8</v> + </c> + </row> + <row r="9" spans="1:1"> + <c r="A9"> + <v>9</v> + </c> + </row> + <row r="10" spans="1:1"> + <c r="A10"> + <v>10</v> + </c> + </row> + <row r="11" spans="1:1"> + <c r="A11"> + <v>11</v> + </c> + </row> + <row r="12" spans="1:1"> + <c r="A12"> + <v>12</v> + </c> + </row> + </sheetData> + <conditionalFormatting sqref="A1:A12"> + <cfRule type="dataBar" priority="1"> + <dataBar minLength="5" maxLength="95"> + <cfvo type="num" val="5"/> + <cfvo type="percent" val="90"/> + <color rgb="FF8DB4E3"/> + </dataBar> + </cfRule> + </conditionalFormatting> + <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/> + </worksheet> + """) + + got = _xml_to_list(fh.getvalue()) + + self.assertEqual(got, exp)
Feature Request: Add minLength and maxLength to dataBar attributes Attributes minLength and maxLength determine maximum and minimum histogram length in percentage of cell width. Currently those attributes are not set. Default values are 10 and 90 percent. It would be useful to have possibility of setting them manually. I've already implemented that. If you're OK I would create a merge request.
0.0
7a48769abe7e68c0f3729c4f7c951ad5ca9a0bf8
[ "xlsxwriter/test/worksheet/test_cond_format21.py::TestAssembleWorksheet::test_assemble_xml_file" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-11-22 18:13:23+00:00
bsd-2-clause
3,257
jmcnamara__XlsxWriter-956
diff --git a/xlsxwriter/worksheet.py b/xlsxwriter/worksheet.py index 7e14ff8b..c935f130 100644 --- a/xlsxwriter/worksheet.py +++ b/xlsxwriter/worksheet.py @@ -1835,6 +1835,10 @@ class Worksheet(xmlwriter.XMLwriter): warn("Autofit is not supported in constant_memory mode.") return + # No data written to the target sheet; nothing to autofit + if self.dim_rowmax is None: + return + # Store the max pixel width for each column. col_width_max = {}
jmcnamara/XlsxWriter
28a93525cdbf4176a9b58bbb26e7e56e259e4c00
diff --git a/xlsxwriter/test/comparison/test_autofit01.py b/xlsxwriter/test/comparison/test_autofit01.py index db83a060..855ae889 100644 --- a/xlsxwriter/test/comparison/test_autofit01.py +++ b/xlsxwriter/test/comparison/test_autofit01.py @@ -24,9 +24,12 @@ class TestCompareXLSXFiles(ExcelComparisonTest): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) - worksheet = workbook.add_worksheet() + # Before writing data, nothing to autofit (should not raise) + worksheet.autofit() + + # Write something that can be autofit worksheet.write_string(0, 0, "A") # Check for handling default/None width.
Bug: `TypeError` raised when autofitting an empty worksheet ### Current behavior If you have an empty `Worksheet` and try to autofit, an unexpected `TypeError` is raised. ### Expected behavior Should not raise an exception if there happens to be nothing to autofit. ### Sample code to reproduce ```python from xlsxwriter import Workbook with Workbook('hello.xlsx') as wb: ws = wb.add_worksheet() ws.autofit() # TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' ``` ### Environment ```markdown - XlsxWriter version: 3.0.8 - Python version: 3.11 ``` ### Any other information _No response_ ### OpenOffice and LibreOffice users - [ ] I have tested the output file with Excel.
0.0
28a93525cdbf4176a9b58bbb26e7e56e259e4c00
[ "xlsxwriter/test/comparison/test_autofit01.py::TestCompareXLSXFiles::test_create_file" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-02-24 05:18:23+00:00
bsd-2-clause
3,258
jmoiron__humanize-104
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index cfc7f74..d885c34 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,7 +28,7 @@ repos: - id: isort - repo: https://github.com/pre-commit/pygrep-hooks - rev: v1.4.4 + rev: v1.5.1 hooks: - id: python-check-blanket-noqa diff --git a/LICENCE b/LICENCE index 5a60037..e068795 100644 --- a/LICENCE +++ b/LICENCE @@ -1,4 +1,4 @@ -Copyright (c) 2010 Jason Moiron and Contributors +Copyright (c) 2010-2020 Jason Moiron and Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index 4201fe1..1398875 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ readable size or throughput. It is localized to: ## Usage -Integer humanization: +### Integer humanization ```pycon >>> import humanize @@ -46,7 +46,7 @@ Integer humanization: '41' ``` -Date & time humanization: +### Date & time humanization ```pycon >>> import humanize @@ -67,7 +67,35 @@ Date & time humanization: 'an hour ago' ``` -File size humanization: +#### Smaller units + +If seconds are too large, set `minimum_unit` to milliseconds or microseconds: + +```pycon +>>> import humanize +>>> import datetime as dt +>>> humanize.naturaldelta(dt.timedelta(seconds=2)) +'2 seconds' +``` +```pycon +>>> delta = dt.timedelta(milliseconds=4) +>>> humanize.naturaldelta(delta) +'a moment' +>>> humanize.naturaldelta(delta, minimum_unit="milliseconds") +'4 milliseconds' +>>> humanize.naturaldelta(delta, minimum_unit="microseconds") +'4000 microseconds' +``` +```pycon +>>> humanize.naturaltime(delta) +'now' +>>> humanize.naturaltime(delta, minimum_unit="milliseconds") +'4 milliseconds ago' +>>> humanize.naturaltime(delta, minimum_unit="microseconds") +'4000 microseconds ago' +``` + +### File size humanization ```pycon >>> import humanize @@ -79,7 +107,7 @@ File size humanization: '976.6K' ``` -Human readable floating point numbers: +### Human-readable floating point numbers ```pycon >>> import humanize diff --git a/setup.cfg b/setup.cfg index e7f6993..1fdc9cd 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,7 +2,7 @@ max_line_length = 88 [tool:isort] -known_third_party = freezegun,humanize,pkg_resources,setuptools +known_third_party = freezegun,humanize,pkg_resources,pytest,setuptools force_grid_wrap = 0 include_trailing_comma = True line_length = 88 diff --git a/src/humanize/time.py b/src/humanize/time.py index 5e90610..7f68ff9 100644 --- a/src/humanize/time.py +++ b/src/humanize/time.py @@ -4,6 +4,7 @@ ``contrib.humanize``.""" import datetime as dt +from enum import Enum from .i18n import gettext as _ from .i18n import ngettext @@ -11,6 +12,12 @@ from .i18n import ngettext __all__ = ["naturaldelta", "naturaltime", "naturalday", "naturaldate"] +class Unit(Enum): + MILLISECONDS = 0 + MICROSECONDS = 1 + SECONDS = 2 + + def _now(): return dt.datetime.now() @@ -24,10 +31,11 @@ def abs_timedelta(delta): return delta -def date_and_delta(value): +def date_and_delta(value, *, now=None): """Turn a value into a date and a timedelta which represents how long ago it was. If that's not possible, return (None, value).""" - now = _now() + if not now: + now = _now() if isinstance(value, dt.datetime): date = value delta = now - value @@ -44,12 +52,22 @@ def date_and_delta(value): return date, abs_timedelta(delta) -def naturaldelta(value, months=True): - """Given a timedelta or a number of seconds, return a natural - representation of the amount of time elapsed. This is similar to - ``naturaltime``, but does not add tense to the result. If ``months`` - is True, then a number of months (based on 30.5 days) will be used - for fuzziness between years.""" +def naturaldelta(value, months=True, minimum_unit="seconds"): + """Return a natural representation of a timedelta or number of seconds. + + This is similar to naturaltime, but does not add tense to the result. + + Args: + value: A timedelta or a number of seconds. + months: If True, then a number of months (based on 30.5 days) will be used for + fuzziness between years. + minimum_unit: If microseconds or milliseconds, use those units for subsecond + deltas. + + Returns: + str: A natural representation of the amount of time elapsed. + """ + minimum_unit = Unit[minimum_unit.upper()] date, delta = date_and_delta(value) if date is None: return value @@ -64,6 +82,17 @@ def naturaldelta(value, months=True): if not years and days < 1: if seconds == 0: + if minimum_unit == Unit.MICROSECONDS: + return ( + ngettext("%d microsecond", "%d microseconds", delta.microseconds) + % delta.microseconds + ) + elif minimum_unit == Unit.MILLISECONDS: + milliseconds = delta.microseconds / 1000 + return ( + ngettext("%d millisecond", "%d milliseconds", milliseconds) + % milliseconds + ) return _("a moment") elif seconds == 1: return _("a second") @@ -109,15 +138,26 @@ def naturaldelta(value, months=True): return ngettext("%d year", "%d years", years) % years -def naturaltime(value, future=False, months=True): - """Given a datetime or a number of seconds, return a natural representation - of that time in a resolution that makes sense. This is more or less - compatible with Django's ``naturaltime`` filter. ``future`` is ignored for - datetimes, where the tense is always figured out based on the current time. - If an integer is passed, the return value will be past tense by default, - unless ``future`` is set to True.""" +def naturaltime(value, future=False, months=True, minimum_unit="seconds"): + """Return a natural representation of a time in a resolution that makes sense. + + This is more or less compatible with Django's naturaltime filter. + + Args: + value: A timedate or a number of seconds. + future: Ignored for datetimes, where the tense is always figured out based on + the current time. For integers, the return value will be past tense by + default, unless future is True. + months: If True, then a number of months (based on 30.5 days) will be used for + fuzziness between years. + minimum_unit: If microseconds or milliseconds, use those units for subsecond + times. + + Returns: + str: A natural representation of the input in a resolution that makes sense. + """ now = _now() - date, delta = date_and_delta(value) + date, delta = date_and_delta(value, now=now) if date is None: return value # determine tense by value only if datetime/timedelta were passed @@ -125,7 +165,7 @@ def naturaltime(value, future=False, months=True): future = date > now ago = _("%s from now") if future else _("%s ago") - delta = naturaldelta(delta, months) + delta = naturaldelta(delta, months, minimum_unit) if delta == _("a moment"): return _("now")
jmoiron/humanize
d64655aa8f2736b1131ff8a91a128daed7f36cc3
diff --git a/tests/test_time.py b/tests/test_time.py index 0c0e3ea..3ce02be 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -5,12 +5,22 @@ import datetime as dt from unittest.mock import patch +import pytest from freezegun import freeze_time from humanize import time from .base import HumanizeTestCase -ONE_DAY = dt.timedelta(days=1) +ONE_DAY_DELTA = dt.timedelta(days=1) + +# In seconds +ONE_YEAR = 31556952 +ONE_DAY = 86400 +ONE_HOUR = 3600 +FOUR_MILLISECONDS = 4 / 1000 +ONE_MILLISECOND = 1 / 1000 +FOUR_MICROSECONDS = 4 / 1000000 +ONE_MICROSECOND = 1 / 1000000 class FakeDate: @@ -268,8 +278,8 @@ class TimeTestCase(HumanizeTestCase): def test_naturalday(self): # Arrange today = dt.date.today() - tomorrow = today + ONE_DAY - yesterday = today - ONE_DAY + tomorrow = today + ONE_DAY_DELTA + yesterday = today - ONE_DAY_DELTA someday = dt.date(today.year, 3, 5) someday_result = "Mar 05" @@ -309,8 +319,8 @@ class TimeTestCase(HumanizeTestCase): def test_naturaldate(self): # Arrange today = dt.date.today() - tomorrow = today + ONE_DAY - yesterday = today - ONE_DAY + tomorrow = today + ONE_DAY_DELTA + yesterday = today - ONE_DAY_DELTA someday = dt.date(today.year, 3, 5) someday_result = "Mar 05" @@ -340,3 +350,117 @@ class TimeTestCase(HumanizeTestCase): # Act / Assert self.assertManyResults(time.naturaldate, test_list, result_list) + + [email protected]( + "seconds, expected", + [ + (ONE_MICROSECOND, "a moment"), + (FOUR_MICROSECONDS, "a moment"), + (ONE_MILLISECOND, "a moment"), + (FOUR_MILLISECONDS, "a moment"), + (2, "2 seconds"), + (4, "4 seconds"), + (ONE_HOUR + FOUR_MILLISECONDS, "an hour"), + (ONE_DAY + FOUR_MILLISECONDS, "a day"), + (ONE_YEAR + FOUR_MICROSECONDS, "a year"), + ], +) +def test_naturaldelta_minimum_unit_default(seconds, expected): + # Arrange + delta = dt.timedelta(seconds=seconds) + + # Act / Assert + assert time.naturaldelta(delta) == expected + + [email protected]( + "minimum_unit, seconds, expected", + [ + ("seconds", ONE_MICROSECOND, "a moment"), + ("seconds", FOUR_MICROSECONDS, "a moment"), + ("seconds", ONE_MILLISECOND, "a moment"), + ("seconds", FOUR_MILLISECONDS, "a moment"), + ("seconds", 2, "2 seconds"), + ("seconds", 4, "4 seconds"), + ("seconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour"), + ("seconds", ONE_DAY + FOUR_MILLISECONDS, "a day"), + ("seconds", ONE_YEAR + FOUR_MICROSECONDS, "a year"), + ("microseconds", ONE_MICROSECOND, "1 microsecond"), + ("microseconds", FOUR_MICROSECONDS, "4 microseconds"), + ("microseconds", 2, "2 seconds"), + ("microseconds", 4, "4 seconds"), + ("microseconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour"), + ("microseconds", ONE_DAY + FOUR_MILLISECONDS, "a day"), + ("microseconds", ONE_YEAR + FOUR_MICROSECONDS, "a year"), + ("milliseconds", ONE_MILLISECOND, "1 millisecond"), + ("milliseconds", FOUR_MILLISECONDS, "4 milliseconds"), + ("milliseconds", 2, "2 seconds"), + ("milliseconds", 4, "4 seconds"), + ("milliseconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour"), + ("milliseconds", ONE_YEAR + FOUR_MICROSECONDS, "a year"), + ], +) +def test_naturaldelta_minimum_unit_explicit(minimum_unit, seconds, expected): + # Arrange + delta = dt.timedelta(seconds=seconds) + + # Act / Assert + assert time.naturaldelta(delta, minimum_unit=minimum_unit) == expected + + [email protected]( + "seconds, expected", + [ + (ONE_MICROSECOND, "now"), + (FOUR_MICROSECONDS, "now"), + (ONE_MILLISECOND, "now"), + (FOUR_MILLISECONDS, "now"), + (2, "2 seconds ago"), + (4, "4 seconds ago"), + (ONE_HOUR + FOUR_MILLISECONDS, "an hour ago"), + (ONE_DAY + FOUR_MILLISECONDS, "a day ago"), + (ONE_YEAR + FOUR_MICROSECONDS, "a year ago"), + ], +) +def test_naturaltime_minimum_unit_default(seconds, expected): + # Arrange + delta = dt.timedelta(seconds=seconds) + + # Act / Assert + assert time.naturaltime(delta) == expected + + [email protected]( + "minimum_unit, seconds, expected", + [ + ("seconds", ONE_MICROSECOND, "now"), + ("seconds", FOUR_MICROSECONDS, "now"), + ("seconds", ONE_MILLISECOND, "now"), + ("seconds", FOUR_MILLISECONDS, "now"), + ("seconds", 2, "2 seconds ago"), + ("seconds", 4, "4 seconds ago"), + ("seconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour ago"), + ("seconds", ONE_DAY + FOUR_MILLISECONDS, "a day ago"), + ("seconds", ONE_YEAR + FOUR_MICROSECONDS, "a year ago"), + ("microseconds", ONE_MICROSECOND, "1 microsecond ago"), + ("microseconds", FOUR_MICROSECONDS, "4 microseconds ago"), + ("microseconds", 2, "2 seconds ago"), + ("microseconds", 4, "4 seconds ago"), + ("microseconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour ago"), + ("microseconds", ONE_DAY + FOUR_MILLISECONDS, "a day ago"), + ("microseconds", ONE_YEAR + FOUR_MICROSECONDS, "a year ago"), + ("milliseconds", ONE_MILLISECOND, "1 millisecond ago"), + ("milliseconds", FOUR_MILLISECONDS, "4 milliseconds ago"), + ("milliseconds", 2, "2 seconds ago"), + ("milliseconds", 4, "4 seconds ago"), + ("milliseconds", ONE_HOUR + FOUR_MILLISECONDS, "an hour ago"), + ("milliseconds", ONE_YEAR + FOUR_MICROSECONDS, "a year ago"), + ], +) +def test_naturaltime_minimum_unit_explicit(minimum_unit, seconds, expected): + # Arrange + delta = dt.timedelta(seconds=seconds) + + # Act / Assert + assert time.naturaltime(delta, minimum_unit=minimum_unit) == expected
Support milliseconds, microseconds etc. If you run something for a minute, `humanize` is great. If you want to tell the user what you did in that time (100.000 things), and then want to brag about how fast that is (`a moment` per thing?), `humanize` is not super-great any more :)
0.0
d64655aa8f2736b1131ff8a91a128daed7f36cc3
[ "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-31556952.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-31556952.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-31556952.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-31556952.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-31556952.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-31556952.000004-a" ]
[ "tests/test_time.py::TimeUtilitiesTestCase::test_date_and_delta", "tests/test_time.py::TimeTestCase::test_naturaldate", "tests/test_time.py::TimeTestCase::test_naturalday", "tests/test_time.py::TimeTestCase::test_naturaldelta", "tests/test_time.py::TimeTestCase::test_naturaldelta_nomonths", "tests/test_time.py::TimeTestCase::test_naturaltime", "tests/test_time.py::TimeTestCase::test_naturaltime_nomonths", "tests/test_time.py::test_naturaldelta_minimum_unit_default[1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[31556952.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_default[1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[2-2", "tests/test_time.py::test_naturaltime_minimum_unit_default[4-4", "tests/test_time.py::test_naturaltime_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_default[31556952.000004-a" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-12 12:37:24+00:00
mit
3,259
jmoiron__humanize-121
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 225fdc9..7fa46ec 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -2,6 +2,6 @@ Fixes # Changes proposed in this pull request: - * - * - * +* +* +* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 50a676f..3883da1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/asottile/pyupgrade - rev: v2.0.1 + rev: v2.1.0 hooks: - id: pyupgrade args: ["--py3-plus"] @@ -18,7 +18,7 @@ repos: additional_dependencies: [flake8-2020, flake8-implicit-str-concat] - repo: https://github.com/asottile/seed-isort-config - rev: v1.9.4 + rev: v2.1.0 hooks: - id: seed-isort-config diff --git a/src/humanize/number.py b/src/humanize/number.py index ffe257f..f57588e 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -106,16 +106,23 @@ def intword(value, format="%.1f"): def apnumber(value): - """For numbers 1-9, returns the number spelled out. Otherwise, returns the - number. This follows Associated Press style. This always returns a string - unless the value was not int-able, unlike the Django filter.""" + """Converts an integer to Associated Press style. + + Args: + value (int, float, string): Integer to convert. + + Returns: + str: For numbers 0-9, the number spelled out. Otherwise, the number. This always + returns a string unless the value was not int-able, unlike the Django filter. + """ try: value = int(value) except (TypeError, ValueError): return value - if not 0 < value < 10: + if not 0 <= value < 10: return str(value) return ( + _("zero"), _("one"), _("two"), _("three"), @@ -125,7 +132,7 @@ def apnumber(value): _("seven"), _("eight"), _("nine"), - )[value - 1] + )[value] def fractional(value):
jmoiron/humanize
aaca29f35306c48c9965047ac5d39807a33652a7
diff --git a/tests/test_number.py b/tests/test_number.py index 4b827d3..cdb0d7c 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -86,6 +86,7 @@ def test_intword(test_args, expected): @pytest.mark.parametrize( "test_input, expected", [ + (0, "zero"), (1, "one"), (2, "two"), (4, "four"),
humanize.apnumber(0) should return zero `humanize.appnumber` returns 0 for 0, while (I think) it should return 'zero': ```pycon >>> import humanize >>> humanize.apnumber(0) '0' >>> humanize.apnumber(1) 'one' >>> humanize.apnumber(2) 'two' >>> ```
0.0
aaca29f35306c48c9965047ac5d39807a33652a7
[ "tests/test_number.py::test_apnumber[0-zero]" ]
[ "tests/test_number.py::test_ordinal[1-1st]", "tests/test_number.py::test_ordinal[2-2nd]", "tests/test_number.py::test_ordinal[3-3rd]", "tests/test_number.py::test_ordinal[4-4th]", "tests/test_number.py::test_ordinal[11-11th]", "tests/test_number.py::test_ordinal[12-12th]", "tests/test_number.py::test_ordinal[13-13th]", "tests/test_number.py::test_ordinal[101-101st]", "tests/test_number.py::test_ordinal[102-102nd]", "tests/test_number.py::test_ordinal[103-103rd]", "tests/test_number.py::test_ordinal[111-111th]", "tests/test_number.py::test_ordinal[something", "tests/test_number.py::test_ordinal[None-None]", "tests/test_number.py::test_intcomma[100-100_0]", "tests/test_number.py::test_intcomma[1000-1,000_0]", "tests/test_number.py::test_intcomma[10123-10,123_0]", "tests/test_number.py::test_intcomma[10311-10,311_0]", "tests/test_number.py::test_intcomma[1000000-1,000,000_0]", "tests/test_number.py::test_intcomma[1234567.25-1,234,567.25]", "tests/test_number.py::test_intcomma[100-100_1]", "tests/test_number.py::test_intcomma[1000-1,000_1]", "tests/test_number.py::test_intcomma[10123-10,123_1]", "tests/test_number.py::test_intcomma[10311-10,311_1]", "tests/test_number.py::test_intcomma[1000000-1,000,000_1]", "tests/test_number.py::test_intcomma[1234567.1234567-1,234,567.1234567]", "tests/test_number.py::test_intcomma[None-None]", "tests/test_number.py::test_intword_powers", "tests/test_number.py::test_intword[test_args0-100]", "tests/test_number.py::test_intword[test_args1-1.0", "tests/test_number.py::test_intword[test_args2-1.2", "tests/test_number.py::test_intword[test_args3-1.3", "tests/test_number.py::test_intword[test_args4-1.0", "tests/test_number.py::test_intword[test_args5-1.0", "tests/test_number.py::test_intword[test_args6-2.0", "tests/test_number.py::test_intword[test_args7-1.0", "tests/test_number.py::test_intword[test_args8-1.0", "tests/test_number.py::test_intword[test_args9-6.0", "tests/test_number.py::test_intword[test_args10-1.0", "tests/test_number.py::test_intword[test_args11-1.0", "tests/test_number.py::test_intword[test_args12-1.3", "tests/test_number.py::test_intword[test_args13-3.5", "tests/test_number.py::test_intword[test_args14-8.1", "tests/test_number.py::test_intword[test_args15-None]", "tests/test_number.py::test_intword[test_args16-1.23", "tests/test_number.py::test_intword[test_args17-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000]", "tests/test_number.py::test_apnumber[1-one]", "tests/test_number.py::test_apnumber[2-two]", "tests/test_number.py::test_apnumber[4-four]", "tests/test_number.py::test_apnumber[5-five]", "tests/test_number.py::test_apnumber[9-nine]", "tests/test_number.py::test_apnumber[10-10]", "tests/test_number.py::test_apnumber[7-seven]", "tests/test_number.py::test_apnumber[None-None]", "tests/test_number.py::test_fractional[1-1]", "tests/test_number.py::test_fractional[2.0-2]", "tests/test_number.py::test_fractional[1.3333333333333333-1", "tests/test_number.py::test_fractional[0.8333333333333334-5/6]", "tests/test_number.py::test_fractional[7-7]", "tests/test_number.py::test_fractional[8.9-8", "tests/test_number.py::test_fractional[ten-ten]", "tests/test_number.py::test_fractional[None-None]", "tests/test_number.py::test_scientific[test_args0-1.00", "tests/test_number.py::test_scientific[test_args1-1.00", "tests/test_number.py::test_scientific[test_args2-5.50", "tests/test_number.py::test_scientific[test_args3-5.78", "tests/test_number.py::test_scientific[test_args4-1.00", "tests/test_number.py::test_scientific[test_args5-9.90", "tests/test_number.py::test_scientific[test_args6-3.00", "tests/test_number.py::test_scientific[test_args7-foo]", "tests/test_number.py::test_scientific[test_args8-None]", "tests/test_number.py::test_scientific[test_args9-1.0", "tests/test_number.py::test_scientific[test_args10-3.0", "tests/test_number.py::test_scientific[test_args11-1", "tests/test_number.py::test_scientific[test_args12-3" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-05 21:23:26+00:00
mit
3,260
jmoiron__humanize-123
diff --git a/src/humanize/number.py b/src/humanize/number.py index f57588e..013448e 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -35,11 +35,19 @@ def ordinal(value): return "%d%s" % (value, t[value % 10]) -def intcomma(value): +def intcomma(value, ndigits=None): """Converts an integer to a string containing commas every three digits. - For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain - some compatibility with Django's intcomma, this function also accepts - floats.""" + + For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some + compatibility with Django's intcomma, this function also accepts floats. + + Args: + value (int, float, string): Integer or float to convert. + ndigits (int, None): digits of precision for rounding after the decimal point. + + Returns: + str: string containing commas every three digits. + """ try: if isinstance(value, str): float(value.replace(",", "")) @@ -47,7 +55,12 @@ def intcomma(value): float(value) except (TypeError, ValueError): return value - orig = str(value) + + if ndigits: + orig = "{0:.{1}f}".format(value, ndigits) + else: + orig = str(value) + new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig) if orig == new: return new
jmoiron/humanize
77d943afaaef5a20b946f09ca2130dddb1dc85da
diff --git a/tests/test_number.py b/tests/test_number.py index cdb0d7c..c7cbc66 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -30,25 +30,36 @@ def test_ordinal(test_input, expected): @pytest.mark.parametrize( - "test_input, expected", + "test_args, expected", [ - (100, "100"), - (1000, "1,000"), - (10123, "10,123"), - (10311, "10,311"), - (1000000, "1,000,000"), - (1234567.25, "1,234,567.25"), - ("100", "100"), - ("1000", "1,000"), - ("10123", "10,123"), - ("10311", "10,311"), - ("1000000", "1,000,000"), - ("1234567.1234567", "1,234,567.1234567"), - (None, None), + ([100], "100"), + ([1000], "1,000"), + ([10123], "10,123"), + ([10311], "10,311"), + ([1000000], "1,000,000"), + ([1234567.25], "1,234,567.25"), + (["100"], "100"), + (["1000"], "1,000"), + (["10123"], "10,123"), + (["10311"], "10,311"), + (["1000000"], "1,000,000"), + (["1234567.1234567"], "1,234,567.1234567"), + ([None], None), + ([14308.40], "14,308.4"), + ([14308.40, None], "14,308.4"), + ([14308.40, 1], "14,308.4"), + ([14308.40, 2], "14,308.40"), + ([14308.40, 3], "14,308.400"), + ([1234.5454545], "1,234.5454545"), + ([1234.5454545, None], "1,234.5454545"), + ([1234.5454545, 1], "1,234.5"), + ([1234.5454545, 2], "1,234.55"), + ([1234.5454545, 3], "1,234.545"), + ([1234.5454545, 10], "1,234.5454545000"), ], ) -def test_intcomma(test_input, expected): - assert humanize.intcomma(test_input) == expected +def test_intcomma(test_args, expected): + assert humanize.intcomma(*test_args) == expected def test_intword_powers():
intcomma() variant needed to handle money When using intcomma on a dollar value like 14308.40, I get '14,308.4'. It would be nice to have a moneycomma(14308.40,2) which gives me '14,308.40'.
0.0
77d943afaaef5a20b946f09ca2130dddb1dc85da
[ "tests/test_number.py::test_intcomma[test_args14-14,308.4]", "tests/test_number.py::test_intcomma[test_args15-14,308.4]", "tests/test_number.py::test_intcomma[test_args16-14,308.40]", "tests/test_number.py::test_intcomma[test_args17-14,308.400]", "tests/test_number.py::test_intcomma[test_args19-1,234.5454545]", "tests/test_number.py::test_intcomma[test_args20-1,234.5]", "tests/test_number.py::test_intcomma[test_args21-1,234.55]", "tests/test_number.py::test_intcomma[test_args22-1,234.545]", "tests/test_number.py::test_intcomma[test_args23-1,234.5454545000]" ]
[ "tests/test_number.py::test_ordinal[1-1st]", "tests/test_number.py::test_ordinal[2-2nd]", "tests/test_number.py::test_ordinal[3-3rd]", "tests/test_number.py::test_ordinal[4-4th]", "tests/test_number.py::test_ordinal[11-11th]", "tests/test_number.py::test_ordinal[12-12th]", "tests/test_number.py::test_ordinal[13-13th]", "tests/test_number.py::test_ordinal[101-101st]", "tests/test_number.py::test_ordinal[102-102nd]", "tests/test_number.py::test_ordinal[103-103rd]", "tests/test_number.py::test_ordinal[111-111th]", "tests/test_number.py::test_ordinal[something", "tests/test_number.py::test_ordinal[None-None]", "tests/test_number.py::test_intcomma[test_args0-100]", "tests/test_number.py::test_intcomma[test_args1-1,000]", "tests/test_number.py::test_intcomma[test_args2-10,123]", "tests/test_number.py::test_intcomma[test_args3-10,311]", "tests/test_number.py::test_intcomma[test_args4-1,000,000]", "tests/test_number.py::test_intcomma[test_args5-1,234,567.25]", "tests/test_number.py::test_intcomma[test_args6-100]", "tests/test_number.py::test_intcomma[test_args7-1,000]", "tests/test_number.py::test_intcomma[test_args8-10,123]", "tests/test_number.py::test_intcomma[test_args9-10,311]", "tests/test_number.py::test_intcomma[test_args10-1,000,000]", "tests/test_number.py::test_intcomma[test_args11-1,234,567.1234567]", "tests/test_number.py::test_intcomma[test_args12-None]", "tests/test_number.py::test_intcomma[test_args13-14,308.4]", "tests/test_number.py::test_intcomma[test_args18-1,234.5454545]", "tests/test_number.py::test_intword_powers", "tests/test_number.py::test_intword[test_args0-100]", "tests/test_number.py::test_intword[test_args1-1.0", "tests/test_number.py::test_intword[test_args2-1.2", "tests/test_number.py::test_intword[test_args3-1.3", "tests/test_number.py::test_intword[test_args4-1.0", "tests/test_number.py::test_intword[test_args5-1.0", "tests/test_number.py::test_intword[test_args6-2.0", "tests/test_number.py::test_intword[test_args7-1.0", "tests/test_number.py::test_intword[test_args8-1.0", "tests/test_number.py::test_intword[test_args9-6.0", "tests/test_number.py::test_intword[test_args10-1.0", "tests/test_number.py::test_intword[test_args11-1.0", "tests/test_number.py::test_intword[test_args12-1.3", "tests/test_number.py::test_intword[test_args13-3.5", "tests/test_number.py::test_intword[test_args14-8.1", "tests/test_number.py::test_intword[test_args15-None]", "tests/test_number.py::test_intword[test_args16-1.23", "tests/test_number.py::test_intword[test_args17-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000]", "tests/test_number.py::test_apnumber[0-zero]", "tests/test_number.py::test_apnumber[1-one]", "tests/test_number.py::test_apnumber[2-two]", "tests/test_number.py::test_apnumber[4-four]", "tests/test_number.py::test_apnumber[5-five]", "tests/test_number.py::test_apnumber[9-nine]", "tests/test_number.py::test_apnumber[10-10]", "tests/test_number.py::test_apnumber[7-seven]", "tests/test_number.py::test_apnumber[None-None]", "tests/test_number.py::test_fractional[1-1]", "tests/test_number.py::test_fractional[2.0-2]", "tests/test_number.py::test_fractional[1.3333333333333333-1", "tests/test_number.py::test_fractional[0.8333333333333334-5/6]", "tests/test_number.py::test_fractional[7-7]", "tests/test_number.py::test_fractional[8.9-8", "tests/test_number.py::test_fractional[ten-ten]", "tests/test_number.py::test_fractional[None-None]", "tests/test_number.py::test_scientific[test_args0-1.00", "tests/test_number.py::test_scientific[test_args1-1.00", "tests/test_number.py::test_scientific[test_args2-5.50", "tests/test_number.py::test_scientific[test_args3-5.78", "tests/test_number.py::test_scientific[test_args4-1.00", "tests/test_number.py::test_scientific[test_args5-9.90", "tests/test_number.py::test_scientific[test_args6-3.00", "tests/test_number.py::test_scientific[test_args7-foo]", "tests/test_number.py::test_scientific[test_args8-None]", "tests/test_number.py::test_scientific[test_args9-1.0", "tests/test_number.py::test_scientific[test_args10-3.0", "tests/test_number.py::test_scientific[test_args11-1", "tests/test_number.py::test_scientific[test_args12-3" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-03-09 15:00:51+00:00
mit
3,261
jmoiron__humanize-170
diff --git a/src/humanize/time.py b/src/humanize/time.py index 319d7e4..e40c482 100644 --- a/src/humanize/time.py +++ b/src/humanize/time.py @@ -426,6 +426,20 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"): >>> precisedelta(delta, suppress=['seconds', 'milliseconds', 'microseconds']) '1.50 minutes' + ``` + + If the delta is too small to be represented with the minimum unit, + a value of zero will be returned: + + ```pycon + >>> delta = dt.timedelta(seconds=1) + >>> precisedelta(delta, minimum_unit="minutes") + '0.02 minutes' + + >>> delta = dt.timedelta(seconds=0.1) + >>> precisedelta(delta, minimum_unit="minutes") + '0 minutes' + ``` """ date, delta = date_and_delta(value) @@ -501,7 +515,7 @@ def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f"): texts = [] for unit, fmt in zip(reversed(Unit), fmts): singular_txt, plural_txt, value = fmt - if value > 0: + if value > 0 or (not texts and unit == min_unit): fmt_txt = ngettext(singular_txt, plural_txt, value) if unit == min_unit and math.modf(value)[0] > 0: fmt_txt = fmt_txt.replace("%d", format)
jmoiron/humanize
9d9de69177154b41b2d6ef412d1487639e99833d
diff --git a/tests/test_time.py b/tests/test_time.py index 90c0130..f0311ce 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -496,6 +496,11 @@ def test_precisedelta_one_unit_enough(val, min_unit, expected): "microseconds", "1 year, 5 days and 2 seconds", ), + ( + dt.timedelta(seconds=0.01), + "minutes", + "0 minutes", + ), ], ) def test_precisedelta_multiple_units(val, min_unit, expected):
precisedelta with minimum unit seconds fails when seconds is a very small value ### What did you do? Calculated a small delta. ```python import humanize from datetime import timedelta duration_seconds = 1e-06 # A small value, or 0 delta = timedelta(seconds=duration_seconds) output = humanize.precisedelta(delta, minimum_unit="minutes") print(output) ``` ### What did you expect to happen? Output would be 0 seconds. Alternatively, a better error message or a warning in the documentation would be helpful. ### What actually happened? ``` > tail = texts[-1] E IndexError: list index out of range ``` ### What versions are you using? * OS: ubuntu * Python: 3.6.12 * Humanize: 2.6.0
0.0
9d9de69177154b41b2d6ef412d1487639e99833d
[ "tests/test_time.py::test_precisedelta_multiple_units[val8-minutes-0" ]
[ "tests/test_time.py::test_date_and_delta", "tests/test_time.py::test_naturaldelta_nomonths[test_input0-7", "tests/test_time.py::test_naturaldelta_nomonths[test_input1-31", "tests/test_time.py::test_naturaldelta_nomonths[test_input2-230", "tests/test_time.py::test_naturaldelta_nomonths[test_input3-1", "tests/test_time.py::test_naturaldelta[0-a", "tests/test_time.py::test_naturaldelta[1-a", "tests/test_time.py::test_naturaldelta[30-30", "tests/test_time.py::test_naturaldelta[test_input3-a", "tests/test_time.py::test_naturaldelta[test_input4-2", "tests/test_time.py::test_naturaldelta[test_input5-an", "tests/test_time.py::test_naturaldelta[test_input6-23", "tests/test_time.py::test_naturaldelta[test_input7-a", "tests/test_time.py::test_naturaldelta[test_input8-1", "tests/test_time.py::test_naturaldelta[test_input9-2", "tests/test_time.py::test_naturaldelta[test_input10-a", "tests/test_time.py::test_naturaldelta[test_input11-30", "tests/test_time.py::test_naturaldelta[test_input12-a", "tests/test_time.py::test_naturaldelta[test_input13-2", "tests/test_time.py::test_naturaldelta[test_input14-an", "tests/test_time.py::test_naturaldelta[test_input15-23", "tests/test_time.py::test_naturaldelta[test_input16-a", "tests/test_time.py::test_naturaldelta[test_input17-1", "tests/test_time.py::test_naturaldelta[test_input18-2", "tests/test_time.py::test_naturaldelta[test_input19-27", "tests/test_time.py::test_naturaldelta[test_input20-1", "tests/test_time.py::test_naturaldelta[test_input22-2", "tests/test_time.py::test_naturaldelta[test_input23-1", "tests/test_time.py::test_naturaldelta[test_input24-a", "tests/test_time.py::test_naturaldelta[test_input25-2", "tests/test_time.py::test_naturaldelta[test_input26-9", "tests/test_time.py::test_naturaldelta[test_input27-a", "tests/test_time.py::test_naturaldelta[NaN-NaN]", "tests/test_time.py::test_naturaltime[test_input0-now]", "tests/test_time.py::test_naturaltime[test_input1-a", "tests/test_time.py::test_naturaltime[test_input2-30", "tests/test_time.py::test_naturaltime[test_input3-a", "tests/test_time.py::test_naturaltime[test_input4-2", "tests/test_time.py::test_naturaltime[test_input5-an", "tests/test_time.py::test_naturaltime[test_input6-23", "tests/test_time.py::test_naturaltime[test_input7-a", "tests/test_time.py::test_naturaltime[test_input8-1", "tests/test_time.py::test_naturaltime[test_input9-2", "tests/test_time.py::test_naturaltime[test_input10-a", "tests/test_time.py::test_naturaltime[test_input11-30", "tests/test_time.py::test_naturaltime[test_input12-a", "tests/test_time.py::test_naturaltime[test_input13-2", "tests/test_time.py::test_naturaltime[test_input14-an", "tests/test_time.py::test_naturaltime[test_input15-23", "tests/test_time.py::test_naturaltime[test_input16-a", "tests/test_time.py::test_naturaltime[test_input17-1", "tests/test_time.py::test_naturaltime[test_input18-2", "tests/test_time.py::test_naturaltime[test_input19-27", "tests/test_time.py::test_naturaltime[test_input20-1", "tests/test_time.py::test_naturaltime[30-30", "tests/test_time.py::test_naturaltime[test_input22-2", "tests/test_time.py::test_naturaltime[test_input23-1", "tests/test_time.py::test_naturaltime[NaN-NaN]", "tests/test_time.py::test_naturaltime_nomonths[test_input0-now]", "tests/test_time.py::test_naturaltime_nomonths[test_input1-a", "tests/test_time.py::test_naturaltime_nomonths[test_input2-30", "tests/test_time.py::test_naturaltime_nomonths[test_input3-a", "tests/test_time.py::test_naturaltime_nomonths[test_input4-2", "tests/test_time.py::test_naturaltime_nomonths[test_input5-an", "tests/test_time.py::test_naturaltime_nomonths[test_input6-23", "tests/test_time.py::test_naturaltime_nomonths[test_input7-a", "tests/test_time.py::test_naturaltime_nomonths[test_input8-17", "tests/test_time.py::test_naturaltime_nomonths[test_input9-47", "tests/test_time.py::test_naturaltime_nomonths[test_input10-1", "tests/test_time.py::test_naturaltime_nomonths[test_input11-2", "tests/test_time.py::test_naturaltime_nomonths[test_input12-a", "tests/test_time.py::test_naturaltime_nomonths[test_input13-30", "tests/test_time.py::test_naturaltime_nomonths[test_input14-a", "tests/test_time.py::test_naturaltime_nomonths[test_input15-2", "tests/test_time.py::test_naturaltime_nomonths[test_input16-an", "tests/test_time.py::test_naturaltime_nomonths[test_input17-23", "tests/test_time.py::test_naturaltime_nomonths[test_input18-a", "tests/test_time.py::test_naturaltime_nomonths[test_input19-1", "tests/test_time.py::test_naturaltime_nomonths[test_input20-2", "tests/test_time.py::test_naturaltime_nomonths[test_input21-27", "tests/test_time.py::test_naturaltime_nomonths[test_input22-1", "tests/test_time.py::test_naturaltime_nomonths[30-30", "tests/test_time.py::test_naturaltime_nomonths[test_input24-2", "tests/test_time.py::test_naturaltime_nomonths[test_input25-1", "tests/test_time.py::test_naturaltime_nomonths[NaN-NaN]", "tests/test_time.py::test_naturalday[test_args0-today]", "tests/test_time.py::test_naturalday[test_args1-tomorrow]", "tests/test_time.py::test_naturalday[test_args2-yesterday]", "tests/test_time.py::test_naturalday[test_args3-Mar", "tests/test_time.py::test_naturalday[test_args4-02/26/1984]", "tests/test_time.py::test_naturalday[test_args5-1982.06.27]", "tests/test_time.py::test_naturalday[test_args6-None]", "tests/test_time.py::test_naturalday[test_args7-Not", "tests/test_time.py::test_naturalday[test_args8-expected8]", "tests/test_time.py::test_naturalday[test_args9-expected9]", "tests/test_time.py::test_naturaldate[test_input0-today]", "tests/test_time.py::test_naturaldate[test_input1-tomorrow]", "tests/test_time.py::test_naturaldate[test_input2-yesterday]", "tests/test_time.py::test_naturaldate[test_input3-Mar", "tests/test_time.py::test_naturaldate[test_input4-Jun", "tests/test_time.py::test_naturaldate[None-None]", "tests/test_time.py::test_naturaldate[Not", "tests/test_time.py::test_naturaldate[test_input7-expected7]", "tests/test_time.py::test_naturaldate[test_input8-expected8]", "tests/test_time.py::test_naturaldate[test_input9-Feb", "tests/test_time.py::test_naturaldate[test_input10-Mar", "tests/test_time.py::test_naturaldate[test_input11-Apr", "tests/test_time.py::test_naturaldate[test_input12-May", "tests/test_time.py::test_naturaldate[test_input13-Jun", "tests/test_time.py::test_naturaldate[test_input14-Jul", "tests/test_time.py::test_naturaldate[test_input15-Aug", "tests/test_time.py::test_naturaldate[test_input16-Sep", "tests/test_time.py::test_naturaldate[test_input17-Oct", "tests/test_time.py::test_naturaldate[test_input18-Nov", "tests/test_time.py::test_naturaldate[test_input19-Dec", "tests/test_time.py::test_naturaldate[test_input20-Jan", "tests/test_time.py::test_naturaldate[test_input21-today]", "tests/test_time.py::test_naturaldate[test_input22-Mar", "tests/test_time.py::test_naturaldate[test_input23-Apr", "tests/test_time.py::test_naturaldate[test_input24-May", "tests/test_time.py::test_naturaldate[test_input25-Jun", "tests/test_time.py::test_naturaldate[test_input26-Jul", "tests/test_time.py::test_naturaldate[test_input27-Aug", "tests/test_time.py::test_naturaldate[test_input28-Sep", "tests/test_time.py::test_naturaldate[test_input29-Oct", "tests/test_time.py::test_naturaldate[test_input30-Nov", "tests/test_time.py::test_naturaldate[test_input31-Dec", "tests/test_time.py::test_naturaldate[test_input32-Jan", "tests/test_time.py::test_naturaldate[test_input33-Feb", "tests/test_time.py::test_naturaldelta_minimum_unit_default[1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.101943-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-4e-06-0", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.101943-101", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-0.004-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-0.101943-101", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_when_explicit[test_input0-when0-a", "tests/test_time.py::test_naturaldelta_when_explicit[test_input1-when1-a", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value0-None]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value1-when1]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value2-None]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value3-when3]", "tests/test_time.py::test_naturaltime_minimum_unit_default[1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[2-2", "tests/test_time.py::test_naturaltime_minimum_unit_default[4-4", "tests/test_time.py::test_naturaltime_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_default[31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.101943-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-4e-06-0", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.101943-101", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-0.004-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-0.101943-101", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-31557600.000004-a", "tests/test_time.py::test_precisedelta_one_unit_enough[val0-microseconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[val1-microseconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[val2-microseconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[val3-microseconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[val4-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[1-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[2-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[60-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[120-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[3600-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[7200-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[86400-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[172800-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[31536000-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[63072000-seconds-2", "tests/test_time.py::test_precisedelta_multiple_units[val0-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val1-microseconds-2", "tests/test_time.py::test_precisedelta_multiple_units[val2-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val3-microseconds-4", "tests/test_time.py::test_precisedelta_multiple_units[val4-microseconds-5", "tests/test_time.py::test_precisedelta_multiple_units[val5-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val6-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val7-microseconds-1", "tests/test_time.py::test_precisedelta_custom_format[val0-milliseconds-%0.4f-1.0010", "tests/test_time.py::test_precisedelta_custom_format[val1-milliseconds-%0.4f-2.0020", "tests/test_time.py::test_precisedelta_custom_format[val2-milliseconds-%0.2f-2.00", "tests/test_time.py::test_precisedelta_custom_format[val3-seconds-%0.2f-1.23", "tests/test_time.py::test_precisedelta_custom_format[val4-seconds-%0.2f-4", "tests/test_time.py::test_precisedelta_custom_format[val5-seconds-%0.2f-5", "tests/test_time.py::test_precisedelta_custom_format[val6-hours-%0.2f-5", "tests/test_time.py::test_precisedelta_custom_format[val7-days-%0.2f-5.19", "tests/test_time.py::test_precisedelta_custom_format[val8-months-%0.2f-3.93", "tests/test_time.py::test_precisedelta_custom_format[val9-years-%0.1f-0.5", "tests/test_time.py::test_precisedelta_suppress_units[val0-microseconds-suppress0-1", "tests/test_time.py::test_precisedelta_suppress_units[val1-microseconds-suppress1-1200", "tests/test_time.py::test_precisedelta_suppress_units[val2-microseconds-suppress2-1.20", "tests/test_time.py::test_precisedelta_suppress_units[val3-microseconds-suppress3-1000", "tests/test_time.py::test_precisedelta_suppress_units[val4-microseconds-suppress4-1", "tests/test_time.py::test_precisedelta_suppress_units[val5-microseconds-suppress5-1.20", "tests/test_time.py::test_precisedelta_suppress_units[val6-microseconds-suppress6-4", "tests/test_time.py::test_precisedelta_suppress_units[val7-microseconds-suppress7-4", "tests/test_time.py::test_precisedelta_suppress_units[val8-microseconds-suppress8-4", "tests/test_time.py::test_precisedelta_suppress_units[val9-microseconds-suppress9-240", "tests/test_time.py::test_precisedelta_suppress_units[val10-microseconds-suppress10-240.50", "tests/test_time.py::test_precisedelta_bogus_call", "tests/test_time.py::test_time_unit" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-10-19 15:06:44+00:00
mit
3,262
jmoiron__humanize-183
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5320a9e..518e990 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,17 +11,17 @@ repos: - id: black args: ["--target-version", "py36"] + - repo: https://github.com/PyCQA/isort + rev: 5.6.4 + hooks: + - id: isort + - repo: https://gitlab.com/pycqa/flake8 rev: 3.8.4 hooks: - id: flake8 additional_dependencies: [flake8-2020, flake8-implicit-str-concat] - - repo: https://github.com/timothycrosley/isort - rev: 5.6.4 - hooks: - - id: isort - - repo: https://github.com/pre-commit/pygrep-hooks rev: v1.7.0 hooks: @@ -33,6 +33,7 @@ repos: - id: check-merge-conflict - id: check-toml - id: check-yaml + - id: end-of-file-fixer - repo: https://github.com/PyCQA/pydocstyle rev: 5.1.1 @@ -41,6 +42,11 @@ repos: args: ["--convention", "google"] files: "src/" + - repo: https://github.com/tox-dev/tox-ini-fmt + rev: 0.5.0 + hooks: + - id: tox-ini-fmt + - repo: https://github.com/asottile/setup-cfg-fmt rev: v1.15.1 hooks: diff --git a/setup.cfg b/setup.cfg index bc71a94..e0335c4 100644 --- a/setup.cfg +++ b/setup.cfg @@ -56,12 +56,7 @@ max_line_length = 88 convention = google [tool:isort] -known_third_party = freezegun,humanize,pkg_resources,pytest,setuptools -force_grid_wrap = 0 -include_trailing_comma = True -line_length = 88 -multi_line_output = 3 -use_parentheses = True +profile = black [tool:pytest] addopts = --color=yes diff --git a/src/humanize/__init__.py b/src/humanize/__init__.py index 44d7c1d..96b2655 100644 --- a/src/humanize/__init__.py +++ b/src/humanize/__init__.py @@ -1,7 +1,8 @@ """Main package for humanize.""" import pkg_resources + from humanize.filesize import naturalsize -from humanize.i18n import activate, deactivate +from humanize.i18n import activate, deactivate, thousands_separator from humanize.number import apnumber, fractional, intcomma, intword, ordinal, scientific from humanize.time import ( naturaldate, @@ -30,5 +31,6 @@ __all__ = [ "ordinal", "precisedelta", "scientific", + "thousands_separator", "VERSION", ] diff --git a/src/humanize/i18n.py b/src/humanize/i18n.py index 95e7be9..d2625b6 100644 --- a/src/humanize/i18n.py +++ b/src/humanize/i18n.py @@ -3,12 +3,18 @@ import gettext as gettext_module import os.path from threading import local -__all__ = ["activate", "deactivate", "gettext", "ngettext"] +__all__ = ["activate", "deactivate", "gettext", "ngettext", "thousands_separator"] _TRANSLATIONS = {None: gettext_module.NullTranslations()} _CURRENT = local() +# Mapping of locale to thousands separator +_THOUSANDS_SEPARATOR = { + "fr_FR": " ", +} + + def _get_default_locale_path(): try: if __file__ is None: @@ -129,3 +135,16 @@ def gettext_noop(message): str: Original text, unchanged. """ return message + + +def thousands_separator() -> str: + """Return the thousands separator for a locale, default to comma. + + Returns: + str: Thousands separator. + """ + try: + sep = _THOUSANDS_SEPARATOR[_CURRENT.locale] + except (AttributeError, KeyError): + sep = "," + return sep diff --git a/src/humanize/number.py b/src/humanize/number.py index 0fef81f..f425395 100644 --- a/src/humanize/number.py +++ b/src/humanize/number.py @@ -8,6 +8,7 @@ from fractions import Fraction from .i18n import gettext as _ from .i18n import gettext_noop as N_ from .i18n import pgettext as P_ +from .i18n import thousands_separator def ordinal(value): @@ -97,9 +98,10 @@ def intcomma(value, ndigits=None): Returns: str: string containing commas every three digits. """ + sep = thousands_separator() try: if isinstance(value, str): - float(value.replace(",", "")) + float(value.replace(sep, "")) else: float(value) except (TypeError, ValueError): @@ -110,7 +112,7 @@ def intcomma(value, ndigits=None): else: orig = str(value) - new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig) + new = re.sub(r"^(-?\d+)(\d{3})", fr"\g<1>{sep}\g<2>", orig) if orig == new: return new else: diff --git a/tox.ini b/tox.ini index 294b122..b961099 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [tox] envlist = - py{36, 37, 38, 39, py3} + py{py3, 39, 38, 37, 36} [testenv] extras = @@ -9,14 +9,19 @@ commands = {envpython} -m pytest --cov humanize --cov tests --cov-report xml {posargs} [testenv:docs] -deps = -r docs/requirements.txt -commands = mkdocs build +deps = + -rdocs/requirements.txt +commands = + mkdocs build [testenv:lint] -deps = pre-commit -commands = pre-commit run --all-files --show-diff-on-failure +passenv = + PRE_COMMIT_COLOR skip_install = true -passenv = PRE_COMMIT_COLOR +deps = + pre-commit +commands = + pre-commit run --all-files --show-diff-on-failure [pytest] -addopts = --doctest-modules \ No newline at end of file +addopts = --doctest-modules
jmoiron/humanize
0cbd1ababec2dcdd71e57856f9b0cce8c4d21b51
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5064efd..431d3af 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -46,21 +46,10 @@ jobs: python -m pip install --upgrade tox - name: Tox tests - if: matrix.python-version != 'pypy3' shell: bash run: | tox -e py - # Temporarily test PyPy3 without tox: - # https://foss.heptapod.net/pypy/pypy/-/issues/3331 - # https://github.com/tox-dev/tox/issues/1704 - - name: Non-tox tests (PyPy3) - if: matrix.python-version == 'pypy3' - shell: bash - run: | - python -m pip install ".[tests]" - python -m pytest --cov humanize --cov tests --cov-report xml - - name: Upload coverage uses: codecov/codecov-action@v1 with: diff --git a/tests/test_filesize.py b/tests/test_filesize.py index 871c61a..a629b93 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -2,9 +2,10 @@ """Tests for filesize humanizing.""" -import humanize import pytest +import humanize + @pytest.mark.parametrize( "test_args, expected", diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 385be25..d778583 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -1,9 +1,10 @@ import datetime as dt import importlib -import humanize import pytest +import humanize + def test_i18n(): three_seconds = dt.timedelta(seconds=3) @@ -26,6 +27,20 @@ def test_i18n(): assert humanize.precisedelta(one_min_three_seconds) == "1 minute and 7 seconds" +def test_intcomma(): + number = 10_000_000 + + assert humanize.intcomma(number) == "10,000,000" + + try: + humanize.i18n.activate("fr_FR") + assert humanize.intcomma(number) == "10 000 000" + + finally: + humanize.i18n.deactivate() + assert humanize.intcomma(number) == "10,000,000" + + def test_default_locale_path_defined__file__(): i18n = importlib.import_module("humanize.i18n") assert i18n._get_default_locale_path() is not None diff --git a/tests/test_number.py b/tests/test_number.py index 347217d..25f1d72 100644 --- a/tests/test_number.py +++ b/tests/test_number.py @@ -2,8 +2,9 @@ """Number tests.""" -import humanize import pytest + +import humanize from humanize import number diff --git a/tests/test_time.py b/tests/test_time.py index f0311ce..19e0ce6 100644 --- a/tests/test_time.py +++ b/tests/test_time.py @@ -4,9 +4,10 @@ import datetime as dt -import humanize import pytest from freezegun import freeze_time + +import humanize from humanize import time ONE_DAY_DELTA = dt.timedelta(days=1)
intcomma doesn't support internationalization ### What did you do? I tried to use `intcomma` with the `fr_FR` locale ### What did you expect to happen? A space separated decimal like `10 000 000` ### What actually happened? A comma separated decimal like `10,000,000` ### What versions are you using? * OS: Ubuntu * Python: 3.6 * Humanize: 3.1 ```python number = 10000000 humanize.i18n.activate("fr_FR") humanize.intcomma(number) ``` Django `intcomma` does support internationalization FYI: https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize.py#L60
0.0
0cbd1ababec2dcdd71e57856f9b0cce8c4d21b51
[ "tests/test_i18n.py::test_intcomma" ]
[ "tests/test_filesize.py::test_naturalsize[test_args0-300", "tests/test_filesize.py::test_naturalsize[test_args1-3.0", "tests/test_filesize.py::test_naturalsize[test_args2-3.0", "tests/test_filesize.py::test_naturalsize[test_args3-3.0", "tests/test_filesize.py::test_naturalsize[test_args4-3.0", "tests/test_filesize.py::test_naturalsize[test_args5-300", "tests/test_filesize.py::test_naturalsize[test_args6-2.9", "tests/test_filesize.py::test_naturalsize[test_args7-2.9", "tests/test_filesize.py::test_naturalsize[test_args8-300B]", "tests/test_filesize.py::test_naturalsize[test_args9-2.9K]", "tests/test_filesize.py::test_naturalsize[test_args10-2.9M]", "tests/test_filesize.py::test_naturalsize[test_args11-1.0K]", "tests/test_filesize.py::test_naturalsize[test_args12-2481.5Y]", "tests/test_filesize.py::test_naturalsize[test_args13-2481.5", "tests/test_filesize.py::test_naturalsize[test_args14-3000.0", "tests/test_filesize.py::test_naturalsize[test_args15-1", "tests/test_filesize.py::test_naturalsize[test_args16-3.14", "tests/test_filesize.py::test_naturalsize[test_args17-2.930K]", "tests/test_filesize.py::test_naturalsize[test_args18-3G]", "tests/test_filesize.py::test_naturalsize[test_args19-2481.542", "tests/test_i18n.py::test_i18n", "tests/test_i18n.py::test_default_locale_path_defined__file__", "tests/test_i18n.py::test_default_locale_path_null__file__", "tests/test_i18n.py::test_default_locale_path_undefined__file__", "tests/test_i18n.py::TestActivate::test_default_locale_path_null__file__", "tests/test_i18n.py::TestActivate::test_default_locale_path_undefined__file__", "tests/test_number.py::test_ordinal[1-1st]", "tests/test_number.py::test_ordinal[2-2nd]", "tests/test_number.py::test_ordinal[3-3rd]", "tests/test_number.py::test_ordinal[4-4th]", "tests/test_number.py::test_ordinal[11-11th]", "tests/test_number.py::test_ordinal[12-12th]", "tests/test_number.py::test_ordinal[13-13th]", "tests/test_number.py::test_ordinal[101-101st]", "tests/test_number.py::test_ordinal[102-102nd]", "tests/test_number.py::test_ordinal[103-103rd]", "tests/test_number.py::test_ordinal[111-111th]", "tests/test_number.py::test_ordinal[something", "tests/test_number.py::test_ordinal[None-None]", "tests/test_number.py::test_intcomma[test_args0-100]", "tests/test_number.py::test_intcomma[test_args1-1,000]", "tests/test_number.py::test_intcomma[test_args2-10,123]", "tests/test_number.py::test_intcomma[test_args3-10,311]", "tests/test_number.py::test_intcomma[test_args4-1,000,000]", "tests/test_number.py::test_intcomma[test_args5-1,234,567.25]", "tests/test_number.py::test_intcomma[test_args6-100]", "tests/test_number.py::test_intcomma[test_args7-1,000]", "tests/test_number.py::test_intcomma[test_args8-10,123]", "tests/test_number.py::test_intcomma[test_args9-10,311]", "tests/test_number.py::test_intcomma[test_args10-1,000,000]", "tests/test_number.py::test_intcomma[test_args11-1,234,567.1234567]", "tests/test_number.py::test_intcomma[test_args12-None]", "tests/test_number.py::test_intcomma[test_args13-14,308.4]", "tests/test_number.py::test_intcomma[test_args14-14,308.4]", "tests/test_number.py::test_intcomma[test_args15-14,308.4]", "tests/test_number.py::test_intcomma[test_args16-14,308.40]", "tests/test_number.py::test_intcomma[test_args17-14,308.400]", "tests/test_number.py::test_intcomma[test_args18-1,234.5454545]", "tests/test_number.py::test_intcomma[test_args19-1,234.5454545]", "tests/test_number.py::test_intcomma[test_args20-1,234.5]", "tests/test_number.py::test_intcomma[test_args21-1,234.55]", "tests/test_number.py::test_intcomma[test_args22-1,234.545]", "tests/test_number.py::test_intcomma[test_args23-1,234.5454545000]", "tests/test_number.py::test_intword_powers", "tests/test_number.py::test_intword[test_args0-100]", "tests/test_number.py::test_intword[test_args1-1.0", "tests/test_number.py::test_intword[test_args2-1.2", "tests/test_number.py::test_intword[test_args3-1.3", "tests/test_number.py::test_intword[test_args4-1.0", "tests/test_number.py::test_intword[test_args5-1.0", "tests/test_number.py::test_intword[test_args6-2.0", "tests/test_number.py::test_intword[test_args7-1.0", "tests/test_number.py::test_intword[test_args8-1.0", "tests/test_number.py::test_intword[test_args9-6.0", "tests/test_number.py::test_intword[test_args10-1.0", "tests/test_number.py::test_intword[test_args11-1.0", "tests/test_number.py::test_intword[test_args12-1.3", "tests/test_number.py::test_intword[test_args13-3.5", "tests/test_number.py::test_intword[test_args14-8.1", "tests/test_number.py::test_intword[test_args15-None]", "tests/test_number.py::test_intword[test_args16-1.23", "tests/test_number.py::test_intword[test_args17-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000]", "tests/test_number.py::test_apnumber[0-zero]", "tests/test_number.py::test_apnumber[1-one]", "tests/test_number.py::test_apnumber[2-two]", "tests/test_number.py::test_apnumber[4-four]", "tests/test_number.py::test_apnumber[5-five]", "tests/test_number.py::test_apnumber[9-nine]", "tests/test_number.py::test_apnumber[10-10]", "tests/test_number.py::test_apnumber[7-seven]", "tests/test_number.py::test_apnumber[None-None]", "tests/test_number.py::test_fractional[1-1]", "tests/test_number.py::test_fractional[2.0-2]", "tests/test_number.py::test_fractional[1.3333333333333333-1", "tests/test_number.py::test_fractional[0.8333333333333334-5/6]", "tests/test_number.py::test_fractional[7-7]", "tests/test_number.py::test_fractional[8.9-8", "tests/test_number.py::test_fractional[ten-ten]", "tests/test_number.py::test_fractional[None-None]", "tests/test_number.py::test_fractional[0.3333333333333333-1/3]", "tests/test_number.py::test_fractional[1.5-1", "tests/test_number.py::test_fractional[0.3-3/10]", "tests/test_number.py::test_fractional[0.333-333/1000]", "tests/test_number.py::test_scientific[test_args0-1.00", "tests/test_number.py::test_scientific[test_args1-1.00", "tests/test_number.py::test_scientific[test_args2-5.50", "tests/test_number.py::test_scientific[test_args3-5.78", "tests/test_number.py::test_scientific[test_args4-1.00", "tests/test_number.py::test_scientific[test_args5-9.90", "tests/test_number.py::test_scientific[test_args6-3.00", "tests/test_number.py::test_scientific[test_args7-foo]", "tests/test_number.py::test_scientific[test_args8-None]", "tests/test_number.py::test_scientific[test_args9-1.0", "tests/test_number.py::test_scientific[test_args10-3.0", "tests/test_number.py::test_scientific[test_args11-1", "tests/test_number.py::test_scientific[test_args12-3", "tests/test_time.py::test_date_and_delta", "tests/test_time.py::test_naturaldelta_nomonths[test_input0-7", "tests/test_time.py::test_naturaldelta_nomonths[test_input1-31", "tests/test_time.py::test_naturaldelta_nomonths[test_input2-230", "tests/test_time.py::test_naturaldelta_nomonths[test_input3-1", "tests/test_time.py::test_naturaldelta[0-a", "tests/test_time.py::test_naturaldelta[1-a", "tests/test_time.py::test_naturaldelta[30-30", "tests/test_time.py::test_naturaldelta[test_input3-a", "tests/test_time.py::test_naturaldelta[test_input4-2", "tests/test_time.py::test_naturaldelta[test_input5-an", "tests/test_time.py::test_naturaldelta[test_input6-23", "tests/test_time.py::test_naturaldelta[test_input7-a", "tests/test_time.py::test_naturaldelta[test_input8-1", "tests/test_time.py::test_naturaldelta[test_input9-2", "tests/test_time.py::test_naturaldelta[test_input10-a", "tests/test_time.py::test_naturaldelta[test_input11-30", "tests/test_time.py::test_naturaldelta[test_input12-a", "tests/test_time.py::test_naturaldelta[test_input13-2", "tests/test_time.py::test_naturaldelta[test_input14-an", "tests/test_time.py::test_naturaldelta[test_input15-23", "tests/test_time.py::test_naturaldelta[test_input16-a", "tests/test_time.py::test_naturaldelta[test_input17-1", "tests/test_time.py::test_naturaldelta[test_input18-2", "tests/test_time.py::test_naturaldelta[test_input19-27", "tests/test_time.py::test_naturaldelta[test_input20-1", "tests/test_time.py::test_naturaldelta[test_input22-2", "tests/test_time.py::test_naturaldelta[test_input23-1", "tests/test_time.py::test_naturaldelta[test_input24-a", "tests/test_time.py::test_naturaldelta[test_input25-2", "tests/test_time.py::test_naturaldelta[test_input26-9", "tests/test_time.py::test_naturaldelta[test_input27-a", "tests/test_time.py::test_naturaldelta[NaN-NaN]", "tests/test_time.py::test_naturaltime[test_input0-now]", "tests/test_time.py::test_naturaltime[test_input1-a", "tests/test_time.py::test_naturaltime[test_input2-30", "tests/test_time.py::test_naturaltime[test_input3-a", "tests/test_time.py::test_naturaltime[test_input4-2", "tests/test_time.py::test_naturaltime[test_input5-an", "tests/test_time.py::test_naturaltime[test_input6-23", "tests/test_time.py::test_naturaltime[test_input7-a", "tests/test_time.py::test_naturaltime[test_input8-1", "tests/test_time.py::test_naturaltime[test_input9-2", "tests/test_time.py::test_naturaltime[test_input10-a", "tests/test_time.py::test_naturaltime[test_input11-30", "tests/test_time.py::test_naturaltime[test_input12-a", "tests/test_time.py::test_naturaltime[test_input13-2", "tests/test_time.py::test_naturaltime[test_input14-an", "tests/test_time.py::test_naturaltime[test_input15-23", "tests/test_time.py::test_naturaltime[test_input16-a", "tests/test_time.py::test_naturaltime[test_input17-1", "tests/test_time.py::test_naturaltime[test_input18-2", "tests/test_time.py::test_naturaltime[test_input19-27", "tests/test_time.py::test_naturaltime[test_input20-1", "tests/test_time.py::test_naturaltime[30-30", "tests/test_time.py::test_naturaltime[test_input22-2", "tests/test_time.py::test_naturaltime[test_input23-1", "tests/test_time.py::test_naturaltime[NaN-NaN]", "tests/test_time.py::test_naturaltime_nomonths[test_input0-now]", "tests/test_time.py::test_naturaltime_nomonths[test_input1-a", "tests/test_time.py::test_naturaltime_nomonths[test_input2-30", "tests/test_time.py::test_naturaltime_nomonths[test_input3-a", "tests/test_time.py::test_naturaltime_nomonths[test_input4-2", "tests/test_time.py::test_naturaltime_nomonths[test_input5-an", "tests/test_time.py::test_naturaltime_nomonths[test_input6-23", "tests/test_time.py::test_naturaltime_nomonths[test_input7-a", "tests/test_time.py::test_naturaltime_nomonths[test_input8-17", "tests/test_time.py::test_naturaltime_nomonths[test_input9-47", "tests/test_time.py::test_naturaltime_nomonths[test_input10-1", "tests/test_time.py::test_naturaltime_nomonths[test_input11-2", "tests/test_time.py::test_naturaltime_nomonths[test_input12-a", "tests/test_time.py::test_naturaltime_nomonths[test_input13-30", "tests/test_time.py::test_naturaltime_nomonths[test_input14-a", "tests/test_time.py::test_naturaltime_nomonths[test_input15-2", "tests/test_time.py::test_naturaltime_nomonths[test_input16-an", "tests/test_time.py::test_naturaltime_nomonths[test_input17-23", "tests/test_time.py::test_naturaltime_nomonths[test_input18-a", "tests/test_time.py::test_naturaltime_nomonths[test_input19-1", "tests/test_time.py::test_naturaltime_nomonths[test_input20-2", "tests/test_time.py::test_naturaltime_nomonths[test_input21-27", "tests/test_time.py::test_naturaltime_nomonths[test_input22-1", "tests/test_time.py::test_naturaltime_nomonths[30-30", "tests/test_time.py::test_naturaltime_nomonths[test_input24-2", "tests/test_time.py::test_naturaltime_nomonths[test_input25-1", "tests/test_time.py::test_naturaltime_nomonths[NaN-NaN]", "tests/test_time.py::test_naturalday[test_args0-today]", "tests/test_time.py::test_naturalday[test_args1-tomorrow]", "tests/test_time.py::test_naturalday[test_args2-yesterday]", "tests/test_time.py::test_naturalday[test_args3-Mar", "tests/test_time.py::test_naturalday[test_args4-02/26/1984]", "tests/test_time.py::test_naturalday[test_args5-1982.06.27]", "tests/test_time.py::test_naturalday[test_args6-None]", "tests/test_time.py::test_naturalday[test_args7-Not", "tests/test_time.py::test_naturalday[test_args8-expected8]", "tests/test_time.py::test_naturalday[test_args9-expected9]", "tests/test_time.py::test_naturaldate[test_input0-today]", "tests/test_time.py::test_naturaldate[test_input1-tomorrow]", "tests/test_time.py::test_naturaldate[test_input2-yesterday]", "tests/test_time.py::test_naturaldate[test_input3-Mar", "tests/test_time.py::test_naturaldate[test_input4-Jun", "tests/test_time.py::test_naturaldate[None-None]", "tests/test_time.py::test_naturaldate[Not", "tests/test_time.py::test_naturaldate[test_input7-expected7]", "tests/test_time.py::test_naturaldate[test_input8-expected8]", "tests/test_time.py::test_naturaldate[test_input9-Feb", "tests/test_time.py::test_naturaldate[test_input10-Mar", "tests/test_time.py::test_naturaldate[test_input11-Apr", "tests/test_time.py::test_naturaldate[test_input12-May", "tests/test_time.py::test_naturaldate[test_input13-Jun", "tests/test_time.py::test_naturaldate[test_input14-Jul", "tests/test_time.py::test_naturaldate[test_input15-Aug", "tests/test_time.py::test_naturaldate[test_input16-Sep", "tests/test_time.py::test_naturaldate[test_input17-Oct", "tests/test_time.py::test_naturaldate[test_input18-Nov", "tests/test_time.py::test_naturaldate[test_input19-Dec", "tests/test_time.py::test_naturaldate[test_input20-Jan", "tests/test_time.py::test_naturaldate[test_input21-today]", "tests/test_time.py::test_naturaldate[test_input22-Mar", "tests/test_time.py::test_naturaldate[test_input23-Apr", "tests/test_time.py::test_naturaldate[test_input24-May", "tests/test_time.py::test_naturaldate[test_input25-Jun", "tests/test_time.py::test_naturaldate[test_input26-Jul", "tests/test_time.py::test_naturaldate[test_input27-Aug", "tests/test_time.py::test_naturaldate[test_input28-Sep", "tests/test_time.py::test_naturaldate[test_input29-Oct", "tests/test_time.py::test_naturaldate[test_input30-Nov", "tests/test_time.py::test_naturaldate[test_input31-Dec", "tests/test_time.py::test_naturaldate[test_input32-Jan", "tests/test_time.py::test_naturaldate[test_input33-Feb", "tests/test_time.py::test_naturaldelta_minimum_unit_default[1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_default[4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_default[31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-1e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4e-06-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.001-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-0.101943-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[seconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-4e-06-0", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-0.101943-101", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[milliseconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-0.004-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-0.101943-101", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-1.337-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaldelta_minimum_unit_explicit[microseconds-31557600.000004-a", "tests/test_time.py::test_naturaldelta_when_explicit[test_input0-when0-a", "tests/test_time.py::test_naturaldelta_when_explicit[test_input1-when1-a", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value0-None]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value1-when1]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value2-None]", "tests/test_time.py::test_naturaldelta_when_missing_tzinfo[value3-when3]", "tests/test_time.py::test_naturaltime_minimum_unit_default[1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_default[2-2", "tests/test_time.py::test_naturaltime_minimum_unit_default[4-4", "tests/test_time.py::test_naturaltime_minimum_unit_default[3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_default[86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_default[31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-1e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4e-06-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.001-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.004-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-0.101943-now]", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[seconds-31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-4e-06-0", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.001-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.004-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-0.101943-101", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[milliseconds-31557600.000004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-1e-06-1", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4e-06-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-0.004-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-0.101943-101", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-1.337-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-2-2", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-4-4", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-3600.004-an", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-86400.004-a", "tests/test_time.py::test_naturaltime_minimum_unit_explicit[microseconds-31557600.000004-a", "tests/test_time.py::test_precisedelta_one_unit_enough[val0-microseconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[val1-microseconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[val2-microseconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[val3-microseconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[val4-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[1-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[2-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[60-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[120-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[3600-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[7200-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[86400-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[172800-seconds-2", "tests/test_time.py::test_precisedelta_one_unit_enough[31536000-seconds-1", "tests/test_time.py::test_precisedelta_one_unit_enough[63072000-seconds-2", "tests/test_time.py::test_precisedelta_multiple_units[val0-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val1-microseconds-2", "tests/test_time.py::test_precisedelta_multiple_units[val2-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val3-microseconds-4", "tests/test_time.py::test_precisedelta_multiple_units[val4-microseconds-5", "tests/test_time.py::test_precisedelta_multiple_units[val5-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val6-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val7-microseconds-1", "tests/test_time.py::test_precisedelta_multiple_units[val8-minutes-0", "tests/test_time.py::test_precisedelta_custom_format[val0-milliseconds-%0.4f-1.0010", "tests/test_time.py::test_precisedelta_custom_format[val1-milliseconds-%0.4f-2.0020", "tests/test_time.py::test_precisedelta_custom_format[val2-milliseconds-%0.2f-2.00", "tests/test_time.py::test_precisedelta_custom_format[val3-seconds-%0.2f-1.23", "tests/test_time.py::test_precisedelta_custom_format[val4-seconds-%0.2f-4", "tests/test_time.py::test_precisedelta_custom_format[val5-seconds-%0.2f-5", "tests/test_time.py::test_precisedelta_custom_format[val6-hours-%0.2f-5", "tests/test_time.py::test_precisedelta_custom_format[val7-days-%0.2f-5.19", "tests/test_time.py::test_precisedelta_custom_format[val8-months-%0.2f-3.93", "tests/test_time.py::test_precisedelta_custom_format[val9-years-%0.1f-0.5", "tests/test_time.py::test_precisedelta_suppress_units[val0-microseconds-suppress0-1", "tests/test_time.py::test_precisedelta_suppress_units[val1-microseconds-suppress1-1200", "tests/test_time.py::test_precisedelta_suppress_units[val2-microseconds-suppress2-1.20", "tests/test_time.py::test_precisedelta_suppress_units[val3-microseconds-suppress3-1000", "tests/test_time.py::test_precisedelta_suppress_units[val4-microseconds-suppress4-1", "tests/test_time.py::test_precisedelta_suppress_units[val5-microseconds-suppress5-1.20", "tests/test_time.py::test_precisedelta_suppress_units[val6-microseconds-suppress6-4", "tests/test_time.py::test_precisedelta_suppress_units[val7-microseconds-suppress7-4", "tests/test_time.py::test_precisedelta_suppress_units[val8-microseconds-suppress8-4", "tests/test_time.py::test_precisedelta_suppress_units[val9-microseconds-suppress9-240", "tests/test_time.py::test_precisedelta_suppress_units[val10-microseconds-suppress10-240.50", "tests/test_time.py::test_precisedelta_bogus_call", "tests/test_time.py::test_time_unit" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-27 15:36:38+00:00
mit
3,263
jmwri__ioccontainer-4
diff --git a/ioccontainer/inject.py b/ioccontainer/inject.py index 162f6e1..98ba622 100644 --- a/ioccontainer/inject.py +++ b/ioccontainer/inject.py @@ -50,7 +50,11 @@ def inject_decorator(container: 'Container'): service = container.get(cls) if _is_positional_argument(position, parameter, new_args): - new_args.append(service) + if len(new_args) >= position + 1: + new_args[position] = service + else: + new_args.append(service) + elif _is_keyword_argument(parameter): kwargs[parameter.name] = service else: @@ -96,7 +100,9 @@ def _default_parameter_provided(parameter: inspect.Parameter) -> bool: def _argument_provided(position: int, parameter: inspect.Parameter, args: typing.List, kwargs: typing.Dict) -> bool: - return position < len(args) or parameter.name in kwargs.keys() + if position < len(args) and args[position] is not None: + return True + return kwargs.get(parameter.name) is not None def _is_positional_argument( @@ -106,7 +112,9 @@ def _is_positional_argument( inspect.Parameter.POSITIONAL_OR_KEYWORD) if parameter.kind not in positional_types: return False - return position == len(args) + if position == len(args): + return True + return position + 1 == len(args) and args[position] is None def _is_keyword_argument(parameter: inspect.Parameter) -> bool:
jmwri/ioccontainer
9155dbf9030df7bd911a5bc93feb397d1f545feb
diff --git a/tests/test_container.py b/tests/test_container.py index d76d2e1..f338f75 100644 --- a/tests/test_container.py +++ b/tests/test_container.py @@ -148,3 +148,29 @@ def test_injection_to_constructor(): my_class = MyClass('my_test_string') assert my_class.some_str is 'my_test_string' assert my_class.get_val() is 1 + + +@provider('str_service') +def provide_str(): + return 'string service' + + +def test_param_overriding(): + @inject(string='str_service') + def my_fn(string): + return string + + assert my_fn() == 'string service' + assert my_fn('overridden') == 'overridden' + assert my_fn(None) == 'string service' + + +def test_multiple_param_overriding(): + @inject(s1='str_service', s2='str_service') + def my_fn(s1, s2): + return s1, s2 + + assert my_fn() == ('string service', 'string service') + assert my_fn('overridden') == ('overridden', 'string service') + assert my_fn(None) == ('string service', 'string service') + assert my_fn('overridden', None) == ('overridden', 'string service')
Inject should override value if None When using the `@inject` decorator, the provided parameter should be overridden if it is `None`. At the moment the provider parameter takes precedence 100% of the time.
0.0
9155dbf9030df7bd911a5bc93feb397d1f545feb
[ "tests/test_container.py::test_param_overriding", "tests/test_container.py::test_multiple_param_overriding" ]
[ "tests/test_container.py::test_injection", "tests/test_container.py::test_singleton", "tests/test_container.py::test_invalid_scope", "tests/test_container.py::test_duplicate_provider", "tests/test_container.py::test_invalid_provider", "tests/test_container.py::test_invalid_service_name", "tests/test_container.py::test_no_provider_specified", "tests/test_container.py::test_multiple_params", "tests/test_container.py::test_default_provided", "tests/test_container.py::test_argument_provided", "tests/test_container.py::test_threaded_provider", "tests/test_container.py::test_injection_to_constructor" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2018-02-23 20:50:01+00:00
mit
3,264
jnothman__UpSetPlot-248
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 837abcc..9624e07 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,11 @@ What's new in version 0.9 ------------------------- -- Ability to disable totals plot with `totals_plot_elements=0`. + +- Fixes a bug where ``show_percentages`` used the incorrect denominator if + filtering (e.g. ``min_subset_size``) was applied. This bug was a regression + introduced in version 0.7. (:issue:`248`) +- Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`) +- Ability to set totals y axis label (:issue:`243`) What's new in version 0.8 ------------------------- @@ -14,7 +19,7 @@ What's new in version 0.8 - Added `subsets` attribute to QueryResult. (:issue:`198`) - Fixed a bug where more than 64 categories could result in an error. (:issue:`193`) -Patch release 0.8.1 handles deprecations in dependencies. +Patch release 0.8.2 handles deprecations in dependencies. What's new in version 0.7 ------------------------- diff --git a/upsetplot/plotting.py b/upsetplot/plotting.py index 32ef1d8..1686251 100644 --- a/upsetplot/plotting.py +++ b/upsetplot/plotting.py @@ -50,8 +50,6 @@ def _process_data( df = results.data agg = results.subset_sizes - totals = results.category_totals - total = agg.sum() # add '_bin' to df indicating index in agg # XXX: ugly! @@ -75,7 +73,7 @@ def _process_data( if reverse: agg = agg[::-1] - return total, df, agg, totals + return results.total, df, agg, results.category_totals def _multiply_alpha(c, mult): @@ -673,8 +671,6 @@ class UpSet: fig.set_figheight((colw * (n_cats + sizes.sum())) / render_ratio) text_nelems = int(np.ceil(figw / colw - non_text_nelems)) - # print('textw', textw, 'figw', figw, 'colw', colw, - # 'ncols', figw/colw, 'text_nelems', text_nelems) GS = self._reorient(matplotlib.gridspec.GridSpec) gridspec = GS( diff --git a/upsetplot/reformat.py b/upsetplot/reformat.py index f22ee9c..05234d9 100644 --- a/upsetplot/reformat.py +++ b/upsetplot/reformat.py @@ -162,17 +162,20 @@ class QueryResult: for `data`. category_totals : Series Total size of each category, regardless of selection. + total : number + Total number of samples / sum of value """ - def __init__(self, data, subset_sizes, category_totals): + def __init__(self, data, subset_sizes, category_totals, total): self.data = data self.subset_sizes = subset_sizes self.category_totals = category_totals + self.total = total def __repr__(self): return ( "QueryResult(data={data}, subset_sizes={subset_sizes}, " - "category_totals={category_totals}".format(**vars(self)) + "category_totals={category_totals}, total={total}".format(**vars(self)) ) @property @@ -267,7 +270,7 @@ def query( ------- QueryResult Including filtered ``data``, filtered and sorted ``subset_sizes`` and - overall ``category_totals``. + overall ``category_totals`` and ``total``. Examples -------- @@ -322,11 +325,12 @@ def query( data, agg = _aggregate_data(data, subset_size, sum_over) data = _check_index(data) - totals = [ + grand_total = agg.sum() + category_totals = [ agg[agg.index.get_level_values(name).values.astype(bool)].sum() for name in agg.index.names ] - totals = pd.Series(totals, index=agg.index.names) + category_totals = pd.Series(category_totals, index=agg.index.names) if include_empty_subsets: nlevels = len(agg.index.levels) @@ -358,15 +362,17 @@ def query( # sort: if sort_categories_by in ("cardinality", "-cardinality"): - totals.sort_values(ascending=sort_categories_by[:1] == "-", inplace=True) + category_totals.sort_values( + ascending=sort_categories_by[:1] == "-", inplace=True + ) elif sort_categories_by == "-input": - totals = totals[::-1] + category_totals = category_totals[::-1] elif sort_categories_by in (None, "input"): pass else: raise ValueError("Unknown sort_categories_by: %r" % sort_categories_by) - data = data.reorder_levels(totals.index.values) - agg = agg.reorder_levels(totals.index.values) + data = data.reorder_levels(category_totals.index.values) + agg = agg.reorder_levels(category_totals.index.values) if sort_by in ("cardinality", "-cardinality"): agg = agg.sort_values(ascending=sort_by[:1] == "-") @@ -380,12 +386,12 @@ def query( pd.MultiIndex.from_tuples(index_tuples, names=agg.index.names) ) elif sort_by == "-input": - print("<", agg) agg = agg[::-1] - print(">", agg) elif sort_by in (None, "input"): pass else: raise ValueError("Unknown sort_by: %r" % sort_by) - return QueryResult(data=data, subset_sizes=agg, category_totals=totals) + return QueryResult( + data=data, subset_sizes=agg, category_totals=category_totals, total=grand_total + )
jnothman/UpSetPlot
3bf5ad55c6e25e1a2cf4d02745dc7fac3f81469c
diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py index 3f65142..ffb112e 100644 --- a/upsetplot/tests/test_upsetplot.py +++ b/upsetplot/tests/test_upsetplot.py @@ -822,6 +822,7 @@ def test_filter_subsets(filter_params, expected, sort_by): ) # category totals should not be affected assert_series_equal(upset_full.totals, upset_filtered.totals) + assert upset_full.total == pytest.approx(upset_filtered.total) @pytest.mark.parametrize(
Problems with show_percentages I am using the plot function to make an upset plot with show_percentages=True. When I plot the whole upset plot the % values are calculated correctly, however when I use the min_subset_size=100 parameter, the % calculations change. I don't think the new percentage calculations uses the whole dataset but only what is being plotted. Is there a way to change this? ![image](https://github.com/jnothman/UpSetPlot/assets/54101443/4e0ee2c0-c450-4e8f-bc82-8dc38e0e3073) ![image](https://github.com/jnothman/UpSetPlot/assets/54101443/fcbee063-4c25-43cb-8757-c15379169d92)
0.0
3bf5ad55c6e25e1a2cf4d02745dc7fac3f81469c
[ "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params4-expected4]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params4-expected4]" ]
[ "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x1]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-degree]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-degree]", "upsetplot/tests/test_upsetplot.py::test_include_empty_subsets", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw0]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw1]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw2]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw0]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw1]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw2]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw4]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw5]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw6]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set13]", "upsetplot/tests/test_upsetplot.py::test_vertical", "upsetplot/tests/test_upsetplot.py::test_element_size", "upsetplot/tests/test_upsetplot.py::test_show_counts[horizontal]", "upsetplot/tests/test_upsetplot.py::test_show_counts[vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors0-expected0]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors1-expected1]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[Pastel1-expected2]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors3-expected3]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[<lambda>-expected4]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-True]", "upsetplot/tests/test_upsetplot.py::test_index_must_be_bool[x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x2]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list0-expected_subset_styles0-expected_legend0]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list1-expected_subset_styles1-expected_legend1]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list2-expected_subset_styles2-expected_legend2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list3-expected_subset_styles3-expected_legend3]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list4-expected_subset_styles4-expected_legend4]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list5-expected_subset_styles5-expected_legend5]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list6-expected_subset_styles6-expected_legend6]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list7-expected_subset_styles7-expected_legend7]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list8-expected_subset_styles8-expected_legend8]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list9-expected_subset_styles9-expected_legend9]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list10-expected_subset_styles10-expected_legend10]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list11-expected_subset_styles11-expected_legend11]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list12-expected_subset_styles12-expected_legend12]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list13-expected_subset_styles13-expected_legend13]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list14-expected_subset_styles14-expected_legend14]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list15-expected_subset_styles15-expected_legend15]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list16-expected_subset_styles16-expected_legend16]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list17-expected_subset_styles17-expected_legend17]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[horizontal]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[vertical]", "upsetplot/tests/test_upsetplot.py::test_many_categories" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-28 07:21:32+00:00
bsd-3-clause
3,265
jnothman__UpSetPlot-253
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 9624e07..27421f4 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,7 @@ What's new in version 0.9 introduced in version 0.7. (:issue:`248`) - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`) - Ability to set totals y axis label (:issue:`243`) +- Added ``max_subset_rank`` to get only n most populous subsets. What's new in version 0.8 ------------------------- diff --git a/upsetplot/plotting.py b/upsetplot/plotting.py index 0451215..a4d85cf 100644 --- a/upsetplot/plotting.py +++ b/upsetplot/plotting.py @@ -28,6 +28,7 @@ def _process_data( sum_over, min_subset_size=None, max_subset_size=None, + max_subset_rank=None, min_degree=None, max_degree=None, reverse=False, @@ -41,6 +42,7 @@ def _process_data( sum_over=sum_over, min_subset_size=min_subset_size, max_subset_size=max_subset_size, + max_subset_rank=max_subset_rank, min_degree=min_degree, max_degree=max_degree, include_empty_subsets=include_empty_subsets, @@ -200,6 +202,11 @@ class UpSet: a size greater than this threshold will be omitted from plotting. .. versionadded:: 0.5 + max_subset_rank : int, optional + Limit to the top N ranked subsets in descending order of size. + All tied subsets are included. + + .. versionadded:: 0.9 min_degree : int, optional Minimum degree of a subset to be shown in the plot. @@ -270,6 +277,7 @@ class UpSet: sum_over=None, min_subset_size=None, max_subset_size=None, + max_subset_rank=None, min_degree=None, max_degree=None, facecolor="auto", @@ -324,6 +332,7 @@ class UpSet: sum_over=sum_over, min_subset_size=min_subset_size, max_subset_size=max_subset_size, + max_subset_rank=max_subset_rank, min_degree=min_degree, max_degree=max_degree, reverse=not self._horizontal, @@ -345,6 +354,7 @@ class UpSet: absent=None, min_subset_size=None, max_subset_size=None, + max_subset_rank=None, min_degree=None, max_degree=None, facecolor=None, @@ -371,6 +381,11 @@ class UpSet: Minimum size of a subset to be styled. max_subset_size : int, optional Maximum size of a subset to be styled. + max_subset_rank : int, optional + Limit to the top N ranked subsets in descending order of size. + All tied subsets are included. + + .. versionadded:: 0.9 min_degree : int, optional Minimum degree of a subset to be styled. max_degree : int, optional @@ -405,6 +420,7 @@ class UpSet: absent=absent, min_subset_size=min_subset_size, max_subset_size=max_subset_size, + max_subset_rank=max_subset_rank, min_degree=min_degree, max_degree=max_degree, ) diff --git a/upsetplot/reformat.py b/upsetplot/reformat.py index aaca407..821a359 100644 --- a/upsetplot/reformat.py +++ b/upsetplot/reformat.py @@ -94,7 +94,14 @@ def _scalar_to_list(val): def _get_subset_mask( - agg, min_subset_size, max_subset_size, min_degree, max_degree, present, absent + agg, + min_subset_size, + max_subset_size, + max_subset_rank, + min_degree, + max_degree, + present, + absent, ): """Get a mask over subsets based on size, degree or category presence""" subset_mask = True @@ -102,6 +109,10 @@ def _get_subset_mask( subset_mask = np.logical_and(subset_mask, agg >= min_subset_size) if max_subset_size is not None: subset_mask = np.logical_and(subset_mask, agg <= max_subset_size) + if max_subset_rank is not None: + subset_mask = np.logical_and( + subset_mask, agg.rank(method="min", ascending=False) <= max_subset_rank + ) if (min_degree is not None and min_degree >= 0) or max_degree is not None: degree = agg.index.to_frame().sum(axis=1) if min_degree is not None: @@ -121,12 +132,21 @@ def _get_subset_mask( def _filter_subsets( - df, agg, min_subset_size, max_subset_size, min_degree, max_degree, present, absent + df, + agg, + min_subset_size, + max_subset_size, + max_subset_rank, + min_degree, + max_degree, + present, + absent, ): subset_mask = _get_subset_mask( agg, min_subset_size=min_subset_size, max_subset_size=max_subset_size, + max_subset_rank=max_subset_rank, min_degree=min_degree, max_degree=max_degree, present=present, @@ -189,6 +209,7 @@ def query( absent=None, min_subset_size=None, max_subset_size=None, + max_subset_rank=None, min_degree=None, max_degree=None, sort_by="degree", @@ -221,6 +242,11 @@ def query( Size may be a sum of values, see `subset_size`. max_subset_size : int, optional Maximum size of a subset to be reported. + max_subset_rank : int, optional + Limit to the top N ranked subsets in descending order of size. + All tied subsets are included. + + .. versionadded:: 0.9 min_degree : int, optional Minimum degree of a subset to be reported. max_degree : int, optional @@ -348,6 +374,7 @@ def query( agg, min_subset_size=min_subset_size, max_subset_size=max_subset_size, + max_subset_rank=max_subset_rank, min_degree=min_degree, max_degree=max_degree, present=present,
jnothman/UpSetPlot
16ff93055ec5a2b0ee96eea6f089734e94098bab
diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py index 673f893..80dfa76 100644 --- a/upsetplot/tests/test_upsetplot.py +++ b/upsetplot/tests/test_upsetplot.py @@ -753,6 +753,14 @@ def test_index_must_be_bool(x): (True, True, True): 990, }, ), + ( + {"max_subset_rank": 3}, + { + (True, False, False): 884, + (True, True, False): 1547, + (True, True, True): 990, + }, + ), ( {"min_subset_size": 800, "max_subset_size": 990}, { @@ -822,6 +830,29 @@ def test_filter_subsets(filter_params, expected, sort_by): assert upset_full.total == pytest.approx(upset_filtered.total) +def test_filter_subsets_max_subset_rank_tie(): + data = generate_samples(seed=0, n_samples=5, n_categories=3) + tested_non_tie = False + tested_tie = True + full = UpSet(data, subset_size="count").intersections + prev = None + for max_rank in range(1, 5): + cur = UpSet(data, subset_size="count", max_subset_rank=max_rank).intersections + if prev is not None: + if cur.shape[0] > prev.shape[0]: + # check we add rows only when they are new + assert cur.min() < prev.min() + tested_non_tie = True + elif cur.shape[0] != full.shape[0]: + assert (cur == cur.min()).sum() > 1 + tested_tie = True + + prev = cur + assert tested_non_tie + assert tested_tie + assert cur.shape[0] == full.shape[0] + + @pytest.mark.parametrize( "x", [
Specify maximum number of intersections to display Hi, Apologies if this has already been implemented, but after going through the [API documentation](https://upsetplot.readthedocs.io/en/stable/api.html), I'm unable to find an option that limits the number of displayed intersections, which forces me to manually truncate my dataframe I'm trying to plot from. If you can point me to an argument that lets me do this that would be great. If this is not already implemented, it certainly would be useful! Thanks!
0.0
16ff93055ec5a2b0ee96eea6f089734e94098bab
[ "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets_max_subset_rank_tie" ]
[ "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x1]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-degree]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-degree]", "upsetplot/tests/test_upsetplot.py::test_include_empty_subsets", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw0]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw1]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw2]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw0]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw1]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw2]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw4]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw5]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw6]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set13]", "upsetplot/tests/test_upsetplot.py::test_vertical", "upsetplot/tests/test_upsetplot.py::test_element_size", "upsetplot/tests/test_upsetplot.py::test_show_counts[horizontal]", "upsetplot/tests/test_upsetplot.py::test_show_counts[vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors0-expected0]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors1-expected1]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[Pastel1-expected2]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors3-expected3]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[<lambda>-expected4]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-True]", "upsetplot/tests/test_upsetplot.py::test_index_must_be_bool[x0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params4-expected4]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params5-expected5]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params4-expected4]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params5-expected5]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x2]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list0-expected_subset_styles0-expected_legend0]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list1-expected_subset_styles1-expected_legend1]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list2-expected_subset_styles2-expected_legend2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list3-expected_subset_styles3-expected_legend3]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list4-expected_subset_styles4-expected_legend4]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list5-expected_subset_styles5-expected_legend5]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list6-expected_subset_styles6-expected_legend6]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list7-expected_subset_styles7-expected_legend7]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list8-expected_subset_styles8-expected_legend8]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list9-expected_subset_styles9-expected_legend9]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list10-expected_subset_styles10-expected_legend10]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list11-expected_subset_styles11-expected_legend11]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list12-expected_subset_styles12-expected_legend12]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list13-expected_subset_styles13-expected_legend13]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list14-expected_subset_styles14-expected_legend14]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list15-expected_subset_styles15-expected_legend15]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list16-expected_subset_styles16-expected_legend16]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list17-expected_subset_styles17-expected_legend17]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[horizontal]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[vertical]", "upsetplot/tests/test_upsetplot.py::test_many_categories" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-12-28 13:53:58+00:00
bsd-3-clause
3,266
jnothman__UpSetPlot-264
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index a00b4d9..37a37ef 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -8,7 +8,10 @@ What's new in version 0.9 shading of rows in the intersection matrix, and bars in the totals plot. (:issue:`261` with thanks to :user:`Marcel Albus <maralbus>`). - Ability to disable totals plot with `totals_plot_elements=0`. (:issue:`246`) +- Ability to set totals y axis label (:issue:`243`) - Added ``max_subset_rank`` to get only n most populous subsets. (:issue:`253`) +- Added support for ``min_subset_size`` and ``max_subset_size`` specified as + percentage. (:issue:`264`) What's new in version 0.8 ------------------------- diff --git a/upsetplot/plotting.py b/upsetplot/plotting.py index e2f50bd..3d5630f 100644 --- a/upsetplot/plotting.py +++ b/upsetplot/plotting.py @@ -191,17 +191,27 @@ class UpSet: If `subset_size='sum'` or `'auto'`, then the intersection size is the sum of the specified field in the `data` DataFrame. If a Series, only None is supported and its value is summed. - min_subset_size : int, optional + min_subset_size : int or "number%", optional Minimum size of a subset to be shown in the plot. All subsets with a size smaller than this threshold will be omitted from plotting. + This may be specified as a percentage + using a string, like "50%". Size may be a sum of values, see `subset_size`. .. versionadded:: 0.5 - max_subset_size : int, optional + + .. versionchanged:: 0.9 + Support percentages + max_subset_size : int or "number%", optional Maximum size of a subset to be shown in the plot. All subsets with a size greater than this threshold will be omitted from plotting. + This may be specified as a percentage + using a string, like "50%". .. versionadded:: 0.5 + + .. versionchanged:: 0.9 + Support percentages max_subset_rank : int, optional Limit to the top N ranked subsets in descending order of size. All tied subsets are included. @@ -379,10 +389,18 @@ class UpSet: absent : str or list of str, optional Category or categories that must not be present in subsets for styling. - min_subset_size : int, optional + min_subset_size : int or "number%", optional Minimum size of a subset to be styled. - max_subset_size : int, optional + This may be specified as a percentage using a string, like "50%". + + .. versionchanged:: 0.9 + Support percentages + max_subset_size : int or "number%", optional Maximum size of a subset to be styled. + This may be specified as a percentage using a string, like "50%". + + .. versionchanged:: 0.9 + Support percentages max_subset_rank : int, optional Limit to the top N ranked subsets in descending order of size. All tied subsets are included. diff --git a/upsetplot/reformat.py b/upsetplot/reformat.py index 821a359..5853729 100644 --- a/upsetplot/reformat.py +++ b/upsetplot/reformat.py @@ -93,6 +93,19 @@ def _scalar_to_list(val): return val +def _check_percent(value, agg): + if not isinstance(value, str): + return value + try: + if value.endswith("%") and 0 <= float(value[:-1]) <= 100: + return float(value[:-1]) / 100 * agg.sum() + except ValueError: + pass + raise ValueError( + f"String value must be formatted as percentage between 0 and 100. Got {value}" + ) + + def _get_subset_mask( agg, min_subset_size, @@ -104,6 +117,8 @@ def _get_subset_mask( absent, ): """Get a mask over subsets based on size, degree or category presence""" + min_subset_size = _check_percent(min_subset_size, agg) + max_subset_size = _check_percent(max_subset_size, agg) subset_mask = True if min_subset_size is not None: subset_mask = np.logical_and(subset_mask, agg >= min_subset_size) @@ -235,13 +250,20 @@ def query( absent : str or list of str, optional Category or categories that must not be present in subsets for styling. - min_subset_size : int, optional + min_subset_size : int or "number%", optional Minimum size of a subset to be reported. All subsets with a size smaller than this threshold will be omitted from - category_totals and data. + category_totals and data. This may be specified as a percentage + using a string, like "50%". Size may be a sum of values, see `subset_size`. - max_subset_size : int, optional + + .. versionchanged:: 0.9 + Support percentages + max_subset_size : int or "number%", optional Maximum size of a subset to be reported. + + .. versionchanged:: 0.9 + Support percentages max_subset_rank : int, optional Limit to the top N ranked subsets in descending order of size. All tied subsets are included.
jnothman/UpSetPlot
da64c81a12f5e6c8283e10a4f6cd7a42ccda1491
diff --git a/upsetplot/tests/test_upsetplot.py b/upsetplot/tests/test_upsetplot.py index d96b42d..3c33dea 100644 --- a/upsetplot/tests/test_upsetplot.py +++ b/upsetplot/tests/test_upsetplot.py @@ -768,6 +768,13 @@ def test_index_must_be_bool(x): (True, True, True): 990, }, ), + ( + {"min_subset_size": "15%", "max_subset_size": "30.1%"}, + { + (True, False, False): 884, + (True, True, True): 990, + }, + ), ( {"min_degree": 2}, { @@ -853,6 +860,22 @@ def test_filter_subsets_max_subset_rank_tie(): assert cur.shape[0] == full.shape[0] [email protected]( + "value", + [ + "1", + "-1%", + "1%%", + "%1", + "hello", + ], +) +def test_bad_percentages(value): + data = generate_samples(seed=0, n_samples=5, n_categories=3) + with pytest.raises(ValueError, match="percentage"): + UpSet(data, min_subset_size=value) + + @pytest.mark.parametrize( "x", [
Express min_subset_size as a percentage / fraction It should be possible to use `min_subset_size="30%"` and similar percentage specification of `max_subset_size`, corresponding to the values displayed with `show_percentages`. From #170
0.0
da64c81a12f5e6c8283e10a4f6cd7a42ccda1491
[ "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params3-expected3]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[-1%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[1%%]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[%1]", "upsetplot/tests/test_upsetplot.py::test_bad_percentages[hello]" ]
[ "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[None--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-input--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--cardinality-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--degree-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-None-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality-input-x1]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x0]", "upsetplot/tests/test_upsetplot.py::test_process_data_series[-cardinality--input-x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_series[x1]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x0]", "upsetplot/tests/test_upsetplot.py::test_subset_size_frame[x1]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[None-degree]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-cardinality]", "upsetplot/tests/test_upsetplot.py::test_not_unique[cardinality-degree]", "upsetplot/tests/test_upsetplot.py::test_include_empty_subsets", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw0]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw1]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw2]", "upsetplot/tests/test_upsetplot.py::test_param_validation[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw0]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw1]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw2]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw3]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw4]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw5]", "upsetplot/tests/test_upsetplot.py::test_plot_smoke_test[kw6]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set20-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set21-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set22-set13]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set10]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set11]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set12]", "upsetplot/tests/test_upsetplot.py::test_two_sets[set23-set13]", "upsetplot/tests/test_upsetplot.py::test_vertical", "upsetplot/tests/test_upsetplot.py::test_element_size", "upsetplot/tests/test_upsetplot.py::test_show_counts[horizontal]", "upsetplot/tests/test_upsetplot.py::test_show_counts[vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[False-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-horizontal]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars[True-vertical]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors0-expected0]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors1-expected1]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[Pastel1-expected2]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[colors3-expected3]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_colors[<lambda>-expected4]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[False-True-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-False-True]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-False]", "upsetplot/tests/test_upsetplot.py::test_add_stacked_bars_sum_over[True-True-True]", "upsetplot/tests/test_upsetplot.py::test_index_must_be_bool[x0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params4-expected4]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params5-expected5]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[cardinality-filter_params6-expected6]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params0-expected0]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params1-expected1]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params2-expected2]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params4-expected4]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params5-expected5]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets[degree-filter_params6-expected6]", "upsetplot/tests/test_upsetplot.py::test_filter_subsets_max_subset_rank_tie", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[horizontal-x2]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x0]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x1]", "upsetplot/tests/test_upsetplot.py::test_matrix_plot_margins[vertical-x2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list0-expected_subset_styles0-expected_legend0]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list1-expected_subset_styles1-expected_legend1]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list2-expected_subset_styles2-expected_legend2]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list3-expected_subset_styles3-expected_legend3]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list4-expected_subset_styles4-expected_legend4]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list5-expected_subset_styles5-expected_legend5]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list6-expected_subset_styles6-expected_legend6]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list7-expected_subset_styles7-expected_legend7]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list8-expected_subset_styles8-expected_legend8]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list9-expected_subset_styles9-expected_legend9]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list10-expected_subset_styles10-expected_legend10]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list11-expected_subset_styles11-expected_legend11]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list12-expected_subset_styles12-expected_legend12]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list13-expected_subset_styles13-expected_legend13]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list14-expected_subset_styles14-expected_legend14]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list15-expected_subset_styles15-expected_legend15]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list16-expected_subset_styles16-expected_legend16]", "upsetplot/tests/test_upsetplot.py::test_style_subsets[kwarg_list17-expected_subset_styles17-expected_legend17]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[horizontal]", "upsetplot/tests/test_upsetplot.py::test_style_subsets_artists[vertical]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list0-expected_category_styles0]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list1-expected_category_styles1]", "upsetplot/tests/test_upsetplot.py::test_categories[kwarg_list2-expected_category_styles2]", "upsetplot/tests/test_upsetplot.py::test_many_categories" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-12-29 04:57:30+00:00
bsd-3-clause
3,267
joanvila__aioredlock-77
diff --git a/aioredlock/algorithm.py b/aioredlock/algorithm.py index bf192ab..51707b7 100644 --- a/aioredlock/algorithm.py +++ b/aioredlock/algorithm.py @@ -238,3 +238,18 @@ class Aioredlock: self._watchdogs.clear() await self.redis.clear_connections() + + async def get_active_locks(self): + """ + Return all stored locks that are valid. + + .. note:: + This function is only really useful in learning if there are no + active locks. It is possible that by the time the a lock is + returned from this function that it is no longer active. + """ + ret = [] + for lock in self._locks.values(): + if lock.valid is True and await lock.is_locked(): + ret.append(lock) + return ret diff --git a/aioredlock/lock.py b/aioredlock/lock.py index a44b84c..58f5b09 100644 --- a/aioredlock/lock.py +++ b/aioredlock/lock.py @@ -21,3 +21,6 @@ class Lock: async def release(self): await self.lock_manager.unlock(self) + + async def is_locked(self): + return await self.lock_manager.is_locked(self)
joanvila/aioredlock
cf2ffca3df65decb64de6dd93bcd139244db930e
diff --git a/tests/ut/conftest.py b/tests/ut/conftest.py index 7acbe39..7004ad1 100644 --- a/tests/ut/conftest.py +++ b/tests/ut/conftest.py @@ -12,8 +12,19 @@ async def dummy_sleep(seconds): @pytest.fixture -def locked_lock(): - return Lock(None, "resource_name", 1, -1, True) +def locked_lock(lock_manager_redis_patched): + lock_manager, _ = lock_manager_redis_patched + lock = Lock(lock_manager, "resource_name", 1, -1, True) + lock_manager._locks[lock.resource] = lock + return lock + + [email protected] +def unlocked_lock(lock_manager_redis_patched): + lock_manager, _ = lock_manager_redis_patched + lock = Lock(lock_manager, "other_resource_name", 1, -1, False) + lock_manager._locks[lock.resource] = lock + return lock @pytest.fixture diff --git a/tests/ut/test_algorithm.py b/tests/ut/test_algorithm.py index f4ef3ed..e2655c0 100644 --- a/tests/ut/test_algorithm.py +++ b/tests/ut/test_algorithm.py @@ -344,3 +344,13 @@ class TestAioredlock: await lock_manager.unlock(lock) assert lock.valid is False + + @pytest.mark.asyncio + async def test_get_active_locks(self, lock_manager_redis_patched, locked_lock, unlocked_lock): + lock_manager, redis = lock_manager_redis_patched + redis.is_locked.return_value = True + + locks = await lock_manager.get_active_locks() + + assert locked_lock in locks + assert unlocked_lock not in locks
A function to return number of active locks Would be a nice to have a feature to do that.
0.0
cf2ffca3df65decb64de6dd93bcd139244db930e
[ "tests/ut/test_algorithm.py::TestAioredlock::test_get_active_locks" ]
[ "tests/ut/test_algorithm.py::test_validator[_validate_retry_count-Retry", "tests/ut/test_algorithm.py::test_validator[_validate_retry_delay-Retry", "tests/ut/test_algorithm.py::test_validator[_validate_internal_lock_timeout-Internal", "tests/ut/test_algorithm.py::TestAioredlock::test_default_initialization", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_params", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[-1-ValueError-retry_count]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[-1-ValueError-retry_delay_min]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[-1-ValueError-retry_delay_max]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[-1-ValueError-internal_lock_timeout]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[0-ValueError-retry_count]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[0-ValueError-retry_delay_min]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[0-ValueError-retry_delay_max]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[0-ValueError-internal_lock_timeout]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[string-ValueError-retry_count]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[string-ValueError-retry_delay_min]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[string-ValueError-retry_delay_max]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[string-ValueError-internal_lock_timeout]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[None-TypeError-retry_count]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[None-TypeError-retry_delay_min]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[None-TypeError-retry_delay_max]", "tests/ut/test_algorithm.py::TestAioredlock::test_initialization_with_invalid_params[None-TypeError-internal_lock_timeout]", "tests/ut/test_algorithm.py::TestAioredlock::test_lock", "tests/ut/test_algorithm.py::TestAioredlock::test_lock_with_invalid_param", "tests/ut/test_algorithm.py::TestAioredlock::test_lock_one_retry", "tests/ut/test_algorithm.py::TestAioredlock::test_lock_expire_retries", "tests/ut/test_algorithm.py::TestAioredlock::test_lock_one_timeout", "tests/ut/test_algorithm.py::TestAioredlock::test_lock_expire_retries_for_timeouts", "tests/ut/test_algorithm.py::TestAioredlock::test_cancel_lock_", "tests/ut/test_algorithm.py::TestAioredlock::test_extend_lock", "tests/ut/test_algorithm.py::TestAioredlock::test_extend_with_invalid_param", "tests/ut/test_algorithm.py::TestAioredlock::test_extend_lock_error", "tests/ut/test_algorithm.py::TestAioredlock::test_unlock", "tests/ut/test_algorithm.py::TestAioredlock::test_is_locked[True-True]", "tests/ut/test_algorithm.py::TestAioredlock::test_is_locked[True-False]", "tests/ut/test_algorithm.py::TestAioredlock::test_is_locked[False-True]", "tests/ut/test_algorithm.py::TestAioredlock::test_is_locked[False-False]", "tests/ut/test_algorithm.py::TestAioredlock::test_is_locked_type_error", "tests/ut/test_algorithm.py::TestAioredlock::test_context_manager", "tests/ut/test_algorithm.py::TestAioredlock::test_destroy_lock_manager", "tests/ut/test_algorithm.py::TestAioredlock::test_auto_extend", "tests/ut/test_algorithm.py::TestAioredlock::test_auto_extend_with_extend_failed", "tests/ut/test_algorithm.py::TestAioredlock::test_unlock_with_watchdog_failed" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-07-07 17:35:45+00:00
mit
3,268
joblib__joblib-1149
diff --git a/CHANGES.rst b/CHANGES.rst index b6c3610..25d3f27 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -32,6 +32,10 @@ In development previous versions of Joblib. https://github.com/joblib/joblib/pull/1374 +- Add ``cache_validation_callback`` in :meth:`joblib.Memory.cache`, to allow + custom cache invalidation based on the metadata of the function call. + https://github.com/joblib/joblib/pull/1149 + - Add a ``return_generator`` parameter for ``Parallel``, that allows to consume results asynchronously. https://github.com/joblib/joblib/pull/1393 diff --git a/doc/memory.rst b/doc/memory.rst index 7b6b176..0a6abd8 100644 --- a/doc/memory.rst +++ b/doc/memory.rst @@ -375,9 +375,9 @@ Gotchas ``self.method = memory.cache(self.method, ignore=['self'])``. * **joblib cache entries may be invalidated after environment updates**. - Values returned by ``joblib.hash`` are not guaranteed to stay + Values returned by :func:`joblib.hash` are not guaranteed to stay constant across ``joblib`` versions. This means that **all** entries of a - ``joblib.Memory`` cache can get invalidated when upgrading ``joblib``. + :class:`Memory` cache can get invalidated when upgrading ``joblib``. Invalidation can also happen when upgrading a third party library (such as ``numpy``): in such a case, only the cached function calls with parameters that are constructs (or contain references to constructs) defined in the @@ -388,7 +388,8 @@ Ignoring some arguments ----------------------- It may be useful not to recalculate a function when certain arguments -change, for instance a debug flag. `Memory` provides the `ignore` list:: +change, for instance a debug flag. :class:`Memory` provides the ``ignore`` +list:: >>> @memory.cache(ignore=['debug']) ... def my_func(x, debug=True): @@ -400,6 +401,62 @@ change, for instance a debug flag. `Memory` provides the `ignore` list:: >>> # my_func was not reevaluated +Custom cache validation +----------------------- + +In some cases, external factors can invalidate the cached results and +one wants to have more control on whether to reuse a result or not. + +This is for instance the case if the results depends on database records +that change over time: a small delay in the updates might be tolerable +but after a while, the results might be invalid. + +One can have a finer control on the cache validity specifying a function +via ``cache_validation_callback`` in :meth:`~joblib.Memory.cache`. For +instance, one can only cache results that take more than 1s to be computed. + + >>> import time + >>> def cache_validation_cb(metadata): + ... # Only retrieve cached results for calls that take more than 1s + ... return metadata['duration'] > 1 + + >>> @memory.cache(cache_validation_callback=cache_validation_cb) + ... def my_func(delay=0): + ... time.sleep(delay) + ... print(f'Called with {delay}s delay') + + >>> my_func() + Called with 0s delay + >>> my_func(1.1) + Called with 1.1s delay + >>> my_func(1.1) # This result is retrieved from cache + >>> my_func() # This one is not and the call is repeated + Called with 0s delay + +``cache_validation_cb`` will be called with a single argument containing +the metadata of the cached call as a dictionary containing the following +keys: + + - ``duration``: the duration of the function call, + - ``time``: the timestamp when the cache called has been recorded + - ``input_args``: a dictionary of keywords arguments for the cached function call. + +Note a validity duration for cached results can be defined via +:func:`joblib.expires_after` by providing similar with arguments similar to the +ones of a ``datetime.timedelta``: + + >>> from joblib import expires_after + >>> @memory.cache(cache_validation_callback=expires_after(seconds=0.5)) + ... def my_func(): + ... print(f'Function run') + >>> my_func() + Function run + >>> my_func() + >>> time.sleep(0.5) + >>> my_func() + Function run + + .. _memory_reference: Reference documentation of the :class:`~joblib.Memory` class @@ -448,3 +505,9 @@ without actually needing to call the function itself:: ... shutil.rmtree(cachedir2) ... except OSError: ... pass # this can sometimes fail under Windows + + +Helper Reference +~~~~~~~~~~~~~~~~ + +.. autofunction:: joblib.expires_after diff --git a/examples/serialization_and_wrappers.py b/examples/serialization_and_wrappers.py index d463242..0b21564 100644 --- a/examples/serialization_and_wrappers.py +++ b/examples/serialization_and_wrappers.py @@ -118,7 +118,7 @@ except Exception: ############################################################################### # To have both fast pickling, safe process creation and serialization of # interactive functions, ``loky`` provides a wrapper function -# :func:`wrap_non_picklable_objects` to wrap the non-picklable function and +# ``wrap_non_picklable_objects`` to wrap the non-picklable function and # indicate to the serialization process that this specific function should be # serialized using ``cloudpickle``. This changes the serialization behavior # only for this function and keeps using ``pickle`` for all other objects. The diff --git a/joblib/__init__.py b/joblib/__init__.py index bc34d81..b5be5fe 100644 --- a/joblib/__init__.py +++ b/joblib/__init__.py @@ -110,13 +110,22 @@ __version__ = '1.3.0.dev0' import os -from .memory import Memory, MemorizedResult, register_store_backend + +from .memory import Memory +from .memory import MemorizedResult +from .memory import register_store_backend +from .memory import expires_after + from .logger import PrintTime from .logger import Logger + from .hashing import hash + from .numpy_pickle import dump from .numpy_pickle import load + from .compressor import register_compressor + from .parallel import Parallel from .parallel import delayed from .parallel import cpu_count @@ -129,7 +138,7 @@ from ._cloudpickle_wrapper import wrap_non_picklable_objects __all__ = ['Memory', 'MemorizedResult', 'PrintTime', 'Logger', 'hash', 'dump', 'load', 'Parallel', 'delayed', 'cpu_count', 'effective_n_jobs', - 'register_parallel_backend', 'parallel_backend', + 'register_parallel_backend', 'parallel_backend', 'expires_after', 'register_store_backend', 'register_compressor', 'wrap_non_picklable_objects', 'parallel_config'] diff --git a/joblib/memory.py b/joblib/memory.py index cc832c8..8171d24 100644 --- a/joblib/memory.py +++ b/joblib/memory.py @@ -22,6 +22,7 @@ import traceback import warnings import inspect import weakref +from datetime import timedelta from tokenize import open as open_py_source @@ -408,17 +409,26 @@ class MemorizedFunc(Logger): verbose: int, optional The verbosity flag, controls messages that are issued as the function is evaluated. + + cache_validation_callback: callable, optional + Callable to check if a result in cache is valid or is to be recomputed. + When the function is called with arguments for which a cache exists, + the callback is called with the cache entry's metadata as its sole + argument. If it returns True, the cached result is returned, else the + cache for these arguments is cleared and the result is recomputed. """ # ------------------------------------------------------------------------ # Public interface # ------------------------------------------------------------------------ def __init__(self, func, location, backend='local', ignore=None, - mmap_mode=None, compress=False, verbose=1, timestamp=None): + mmap_mode=None, compress=False, verbose=1, timestamp=None, + cache_validation_callback=None): Logger.__init__(self) self.mmap_mode = mmap_mode self.compress = compress self.func = func + self.cache_validation_callback = cache_validation_callback if ignore is None: ignore = [] @@ -434,15 +444,16 @@ class MemorizedFunc(Logger): ) if self.store_backend is not None: # Create func directory on demand. - self.store_backend.\ - store_cached_func_code([_build_func_identifier(self.func)]) + self.store_backend.store_cached_func_code([ + _build_func_identifier(self.func) + ]) if timestamp is None: timestamp = time.time() self.timestamp = timestamp try: functools.update_wrapper(self, func) - except: # noqa: E722 + except Exception: " Objects like ufunc don't like that " if inspect.isfunction(func): doc = pydoc.TextDoc().document(func) @@ -458,6 +469,34 @@ class MemorizedFunc(Logger): self._func_code_info = None self._func_code_id = None + def _is_in_cache_and_valid(self, path): + """Check if the function call is cached and valid for given arguments. + + - Compare the function code with the one from the cached function, + asserting if it has changed. + - Check if the function call is present in the cache. + - Call `cache_validation_callback` for user define cache validation. + + Returns True if the function call is in cache and can be used, and + returns False otherwise. + """ + # Check if the code of the function has changed + if not self._check_previous_func_code(stacklevel=4): + return False + + # Check if this specific call is in the cache + if not self.store_backend.contains_item(path): + return False + + # Call the user defined cache validation callback + metadata = self.store_backend.get_metadata(path) + if (self.cache_validation_callback is not None and + not self.cache_validation_callback(metadata)): + self.store_backend.clear_item(path) + return False + + return True + def _cached_call(self, args, kwargs, shelving=False): """Call wrapped function and cache result, or read cache if available. @@ -513,20 +552,10 @@ class MemorizedFunc(Logger): ) ) - # FIXME: The statements below should be try/excepted # Compare the function code with the previous to see if the - # function code has changed - if not (self._check_previous_func_code(stacklevel=4) and - self.store_backend.contains_item([func_id, args_id])): - if self._verbose > 10: - _, name = get_func_name(self.func) - self.warn('Computing func {0}, argument hash {1} ' - 'in location {2}' - .format(name, args_id, - self.store_backend. - get_cached_func_info([func_id])['location'])) - must_call = True - else: + # function code has changed and check if the results are present in + # the cache. + if self._is_in_cache_and_valid([func_id, args_id]): try: t0 = time.time() if self._verbose: @@ -555,6 +584,15 @@ class MemorizedFunc(Logger): '{}\n {}'.format(signature, traceback.format_exc())) must_call = True + else: + if self._verbose > 10: + _, name = get_func_name(self.func) + self.warn('Computing func {0}, argument hash {1} ' + 'in location {2}' + .format(name, args_id, + self.store_backend. + get_cached_func_info([func_id])['location'])) + must_call = True if must_call: out, metadata = self.call(*args, **kwargs) @@ -852,7 +890,9 @@ class MemorizedFunc(Logger): input_repr = dict((k, repr(v)) for k, v in argument_dict.items()) # This can fail due to race-conditions with multiple # concurrent joblibs removing the file or the directory - metadata = {"duration": duration, "input_args": input_repr} + metadata = { + "duration": duration, "input_args": input_repr, "time": start_time, + } func_id, args_id = self._get_output_identifiers(*args, **kwargs) self.store_backend.store_metadata([func_id, args_id], metadata) @@ -982,7 +1022,8 @@ class Memory(Logger): backend_options=dict(compress=compress, mmap_mode=mmap_mode, **backend_options)) - def cache(self, func=None, ignore=None, verbose=None, mmap_mode=False): + def cache(self, func=None, ignore=None, verbose=None, mmap_mode=False, + cache_validation_callback=None): """ Decorates the given function func to only compute its return value for input arguments not cached on disk. @@ -999,6 +1040,13 @@ class Memory(Logger): The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments. By default that of the memory object is used. + cache_validation_callback: callable, optional + Callable to validate whether or not the cache is valid. When + the cached function is called with arguments for which a cache + exists, this callable is called with the metadata of the cached + result as its sole argument. If it returns True, then the + cached result is returned, else the cache for these arguments + is cleared and recomputed. Returns ------- @@ -1008,11 +1056,21 @@ class Memory(Logger): methods for cache lookup and management. See the documentation for :class:`joblib.memory.MemorizedFunc`. """ + if (cache_validation_callback is not None and + not callable(cache_validation_callback)): + raise ValueError( + "cache_validation_callback needs to be callable. " + f"Got {cache_validation_callback}." + ) if func is None: # Partial application, to be able to specify extra keyword # arguments in decorators - return functools.partial(self.cache, ignore=ignore, - verbose=verbose, mmap_mode=mmap_mode) + return functools.partial( + self.cache, ignore=ignore, + mmap_mode=mmap_mode, + verbose=verbose, + cache_validation_callback=cache_validation_callback + ) if self.store_backend is None: return NotMemorizedFunc(func) if verbose is None: @@ -1021,11 +1079,12 @@ class Memory(Logger): mmap_mode = self.mmap_mode if isinstance(func, MemorizedFunc): func = func.func - return MemorizedFunc(func, location=self.store_backend, - backend=self.backend, - ignore=ignore, mmap_mode=mmap_mode, - compress=self.compress, - verbose=verbose, timestamp=self.timestamp) + return MemorizedFunc( + func, location=self.store_backend, backend=self.backend, + ignore=ignore, mmap_mode=mmap_mode, compress=self.compress, + verbose=verbose, timestamp=self.timestamp, + cache_validation_callback=cache_validation_callback + ) def clear(self, warn=True): """ Erase the complete cache directory. @@ -1113,3 +1172,28 @@ class Memory(Logger): state = self.__dict__.copy() state['timestamp'] = None return state + + +############################################################################### +# cache_validation_callback helpers +############################################################################### + +def expires_after(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, + hours=0, weeks=0): + """Helper cache_validation_callback to force recompute after a duration. + + Parameters + ---------- + days, seconds, microseconds, milliseconds, minutes, hours, weeks: numbers + argument passed to a timedelta. + """ + delta = timedelta( + days=days, seconds=seconds, microseconds=microseconds, + milliseconds=milliseconds, minutes=minutes, hours=hours, weeks=weeks + ) + + def cache_validation_callback(metadata): + computation_age = time.time() - metadata['time'] + return computation_age < delta.total_seconds() + + return cache_validation_callback
joblib/joblib
9f7edc2f67d1d27757be88168ffe533a916e1032
diff --git a/joblib/test/test_memory.py b/joblib/test/test_memory.py index 98cfce6..ff018fb 100644 --- a/joblib/test/test_memory.py +++ b/joblib/test/test_memory.py @@ -22,6 +22,7 @@ import textwrap import pytest from joblib.memory import Memory +from joblib.memory import expires_after from joblib.memory import MemorizedFunc, NotMemorizedFunc from joblib.memory import MemorizedResult, NotMemorizedResult from joblib.memory import _FUNCTION_HASHES @@ -87,10 +88,10 @@ def test_memory_integration(tmpdir): """ Simple test of memory lazy evaluation. """ accumulator = list() + # Rmk: this function has the same name than a module-level function, # thus it serves as a test to see that both are identified # as different. - def f(arg): accumulator.append(1) return arg @@ -1401,3 +1402,87 @@ def test_deprecated_bytes_limit(tmpdir): ) with pytest.warns(DeprecationWarning, match="bytes_limit"): _ = Memory(location=tmpdir.strpath, bytes_limit='1K') + + +class TestCacheValidationCallback: + "Tests on parameter `cache_validation_callback`" + + @pytest.fixture() + def memory(self, tmp_path): + mem = Memory(location=tmp_path) + yield mem + mem.clear() + + def foo(self, x, d, delay=None): + d["run"] = True + if delay is not None: + time.sleep(delay) + return x * 2 + + def test_invalid_cache_validation_callback(self, memory): + "Test invalid values for `cache_validation_callback" + match = "cache_validation_callback needs to be callable. Got True." + with pytest.raises(ValueError, match=match): + memory.cache(cache_validation_callback=True) + + @pytest.mark.parametrize("consider_cache_valid", [True, False]) + def test_constant_cache_validation_callback( + self, memory, consider_cache_valid + ): + "Test expiry of old results" + f = memory.cache( + self.foo, cache_validation_callback=lambda _: consider_cache_valid, + ignore=["d"] + ) + + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1) == 4 + assert f(2, d2) == 4 + + assert d1["run"] + assert d2["run"] != consider_cache_valid + + def test_memory_only_cache_long_run(self, memory): + "Test cache validity based on run duration." + + def cache_validation_callback(metadata): + duration = metadata['duration'] + if duration > 0.1: + return True + + f = memory.cache( + self.foo, cache_validation_callback=cache_validation_callback, + ignore=["d"] + ) + + # Short run are not cached + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1, delay=0) == 4 + assert f(2, d2, delay=0) == 4 + assert d1["run"] + assert d2["run"] + + # Longer run are cached + d1, d2 = {"run": False}, {"run": False} + assert f(2, d1, delay=0.2) == 4 + assert f(2, d2, delay=0.2) == 4 + assert d1["run"] + assert not d2["run"] + + def test_memory_expires_after(self, memory): + "Test expiry of old cached results" + + f = memory.cache( + self.foo, cache_validation_callback=expires_after(seconds=.3), + ignore=["d"] + ) + + d1, d2, d3 = {"run": False}, {"run": False}, {"run": False} + assert f(2, d1) == 4 + assert f(2, d2) == 4 + time.sleep(.5) + assert f(2, d3) == 4 + + assert d1["run"] + assert not d2["run"] + assert d3["run"]
Expiry of old results I've added a small extra feature that recalculates if a result is older than a certain age. ``` @memory.cache(expires_after=60) def f(x): ... ``` Will recompute if cached result is older than 60 seconds. Code is in this branch: https://github.com/fredludlow/joblib/tree/expires-after Is this of interest? And if so, is there anything else that needs doing before sending a pull request? (I've added test coverage in test_memory.py)
0.0
9f7edc2f67d1d27757be88168ffe533a916e1032
[ "joblib/test/test_memory.py::test_memory_integration", "joblib/test/test_memory.py::test_no_memory", "joblib/test/test_memory.py::test_memory_kwarg", "joblib/test/test_memory.py::test_memory_lambda", "joblib/test/test_memory.py::test_memory_name_collision", "joblib/test/test_memory.py::test_memory_warning_lambda_collisions", "joblib/test/test_memory.py::test_memory_warning_collision_detection", "joblib/test/test_memory.py::test_memory_partial", "joblib/test/test_memory.py::test_memory_eval", "joblib/test/test_memory.py::test_argument_change", "joblib/test/test_memory.py::test_memory_exception", "joblib/test/test_memory.py::test_memory_ignore", "joblib/test/test_memory.py::test_memory_ignore_decorated", "joblib/test/test_memory.py::test_memory_args_as_kwargs", "joblib/test/test_memory.py::test_partial_decoration[ignore0-100-r]", "joblib/test/test_memory.py::test_partial_decoration[ignore1-10-None]", "joblib/test/test_memory.py::test_func_dir", "joblib/test/test_memory.py::test_persistence", "joblib/test/test_memory.py::test_check_call_in_cache", "joblib/test/test_memory.py::test_call_and_shelve", "joblib/test/test_memory.py::test_call_and_shelve_argument_hash", "joblib/test/test_memory.py::test_call_and_shelve_lazily_load_stored_result", "joblib/test/test_memory.py::test_memorized_pickling", "joblib/test/test_memory.py::test_memorized_repr", "joblib/test/test_memory.py::test_memory_file_modification", "joblib/test/test_memory.py::test_memory_in_memory_function_code_change", "joblib/test/test_memory.py::test_clear_memory_with_none_location", "joblib/test/test_memory.py::test_memory_func_with_kwonly_args", "joblib/test/test_memory.py::test_memory_func_with_signature", "joblib/test/test_memory.py::test__get_items", "joblib/test/test_memory.py::test__get_items_to_delete", "joblib/test/test_memory.py::test_memory_reduce_size_bytes_limit", "joblib/test/test_memory.py::test_memory_reduce_size_items_limit", "joblib/test/test_memory.py::test_memory_reduce_size_age_limit", "joblib/test/test_memory.py::test_memory_clear", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output_2", "joblib/test/test_memory.py::test_memory_recomputes_after_an_error_while_loading_results", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[None]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix1]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix2]", "joblib/test/test_memory.py::test_register_invalid_store_backends_object", "joblib/test/test_memory.py::test_memory_default_store_backend", "joblib/test/test_memory.py::test_warning_on_unknown_location_type", "joblib/test/test_memory.py::test_instanciate_incomplete_store_backend", "joblib/test/test_memory.py::test_dummy_store_backend", "joblib/test/test_memory.py::test_instanciate_store_backend_with_pathlib_path", "joblib/test/test_memory.py::test_filesystem_store_backend_repr", "joblib/test/test_memory.py::test_memory_objects_repr", "joblib/test/test_memory.py::test_memorized_result_pickle", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs0]", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs1]", "joblib/test/test_memory.py::test_info_log", "joblib/test/test_memory.py::test_deprecated_bytes_limit", "joblib/test/test_memory.py::TestCacheValidationCallback::test_invalid_cache_validation_callback", "joblib/test/test_memory.py::TestCacheValidationCallback::test_constant_cache_validation_callback[True]", "joblib/test/test_memory.py::TestCacheValidationCallback::test_constant_cache_validation_callback[False]", "joblib/test/test_memory.py::TestCacheValidationCallback::test_memory_only_cache_long_run", "joblib/test/test_memory.py::TestCacheValidationCallback::test_memory_expires_after" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-01-11 23:51:23+00:00
bsd-3-clause
3,269
joblib__joblib-1165
diff --git a/CHANGES.rst b/CHANGES.rst index 5328c2c..93144b3 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,13 @@ Latest changes ============== +Development version +------------------- + +- Fix joblib.Memory bug with the ``ignore`` parameter when the cached function + is a decorated function. + https://github.com/joblib/joblib/pull/1165 + 1.0.1 ----- diff --git a/joblib/func_inspect.py b/joblib/func_inspect.py index ec6bb4a..3751347 100644 --- a/joblib/func_inspect.py +++ b/joblib/func_inspect.py @@ -171,10 +171,9 @@ def get_func_name(func, resolv_alias=True, win_characters=True): return module, name -def _signature_str(function_name, arg_spec): +def _signature_str(function_name, arg_sig): """Helper function to output a function signature""" - arg_spec_str = inspect.formatargspec(*arg_spec) - return '{}{}'.format(function_name, arg_spec_str) + return '{}{}'.format(function_name, arg_sig) def _function_called_str(function_name, args, kwargs): @@ -221,20 +220,34 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): warnings.warn('Cannot inspect object %s, ignore list will ' 'not work.' % func, stacklevel=2) return {'*': args, '**': kwargs} - arg_spec = inspect.getfullargspec(func) - arg_names = arg_spec.args + arg_spec.kwonlyargs - arg_defaults = arg_spec.defaults or () - if arg_spec.kwonlydefaults: - arg_defaults = arg_defaults + tuple(arg_spec.kwonlydefaults[k] - for k in arg_spec.kwonlyargs - if k in arg_spec.kwonlydefaults) - arg_varargs = arg_spec.varargs - arg_varkw = arg_spec.varkw - + arg_sig = inspect.signature(func) + arg_names = [] + arg_defaults = [] + arg_kwonlyargs = [] + arg_varargs = None + arg_varkw = None + for param in arg_sig.parameters.values(): + if param.kind is param.POSITIONAL_OR_KEYWORD: + arg_names.append(param.name) + elif param.kind is param.KEYWORD_ONLY: + arg_names.append(param.name) + arg_kwonlyargs.append(param.name) + elif param.kind is param.VAR_POSITIONAL: + arg_varargs = param.name + elif param.kind is param.VAR_KEYWORD: + arg_varkw = param.name + if param.default is not param.empty: + arg_defaults.append(param.default) if inspect.ismethod(func): # First argument is 'self', it has been removed by Python # we need to add it back: args = [func.__self__, ] + args + # func is an instance method, inspect.signature(func) does not + # include self, we need to fetch it from the class method, i.e + # func.__func__ + class_method_sig = inspect.signature(func.__func__) + self_name = next(iter(class_method_sig.parameters)) + arg_names = [self_name] + arg_names # XXX: Maybe I need an inspect.isbuiltin to detect C-level methods, such # as on ndarrays. @@ -244,7 +257,7 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): for arg_position, arg_name in enumerate(arg_names): if arg_position < len(args): # Positional argument or keyword argument given as positional - if arg_name not in arg_spec.kwonlyargs: + if arg_name not in arg_kwonlyargs: arg_dict[arg_name] = args[arg_position] else: raise ValueError( @@ -252,7 +265,7 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): 'positional parameter for %s:\n' ' %s was called.' % (arg_name, - _signature_str(name, arg_spec), + _signature_str(name, arg_sig), _function_called_str(name, args, kwargs)) ) @@ -268,7 +281,7 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): raise ValueError( 'Wrong number of arguments for %s:\n' ' %s was called.' - % (_signature_str(name, arg_spec), + % (_signature_str(name, arg_sig), _function_called_str(name, args, kwargs)) ) from e @@ -296,7 +309,7 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): raise ValueError("Ignore list: argument '%s' is not defined for " "function %s" % (item, - _signature_str(name, arg_spec)) + _signature_str(name, arg_sig)) ) # XXX: Return a sorted list of pairs? return arg_dict diff --git a/joblib/memory.py b/joblib/memory.py index 424d9fe..f5d59eb 100644 --- a/joblib/memory.py +++ b/joblib/memory.py @@ -882,7 +882,10 @@ class Memory(Logger): as functions are evaluated. bytes_limit: int, optional - Limit in bytes of the size of the cache. + Limit in bytes of the size of the cache. By default, the size of + the cache is unlimited. + Note: You need to call :meth:`joblib.Memory.reduce_size` to + actually reduce the cache size to be less than ``bytes_limit``. backend_options: dict, optional Contains a dictionnary of named parameters used to configure
joblib/joblib
5c7c4566bc2668a435799713fcbf467234f4e984
diff --git a/joblib/test/test_memory.py b/joblib/test/test_memory.py index ad0ddf4..e917871 100644 --- a/joblib/test/test_memory.py +++ b/joblib/test/test_memory.py @@ -6,6 +6,7 @@ Test the memory module. # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. +import functools import gc import shutil import os @@ -488,6 +489,32 @@ def test_memory_ignore(tmpdir): assert len(accumulator) == 1 +def test_memory_ignore_decorated(tmpdir): + " Test the ignore feature of memory on a decorated function " + memory = Memory(location=tmpdir.strpath, verbose=0) + accumulator = list() + + def decorate(f): + @functools.wraps(f) + def wrapped(*args, **kwargs): + return f(*args, **kwargs) + return wrapped + + @memory.cache(ignore=['y']) + @decorate + def z(x, y=1): + accumulator.append(1) + + assert z.ignore == ['y'] + + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=1) + assert len(accumulator) == 1 + z(0, y=2) + assert len(accumulator) == 1 + + def test_memory_args_as_kwargs(tmpdir): """Non-regression test against 0.12.0 changes.
Use inspect.signature() instead of inspect.getfullargspec() Currently, the implementation of `Memory.cache()` implements the `ignore` option using [`inspect.getfullargspec()`](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec). However, this function does not handle decorated functions correctly; [`inspect.signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature), on the other hand, does. Observe: ```python from functools import wraps import inspect def decorate(f): @wraps(f) def wrapped(*args, **kwargs): return f(*args, **kwargs) return wrapped @decorate def foo(arg, extra=None): return arg print(inspect.signature(foo)) print(inspect.getfullargspec(foo)) ``` This prints out: ``` (arg, extra=None) FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) ``` Note that `signature()` reports the signature of the original `foo`, while `getfullargspec()` reports the signature of `wrapped`. As a consequence of this, using the `ignore` option on a Memory-cached function with an intervening decorator does not work. Example: ```python from functools import wraps import inspect from joblib import Memory mem = Memory("cache", verbose=0) def decorate(f): @wraps(f) def wrapped(*args, **kwargs): return f(*args, **kwargs) return wrapped @mem.cache(ignore=["extra"]) @decorate def foo(arg, extra=None): return arg foo(1) ``` This fails with the error `ValueError: Ignore list: argument 'extra' is not defined for function foo(*args, **kwargs)`.
0.0
5c7c4566bc2668a435799713fcbf467234f4e984
[ "joblib/test/test_memory.py::test_memory_ignore_decorated" ]
[ "joblib/test/test_memory.py::test_memory_integration", "joblib/test/test_memory.py::test_no_memory", "joblib/test/test_memory.py::test_memory_kwarg", "joblib/test/test_memory.py::test_memory_lambda", "joblib/test/test_memory.py::test_memory_name_collision", "joblib/test/test_memory.py::test_memory_warning_lambda_collisions", "joblib/test/test_memory.py::test_memory_warning_collision_detection", "joblib/test/test_memory.py::test_memory_partial", "joblib/test/test_memory.py::test_memory_eval", "joblib/test/test_memory.py::test_argument_change", "joblib/test/test_memory.py::test_memory_exception", "joblib/test/test_memory.py::test_memory_ignore", "joblib/test/test_memory.py::test_memory_args_as_kwargs", "joblib/test/test_memory.py::test_partial_decoration[ignore0-100-r]", "joblib/test/test_memory.py::test_partial_decoration[ignore1-10-None]", "joblib/test/test_memory.py::test_func_dir", "joblib/test/test_memory.py::test_persistence", "joblib/test/test_memory.py::test_call_and_shelve", "joblib/test/test_memory.py::test_call_and_shelve_argument_hash", "joblib/test/test_memory.py::test_call_and_shelve_lazily_load_stored_result", "joblib/test/test_memory.py::test_memorized_pickling", "joblib/test/test_memory.py::test_memorized_repr", "joblib/test/test_memory.py::test_memory_file_modification", "joblib/test/test_memory.py::test_memory_in_memory_function_code_change", "joblib/test/test_memory.py::test_clear_memory_with_none_location", "joblib/test/test_memory.py::test_memory_func_with_kwonly_args", "joblib/test/test_memory.py::test_memory_func_with_signature", "joblib/test/test_memory.py::test__get_items", "joblib/test/test_memory.py::test__get_items_to_delete", "joblib/test/test_memory.py::test_memory_reduce_size", "joblib/test/test_memory.py::test_memory_clear", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output_2", "joblib/test/test_memory.py::test_memory_recomputes_after_an_error_while_loading_results", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[None]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix1]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix2]", "joblib/test/test_memory.py::test_register_invalid_store_backends_object", "joblib/test/test_memory.py::test_memory_default_store_backend", "joblib/test/test_memory.py::test_warning_on_unknown_location_type", "joblib/test/test_memory.py::test_instanciate_incomplete_store_backend", "joblib/test/test_memory.py::test_dummy_store_backend", "joblib/test/test_memory.py::test_instanciate_store_backend_with_pathlib_path", "joblib/test/test_memory.py::test_filesystem_store_backend_repr", "joblib/test/test_memory.py::test_memory_objects_repr", "joblib/test/test_memory.py::test_memorized_result_pickle", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs0]", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs1]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-15 13:14:57+00:00
bsd-3-clause
3,270
joblib__joblib-1200
diff --git a/CHANGES.rst b/CHANGES.rst index 3decb56..b6c3610 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,15 +4,15 @@ Latest changes In development -------------- -- Ensure native byte order for memmap arrays in `joblib.load`. +- Ensure native byte order for memmap arrays in ``joblib.load``. https://github.com/joblib/joblib/issues/1353 - Add ability to change default Parallel backend in tests by setting the - JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND environment variable. + ``JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND`` environment variable. https://github.com/joblib/joblib/pull/1356 - Fix temporary folder creation in `joblib.Parallel` on Linux subsystems on Windows - which do have `/dev/shm` but don't have the `os.statvfs` function + which do have `/dev/shm` but don't have the `os.statvfs` function https://github.com/joblib/joblib/issues/1353 - Drop runtime dependency on ``distutils``. ``distutils`` is going away @@ -24,7 +24,7 @@ In development - A warning is raised when a pickling error occurs during caching operations. In version 1.5, this warning will be turned into an error. For all other - errors, a new warning has been introduced: `joblib.memory.CacheWarning`. + errors, a new warning has been introduced: ``joblib.memory.CacheWarning``. https://github.com/joblib/joblib/pull/1359 - Avoid (module, name) collisions when caching nested functions. This fix @@ -40,12 +40,18 @@ In development tracebacks and more efficient running time. https://github.com/joblib/joblib/pull/1393 -- Add the `parallel_config` context manager to allow for more fine-grained +- Add the ``parallel_config`` context manager to allow for more fine-grained control over the backend configuration. It should be used in place of the - `parallel_backend` context manager. In particular, it has the advantage + ``parallel_backend`` context manager. In particular, it has the advantage of not requiring to set a specific backend in the context manager. https://github.com/joblib/joblib/pull/1392 +- Add ``items_limit`` and ``age_limit`` in :meth:`joblib.Memory.reduce_size` + to make it easy to limit the number of items and remove items that have + not been accessed for a long time in the cache. + https://github.com/joblib/joblib/pull/1200 + + Release 1.2.0 ------------- @@ -59,7 +65,7 @@ Release 1.2.0 - Avoid unnecessary warnings when workers and main process delete the temporary memmap folder contents concurrently. - https://github.com/joblib/joblib/pull/1263 + https://github.com/joblib/joblib/pull/1263 - Fix memory alignment bug for pickles containing numpy arrays. This is especially important when loading the pickle with @@ -118,7 +124,7 @@ Release 1.0.1 - Add check_call_in_cache method to check cache without calling function. https://github.com/joblib/joblib/pull/820 - + - dask: avoid redundant scattering of large arguments to make a more efficient use of the network resources and avoid crashing dask with "OSError: [Errno 55] No buffer space available" @@ -134,7 +140,7 @@ Release 1.0.0 or a third party library involved in the cached values definition is upgraded. In particular, users updating `joblib` to a release that includes this fix will see their previous cache invalidated if they contained - reference to `numpy` objects. + reference to `numpy` objects. https://github.com/joblib/joblib/pull/1136 - Remove deprecated `check_pickle` argument in `delayed`. diff --git a/joblib/_store_backends.py b/joblib/_store_backends.py index 21a4958..de1e939 100644 --- a/joblib/_store_backends.py +++ b/joblib/_store_backends.py @@ -294,9 +294,15 @@ class StoreBackendMixin(object): """Clear the whole store content.""" self.clear_location(self.location) - def reduce_store_size(self, bytes_limit): - """Reduce store size to keep it under the given bytes limit.""" - items_to_delete = self._get_items_to_delete(bytes_limit) + def enforce_store_limits( + self, bytes_limit, items_limit=None, age_limit=None + ): + """ + Remove the store's oldest files to enforce item, byte, and age limits. + """ + items_to_delete = self._get_items_to_delete( + bytes_limit, items_limit, age_limit + ) for item in items_to_delete: if self.verbose > 10: @@ -310,16 +316,38 @@ class StoreBackendMixin(object): # the folder already. pass - def _get_items_to_delete(self, bytes_limit): - """Get items to delete to keep the store under a size limit.""" + def _get_items_to_delete( + self, bytes_limit, items_limit=None, age_limit=None + ): + """ + Get items to delete to keep the store under size, file, & age limits. + """ if isinstance(bytes_limit, str): bytes_limit = memstr_to_bytes(bytes_limit) items = self.get_items() size = sum(item.size for item in items) - to_delete_size = size - bytes_limit - if to_delete_size < 0: + if bytes_limit is not None: + to_delete_size = size - bytes_limit + else: + to_delete_size = 0 + + if items_limit is not None: + to_delete_items = len(items) - items_limit + else: + to_delete_items = 0 + + if age_limit is not None: + older_item = min(item.last_access for item in items) + deadline = datetime.datetime.now() - age_limit + else: + deadline = None + + if ( + to_delete_size <= 0 and to_delete_items <= 0 + and (deadline is None or older_item > deadline) + ): return [] # We want to delete first the cache items that were accessed a @@ -328,13 +356,19 @@ class StoreBackendMixin(object): items_to_delete = [] size_so_far = 0 + items_so_far = 0 for item in items: - if size_so_far > to_delete_size: + if ( + (size_so_far >= to_delete_size) + and items_so_far >= to_delete_items + and (deadline is None or deadline < item.last_access) + ): break items_to_delete.append(item) size_so_far += item.size + items_so_far += 1 return items_to_delete diff --git a/joblib/memory.py b/joblib/memory.py index 90fe41e..70d0f60 100644 --- a/joblib/memory.py +++ b/joblib/memory.py @@ -926,10 +926,12 @@ class Memory(Logger): Verbosity flag, controls the debug messages that are issued as functions are evaluated. - bytes_limit: int, optional + bytes_limit: int | str, optional Limit in bytes of the size of the cache. By default, the size of the cache is unlimited. When reducing the size of the cache, - ``joblib`` keeps the most recently accessed items first. + ``joblib`` keeps the most recently accessed items first. If a + str is passed, it is converted to a number of bytes using units + { K | M | G} for kilo, mega, giga. **Note:** You need to call :meth:`joblib.Memory.reduce_size` to actually reduce the cache size to be less than ``bytes_limit``. @@ -1022,16 +1024,53 @@ class Memory(Logger): if self.store_backend is not None: self.store_backend.clear() - # As the cache in completely clear, make sure the _FUNCTION_HASHES + # As the cache is completely clear, make sure the _FUNCTION_HASHES # cache is also reset. Else, for a function that is present in this # table, results cached after this clear will be have cache miss # as the function code is not re-written. _FUNCTION_HASHES.clear() - def reduce_size(self): - """Remove cache elements to make cache size fit in ``bytes_limit``.""" - if self.bytes_limit is not None and self.store_backend is not None: - self.store_backend.reduce_store_size(self.bytes_limit) + def reduce_size(self, bytes_limit=None, items_limit=None, age_limit=None): + """Remove cache elements to make the cache fit its limits. + + The limitation can impose that the cache size fits in ``bytes_limit``, + that the number of cache items is no more than ``items_limit``, and + that all files in cache are not older than ``age_limit``. + + Parameters + ---------- + bytes_limit: int | str, optional + Limit in bytes of the size of the cache. By default, the size of + the cache is unlimited. When reducing the size of the cache, + ``joblib`` keeps the most recently accessed items first. If a + str is passed, it is converted to a number of bytes using units + { K | M | G} for kilo, mega, giga. + + items_limit: int, optional + Number of items to limit the cache to. By default, the number of + items in the cache is unlimited. When reducing the size of the + cache, ``joblib`` keeps the most recently accessed items first. + + age_limit: datetime.timedelta, optional + Maximum age of items to limit the cache to. When reducing the size + of the cache, any items last accessed more than the given length of + time ago are deleted. + """ + if bytes_limit is None: + bytes_limit = self.bytes_limit + + if self.store_backend is None: + # No cached results, this function does nothing. + return + + if bytes_limit is None and items_limit is None and age_limit is None: + # No limitation to impose, returning + return + + # Defers the actual limits enforcing to the store backend. + self.store_backend.enforce_store_limits( + bytes_limit, items_limit, age_limit + ) def eval(self, func, *args, **kwargs): """ Eval function func with arguments `*args` and `**kwargs`,
joblib/joblib
2303143c041d34267f73a2ded06fccd73547c3fa
diff --git a/joblib/test/test_memory.py b/joblib/test/test_memory.py index 035e9a1..5fa9d53 100644 --- a/joblib/test/test_memory.py +++ b/joblib/test/test_memory.py @@ -942,7 +942,7 @@ def test__get_items_to_delete(tmpdir): min(ci.last_access for ci in surviving_items)) -def test_memory_reduce_size(tmpdir): +def test_memory_reduce_size_bytes_limit(tmpdir): memory, _, _ = _setup_toy_cache(tmpdir) ref_cache_items = memory.store_backend.get_items() @@ -973,6 +973,64 @@ def test_memory_reduce_size(tmpdir): assert cache_items == [] +def test_memory_reduce_size_items_limit(tmpdir): + memory, _, _ = _setup_toy_cache(tmpdir) + ref_cache_items = memory.store_backend.get_items() + + # By default reduce_size is a noop + memory.reduce_size() + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # No cache items deleted if items_limit greater than the size of + # the cache + memory.reduce_size(items_limit=10) + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # items_limit is set so that only two cache items are kept + memory.reduce_size(items_limit=2) + cache_items = memory.store_backend.get_items() + assert set.issubset(set(cache_items), set(ref_cache_items)) + assert len(cache_items) == 2 + + # bytes_limit set so that no cache item is kept + memory.reduce_size(items_limit=0) + cache_items = memory.store_backend.get_items() + assert cache_items == [] + + +def test_memory_reduce_size_age_limit(tmpdir): + import time + import datetime + memory, _, put_cache = _setup_toy_cache(tmpdir) + ref_cache_items = memory.store_backend.get_items() + + # By default reduce_size is a noop + memory.reduce_size() + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # No cache items deleted if age_limit big. + memory.reduce_size(age_limit=datetime.timedelta(days=1)) + cache_items = memory.store_backend.get_items() + assert sorted(ref_cache_items) == sorted(cache_items) + + # age_limit is set so that only two cache items are kept + time.sleep(1) + put_cache(-1) + put_cache(-2) + memory.reduce_size(age_limit=datetime.timedelta(seconds=1)) + cache_items = memory.store_backend.get_items() + assert not set.issubset(set(cache_items), set(ref_cache_items)) + assert len(cache_items) == 2 + + # age_limit set so that no cache item is kept + memory.reduce_size(age_limit=datetime.timedelta(seconds=0)) + cache_items = memory.store_backend.get_items() + assert cache_items == [] + + def test_memory_clear(tmpdir): memory, _, g = _setup_toy_cache(tmpdir) memory.clear()
Wishlist: more flexible control (not just by size) for clean up Follow up to #1170 . Thank you for the clarifications on logic -- great to know that both `last_access` attribute it stored! In our use case (https://github.com/con/fscacher/) size though is not an issue -- it is just a sheer number of files, and thus inodes consumed. I made a mistake to use "good old" EXT4 for HOME partition instead of BTRFS as for the main bulk storage and now I am paying the price of "running out of space" while still having GBs of actual space available. There is virtually no rule of thumb for what size (in bytes) we should aim for in our use case. But it might be feasible to figure out how many cached items to keep (also the information which is available since you know the number of cached items) and/or even better -- for how long (known since `last_access` is stored). I would have then set in our case cache to not exceed 10k entries and be no older than 1 week or so. Do you think such modes of cleanup could be added to `reduce_size` call? (due to (FWIW: unless `reduce_size` is to be triggered automagically, I see no reason for `bytes_limit` or any of those settings actually to be listed in the constructor, and not just to become arguments for `reduce_size` call).
0.0
2303143c041d34267f73a2ded06fccd73547c3fa
[ "joblib/test/test_memory.py::test_memory_reduce_size_items_limit", "joblib/test/test_memory.py::test_memory_reduce_size_age_limit" ]
[ "joblib/test/test_memory.py::test_memory_integration", "joblib/test/test_memory.py::test_no_memory", "joblib/test/test_memory.py::test_memory_kwarg", "joblib/test/test_memory.py::test_memory_lambda", "joblib/test/test_memory.py::test_memory_name_collision", "joblib/test/test_memory.py::test_memory_warning_lambda_collisions", "joblib/test/test_memory.py::test_memory_warning_collision_detection", "joblib/test/test_memory.py::test_memory_partial", "joblib/test/test_memory.py::test_memory_eval", "joblib/test/test_memory.py::test_argument_change", "joblib/test/test_memory.py::test_memory_exception", "joblib/test/test_memory.py::test_memory_ignore", "joblib/test/test_memory.py::test_memory_ignore_decorated", "joblib/test/test_memory.py::test_memory_args_as_kwargs", "joblib/test/test_memory.py::test_partial_decoration[ignore0-100-r]", "joblib/test/test_memory.py::test_partial_decoration[ignore1-10-None]", "joblib/test/test_memory.py::test_func_dir", "joblib/test/test_memory.py::test_persistence", "joblib/test/test_memory.py::test_check_call_in_cache", "joblib/test/test_memory.py::test_call_and_shelve", "joblib/test/test_memory.py::test_call_and_shelve_argument_hash", "joblib/test/test_memory.py::test_call_and_shelve_lazily_load_stored_result", "joblib/test/test_memory.py::test_memorized_pickling", "joblib/test/test_memory.py::test_memorized_repr", "joblib/test/test_memory.py::test_memory_file_modification", "joblib/test/test_memory.py::test_memory_in_memory_function_code_change", "joblib/test/test_memory.py::test_clear_memory_with_none_location", "joblib/test/test_memory.py::test_memory_func_with_kwonly_args", "joblib/test/test_memory.py::test_memory_func_with_signature", "joblib/test/test_memory.py::test__get_items", "joblib/test/test_memory.py::test__get_items_to_delete", "joblib/test/test_memory.py::test_memory_reduce_size_bytes_limit", "joblib/test/test_memory.py::test_memory_clear", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output", "joblib/test/test_memory.py::test_cached_function_race_condition_when_persisting_output_2", "joblib/test/test_memory.py::test_memory_recomputes_after_an_error_while_loading_results", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[None]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix1]", "joblib/test/test_memory.py::test_register_invalid_store_backends_key[invalid_prefix2]", "joblib/test/test_memory.py::test_register_invalid_store_backends_object", "joblib/test/test_memory.py::test_memory_default_store_backend", "joblib/test/test_memory.py::test_warning_on_unknown_location_type", "joblib/test/test_memory.py::test_instanciate_incomplete_store_backend", "joblib/test/test_memory.py::test_dummy_store_backend", "joblib/test/test_memory.py::test_instanciate_store_backend_with_pathlib_path", "joblib/test/test_memory.py::test_filesystem_store_backend_repr", "joblib/test/test_memory.py::test_memory_objects_repr", "joblib/test/test_memory.py::test_memorized_result_pickle", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs0]", "joblib/test/test_memory.py::test_memory_pickle_dump_load[memory_kwargs1]", "joblib/test/test_memory.py::test_info_log" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-01 13:51:16+00:00
bsd-3-clause
3,271
joblib__joblib-1254
diff --git a/CHANGES.rst b/CHANGES.rst index c5c428a..56c8e76 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -16,6 +16,18 @@ Development version worker processes in case of a crash. https://github.com/joblib/joblib/pull/1269 +- Fix memory alignment bug for pickles containing numpy arrays. + This is especially important when loading the pickle with + ``mmap_mode != None`` as the resulting ``numpy.memmap`` object + would not be able to correct the misalignment without performing + a memory copy. + This bug would cause invalid computation and segmentation faults + with native code that would directly access the underlying data + buffer of a numpy array, for instance C/C++/Cython code compiled + with older GCC versions or some old OpenBLAS written in platform + specific assembly. + https://github.com/joblib/joblib/pull/1254 + Release 1.1.0 -------------- diff --git a/joblib/numpy_pickle.py b/joblib/numpy_pickle.py index 881d1f0..fa450fb 100644 --- a/joblib/numpy_pickle.py +++ b/joblib/numpy_pickle.py @@ -7,6 +7,7 @@ import pickle import os import warnings +import io from pathlib import Path from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR @@ -39,6 +40,11 @@ register_compressor('lz4', LZ4CompressorWrapper()) ############################################################################### # Utility objects for persistence. +# For convenience, 16 bytes are used to be sure to cover all the possible +# dtypes' alignments. For reference, see: +# https://numpy.org/devdocs/dev/alignment.html +NUMPY_ARRAY_ALIGNMENT_BYTES = 16 + class NumpyArrayWrapper(object): """An object to be persisted instead of numpy arrays. @@ -70,13 +76,23 @@ class NumpyArrayWrapper(object): Default: False. """ - def __init__(self, subclass, shape, order, dtype, allow_mmap=False): + def __init__(self, subclass, shape, order, dtype, allow_mmap=False, + numpy_array_alignment_bytes=NUMPY_ARRAY_ALIGNMENT_BYTES): """Constructor. Store the useful information for later.""" self.subclass = subclass self.shape = shape self.order = order self.dtype = dtype self.allow_mmap = allow_mmap + # We make numpy_array_alignment_bytes an instance attribute to allow us + # to change our mind about the default alignment and still load the old + # pickles (with the previous alignment) correctly + self.numpy_array_alignment_bytes = numpy_array_alignment_bytes + + def safe_get_numpy_array_alignment_bytes(self): + # NumpyArrayWrapper instances loaded from joblib <= 1.1 pickles don't + # have an numpy_array_alignment_bytes attribute + return getattr(self, 'numpy_array_alignment_bytes', None) def write_array(self, array, pickler): """Write array bytes to pickler file handle. @@ -92,6 +108,23 @@ class NumpyArrayWrapper(object): # pickle protocol. pickle.dump(array, pickler.file_handle, protocol=2) else: + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + if numpy_array_alignment_bytes is not None: + current_pos = pickler.file_handle.tell() + pos_after_padding_byte = current_pos + 1 + padding_length = numpy_array_alignment_bytes - ( + pos_after_padding_byte % numpy_array_alignment_bytes) + # A single byte is written that contains the padding length in + # bytes + padding_length_byte = int.to_bytes( + padding_length, length=1, byteorder='little') + pickler.file_handle.write(padding_length_byte) + + if padding_length != 0: + padding = b'\xff' * padding_length + pickler.file_handle.write(padding) + for chunk in pickler.np.nditer(array, flags=['external_loop', 'buffered', @@ -118,6 +151,15 @@ class NumpyArrayWrapper(object): # The array contained Python objects. We need to unpickle the data. array = pickle.load(unpickler.file_handle) else: + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + if numpy_array_alignment_bytes is not None: + padding_byte = unpickler.file_handle.read(1) + padding_length = int.from_bytes( + padding_byte, byteorder='little') + if padding_length != 0: + unpickler.file_handle.read(padding_length) + # This is not a real file. We have to read it the # memory-intensive way. # crc32 module fails on reads greater than 2 ** 32 bytes, @@ -150,7 +192,17 @@ class NumpyArrayWrapper(object): def read_mmap(self, unpickler): """Read an array using numpy memmap.""" - offset = unpickler.file_handle.tell() + current_pos = unpickler.file_handle.tell() + offset = current_pos + numpy_array_alignment_bytes = \ + self.safe_get_numpy_array_alignment_bytes() + + if numpy_array_alignment_bytes is not None: + padding_byte = unpickler.file_handle.read(1) + padding_length = int.from_bytes(padding_byte, byteorder='little') + # + 1 is for the padding byte + offset += padding_length + 1 + if unpickler.mmap_mode == 'w+': unpickler.mmap_mode = 'r+' @@ -163,6 +215,20 @@ class NumpyArrayWrapper(object): # update the offset so that it corresponds to the end of the read array unpickler.file_handle.seek(offset + marray.nbytes) + if (numpy_array_alignment_bytes is None and + current_pos % NUMPY_ARRAY_ALIGNMENT_BYTES != 0): + message = ( + f'The memmapped array {marray} loaded from the file ' + f'{unpickler.file_handle.name} is not not bytes aligned. ' + 'This may cause segmentation faults if this memmapped array ' + 'is used in some libraries like BLAS or PyTorch. ' + 'To get rid of this warning, regenerate your pickle file ' + 'with joblib >= 1.2.0. ' + 'See https://github.com/joblib/joblib/issues/563 ' + 'for more details' + ) + warnings.warn(message) + return marray def read(self, unpickler): @@ -239,9 +305,17 @@ class NumpyPickler(Pickler): order = 'F' if (array.flags.f_contiguous and not array.flags.c_contiguous) else 'C' allow_mmap = not self.buffered and not array.dtype.hasobject + + kwargs = {} + try: + self.file_handle.tell() + except io.UnsupportedOperation: + kwargs = {'numpy_array_alignment_bytes': None} + wrapper = NumpyArrayWrapper(type(array), array.shape, order, array.dtype, - allow_mmap=allow_mmap) + allow_mmap=allow_mmap, + **kwargs) return wrapper
joblib/joblib
3d805061e7f1b32df7c1cd5b40d272b34d50e487
diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py index 8019ca5..cce16e3 100644 --- a/joblib/test/test_numpy_pickle.py +++ b/joblib/test/test_numpy_pickle.py @@ -370,7 +370,7 @@ def test_compressed_pickle_dump_and_load(tmpdir): assert result == expected -def _check_pickle(filename, expected_list): +def _check_pickle(filename, expected_list, mmap_mode=None): """Helper function to test joblib pickle content. Note: currently only pickles containing an iterable are supported @@ -390,17 +390,36 @@ def _check_pickle(filename, expected_list): warnings.filterwarnings( 'ignore', module='numpy', message='The compiler package is deprecated') - result_list = numpy_pickle.load(filename) + result_list = numpy_pickle.load(filename, mmap_mode=mmap_mode) filename_base = os.path.basename(filename) - expected_nb_warnings = 1 if ("_0.9" in filename_base or - "_0.8.4" in filename_base) else 0 + expected_nb_deprecation_warnings = 1 if ( + "_0.9" in filename_base or "_0.8.4" in filename_base) else 0 + + expected_nb_user_warnings = 3 if ( + re.search("_0.1.+.pkl$", filename_base) and + mmap_mode is not None) else 0 + expected_nb_warnings = \ + expected_nb_deprecation_warnings + expected_nb_user_warnings assert len(warninfo) == expected_nb_warnings - for w in warninfo: - assert w.category == DeprecationWarning + + deprecation_warnings = [ + w for w in warninfo if issubclass( + w.category, DeprecationWarning)] + user_warnings = [ + w for w in warninfo if issubclass( + w.category, UserWarning)] + for w in deprecation_warnings: assert (str(w.message) == "The file '{0}' has been generated with a joblib " "version less than 0.10. Please regenerate this " "pickle file.".format(filename)) + + for w in user_warnings: + escaped_filename = re.escape(filename) + assert re.search( + f"memmapped.+{escaped_filename}.+segmentation fault", + str(w.message)) + for result, expected in zip(result_list, expected_list): if isinstance(expected, np.ndarray): expected = _ensure_native_byte_order(expected) @@ -467,6 +486,27 @@ def test_joblib_pickle_across_python_versions(): _check_pickle(fname, expected_list) +@with_numpy +def test_joblib_pickle_across_python_versions_with_mmap(): + expected_list = [np.arange(5, dtype=np.dtype('<i8')), + np.arange(5, dtype=np.dtype('<f8')), + np.array([1, 'abc', {'a': 1, 'b': 2}], dtype='O'), + np.arange(256, dtype=np.uint8).tobytes(), + # np.matrix is a subclass of np.ndarray, here we want + # to verify this type of object is correctly unpickled + # among versions. + np.matrix([0, 1, 2], dtype=np.dtype('<i8')), + u"C'est l'\xe9t\xe9 !"] + + test_data_dir = os.path.dirname(os.path.abspath(data.__file__)) + + pickle_filenames = [ + os.path.join(test_data_dir, fn) + for fn in os.listdir(test_data_dir) if fn.endswith('.pkl')] + for fname in pickle_filenames: + _check_pickle(fname, expected_list, mmap_mode='r') + + @with_numpy def test_numpy_array_byte_order_mismatch_detection(): # List of numpy arrays with big endian byteorder. @@ -916,6 +956,17 @@ def test_pickle_in_socket(): np.testing.assert_array_equal(array_reloaded, test_array) + # Check that a byte-aligned numpy array written in a file can be send over + # a socket and then read on the other side + bytes_to_send = io.BytesIO() + numpy_pickle.dump(test_array, bytes_to_send) + server.send(bytes_to_send.getvalue()) + + with client.makefile("rb") as cf: + array_reloaded = numpy_pickle.load(cf) + + np.testing.assert_array_equal(array_reloaded, test_array) + @with_numpy def test_load_memmap_with_big_offset(tmpdir): @@ -1056,3 +1107,65 @@ def test_lz4_compression_without_lz4(tmpdir): with raises(ValueError) as excinfo: numpy_pickle.dump(data, fname + '.lz4') excinfo.match(msg) + + +protocols = [pickle.DEFAULT_PROTOCOL] +if pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL: + protocols.append(pickle.HIGHEST_PROTOCOL) + + +@with_numpy +@parametrize('protocol', protocols) +def test_memmap_alignment_padding(tmpdir, protocol): + # Test that memmaped arrays returned by numpy.load are correctly aligned + fname = tmpdir.join('test.mmap').strpath + + a = np.random.randn(2) + numpy_pickle.dump(a, fname, protocol=protocol) + memmap = numpy_pickle.load(fname, mmap_mode='r') + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(a, memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned + + array_list = [ + np.random.randn(2), np.random.randn(2), + np.random.randn(2), np.random.randn(2) + ] + + # On Windows OSError 22 if reusing the same path for memmap ... + fname = tmpdir.join('test1.mmap').strpath + numpy_pickle.dump(array_list, fname, protocol=protocol) + l_reloaded = numpy_pickle.load(fname, mmap_mode='r') + + for idx, memmap in enumerate(l_reloaded): + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(array_list[idx], memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned + + array_dict = { + 'a0': np.arange(2, dtype=np.uint8), + 'a1': np.arange(3, dtype=np.uint8), + 'a2': np.arange(5, dtype=np.uint8), + 'a3': np.arange(7, dtype=np.uint8), + 'a4': np.arange(11, dtype=np.uint8), + 'a5': np.arange(13, dtype=np.uint8), + 'a6': np.arange(17, dtype=np.uint8), + 'a7': np.arange(19, dtype=np.uint8), + 'a8': np.arange(23, dtype=np.uint8), + } + + # On Windows OSError 22 if reusing the same path for memmap ... + fname = tmpdir.join('test2.mmap').strpath + numpy_pickle.dump(array_dict, fname, protocol=protocol) + d_reloaded = numpy_pickle.load(fname, mmap_mode='r') + + for key, memmap in d_reloaded.items(): + assert isinstance(memmap, np.memmap) + np.testing.assert_array_equal(array_dict[key], memmap) + assert ( + memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0) + assert memmap.flags.aligned
Alignment issue when passing arrays though mmap Arrays that are transfered to subprocesses though mmap appear not always to be aligned: ```python import joblib import numpy as np def func(x): print(type(x)) print(x.flags) print(x.ctypes.data / 8) if __name__ == '__main__': # Make the array larger than 1Mbyte so that mmap is used n = 1024 ** 2 // 8 + 1 x = np.random.randn(n) jobs = joblib.Parallel(2) print(x.nbytes) res = jobs([joblib.delayed(func)(x), joblib.delayed(func)(x)]) ``` This returns ``` <class 'numpy.core.memmap.memmap'> 1048584 C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False 570054683.375 ``` Note the last line, the address of the first element of the array is indeed not aligned. I'm using version 0.11, on OSx sierra. This came up in https://github.com/pymc-devs/pymc3/issues/2640, and seems to happen on several OSs.
0.0
3d805061e7f1b32df7c1cd5b40d272b34d50e487
[ "joblib/test/test_numpy_pickle.py::test_memmap_alignment_padding[5]", "joblib/test/test_numpy_pickle.py::test_memmap_alignment_padding[4]" ]
[ "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_in_memory_mmap", "joblib/test/test_numpy_pickle.py::test_numpy_subclass", "joblib/test/test_numpy_pickle.py::test_standard_types[member15-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[type-0]", "joblib/test/test_numpy_pickle.py::test_pathlib", "joblib/test/test_numpy_pickle.py::test_compress_level_error[-1]", "joblib/test/test_numpy_pickle.py::test_compress_mmap_mode_warning", "joblib/test/test_numpy_pickle.py::test_compress_string_argument[gzip]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_0-1]", "joblib/test/test_numpy_pickle.py::test_register_compressor", "joblib/test/test_numpy_pickle.py::test_compress_level_error[wrong_compress2]", "joblib/test/test_numpy_pickle.py::test_compress_level_error[10]", "joblib/test/test_numpy_pickle.py::test_non_contiguous_array_pickling", "joblib/test/test_numpy_pickle.py::test_compress_string_argument[zlib]", "joblib/test/test_numpy_pickle.py::test_standard_types[None-0]", "joblib/test/test_numpy_pickle.py::test_in_memory_persistence", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[x]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[bz2-6]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.bz2-bz2]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.z-zlib]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[w]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[bz2-3]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_1-1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[gzip-6]", "joblib/test/test_numpy_pickle.py::test_standard_types[member15-1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[lzma-1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[3-a", "joblib/test/test_numpy_pickle.py::test_standard_types[len-0]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple1-Non", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[-1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[zlib-6]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[bad_file1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[1-a", "joblib/test/test_numpy_pickle.py::test_standard_types[_newclass-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[type-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_1-0]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[1]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument[compress_tuple0]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_0-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member8-1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[2]", "joblib/test/test_numpy_pickle.py::test_standard_types[len-1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[gzip-3]", "joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[lzma-6]", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_mmap", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple0-Compress", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_fileobj", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.xz-xz]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple2-Non", "joblib/test/test_numpy_pickle.py::test_pickle_highest_protocol", "joblib/test/test_numpy_pickle.py::test_standard_types[member7-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[True-0]", "joblib/test/test_numpy_pickle.py::test_masked_array_persistence", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_compressed_mmap", "joblib/test/test_numpy_pickle.py::test_standard_types[_function-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member14-0]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence[False]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[xz-1]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence[3]", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[bad_value5]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[gzip-1]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.lzma-lzma]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[9-a", "joblib/test/test_numpy_pickle.py::test_standard_types[member9-1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[bz2-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member8-0]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[a]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[zlib-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member14-1]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument[compress_tuple1]", "joblib/test/test_numpy_pickle.py::test_register_compressor_already_registered", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[bad_value4]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[zlib-3]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[xz-3]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[r]", "joblib/test/test_numpy_pickle.py::test_standard_types[_newclass-0]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[-not-compressed]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[bad_file2]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[10]", "joblib/test/test_numpy_pickle.py::test_standard_types[(1+0j)-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[(1+0j)-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[_function-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[1.0-1]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence_bufferred_array_compression", "joblib/test/test_numpy_pickle.py::test_pickle_in_socket", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[invalid_name2]", "joblib/test/test_numpy_pickle.py::test_standard_types[member7-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member9-0]", "joblib/test/test_numpy_pickle.py::test_load_memmap_with_big_offset", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.pkl-not-compressed]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence[0]", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files[.gz-_gzip_file_decompress]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[xz-6]", "joblib/test/test_numpy_pickle.py::test_standard_types[_class-1]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.gz-gzip]", "joblib/test/test_numpy_pickle.py::test_standard_types[1.0-0]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence[True]", "joblib/test/test_numpy_pickle.py::test_numpy_persistence[zlib]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[1]", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats[lzma-3]", "joblib/test/test_numpy_pickle.py::test_memmap_persistence", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[15]", "joblib/test/test_numpy_pickle.py::test_value_error", "joblib/test/test_numpy_pickle.py::test_standard_types[None-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[True-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[_class-0]", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files[.z-_zlib_file_decompress]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[a]", "joblib/test/test_numpy_pickle.py::test_lz4_compression_without_lz4", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[invalid_name1]", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[1]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-03 08:26:49+00:00
bsd-3-clause
3,272
joblib__joblib-1389
diff --git a/CHANGES.rst b/CHANGES.rst index 6f2dd8a..3f1bf8e 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -27,6 +27,11 @@ In development errors, a new warning has been introduced: `joblib.memory.CacheWarning`. https://github.com/joblib/joblib/pull/1359 +- Avoid (module, name) collisions when caching nested functions. This fix + changes the module name of nested functions, invalidating caches from + previous versions of Joblib. + https://github.com/joblib/joblib/pull/1374 + Release 1.2.0 ------------- diff --git a/azure-pipelines.yml b/azure-pipelines.yml index a9cdaa1..8f1acb0 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -60,10 +60,10 @@ jobs: imageName: 'ubuntu-latest' PYTHON_VERSION: "3.7" EXTRA_CONDA_PACKAGES: "numpy=1.15 distributed=2.13" - linux_py310_cython: + linux_py311_cython: imageName: 'ubuntu-latest' - PYTHON_VERSION: "3.10" - EXTRA_CONDA_PACKAGES: "numpy=1.23" + PYTHON_VERSION: "3.11" + EXTRA_CONDA_PACKAGES: "numpy=1.24.1" CYTHON: "true" linux_py37_no_multiprocessing_no_lzma: imageName: 'ubuntu-latest' diff --git a/doc/memory.rst b/doc/memory.rst index 7f829f7..901ccd0 100644 --- a/doc/memory.rst +++ b/doc/memory.rst @@ -152,7 +152,7 @@ arrays:: square(array([[0., 0., 1.], [1., 1., 1.], [4., 2., 1.]])) - ___________________________________________________________square - 0.0s, 0.0min + ___________________________________________________________square - ...min memmap([[ 0., 0., 1.], [ 1., 1., 1.], [16., 4., 1.]]) diff --git a/joblib/func_inspect.py b/joblib/func_inspect.py index d334a2b..58d9751 100644 --- a/joblib/func_inspect.py +++ b/joblib/func_inspect.py @@ -166,6 +166,10 @@ def get_func_name(func, resolv_alias=True, win_characters=True): if hasattr(func, 'func_globals') and name in func.func_globals: if not func.func_globals[name] is func: name = '%s-alias' % name + if hasattr(func, '__qualname__') and func.__qualname__ != name: + # Extend the module name in case of nested functions to avoid + # (module, name) collisions + module.extend(func.__qualname__.split(".")[:-1]) if inspect.ismethod(func): # We need to add the name of the class if hasattr(func, 'im_class'): diff --git a/pyproject.toml b/pyproject.toml index fd51f1d..c6723bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,7 @@ classifiers = [ "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "Topic :: Scientific/Engineering", "Topic :: Utilities", "Topic :: Software Development :: Libraries",
joblib/joblib
061d4ad3b5bd3bab597a2b22c0e67376fb1e25c8
diff --git a/conftest.py b/conftest.py index 5a7919f..53413de 100644 --- a/conftest.py +++ b/conftest.py @@ -1,9 +1,11 @@ import os +import logging +import faulthandler + import pytest from _pytest.doctest import DoctestItem -import logging from joblib.parallel import mp from joblib.backports import LooseVersion try: @@ -53,6 +55,11 @@ def pytest_configure(config): log.handlers[0].setFormatter(logging.Formatter( '[%(levelname)s:%(processName)s:%(threadName)s] %(message)s')) + # Some CI runs failed with hanging processes that were not terminated + # with the timeout. To make sure we always get a proper trace, set a large + # enough dump_traceback_later to kill the process with a report. + faulthandler.dump_traceback_later(30 * 60, exit=True) + DEFAULT_BACKEND = os.environ.get( "JOBLIB_TESTS_DEFAULT_PARALLEL_BACKEND", None ) @@ -66,12 +73,14 @@ def pytest_configure(config): def pytest_unconfigure(config): + # Setup a global traceback printer callback to debug deadlocks that # would happen once pytest has completed: for instance in atexit # finalizers. At this point the stdout/stderr capture of pytest - # should be disabled. + # should be disabled. Note that we cancel the global dump_traceback_later + # to waiting for too long. + faulthandler.cancel_dump_traceback_later() # Note that we also use a shorter timeout for the per-test callback # configured via the pytest-timeout extension. - import faulthandler faulthandler.dump_traceback_later(60, exit=True) diff --git a/joblib/test/test_func_inspect.py b/joblib/test/test_func_inspect.py index b3b7b7b..a2a010e 100644 --- a/joblib/test/test_func_inspect.py +++ b/joblib/test/test_func_inspect.py @@ -146,6 +146,26 @@ def test_func_name_on_inner_func(cached_func): assert get_func_name(cached_func)[1] == 'cached_func_inner' +def test_func_name_collision_on_inner_func(): + # Check that two functions defining and caching an inner function + # with the same do not cause (module, name) collision + def f(): + def inner_func(): + return # pragma: no cover + return get_func_name(inner_func) + + def g(): + def inner_func(): + return # pragma: no cover + return get_func_name(inner_func) + + module, name = f() + other_module, other_name = g() + + assert name == other_name + assert module != other_module + + def test_func_inspect_errors(): # Check that func_inspect is robust and will work on weird objects assert get_func_name('a'.lower)[-1] == 'lower' diff --git a/joblib/test/test_memmapping.py b/joblib/test/test_memmapping.py index 4d298d0..af90a96 100644 --- a/joblib/test/test_memmapping.py +++ b/joblib/test/test_memmapping.py @@ -798,9 +798,9 @@ def test_child_raises_parent_exits_cleanly(backend): def get_temp_folder(parallel_obj, backend): if "{b}" == "loky": - return Path(p._backend._workers._temp_folder) + return Path(parallel_obj._backend._workers._temp_folder) else: - return Path(p._backend._pool._temp_folder) + return Path(parallel_obj._backend._pool._temp_folder) if __name__ == "__main__": diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py index 5c4bb09..9fee585 100644 --- a/joblib/test/test_numpy_pickle.py +++ b/joblib/test/test_numpy_pickle.py @@ -280,8 +280,9 @@ def test_compress_mmap_mode_warning(tmpdir): numpy_pickle.dump(a, this_filename, compress=1) with warns(UserWarning) as warninfo: numpy_pickle.load(this_filename, mmap_mode='r+') + debug_msg = "\n".join([str(w) for w in warninfo]) warninfo = [w.message for w in warninfo] - assert len(warninfo) == 1 + assert len(warninfo) == 1, debug_msg assert ( str(warninfo[0]) == 'mmap_mode "r+" is not compatible with compressed ' diff --git a/joblib/test/test_testing.py b/joblib/test/test_testing.py index 39ac880..cc94463 100644 --- a/joblib/test/test_testing.py +++ b/joblib/test/test_testing.py @@ -58,7 +58,9 @@ def test_check_subprocess_call_timeout(): 'sys.stdout.flush()', 'sys.stderr.write("before sleep on stderr")', 'sys.stderr.flush()', - 'time.sleep(1.1)', + # We need to sleep for at least 2 * timeout seconds in case the SIGKILL + # is triggered. + 'time.sleep(2.1)', 'print("process should have be killed before")', 'sys.stdout.flush()']) diff --git a/joblib/testing.py b/joblib/testing.py index f8939f0..caab7d2 100644 --- a/joblib/testing.py +++ b/joblib/testing.py @@ -40,20 +40,39 @@ def check_subprocess_call(cmd, timeout=5, stdout_regex=None, stderr_regex=None): """Runs a command in a subprocess with timeout in seconds. + A SIGTERM is sent after `timeout` and if it does not terminate, a + SIGKILL is sent after `2 * timeout`. + Also checks returncode is zero, stdout if stdout_regex is set, and stderr if stderr_regex is set. """ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - def kill_process(): - warnings.warn("Timeout running {}".format(cmd)) + def terminate_process(): # pragma: no cover + """ + Attempt to terminate a leftover process spawned during test execution: + ideally this should not be needed but can help avoid clogging the CI + workers in case of deadlocks. + """ + warnings.warn(f"Timeout running {cmd}") + proc.terminate() + + def kill_process(): # pragma: no cover + """ + Kill a leftover process spawned during test execution: ideally this + should not be needed but can help avoid clogging the CI workers in + case of deadlocks. + """ + warnings.warn(f"Timeout running {cmd}") proc.kill() try: if timeout is not None: - timer = threading.Timer(timeout, kill_process) - timer.start() + terminate_timer = threading.Timer(timeout, terminate_process) + terminate_timer.start() + kill_timer = threading.Timer(2 * timeout, kill_process) + kill_timer.start() stdout, stderr = proc.communicate() stdout, stderr = stdout.decode(), stderr.decode() if proc.returncode != 0: @@ -76,4 +95,5 @@ def check_subprocess_call(cmd, timeout=5, stdout_regex=None, finally: if timeout is not None: - timer.cancel() + terminate_timer.cancel() + kill_timer.cancel()
support python3.11 Release the version supporting python3.11 as soon as possible.
0.0
061d4ad3b5bd3bab597a2b22c0e67376fb1e25c8
[ "joblib/test/test_func_inspect.py::test_func_name_collision_on_inner_func" ]
[ "joblib/test/test_func_inspect.py::test_filter_args[f-args0-filtered_args0]", "joblib/test/test_func_inspect.py::test_filter_args[f-args1-filtered_args1]", "joblib/test/test_func_inspect.py::test_filter_args[f-args2-filtered_args2]", "joblib/test/test_func_inspect.py::test_filter_args[f-args3-filtered_args3]", "joblib/test/test_func_inspect.py::test_filter_args[f-args4-filtered_args4]", "joblib/test/test_func_inspect.py::test_filter_args[f-args5-filtered_args5]", "joblib/test/test_func_inspect.py::test_filter_args[f-args6-filtered_args6]", "joblib/test/test_func_inspect.py::test_filter_args[g-args7-filtered_args7]", "joblib/test/test_func_inspect.py::test_filter_args[i-args8-filtered_args8]", "joblib/test/test_func_inspect.py::test_filter_args_method", "joblib/test/test_func_inspect.py::test_filter_varargs[h-args0-filtered_args0]", "joblib/test/test_func_inspect.py::test_filter_varargs[h-args1-filtered_args1]", "joblib/test/test_func_inspect.py::test_filter_varargs[h-args2-filtered_args2]", "joblib/test/test_func_inspect.py::test_filter_varargs[h-args3-filtered_args3]", "joblib/test/test_func_inspect.py::test_filter_kwargs[k-args0-filtered_args0]", "joblib/test/test_func_inspect.py::test_filter_kwargs[k-args1-filtered_args1]", "joblib/test/test_func_inspect.py::test_filter_kwargs[m1-args2-filtered_args2]", "joblib/test/test_func_inspect.py::test_filter_kwargs[m2-args3-filtered_args3]", "joblib/test/test_func_inspect.py::test_filter_args_2", "joblib/test/test_func_inspect.py::test_func_name[f-f]", "joblib/test/test_func_inspect.py::test_func_name[g-g]", "joblib/test/test_func_inspect.py::test_func_name[cached_func-cached_func]", "joblib/test/test_func_inspect.py::test_func_name_on_inner_func", "joblib/test/test_func_inspect.py::test_func_inspect_errors", "joblib/test/test_func_inspect.py::test_filter_args_edge_cases", "joblib/test/test_func_inspect.py::test_bound_methods", "joblib/test/test_func_inspect.py::test_filter_args_error_msg[ValueError-ignore_lst", "joblib/test/test_func_inspect.py::test_filter_args_error_msg[ValueError-Ignore", "joblib/test/test_func_inspect.py::test_filter_args_error_msg[ValueError-Wrong", "joblib/test/test_func_inspect.py::test_filter_args_no_kwargs_mutation", "joblib/test/test_func_inspect.py::test_clean_win_chars", "joblib/test/test_func_inspect.py::test_format_signature[g-args0-kwargs0-g([0,", "joblib/test/test_func_inspect.py::test_format_signature[k-args1-kwargs1-k(1,", "joblib/test/test_func_inspect.py::test_format_signature_long_arguments", "joblib/test/test_func_inspect.py::test_special_source_encoding", "joblib/test/test_func_inspect.py::test_func_code_consistency", "joblib/test/test_memmapping.py::test_pool_get_temp_dir", "joblib/test/test_memmapping.py::test_pool_get_temp_dir_no_statvfs", "joblib/test/test_memmapping.py::test_weak_array_key_map_no_pickling", "joblib/test/test_numpy_pickle.py::test_standard_types[None-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[None-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[type-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[type-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[True-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[True-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_0-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_0-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[1.0-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[1.0-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[(1+0j)-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[(1+0j)-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_1-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[1_1-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member7-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member7-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member8-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member8-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member9-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member9-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[len-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[len-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[_function-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[_function-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[_class-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[_class-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[_newclass-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[_newclass-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member14-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member14-1]", "joblib/test/test_numpy_pickle.py::test_standard_types[member15-0]", "joblib/test/test_numpy_pickle.py::test_standard_types[member15-1]", "joblib/test/test_numpy_pickle.py::test_value_error", "joblib/test/test_numpy_pickle.py::test_compress_level_error[-1]", "joblib/test/test_numpy_pickle.py::test_compress_level_error[10]", "joblib/test/test_numpy_pickle.py::test_compress_level_error[wrong_compress2]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument[compress_tuple0]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument[compress_tuple1]", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple0-Compress", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple1-Non", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument_exception[compress_tuple2-Non", "joblib/test/test_numpy_pickle.py::test_compress_string_argument[zlib]", "joblib/test/test_numpy_pickle.py::test_compress_string_argument[gzip]", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files[.z-_zlib_file_decompress]", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files[.gz-_gzip_file_decompress]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.z-zlib]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.gz-gzip]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.bz2-bz2]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.lzma-lzma]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.xz-xz]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[.pkl-not-compressed]", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension[-not-compressed]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[1-a", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[3-a", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile[9-a", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[-1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[10]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[15]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[a]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[bad_value4]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_bad_compression_levels[bad_value5]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[a]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[x]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[r]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[w]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_modes[2]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[bad_file1]", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile_invalid_filename_type[bad_file2]", "joblib/test/test_numpy_pickle.py::test_pathlib", "joblib/test/test_numpy_pickle.py::test_register_compressor", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[1]", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[invalid_name1]", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_name[invalid_name2]", "joblib/test/test_numpy_pickle.py::test_register_compressor_invalid_fileobj", "joblib/test/test_numpy_pickle.py::test_register_compressor_already_registered", "joblib/test/test_numpy_pickle.py::test_lz4_compression_without_lz4", "joblib/test/test_testing.py::test_check_subprocess_call", "joblib/test/test_testing.py::test_check_subprocess_call_non_matching_regex", "joblib/test/test_testing.py::test_check_subprocess_call_wrong_command", "joblib/test/test_testing.py::test_check_subprocess_call_non_zero_return_code", "joblib/test/test_testing.py::test_check_subprocess_call_timeout" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-16 10:34:31+00:00
bsd-3-clause
3,273
joblib__joblib-444
diff --git a/joblib/format_stack.py b/joblib/format_stack.py index 3f3d106..4be93c1 100644 --- a/joblib/format_stack.py +++ b/joblib/format_stack.py @@ -135,15 +135,10 @@ def _fixed_getframes(etb, context=1, tb_offset=0): aux = traceback.extract_tb(etb) assert len(records) == len(aux) for i, (file, lnum, _, _) in enumerate(aux): - maybeStart = lnum - 1 - context // 2 - start = max(maybeStart, 0) + maybe_start = lnum - 1 - context // 2 + start = max(maybe_start, 0) end = start + context lines = linecache.getlines(file)[start:end] - # pad with empty lines if necessary - if maybeStart < 0: - lines = (['\n'] * -maybeStart) + lines - if len(lines) < context: - lines += ['\n'] * (context - len(lines)) buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start @@ -400,15 +395,10 @@ def format_outer_frames(context=5, stack_start=None, stack_end=None, if (os.path.basename(filename) in ('iplib.py', 'py3compat.py') and func_name in ('execfile', 'safe_execfile', 'runcode')): break - maybeStart = line_no - 1 - context // 2 - start = max(maybeStart, 0) + maybe_start = line_no - 1 - context // 2 + start = max(maybe_start, 0) end = start + context lines = linecache.getlines(filename)[start:end] - # pad with empty lines if necessary - if maybeStart < 0: - lines = (['\n'] * -maybeStart) + lines - if len(lines) < context: - lines += ['\n'] * (context - len(lines)) buf = list(records[i]) buf[LNUM_POS] = line_no buf[INDEX_POS] = line_no - 1 - start
joblib/joblib
aab21b654e853616b31c6e50255b2dcf47af5818
diff --git a/joblib/test/test_format_stack.py b/joblib/test/test_format_stack.py index 32fc8f5..baa8076 100644 --- a/joblib/test/test_format_stack.py +++ b/joblib/test/test_format_stack.py @@ -6,6 +6,8 @@ Unit tests for the stack formatting utilities # Copyright (c) 2010 Gael Varoquaux # License: BSD Style, 3 clauses. +import imp +import os import re import sys @@ -75,6 +77,38 @@ def test_format_records(): re.MULTILINE) +def test_format_records_file_with_less_lines_than_context(tmpdir): + # See https://github.com/joblib/joblib/issues/420 + filename = os.path.join(tmpdir.strpath, 'small_file.py') + code_lines = ['def func():', ' 1/0'] + code = '\n'.join(code_lines) + open(filename, 'w').write(code) + + small_file = imp.load_source('small_file', filename) + try: + small_file.func() + except ZeroDivisionError: + etb = sys.exc_info()[2] + + records = _fixed_getframes(etb, context=10) + # Check that if context is bigger than the number of lines in + # the file you do not get padding + frame, tb_filename, line, func_name, context, _ = records[-1] + assert [l.rstrip() for l in context] == code_lines + + formatted_records = format_records(records) + # 2 lines for header in the traceback: lines of ...... + + # filename with function + len_header = 2 + nb_lines_formatted_records = len(formatted_records[1].splitlines()) + assert (nb_lines_formatted_records == len_header + len(code_lines)) + # Check exception stack + arrow_regex = r'^-+>\s+\d+\s+' + assert re.search(arrow_regex + r'1/0', + formatted_records[1], + re.MULTILINE) + + @with_numpy def test_format_exc_with_compiled_code(): # Trying to tokenize compiled C code raise SyntaxError.
Wrong line pointed to in subprocess traceback test.py ```py from test_module import exception_on_even from joblib import Parallel, delayed if __name__ == '__main__': Parallel(n_jobs=2)(delayed(exception_on_even)(x) for x in [1, 2, 3]) ``` test_module.py ```py def exception_on_even(x): if x % 2 == 0: 1/0 else: return x ``` Excerpt from the Traceback when running `ipython test.py`: ``` --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- ZeroDivisionError Wed Nov 2 09:52:46 2016 PID: 7267 Python 3.5.2: /home/lesteve/miniconda3/bin/python ........................................................................... /home/lesteve/dev/joblib/joblib/parallel.py in __call__(self=<joblib.parallel.BatchedCalls object>) 126 def __init__(self, iterator_slice): 127 self.items = list(iterator_slice) 128 self._size = len(self.items) 129 130 def __call__(self): --> 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] self.items = [(<function exception_on_even>, (2,), {})] 132 133 def __len__(self): 134 return self._size 135 ........................................................................... /home/lesteve/dev/joblib/joblib/parallel.py in <listcomp>(.0=<list_iterator object>) 126 def __init__(self, iterator_slice): 127 self.items = list(iterator_slice) 128 self._size = len(self.items) 129 130 def __call__(self): --> 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] func = <function exception_on_even> args = (2,) kwargs = {} 132 133 def __len__(self): 134 return self._size 135 ........................................................................... /tmp/test_module.py in exception_on_even(x=2) 1 2 ----> 3 4 def exception_on_even(x): 5 if x % 2 == 0: 6 1/0 7 else: 8 return x 9 10 ZeroDivisionError: division by zero ``` The arrow in the last frame points to line 3 whereas it should point to line 6.
0.0
aab21b654e853616b31c6e50255b2dcf47af5818
[ "joblib/test/test_format_stack.py::test_format_records_file_with_less_lines_than_context" ]
[ "joblib/test/test_format_stack.py::test_safe_repr", "joblib/test/test_format_stack.py::test_format_records" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-12-07 09:55:10+00:00
bsd-3-clause
3,274
joblib__loky-271
diff --git a/CHANGES.md b/CHANGES.md index 6e2c1dc..6b9ab23 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -11,6 +11,9 @@ - Fix support for Python 3.9 and test against python-nightly from now on (#250). +- Add a parameter to ``cpu_count``, ``only_physical_cores``, to return the + number of physical cores instead of the number of logical cores (#271). + ### 2.7.0 - 2020-04-30 - Increase the residual memory increase threshold (100MB -> 300MB) used by diff --git a/loky/backend/context.py b/loky/backend/context.py index dfeb4ed..76f6520 100644 --- a/loky/backend/context.py +++ b/loky/backend/context.py @@ -14,6 +14,8 @@ from __future__ import division import os import sys +import subprocess +import traceback import warnings import multiprocessing as mp @@ -23,6 +25,10 @@ from .process import LokyProcess, LokyInitMainProcess START_METHODS = ['loky', 'loky_init_main'] _DEFAULT_START_METHOD = None +# Cache for the number of physical cores to avoid repeating subprocess calls. +# It should not change during the lifetime of the program. +physical_cores_cache = None + if sys.version_info[:2] >= (3, 4): from multiprocessing import get_context as mp_get_context from multiprocessing.context import assert_spawning, set_spawning_popen @@ -101,7 +107,7 @@ def get_start_method(): return _DEFAULT_START_METHOD -def cpu_count(): +def cpu_count(only_physical_cores=False): """Return the number of CPUs the current process can use. The returned number of CPUs accounts for: @@ -113,15 +119,57 @@ def cpu_count(): set by docker and similar container orchestration systems); * the value of the LOKY_MAX_CPU_COUNT environment variable if defined. and is given as the minimum of these constraints. + + If ``only_physical_cores`` is True, return the number of physical cores + instead of the number of logical cores (hyperthreading / SMT). Note that + this option is not enforced if the number of usable cores is controlled in + any other way such as: process affinity, restricting CFS scheduler policy + or the LOKY_MAX_CPU_COUNT environment variable. If the number of physical + cores is not found, return the number of logical cores. + It is also always larger or equal to 1. """ - import math - + # TODO: use os.cpu_count when dropping python 2 support try: cpu_count_mp = mp.cpu_count() except NotImplementedError: cpu_count_mp = 1 + cpu_count_user = _cpu_count_user(cpu_count_mp) + aggregate_cpu_count = min(cpu_count_mp, cpu_count_user) + + if only_physical_cores: + cpu_count_physical, exception = _count_physical_cores() + if cpu_count_user < cpu_count_mp: + # Respect user setting + cpu_count = max(cpu_count_user, 1) + elif cpu_count_physical == "not found": + # Fallback to default behavior + if exception is not None: + # warns only the first time + warnings.warn( + "Could not find the number of physical cores for the " + "following reason:\n" + str(exception) + "\n" + "Returning the number of logical cores instead. You can " + "silence this warning by setting LOKY_MAX_CPU_COUNT to " + "the number of cores you want to use.") + if sys.version_info >= (3, 5): + # TODO remove the version check when dropping py2 support + traceback.print_tb(exception.__traceback__) + + cpu_count = max(aggregate_cpu_count, 1) + else: + return cpu_count_physical + else: + cpu_count = max(aggregate_cpu_count, 1) + + return cpu_count + + +def _cpu_count_user(cpu_count_mp): + """Number of user defined available CPUs""" + import math + # Number of available CPUs given affinity settings cpu_count_affinity = cpu_count_mp if hasattr(os, 'sched_getaffinity'): @@ -146,11 +194,65 @@ def cpu_count(): # float in python2.7. (See issue #165) cpu_count_cfs = int(math.ceil(cfs_quota_us / cfs_period_us)) - # User defined soft-limit passed as an loky specific environment variable. + # User defined soft-limit passed as a loky specific environment variable. cpu_count_loky = int(os.environ.get('LOKY_MAX_CPU_COUNT', cpu_count_mp)) - aggregate_cpu_count = min(cpu_count_mp, cpu_count_affinity, cpu_count_cfs, - cpu_count_loky) - return max(aggregate_cpu_count, 1) + + return min(cpu_count_affinity, cpu_count_cfs, cpu_count_loky) + + +def _count_physical_cores(): + """Return a tuple (number of physical cores, exception) + + If the number of physical cores is found, exception is set to None. + If it has not been found, return ("not found", exception). + + The number of physical cores is cached to avoid repeating subprocess calls. + """ + exception = None + + # First check if the value is cached + global physical_cores_cache + if physical_cores_cache is not None: + return physical_cores_cache, exception + + # Not cached yet, find it + try: + if sys.platform == "linux": + cpu_info = subprocess.run( + "lscpu --parse=core".split(" "), capture_output=True) + cpu_info = cpu_info.stdout.decode("utf-8").splitlines() + cpu_info = {line for line in cpu_info if not line.startswith("#")} + cpu_count_physical = len(cpu_info) + elif sys.platform == "win32": + cpu_info = subprocess.run( + "wmic CPU Get NumberOfCores /Format:csv".split(" "), + capture_output=True) + cpu_info = cpu_info.stdout.decode('utf-8').splitlines() + cpu_info = [l.split(",")[1] for l in cpu_info + if (l and l != "Node,NumberOfCores")] + cpu_count_physical = sum(map(int, cpu_info)) + elif sys.platform == "darwin": + cpu_info = subprocess.run( + "sysctl -n hw.physicalcpu".split(" "), capture_output=True) + cpu_info = cpu_info.stdout.decode('utf-8') + cpu_count_physical = int(cpu_info) + else: + raise NotImplementedError( + "unsupported platform: {}".format(sys.platform)) + + # if cpu_count_physical < 1, we did not find a valid value + if cpu_count_physical < 1: + raise ValueError( + "found {} physical cores < 1".format(cpu_count_physical)) + + except Exception as e: + exception = e + cpu_count_physical = "not found" + + # Put the result in cache + physical_cores_cache = cpu_count_physical + + return cpu_count_physical, exception class LokyContext(BaseContext):
joblib/loky
7b675b470adcf8fa07cd830a78121349294cd4ae
diff --git a/tests/test_loky_module.py b/tests/test_loky_module.py index 382301a..076e6e4 100644 --- a/tests/test_loky_module.py +++ b/tests/test_loky_module.py @@ -1,12 +1,16 @@ +import multiprocessing as mp import os import sys import shutil +import tempfile from subprocess import check_output +import subprocess import pytest import loky from loky import cpu_count +from loky.backend.context import _cpu_count_user def test_version(): @@ -19,9 +23,18 @@ def test_cpu_count(): assert type(cpus) is int assert cpus >= 1 + cpus_physical = cpu_count(only_physical_cores=True) + assert type(cpus_physical) is int + assert 1 <= cpus_physical <= cpus + + # again to check that it's correctly cached + cpus_physical = cpu_count(only_physical_cores=True) + assert type(cpus_physical) is int + assert 1 <= cpus_physical <= cpus + cpu_count_cmd = ("from loky.backend.context import cpu_count;" - "print(cpu_count())") + "print(cpu_count({args}))") def test_cpu_count_affinity(): @@ -40,9 +53,14 @@ def test_cpu_count_affinity(): pytest.skip() res = check_output([taskset_bin, '-c', '0', - python_bin, '-c', cpu_count_cmd]) + python_bin, '-c', cpu_count_cmd.format(args='')]) + + res_physical = check_output([ + taskset_bin, '-c', '0', python_bin, '-c', + cpu_count_cmd.format(args='only_physical_cores=True')]) assert res.strip().decode('utf-8') == '1' + assert res_physical.strip().decode('utf-8') == '1' def test_cpu_count_cfs_limit(): @@ -64,6 +82,61 @@ def test_cpu_count_cfs_limit(): res = check_output([docker_bin, 'run', '--rm', '--cpus', '0.5', '-v', '%s:/loky' % loky_path, 'python:3.6', - 'python', '-c', cpu_count_cmd]) + 'python', '-c', cpu_count_cmd.format(args='')]) assert res.strip().decode('utf-8') == '1' + + +def test_only_physical_cores_error(): + # Check the warning issued by cpu_count(only_physical_cores=True) when + # unable to retrieve the number of physical cores. + if sys.platform != "linux": + pytest.skip() + + # if number of available cpus is already restricted, cpu_count will return + # that value and no warning is issued even if only_physical_cores == True. + # (tested in another test: test_only_physical_cores_with_user_limitation + cpu_count_mp = mp.cpu_count() + if _cpu_count_user(cpu_count_mp) < cpu_count_mp: + pytest.skip() + + start_dir = os.path.abspath('.') + + with tempfile.TemporaryDirectory() as tmp_dir: + # Write bad lscpu program + lscpu_path = tmp_dir + '/lscpu' + with open(lscpu_path, 'w') as f: + f.write("#!/bin/sh\n" + "exit(1)") + os.chmod(lscpu_path, 0o777) + + try: + old_path = os.environ['PATH'] + os.environ['PATH'] = tmp_dir + ":" + old_path + + # clear the cache otherwise the warning is not triggered + import loky.backend.context + loky.backend.context.physical_cores_cache = None + + with pytest.warns(UserWarning, match="Could not find the number of" + " physical cores"): + cpu_count(only_physical_cores=True) + + # Should not warn the second time + with pytest.warns(None) as record: + cpu_count(only_physical_cores=True) + assert not record + + finally: + os.environ['PATH'] = old_path + + +def test_only_physical_cores_with_user_limitation(): + # Check that user limitation for the available number of cores is + # respected even if only_physical_cores == True + cpu_count_mp = mp.cpu_count() + cpu_count_user = _cpu_count_user(cpu_count_mp) + + if cpu_count_user < cpu_count_mp: + assert cpu_count() == cpu_count_user + assert cpu_count(only_physical_cores=True) == cpu_count_user
Possibility to ignore hyperthreading in loky.cpu_count In many situations it's detrimental to use simultaneous multi-threading (smt) (hyperthreading for intel). It would be interesting to add the option to ignore smt to cpu_count. ``` loky.cpu_count(include_smt=False) ```
0.0
7b675b470adcf8fa07cd830a78121349294cd4ae
[ "tests/test_loky_module.py::test_version", "tests/test_loky_module.py::test_cpu_count", "tests/test_loky_module.py::test_cpu_count_affinity", "tests/test_loky_module.py::test_only_physical_cores_with_user_limitation" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-09-17 16:28:02+00:00
bsd-3-clause
3,275
joblib__loky-390
diff --git a/.azure_pipeline.yml b/.azure_pipeline.yml index 47178e4..1e2648c 100644 --- a/.azure_pipeline.yml +++ b/.azure_pipeline.yml @@ -2,7 +2,7 @@ jobs: - job: linting displayName: Linting pool: - vmImage: ubuntu-20.04 + vmImage: ubuntu-latest steps: - task: UsePythonVersion@0 inputs: @@ -19,46 +19,46 @@ jobs: strategy: matrix: - windows-py310: + windows-py311: imageName: windows-latest - python.version: "3.10" - tox.env: py310 - windows-py37: + python.version: "3.11" + tox.env: py311 + windows-py38: imageName: windows-latest python.version: "3.8" tox.env: py38 - macos-py310: + macos-py311: imageName: "macos-latest" - python.version: "3.10" - tox.env: py310 - macos-py37: + python.version: "3.11" + tox.env: py311 + macos-py38: imageName: "macos-latest" - python.version: "3.7" - tox.env: py37 + python.version: "3.8" + tox.env: py38 linux-pypy3: - imageName: "ubuntu-20.04" + imageName: "ubuntu-latest" python.version: "pypy3" tox.env: pypy3 LOKY_MAX_CPU_COUNT: "2" - linux-py310: - imageName: "ubuntu-20.04" - python.version: "3.10" - tox.env: py310 + linux-py311: + imageName: "ubuntu-latest" + python.version: "3.11" + tox.env: py311 linux-py39-joblib-tests: - imageName: "ubuntu-20.04" + imageName: "ubuntu-latest" python.version: "3.9" tox.env: "py39" joblib.tests: "true" linux-python-py39-high-memory: - imageName: "ubuntu-20.04" + imageName: "ubuntu-latest" python.version: "3.9" tox.env: py39 RUN_MEMORY: "true" linux-py38: - imageName: "ubuntu-20.04" + imageName: "ubuntu-latest" python.version: "3.8" tox.env: py38 diff --git a/CHANGES.md b/CHANGES.md index 7b56908..0dff38f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -6,6 +6,10 @@ - Fix handling of CPU affinity by using `psutil`'s `cpu_affinity` on platforms that do not implement `os.sched_getaffinity`, such as PyPy (#381). +- Fix crash when using `max_workers > 61` on Windows. Loky will no longer + attempt to use more than 61 workers on that platform (or 60 depending on the + Python version). (#390). + ### 3.3.0 - 2022-09-15 - Fix worker management logic in `get_reusable_executor` to ensure diff --git a/loky/backend/context.py b/loky/backend/context.py index af7be78..433d6f5 100644 --- a/loky/backend/context.py +++ b/loky/backend/context.py @@ -18,9 +18,15 @@ import warnings import multiprocessing as mp from multiprocessing import get_context as mp_get_context from multiprocessing.context import BaseContext +from concurrent.futures.process import _MAX_WINDOWS_WORKERS from .process import LokyProcess, LokyInitMainProcess +# Apparently, on older Python versions, loky cannot work 61 workers on Windows +# but instead 60: ¯\_(ツ)_/¯ +if sys.version_info < (3, 10): + _MAX_WINDOWS_WORKERS = _MAX_WINDOWS_WORKERS - 1 + START_METHODS = ["loky", "loky_init_main", "spawn"] if sys.platform != "win32": START_METHODS += ["fork", "forkserver"] @@ -88,10 +94,21 @@ def cpu_count(only_physical_cores=False): or the LOKY_MAX_CPU_COUNT environment variable. If the number of physical cores is not found, return the number of logical cores. + Note that on Windows, the returned number of CPUs cannot exceed 61 (or 60 for + Python < 3.10), see: + https://bugs.python.org/issue26903. + It is also always larger or equal to 1. """ # Note: os.cpu_count() is allowed to return None in its docstring os_cpu_count = os.cpu_count() or 1 + if sys.platform == "win32": + # On Windows, attempting to use more than 61 CPUs would result in a + # OS-level error. See https://bugs.python.org/issue26903. According to + # https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups + # it might be possible to go beyond with a lot of extra work but this + # does not look easy. + os_cpu_count = min(os_cpu_count, _MAX_WINDOWS_WORKERS) cpu_count_user = _cpu_count_user(os_cpu_count) aggregate_cpu_count = max(min(os_cpu_count, cpu_count_user), 1) diff --git a/loky/process_executor.py b/loky/process_executor.py index 9176afe..6e42258 100644 --- a/loky/process_executor.py +++ b/loky/process_executor.py @@ -79,7 +79,7 @@ from multiprocessing.connection import wait from ._base import Future from .backend import get_context -from .backend.context import cpu_count +from .backend.context import cpu_count, _MAX_WINDOWS_WORKERS from .backend.queues import Queue, SimpleQueue from .backend.reduction import set_loky_pickler, get_loky_pickler_name from .backend.utils import kill_process_tree, get_exitcodes_terminated_worker @@ -1064,6 +1064,16 @@ class ProcessPoolExecutor(Executor): raise ValueError("max_workers must be greater than 0") self._max_workers = max_workers + if ( + sys.platform == "win32" + and self._max_workers > _MAX_WINDOWS_WORKERS + ): + warnings.warn( + f"On Windows, max_workers cannot exceed {_MAX_WINDOWS_WORKERS} " + "due to limitations of the operating system." + ) + self._max_workers = _MAX_WINDOWS_WORKERS + if context is None: context = get_context() self._context = context diff --git a/tox.ini b/tox.ini index 650b7dc..91bb53e 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ # content of: tox.ini , put in same dir as setup.py [tox] -envlist = py37, py38, py39, py310, pypy3 +envlist = py38, py39, py310, py311, pypy3 skip_missing_interpreters=True [testenv]
joblib/loky
eb6b8441133263d869116c067725270a6015bb4f
diff --git a/tests/test_loky_module.py b/tests/test_loky_module.py index 474f49d..b9734ea 100644 --- a/tests/test_loky_module.py +++ b/tests/test_loky_module.py @@ -10,7 +10,7 @@ import pytest import loky from loky import cpu_count -from loky.backend.context import _cpu_count_user +from loky.backend.context import _cpu_count_user, _MAX_WINDOWS_WORKERS def test_version(): @@ -34,6 +34,11 @@ def test_cpu_count(): assert 1 <= cpus_physical <= cpus [email protected](sys.platform != "win32", reason="Windows specific test") +def test_windows_max_cpu_count(): + assert cpu_count() <= _MAX_WINDOWS_WORKERS + + cpu_count_cmd = ( "from loky.backend.context import cpu_count;" "print(cpu_count({args}))" ) diff --git a/tests/test_reusable_executor.py b/tests/test_reusable_executor.py index f45e7ed..f9b99d4 100644 --- a/tests/test_reusable_executor.py +++ b/tests/test_reusable_executor.py @@ -20,6 +20,7 @@ from loky import get_reusable_executor from loky.process_executor import _RemoteTraceback, TerminatedWorkerError from loky.process_executor import BrokenProcessPool, ShutdownExecutorError from loky.reusable_executor import _ReusablePoolExecutor +from loky.backend.context import _MAX_WINDOWS_WORKERS try: import psutil @@ -220,7 +221,6 @@ class CExitAtGCInWorker: class TestExecutorDeadLock(ReusableExecutorMixin): - crash_cases = [ # Check problem occuring while pickling a task in (id, (ExitAtPickle(),), PicklingError, None), @@ -1013,3 +1013,41 @@ class TestExecutorInitializer(ReusableExecutorMixin): out, err = p.communicate() assert p.returncode == 1, out.decode() assert b"resource_tracker" not in err, err.decode() + + +def test_no_crash_max_workers_on_windows(): + # Check that loky's reusable process pool executor does not crash when the + # user asks for more workers than the maximum number of workers supported + # by the platform. + + # Note: on overloaded CI hosts, spawning many processes can take a long + # time. We need to increase the timeout to avoid spurious failures when + # making assertions on `len(executor._processes)`. + idle_worker_timeout = 10 * 60 + with warnings.catch_warnings(record=True) as record: + executor = get_reusable_executor( + max_workers=_MAX_WINDOWS_WORKERS + 1, timeout=idle_worker_timeout + ) + assert executor.submit(lambda: None).result() is None + if sys.platform == "win32": + assert len(record) == 1 + assert "max_workers" in str(record[0].message) + assert len(executor._processes) == _MAX_WINDOWS_WORKERS + else: + assert len(record) == 0 + assert len(executor._processes) == _MAX_WINDOWS_WORKERS + 1 + + # Downsizing should never raise a warning. + before_downsizing_executor = executor + with warnings.catch_warnings(record=True) as record: + executor = get_reusable_executor( + max_workers=_MAX_WINDOWS_WORKERS, timeout=idle_worker_timeout + ) + assert executor.submit(lambda: None).result() is None + + # No warning on any OS when max_workers does not exceed the limit. + assert len(record) == 0 + assert before_downsizing_executor is executor + assert len(executor._processes) == _MAX_WINDOWS_WORKERS + + executor.shutdown()
loky is broken on windows with max_workers>62 As reported in scikit-learn/scikit-learn#12263, `loky` hangs when using many workers on windows. The following traceback is given: ```python-traceback Exception in thread QueueManagerThread: File "<<elided>>\lib\site-packages\sklearn\externals\joblib\externals\loky\process_executor.py", line 617, in _queue_management_worker ready = wait(readers + worker_sentinels) File "<<elided>>\lib\multiprocessing\connection.py", line 859, in wait File "<<elided>>\lib\multiprocessing\connection.py", line 791, in _exhaustive_wait res = _winapi.WaitForMultipleObjects(L, False, timeout) ValueError: need at most 63 handles, got a sequence of length 129 ``` It looks like the probelm is caused by our implementation of `wait`, which relies on [`winapi.WaitForMultipleObjects`](https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitformultipleobjects). It seems that this function cannot wait for more than `MAXIMUM_WAIT_OBJECTS=64` objects.
0.0
eb6b8441133263d869116c067725270a6015bb4f
[ "tests/test_loky_module.py::test_version", "tests/test_loky_module.py::test_cpu_count", "tests/test_loky_module.py::test_cpu_count_os_sched_getaffinity", "tests/test_loky_module.py::test_only_physical_cores_with_user_limitation", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args0-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args1-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args2-BrokenProcessPool-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args3-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args4-BrokenProcessPool-UnpicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[id-args5-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[crash-args6-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[exit-args7-SystemExit-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[c_exit-args8-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[raise_error-args9-RuntimeError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args10-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args11-SystemExit-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args12-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args13-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args14-BrokenProcessPool-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_crashes[return_instance-args15-BrokenProcessPool-UnpicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args0-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args1-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args2-BrokenProcessPool-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args3-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args4-BrokenProcessPool-UnpicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[id-args5-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[crash-args6-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[exit-args7-SystemExit-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[c_exit-args8-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[raise_error-args9-RuntimeError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args10-TerminatedWorkerError-SIGSEGV]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args11-SystemExit-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args12-TerminatedWorkerError-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args13-PicklingError-None]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args14-BrokenProcessPool-SystemExit]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_in_callback_submit_with_crash[return_instance-args15-BrokenProcessPool-UnpicklingError]", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_callback_crash_on_submit", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_deadlock_kill", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_imap_handle_iterable_exception", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_queue_full_deadlock", "tests/test_reusable_executor.py::TestExecutorDeadLock::test_informative_error_when_fail_at_unpickle", "tests/test_reusable_executor.py::TestTerminateExecutor::test_shutdown_kill", "tests/test_reusable_executor.py::TestTerminateExecutor::test_kill_workers_on_new_options", "tests/test_reusable_executor.py::TestTerminateExecutor::test_call_item_gc_crash_or_exit[CrashAtGCInWorker-SIGSEGV]", "tests/test_reusable_executor.py::TestTerminateExecutor::test_call_item_gc_crash_or_exit[CExitAtGCInWorker-EXIT\\\\(0\\\\)]", "tests/test_reusable_executor.py::TestTerminateExecutor::test_sigkill_shutdown_leaks_workers", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[True-True]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[True-False]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[False-True]", "tests/test_reusable_executor.py::TestResizeExecutor::test_reusable_executor_resize_many_times[False-False]", "tests/test_reusable_executor.py::TestResizeExecutor::test_resize_after_timeout", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_invalid_process_number", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_invalid_context", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_pass_start_method_name_as_context", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reused_flag", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_interactively_defined_nested_functions", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_interactively_defined_recursive_functions", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_no_deadlock_on_nested_reusable_exector", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_compat_with_concurrent_futures_exception", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reusable_executor_thread_safety[constant-clean_start]", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reusable_executor_thread_safety[constant-broken_start]", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reusable_executor_thread_safety[varying-clean_start]", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reusable_executor_thread_safety[varying-broken_start]", "tests/test_reusable_executor.py::TestGetReusableExecutor::test_reusable_executor_reuse_true", "tests/test_reusable_executor.py::TestExecutorInitializer::test_reusable_initializer", "tests/test_reusable_executor.py::TestExecutorInitializer::test_error_in_nested_call_keeps_resource_tracker_silent", "tests/test_reusable_executor.py::test_no_crash_max_workers_on_windows" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-02 09:34:31+00:00
bsd-3-clause
3,276
joergbuchwald__ogs6py-44
diff --git a/examples/example_THM.py b/examples/example_THM.py index 6430ec3..632afcc 100644 --- a/examples/example_THM.py +++ b/examples/example_THM.py @@ -39,9 +39,32 @@ model.media.add_property(medium_id="0", name="density", type="Linear", reference_value="999.1", - variable_name="temperature", - reference_condition="273.15", - slope="-4e-4") + independent_variables={"temperature": { + "reference_condition":273.15, + "slope":-4e-4}, + "phase_pressure": { + "reference_condition": 1e5, + "slope": 1e-20 + }}) +# Alternative density models using property type Exponential or Function +#model.media.add_property(medium_id="0", +# phase_type="AqueousLiquid", +# name="density", +# type="Exponential", +# reference_value="999.1", +# offset="0.0", +# exponent={"variable_name": "temperature", +# "reference_condition":273.15, +# "factor":-4e-4}) +#model.media.add_property(medium_id="0", +# phase_type="AqueousLiquid", +# name="density", +# type="Function", +# expression="999.1", +# dvalues={"temperature": { +# "expression":0.0}, +# "phase_pressure": { +# "expression": 0.0}}) model.media.add_property(medium_id="0", phase_type="AqueousLiquid", name="thermal_expansivity", diff --git a/ogs6py/classes/media.py b/ogs6py/classes/media.py index 0aa7e8f..a12ab79 100644 --- a/ogs6py/classes/media.py +++ b/ogs6py/classes/media.py @@ -22,6 +22,239 @@ class Media(build_tree.BuildTree): 'children': {} } } + self.properties = {"AverageMolarMass": [], + "BishopsSaturationCutoff": ["cutoff_value"], + "BishopsPowerLaw": ["exponent"], + "CapillaryPressureRegularizedVanGenuchten": ["exponent", + "p_b", + "residual_gas_saturation", + "residual_liquid_saturation"], + "CapillaryPressureVanGenuchten": ["exponent", + "maximum_capillary_pressure" + "p_b", + "residual_gas_saturation", + "residual_liquid_saturation"], + "ClausiusClapeyron": ["critical_pressure", + "critical_temperature", + "reference_pressure", + "reference_temperature", + "triple_pressure", + "triple_temperature"], + "Constant": ["value"], + "Curve" : ["curve", "independent_variable"], + "DupuitPermeability": ["parameter_name"], + "EffectiveThermalConductivityPorosityMixing": [], + "EmbeddedFracturePermeability": ["intrinsic_permeability", + "initial_aperture", + "mean_frac_distance", + "threshold_strain", + "fracture_normal", + "fracture_rotation_xy", + "fracture_rotation_yz"], + "Function": ["value"], + "Exponential": ["offset","reference_value"], + "GasPressureDependentPermeability": ["initial_permeability", + "a1", "a2", + "pressure_threshold", + "minimum_permeability", + "maximum_permeability"], + "IdealGasLaw": [], + "IdealGasLawBinaryMixture": [], + "KozenyCarmanModel": ["intitial_permeability", "initial_prosity"], + "Linear": ["reference_value"], + "LinearSaturationSwellingStress" : ["coefficient", "reference_saturation"], + "LinearWaterVapourLatentHeat" : [], + "OrthotropicEmbeddedFracturePermeability": ["intrinsic_permeability", + "mean_frac_distances", + "threshold_strains", + "fracture_normals", + "fracture_rotation_xy", + "fracture_rotation_yz", + "jacobian_factor"], + "Parameter": ["parameter_name"], + "PermeabilityMohrCoulombFailureIndexModel": ["cohesion", + "fitting_factor", + "friction_angle", + "initial_ppermeability", + "maximum_permeability", + "reference_permeability", + "tensile_strength_parameter"], + "PermeabilityOrthotropicPowerLaw": ["exponents", + "intrinsic_permeabilities"], + "PorosityFromMassBalance": ["initial_porosity", + "maximal_porosity", + "minimal_porosity"], + "RelPermBrooksCorey": ["lambda", + "min_relative_permeability" + "residual_gas_saturation", + "residual_liquid_saturation"], + "RelPermBrooksCoreyNonwettingPhase": ["lambda", + "min_relative_permeability" + "residual_gas_saturation", + "residual_liquid_saturation"], + "RelPermLiakopoulos": [], + "RelativePermeabilityNonWettingVanGenuchten": ["exponent", + "minimum_relative_permeability", + "residual_gas_saturation", + "residual_liquid_saturation"], + "RelativePermeabilityUdell": ["min_relative_permeability", + "residual_gas_saturation", + "residual_liquid_saturation"], + "RelativePermeabilityUdellNonwettingPhase": ["min_relative_permeability", + "residual_gas_saturation", + "residual_liquid_saturation"], + "RelativePermeabilityVanGenuchten": ["exponent", + "minimum_relative_permeability_liquid", + "residual_gas_saturation", + "residual_liquid_saturation"], + "SaturationBrooksCorey": ["entry_pressure", + "lambda", + "residual_gas_saturation", + "residual_liquid_saturation"], + "SaturationDependentSwelling": ["exponents", + "lower_saturation_limit", + "swelling_pressures", + "upper_saturation_limit"], + "SaturationDependentThermalConductivity": ["dry","wet"], + "SaturationExponential": ["exponent", + "maximum_capillary_pressure", + "residual_gas_saturation", + "residual_liquid_saturation"], + "SaturationLiakopoulos": [], + "SaturationVanGenuchten": ["exponent", + "p_b", + "residual_gas_saturation", + "residual_liquid_saturation"], + "SoilThermalConductivitySomerton": ["dry_thermal_conductivity", + "wet_thermal_conductivity"], + "StrainDependentPermeability": ["initial_permeability", + "b1", "b2", "b3", + "minimum_permeability", + "maximum_permeability"], + "TemperatureDependentDiffusion": ["activation_energy", + "reference_diffusion", + "reference_temperature"], + "TransportPorosityFromMassBalance": ["initial_porosity", + "maximal_porosity", + "minimal_porosity"], + "VapourDiffusionFEBEX": ["tortuosity"], + "VapourDiffusionPMQ": [], + "VermaPruessModel": ["critical_porosity", + "exponent", + "initial_permeability", + "initial_porosity"], + "WaterVapourDensity": [], + "WaterVapourLatentHeatWithCriticalTemperature": [] + } + + def _generate_generic_property(self, args): + property_parameters = {} + for parameter in self.properties[args["type"]]: + property_parameters[parameter] = { + 'tag': parameter, + 'text': args[parameter], + 'attr': {}, + 'children': {} + } + return property_parameters + def _generate_linear_property(self, args): + property_parameters = {} + for parameter in self.properties[args["type"]]: + property_parameters[parameter] = { + 'tag': parameter, + 'text': args[parameter], + 'attr': {}, + 'children': {} + } + for var, param in args["independent_variables"].items(): + property_parameters[f"independent_variable{var}"] = { + 'tag': 'independent_variable', + 'text': '', + 'attr': {}, + 'children': {} + } + indep_var = property_parameters[f"independent_variable{var}"]['children'] + indep_var['variable_name'] = { + 'tag': 'variable_name', + 'text': var, + 'attr': {}, + 'children': {} + } + attributes = ['reference_condition','slope'] + for attrib in attributes: + indep_var[attrib] = { + 'tag': attrib, + 'text': str(param[attrib]), + 'attr': {}, + 'children': {} + } + return property_parameters + def _generate_function_property(self, args): + property_parameters = {} + for parameter in self.properties[args["type"]]: + property_parameters[parameter] = { + 'tag': parameter, + 'text': "", + 'attr': {}, + 'children': {} + } + property_parameters["value"]["children"]["expression"] = { + 'tag': "expression", + 'text': args["expression"], + 'attr': {}, + 'children': {} + } + for dvar in args["dvalues"]: + property_parameters[f"dvalue{dvar}"] = { + 'tag': "dvalue", + 'text': "", + 'attr': {}, + 'children': {} + } + property_parameters[f"dvalue{dvar}"]["children"]["variable_name"] = { + 'tag': "variable_name", + 'text': dvar, + 'attr': {}, + 'children': {} + } + property_parameters[f"dvalue{dvar}"]["children"]["expression"] = { + 'tag': "expression", + 'text': args["dvalues"][dvar]["expression"], + 'attr': {}, + 'children': {} + } + return property_parameters + def _generate_exponential_property(self, args): + property_parameters = {} + for parameter in self.properties[args["type"]]: + property_parameters[parameter] = { + 'tag': parameter, + 'text': args[parameter], + 'attr': {}, + 'children': {} + } + property_parameters["exponent"] = { + 'tag': 'exponent', + 'text': '', + 'attr': {}, + 'children': {} + } + indep_var = property_parameters["exponent"]['children'] + indep_var['variable_name'] = { + 'tag': 'variable_name', + 'text': args["exponent"]["variable_name"], + 'attr': {}, + 'children': {} + } + attributes = ['reference_condition','factor'] + for attrib in attributes: + indep_var[attrib] = { + 'tag': attrib, + 'text': str(args["exponent"][attrib]), + 'attr': {}, + 'children': {} + } + return property_parameters def add_property(self, **args): """ @@ -106,76 +339,26 @@ class Media(build_tree.BuildTree): 'attr': {}, 'children': {} } - phase[args['name']]['children']['name'] = { - 'tag': 'name', - 'text': args['name'], - 'attr': {}, - 'children': {} - } - phase[args['name']]['children']['type'] = { - 'tag': 'type', - 'text': args['type'], - 'attr': {}, - 'children': {} - } - if args['type'] == "Constant": - phase[args['name']]['children']['value'] = { - 'tag': 'value', - 'text': args['value'], - 'attr': {}, - 'children': {} - } - elif args['type'] == "Linear": - phase[args['name']]['children']['reference_value'] = { - 'tag': 'reference_value', - 'text': args['reference_value'], + base_property_param = ["name", "type"] + for param in base_property_param: + phase[args['name']]['children'][param] = { + 'tag': param, + 'text': args[param], 'attr': {}, 'children': {} - } - phase[args['name']]['children']['independent_variable'] = { - 'tag': 'independent_variable', - 'text': '', - 'attr': {}, - 'children': {} - } - indep_var = phase[args['name']]['children']['independent_variable']['children'] - indep_var['variable_name'] = { - 'tag': 'variable_name', - 'text': args['variable_name'], - 'attr': {}, - 'children': {} - } - indep_var['reference_condition'] = { - 'tag': 'reference_condition', - 'text': args['reference_condition'], - 'attr': {}, - 'children': {} - } - indep_var['slope'] = { - 'tag': 'slope', - 'text': args['slope'], - 'attr': {}, - 'children': {} - } - elif args['type'] == "Parameter": - phase[args['name']]['children']['parameter'] = { - 'tag': 'parameter_name', - 'text': args['parameter_name'], - 'attr': {}, - 'children': {} - } - elif args['type'] == "BishopsSaturationCutoff": - phase[args['name']]['children']['cutoff_value'] = { - 'tag': 'cutoff_value', - 'text': args['cutoff_value'], - 'attr': {}, - 'children': {} - } - elif args['type'] == "BishopsPowerLaw": - phase[args['name']]['children']['exponent'] = { - 'tag': 'exponent', - 'text': args['exponent'], - 'attr': {}, - 'children': {} - } - + } + try: + if args['type'] == "Linear": + phase[args['name']]['children'].update(self._generate_linear_property(args)) + elif args['type'] == "Exponential": + phase[args['name']]['children'].update(self._generate_exponential_property(args)) + elif args['type'] == "Function": + phase[args['name']]['children'].update(self._generate_function_property(args)) + else: + phase[args['name']]['children'].update(self._generate_generic_property(args)) + except KeyError: + print("Material property parameters incomplete for") + if "phase_type" in args: + print(f"Medium {args['medium_id']}->{args['phase_type']}->{args['name']}[{args['type']}]") + else: + print(f"Medium {args['medium_id']}->{args['name']}[{args['type']}]")
joergbuchwald/ogs6py
91fd62ff3b856aac6c2f98724199acded0183e2f
diff --git a/tests/test_ogs6py.py b/tests/test_ogs6py.py index ee957e9..4f80bdc 100644 --- a/tests/test_ogs6py.py +++ b/tests/test_ogs6py.py @@ -68,13 +68,14 @@ class TestiOGS(unittest.TestCase): type="Constant", value="0.6") model.media.add_property(medium_id="0", - phase_type="AqueousLiquid", - name="density", - type="Linear", - reference_value="999.1", - variable_name="phase_pressure", - reference_condition="1e5", - slope="4.5999999999999996e-10") + phase_type="AqueousLiquid", + name="density", + type="Linear", + reference_value="999.1", + independent_variables={"phase_pressure": { + "reference_condition": "1e5", + "slope": "4.5999999999999996e-10" + }}) model.media.add_property(medium_id="0", phase_type="AqueousLiquid", name="thermal_expansivity",
extending add_property for new MPL models Hi Joerg, we want to use the following MPL model with OGS6PY. But it is not considered yet. ```python model.media.add_property(medium_id="0", name="permeability", type="GasPressureDependentPermeability", initial_permeability="1e-15", a1="0.125", a2="152", pressure_threshold="3.2e6", minimum_permeability="0.0" , maximum_permeability="8.0e-16") ``` THis is actually how the model is translated ```xml <property> <name>permeability</name> <type>GasPressureDependentPermeability</type> </property> ``` and here is how the model should be: ```xml <property> <name>permeability</name> <type>GasPressureDependentPermeability</type> <initial_permeability>permeability0</initial_permeability> <a1>0.125</a1> <a2>152</a2> <pressure_threshold>3.2e6</pressure_threshold> <minimum_permeability>0.0</minimum_permeability> <maximum_permeability>8.0e-16</maximum_permeability> </property> ``` Could you please add this model into ogs6py ? Thanks, Eric
0.0
91fd62ff3b856aac6c2f98724199acded0183e2f
[ "tests/test_ogs6py.py::TestiOGS::test_buildfromscratch" ]
[ "tests/test_ogs6py.py::TestiOGS::test_add_block", "tests/test_ogs6py.py::TestiOGS::test_add_entry", "tests/test_ogs6py.py::TestiOGS::test_empty_replace", "tests/test_ogs6py.py::TestiOGS::test_model_run", "tests/test_ogs6py.py::TestiOGS::test_parallel_1_compare_serial_info", "tests/test_ogs6py.py::TestiOGS::test_parallel_3_debug", "tests/test_ogs6py.py::TestiOGS::test_remove_element", "tests/test_ogs6py.py::TestiOGS::test_replace_block_by_include", "tests/test_ogs6py.py::TestiOGS::test_replace_medium_property", "tests/test_ogs6py.py::TestiOGS::test_replace_mesh", "tests/test_ogs6py.py::TestiOGS::test_replace_parameter", "tests/test_ogs6py.py::TestiOGS::test_replace_phase_property", "tests/test_ogs6py.py::TestiOGS::test_replace_property_in_include", "tests/test_ogs6py.py::TestiOGS::test_replace_text", "tests/test_ogs6py.py::TestiOGS::test_serial_convergence_coupling_iteration_long", "tests/test_ogs6py.py::TestiOGS::test_serial_convergence_newton_iteration_long", "tests/test_ogs6py.py::TestiOGS::test_serial_critical", "tests/test_ogs6py.py::TestiOGS::test_serial_time_vs_iterations", "tests/test_ogs6py.py::TestiOGS::test_serial_warning_only" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-02-18 21:52:54+00:00
bsd-3-clause
3,277
joerick__pyinstrument-271
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 93f9492..22c6de2 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -41,7 +41,7 @@ jobs: python-version: '3.8' - name: Build wheels - uses: joerick/[email protected] + uses: joerick/[email protected] env: CIBW_SKIP: pp* CIBW_ARCHS: ${{matrix.archs}} diff --git a/docs/guide.md b/docs/guide.md index d217787..b6fb68d 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -294,8 +294,7 @@ def auto_profile(request): profiler.stop() PROFILE_ROOT.mkdir(exist_ok=True) results_file = PROFILE_ROOT / f"{request.node.name}.html" - with open(results_file, "w", encoding="utf-8") as f_html: - f_html.write(profiler.output_html()) + profiler.write_html(results_file) ``` This will generate a HTML file for each test node in your test suite inside diff --git a/metrics/interrupt.py b/metrics/interrupt.py index 76f1baa..aa446df 100644 --- a/metrics/interrupt.py +++ b/metrics/interrupt.py @@ -21,5 +21,4 @@ p.stop() print(p.output_text()) -with open("ioerror_out.html", "w") as f: - f.write(p.output_html()) +p.write_html("ioerror_out.html") diff --git a/metrics/overflow.py b/metrics/overflow.py index 912486f..a5c6175 100644 --- a/metrics/overflow.py +++ b/metrics/overflow.py @@ -21,5 +21,4 @@ p.stop() print(p.output_text()) -with open("overflow_out.html", "w") as f: - f.write(p.output_html()) +p.write_html("overflow_out.html") diff --git a/metrics/overhead.py b/metrics/overhead.py index ca906b8..a71b53a 100644 --- a/metrics/overhead.py +++ b/metrics/overhead.py @@ -51,8 +51,7 @@ profiler.stop() # pyinstrument_timeline_timings = test_func() # profiler.stop() -with open("out.html", "w") as f: - f.write(profiler.output_html()) +profiler.write_html("out.html") print(profiler.output_text(unicode=True, color=True)) diff --git a/pyinstrument/__main__.py b/pyinstrument/__main__.py index 4a60fd0..e63df3d 100644 --- a/pyinstrument/__main__.py +++ b/pyinstrument/__main__.py @@ -34,13 +34,25 @@ def main(): parser = optparse.OptionParser(usage=usage, version=version_string) parser.allow_interspersed_args = False - def dash_m_callback(option: str, opt: str, value: str, parser: optparse.OptionParser): - parser.values.module_name = value # type: ignore - - # everything after the -m argument should be passed to that module - parser.values.module_args = parser.rargs + parser.largs # type: ignore - parser.rargs[:] = [] # type: ignore - parser.largs[:] = [] # type: ignore + def store_and_consume_remaining( + option: optparse.Option, opt: str, value: str, parser: optparse.OptionParser + ): + """ + A callback for optparse that stores the value and consumes all + remaining arguments, storing them in the same variable as a tuple. + """ + + # assert a few things we know to be true about the parser + assert option.dest + assert parser.rargs is not None + assert parser.largs is not None + + # everything after this argument should be consumed + remaining_arguments = parser.rargs + parser.largs + parser.rargs[:] = [] + parser.largs[:] = [] + + setattr(parser.values, option.dest, ValueWithRemainingArgs(value, remaining_arguments)) parser.add_option( "--load", @@ -62,12 +74,21 @@ def main(): parser.add_option( "-m", "", - dest="module_name", + dest="module", action="callback", - callback=dash_m_callback, - type="str", + callback=store_and_consume_remaining, + type="string", help="run library module as a script, like 'python -m module'", ) + parser.add_option( + "-c", + "", + dest="program", + action="callback", + callback=store_and_consume_remaining, + type="string", + help="program passed in as string, like 'python -c \"...\"'", + ) parser.add_option( "", "--from-path", @@ -244,7 +265,8 @@ def main(): session_options_used = [ options.load is not None, options.load_prev is not None, - options.module_name is not None, + options.module is not None, + options.program is not None, len(args) > 0, ] if session_options_used.count(True) == 0: @@ -253,7 +275,7 @@ def main(): if session_options_used.count(True) > 1: parser.error("You can only specify one of --load, --load-prev, -m, or script arguments") - if options.module_name is not None and options.from_path: + if options.module is not None and options.from_path: parser.error("The options -m and --from-path are mutually exclusive.") if options.from_path and sys.platform == "win32": @@ -297,14 +319,21 @@ def main(): elif options.load: session = Session.load(options.load) else: - if options.module_name is not None: + # we are running some code + if options.module is not None: if not (sys.path[0] and os.path.samefile(sys.path[0], ".")): # when called with '-m', search the cwd for that module sys.path[0] = os.path.abspath(".") - argv = [options.module_name] + options.module_args + argv = [options.module.value] + options.module.remaining_args code = "run_module(modname, run_name='__main__', alter_sys=True)" - globs = {"run_module": runpy.run_module, "modname": options.module_name} + globs = {"run_module": runpy.run_module, "modname": options.module.value} + elif options.program is not None: + argv = ["-c", *options.program.remaining_args] + code = options.program.value + globs = {"__name__": "__main__"} + # set the first path entry to '' to match behaviour of python -c + sys.path[0] = "" else: argv = args if options.from_path: @@ -322,15 +351,15 @@ def main(): code = "run_path(progname, run_name='__main__')" globs = {"run_path": runpy.run_path, "progname": progname} + old_argv = sys.argv.copy() + # there is no point using async mode for command line invocation, # because it will always be capturing the whole program, we never want # any execution to be <out-of-context>, and it avoids duplicate # profiler errors. profiler = Profiler(interval=options.interval, async_mode="disabled") - profiler.start() - old_argv = sys.argv.copy() try: sys.argv[:] = argv exec(code, globs, None) @@ -552,8 +581,8 @@ class CommandLineOptions: A type that codifies the `options` variable. """ - module_name: str | None - module_args: list[str] + module: ValueWithRemainingArgs | None + program: ValueWithRemainingArgs | None load: str | None load_prev: str | None from_path: str | None @@ -573,5 +602,11 @@ class CommandLineOptions: interval: float +class ValueWithRemainingArgs: + def __init__(self, value: str, remaining_args: list[str]): + self.value = value + self.remaining_args = remaining_args + + if __name__ == "__main__": main() diff --git a/pyinstrument/profiler.py b/pyinstrument/profiler.py index 74dd844..eef5f44 100644 --- a/pyinstrument/profiler.py +++ b/pyinstrument/profiler.py @@ -1,9 +1,11 @@ from __future__ import annotations import inspect +import os import sys import time import types +from pathlib import Path from time import process_time from typing import IO, Any @@ -304,6 +306,16 @@ class Profiler: """ return self.output(renderer=renderers.HTMLRenderer(timeline=timeline)) + def write_html(self, path: str | os.PathLike[str], timeline: bool = False): + """ + Writes the profile output as HTML to a file, as rendered by :class:`HTMLRenderer` + """ + file = Path(path) + file.write_text( + self.output(renderer=renderers.HTMLRenderer(timeline=timeline)), + encoding="utf-8", + ) + def open_in_browser(self, timeline: bool = False): """ Opens the last profile session in your web browser.
joerick/pyinstrument
7b80667760e8a1ca49c0220bc9ed07e6ad059f42
diff --git a/test/test_cmdline.py b/test/test_cmdline.py index 3a0706d..d718a2c 100644 --- a/test/test_cmdline.py +++ b/test/test_cmdline.py @@ -2,14 +2,13 @@ import os import re import subprocess import sys +import textwrap from pathlib import Path import pytest from .util import BUSY_WAIT_SCRIPT -# this script just does a busywait for 0.25 seconds. - EXECUTION_DETAILS_SCRIPT = f""" #!{sys.executable} import sys, os @@ -78,6 +77,35 @@ class TestCommandLine: [*pyinstrument_invocation, "--from-path", "--", "pyi_test_program"], ) + def test_program_passed_as_string(self, pyinstrument_invocation, tmp_path: Path): + # check the program actually runs + output_file = tmp_path / "output.txt" + output = subprocess.check_output( + [ + *pyinstrument_invocation, + "-c", + textwrap.dedent( + f""" + import sys + from pathlib import Path + output_file = Path(sys.argv[1]) + output_file.write_text("Hello World") + print("Finished.") + """ + ), + str(output_file), + ], + ) + + assert "Finished." in str(output) + assert output_file.read_text() == "Hello World" + + # check the output + output = subprocess.check_output([*pyinstrument_invocation, "-c", BUSY_WAIT_SCRIPT]) + + assert "busy_wait" in str(output) + assert "do_nothing" in str(output) + def test_script_execution_details(self, pyinstrument_invocation, tmp_path: Path): program_path = tmp_path / "program.py" program_path.write_text(EXECUTION_DETAILS_SCRIPT) @@ -157,6 +185,27 @@ class TestCommandLine: print("process_native.stderr", process_native.stderr) assert process_pyi.stderr == process_native.stderr + def test_program_passed_as_string_execution_details( + self, pyinstrument_invocation, tmp_path: Path + ): + process_pyi = subprocess.run( + [*pyinstrument_invocation, "-c", EXECUTION_DETAILS_SCRIPT], + stderr=subprocess.PIPE, + check=True, + text=True, + ) + process_native = subprocess.run( + [sys.executable, "-c", EXECUTION_DETAILS_SCRIPT], + stderr=subprocess.PIPE, + check=True, + text=True, + ) + + print("process_pyi.stderr", process_pyi.stderr) + print("process_native.stderr", process_native.stderr) + assert process_native.stderr + assert process_pyi.stderr == process_native.stderr + def test_session_save_and_load(self, pyinstrument_invocation, tmp_path: Path): busy_wait_py = tmp_path / "busy_wait.py" busy_wait_py.write_text(BUSY_WAIT_SCRIPT)
Support `-c` input mode I often want to run pyinstrument on snippets, e.g. just an import or one function call. It would be nice if I could write `pyinstrument -c "import slow_thing"` to profile, instead of having to write a dummy file containing `import slow_thing`.
0.0
7b80667760e8a1ca49c0220bc9ed07e6ad059f42
[ "test/test_cmdline.py::TestCommandLine::test_program_passed_as_string[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_program_passed_as_string[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_program_passed_as_string_execution_details[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_program_passed_as_string_execution_details[pyinstrument_invocation1]" ]
[ "test/test_cmdline.py::TestCommandLine::test_command_line[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_command_line[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_module_running[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_module_running[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_single_file_module_running[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_single_file_module_running[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_running_yourself_as_module[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_running_yourself_as_module[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_path[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_path[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_script_execution_details[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_script_execution_details[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_module_execution_details[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_module_execution_details[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_path_execution_details[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_path_execution_details[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_session_save_and_load[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_session_save_and_load[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_interval[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_interval[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_invocation_machinery_is_trimmed[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_invocation_machinery_is_trimmed[pyinstrument_invocation1]", "test/test_cmdline.py::TestCommandLine::test_binary_output[pyinstrument_invocation0]", "test/test_cmdline.py::TestCommandLine::test_binary_output[pyinstrument_invocation1]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-06 15:33:55+00:00
bsd-3-clause
3,278
joerick__pyinstrument-287
diff --git a/pyinstrument/renderers/pstatsrenderer.py b/pyinstrument/renderers/pstatsrenderer.py index 2bb8157..35428b3 100644 --- a/pyinstrument/renderers/pstatsrenderer.py +++ b/pyinstrument/renderers/pstatsrenderer.py @@ -71,7 +71,7 @@ class PstatsRenderer(FrameRenderer): stats[key] = (call_time, number_calls, total_time, cumulative_time, callers) for child in frame.children: - if not frame.is_synthetic: + if not child.is_synthetic: self.render_frame(child, stats) def render(self, session: Session):
joerick/pyinstrument
f4294a9384281d38927fe117ea371f059a1541d9
diff --git a/test/test_profiler_async.py b/test/test_profiler_async.py index 48cb793..fd67375 100644 --- a/test/test_profiler_async.py +++ b/test/test_profiler_async.py @@ -144,10 +144,10 @@ def test_profiler_task_isolation(engine): ) nursery.start_soon( partial(async_wait, sync_time=0.1, async_time=0.3, engine="trio") - ) + ) # pyright: ignore nursery.start_soon( partial(async_wait, sync_time=0.1, async_time=0.3, engine="trio") - ) + ) # pyright: ignore with fake_time_trio() as fake_clock: trio.run(multi_task, clock=fake_clock.trio_clock) diff --git a/test/test_pstats_renderer.py b/test/test_pstats_renderer.py index 909d5c0..697b76d 100644 --- a/test/test_pstats_renderer.py +++ b/test/test_pstats_renderer.py @@ -2,7 +2,7 @@ import os import time from pathlib import Path from pstats import Stats -from test.fake_time_util import fake_time +from test.fake_time_util import FakeClock, fake_time from typing import Any import pytest @@ -99,3 +99,32 @@ def test_round_trip_encoding_of_binary_data(tmp_path: Path): assert data_blob == data_blob_string.encode(encoding="utf-8", errors="surrogateescape") assert data_blob == file.read_bytes() + + +def sleep_and_busy_wait(clock: FakeClock): + time.sleep(1.0) + # this looks like a busy wait to the profiler + clock.time += 1.0 + + +def test_sum_of_tottime(tmp_path): + # Check that the sum of the tottime of all the functions is equal to the + # total time of the profile + + with fake_time() as clock: + profiler = Profiler() + profiler.start() + + sleep_and_busy_wait(clock) + + profiler.stop() + profiler_session = profiler.last_session + + assert profiler_session + + pstats_data = PstatsRenderer().render(profiler_session) + fname = tmp_path / "test.pstats" + with open(fname, "wb") as fid: + fid.write(pstats_data.encode(encoding="utf-8", errors="surrogateescape")) + stats: Any = Stats(str(fname)) + assert stats.total_tt == pytest.approx(2)
pstats renderer total time The sum of `tottime` for all functions from the pstats output correctly matches the total time displayed in the header of `print_stats()` when using the `pstats` module. However, this does not match the duration shown in the HTML output (it is about twice longer). Is this expected? How much should I trust `tottime` in a pstats output? I tested with both async mode on and off.
0.0
f4294a9384281d38927fe117ea371f059a1541d9
[ "test/test_pstats_renderer.py::test_sum_of_tottime" ]
[ "test/test_profiler_async.py::test_sleep", "test/test_profiler_async.py::test_sleep_trio", "test/test_profiler_async.py::test_profiler_task_isolation[asyncio]", "test/test_profiler_async.py::test_profiler_task_isolation[trio]", "test/test_profiler_async.py::test_greenlet", "test/test_profiler_async.py::test_strict_with_greenlet", "test/test_pstats_renderer.py::test_pstats_renderer", "test/test_pstats_renderer.py::test_round_trip_encoding_of_binary_data" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2024-01-06 16:01:43+00:00
bsd-3-clause
3,279
john-kurkowski__tldextract-258
diff --git a/tldextract/cache.py b/tldextract/cache.py index b714e77..fbd02c9 100644 --- a/tldextract/cache.py +++ b/tldextract/cache.py @@ -7,7 +7,7 @@ import os import os.path import sys from hashlib import md5 -from typing import Callable, Dict, Hashable, List, Optional, TypeVar, Union +from typing import Callable, Dict, Hashable, Iterable, Optional, TypeVar, Union from filelock import FileLock import requests @@ -166,7 +166,7 @@ class DiskCache: func: Callable[..., T], namespace: str, kwargs: Dict[str, Hashable], - hashed_argnames: List[str], + hashed_argnames: Iterable[str], ) -> T: """Get a url but cache the response""" if not self.enabled: @@ -203,7 +203,7 @@ class DiskCache: result: T = self.get(namespace=namespace, key=key_args) except KeyError: result = func(**kwargs) - self.set(namespace="urls", key=key_args, value=result) + self.set(namespace=namespace, key=key_args, value=result) return result
john-kurkowski/tldextract
86c82c3a9e3e9a2980a39ce8b77e1ad0bdebcc12
diff --git a/tests/test_cache.py b/tests/test_cache.py index cb82f4f..3ae30d3 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -2,7 +2,8 @@ import os.path import sys import types -from typing import Any, cast +from typing import Any, Dict, Hashable, cast +from unittest.mock import Mock import pytest import tldextract.cache @@ -72,3 +73,29 @@ def test_get_cache_dir(monkeypatch): monkeypatch.setenv("TLDEXTRACT_CACHE", "/alt-tld-cache") assert get_cache_dir() == "/alt-tld-cache" + + +def test_run_and_cache(tmpdir): + cache = DiskCache(tmpdir) + + return_value1 = "unique return value" + some_fn = Mock(return_value=return_value1) + kwargs1: Dict[str, Hashable] = {"value": 1} + + assert some_fn.call_count == 0 + + call1 = cache.run_and_cache(some_fn, "test_namespace", kwargs1, kwargs1.keys()) + assert call1 == return_value1 + assert some_fn.call_count == 1 + + call2 = cache.run_and_cache(some_fn, "test_namespace", kwargs1, kwargs1.keys()) + assert call2 == return_value1 + assert some_fn.call_count == 1 + + kwargs2: Dict[str, Hashable] = {"value": 2} + return_value2 = "another return value" + some_fn.return_value = return_value2 + + call3 = cache.run_and_cache(some_fn, "test_namespace", kwargs2, kwargs2.keys()) + assert call3 == return_value2 + assert some_fn.call_count == 2
"update" caches public suffix list to wrong directory Hi! First off, I love `tldextract`, thanks for building it! The way we use `tldextract` is slightly special, but used to be fully supported by the public API. Our docker containers don't have internet access, so when we build them, we cache the latest public suffix list. When our applications use `tldextract`, we configure it so that it uses the cache, and never needs an internet connection. Upon upgrading to any 3.* version of `tldextract`, I noticed that the cache was no longer being used to look up information from the public suffix list. Problem reproduction steps ---------------------------- First, run the command: `tldextract --update --private_domains` Then create a basic test file: ```python import os from tldextract import TLDExtract extractor = TLDExtract(cache_dir=os.environ["TLDEXTRACT_CACHE"]) extractor("www.google.com") ``` Now, create a conditional breakpoint [here](https://github.com/john-kurkowski/tldextract/blob/master/tldextract/cache.py#L93), where the condition is that `namespace` equals `publicsuffix.org-tlds`. ### Expected behaviour When running the above program, the break point should be hit, but should not throw a `KeyError`. ### Actual behaviour The breakpoint is hit once during the `__call__(…)`, and immediately throws a `KeyError` because it can't find the cache file. Explanation ------------ The method `run_and_cache` accepts a namespace, which is used to calculate the cache file path. But when the file is downloaded, it uses the hardcoded namespace "urls", which places the file in the wrong location. I'll write a PR that fixes this problem.
0.0
86c82c3a9e3e9a2980a39ce8b77e1ad0bdebcc12
[ "tests/test_cache.py::test_run_and_cache" ]
[ "tests/test_cache.py::test_disk_cache", "tests/test_cache.py::test_get_pkg_unique_identifier", "tests/test_cache.py::test_get_cache_dir" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-03-17 16:22:58+00:00
bsd-3-clause
3,280
johnnoone__json-spec-23
diff --git a/src/jsonspec/validators/draft04.py b/src/jsonspec/validators/draft04.py index adb6ee9..6d2fc9c 100644 --- a/src/jsonspec/validators/draft04.py +++ b/src/jsonspec/validators/draft04.py @@ -379,8 +379,8 @@ class Draft04Validator(Validator): for key, dependencies in self.attrs.get('dependencies', {}).items(): if key in obj: if isinstance(dependencies, sequence_types): - for dep in set(dependencies) - set(obj.keys()): - self.fail('Missing property', obj, pointer) + for name in set(dependencies) - set(obj.keys()): + self.fail('Missing property', obj, pointer_join(pointer, name)) # noqa else: dependencies(obj) return obj @@ -596,7 +596,8 @@ class Draft04Validator(Validator): return obj if additionals is False: - self.fail('Forbidden additional properties', obj, pointer) + for name in pending: + self.fail('Forbidden property', obj, pointer_join(pointer, name)) # noqa return obj validator = additionals @@ -609,7 +610,7 @@ class Draft04Validator(Validator): if 'required' in self.attrs: for name in self.attrs['required']: if name not in obj: - self.fail('Missing property', obj, pointer) + self.fail('Missing property', obj, pointer_join(pointer, name)) # noqa return obj def validate_type(self, obj, pointer=None):
johnnoone/json-spec
5ff563d9450d33531b0a45a570d57756b355d618
diff --git a/tests/test_errors2.py b/tests/test_errors2.py index bf5b4f4..0c121e5 100644 --- a/tests/test_errors2.py +++ b/tests/test_errors2.py @@ -41,21 +41,23 @@ scenarii = [ {'#/foo': {'Wrong type'}}, 'integer required'), ({'bar': 'foo'}, - {'#/': {"Missing property"}}, - 'string required'), + {'#/foo': {"Missing property"}}, + 'missing required'), ({'foo': 12, 'baz': None}, - {'#/': {"Missing property"}}, - 'miss a dependencies'), + {'#/bar': {"Missing property"}}, + 'missing dependencies'), ({'foo': 42}, {'#/foo': {"Exceeded maximum"}}, 'too big'), ({'foo': 12, 'baz': None, 'quux': True}, - {'#/': {'Forbidden additional properties', 'Missing property'}}, - 'too big'), + {'#/quux': {'Forbidden property'}, + '#/bar': {'Missing property'}}, + 'missing dependencies, forbidden additional'), ({'foo': 42, 'baz': None, 'quux': True}, - {'#/': {'Forbidden additional properties', 'Missing property'}, + {'#/quux': {'Forbidden property'}, + '#/bar': {'Missing property'}, '#/foo': {'Exceeded maximum'}}, - 'too big'), + 'missing dependencies, forbidden additional, too big'), ]
Add details to Missing Property error Please consider the patch below. In reporting a missing property during validation, this include the name of the property in the ValidationError's reason. (Sorry for the inline code. I haven't figured out how to properly submit a patch. The github's issues editor won't let me attach a *.patch file to this post, and other options I tried get rejected because I don't have permission to contribute.) ``` From 42c4a75835ccb98907c75b7611f550774e3e245f Mon Sep 17 00:00:00 2001 From: Greg Bullock <[email protected]> Date: Wed, 20 Apr 2016 15:30:37 -0700 Subject: [PATCH] Add details to Missing Property error In reporting a missing property during validation, include the name of the property in the ValidationError's reason. --- src/jsonspec/validators/draft04.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/jsonspec/validators/draft04.py b/src/jsonspec/validators/draft04.py index adb6ee9..f6d67bb 100644 --- a/src/jsonspec/validators/draft04.py +++ b/src/jsonspec/validators/draft04.py @@ -380,7 +380,7 @@ class Draft04Validator(Validator): if key in obj: if isinstance(dependencies, sequence_types): for dep in set(dependencies) - set(obj.keys()): - self.fail('Missing property', obj, pointer) + self.fail('Missing property "{}"'.format(dep), obj, pointer) else: dependencies(obj) return obj @@ -609,7 +609,7 @@ class Draft04Validator(Validator): if 'required' in self.attrs: for name in self.attrs['required']: if name not in obj: - self.fail('Missing property', obj, pointer) + self.fail('Missing property "{}"'.format(name), obj, pointer) return obj def validate_type(self, obj, pointer=None): -- 2.7.1.windows.2 ```
0.0
5ff563d9450d33531b0a45a570d57756b355d618
[ "tests/test_errors2.py::test_errors_object[document2-expected2-missing", "tests/test_errors2.py::test_errors_object[document3-expected3-missing", "tests/test_errors2.py::test_errors_object[document5-expected5-missing", "tests/test_errors2.py::test_errors_object[document6-expected6-missing" ]
[ "tests/test_errors2.py::test_errors_object[foo-expected0-object", "tests/test_errors2.py::test_errors_object[document1-expected1-integer", "tests/test_errors2.py::test_errors_object[document4-expected4-too", "tests/test_errors2.py::test_errors_array[foo-expected0-array", "tests/test_errors2.py::test_errors_array[document1-expected1-multiple", "tests/test_errors2.py::test_errors_array[document2-expected2-string", "tests/test_errors2.py::test_errors_array[document3-expected3-string" ]
{ "failed_lite_validators": [ "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2017-01-06 13:19:53+00:00
bsd-3-clause
3,281
johnsyweb__python_sparse_list-14
diff --git a/.travis.yml b/.travis.yml index 1df6b51..08d9ac6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,10 @@ language: python python: - 2.7 - - 3.3 - 3.4 - 3.5 - 3.6 - - 3.7-dev + - 3.7 - nightly - pypy install: pip install -r requirements.txt diff --git a/sparse_list.py b/sparse_list.py index e6a0cd1..abf2648 100644 --- a/sparse_list.py +++ b/sparse_list.py @@ -69,14 +69,26 @@ class SparseList(object): def __delitem__(self, item): if isinstance(item, slice): indices = xrange(*item.indices(self.size)) + elif item < 0: + indices = (self.size + item, ) else: indices = (item, ) - for i in indices: - try: - del self.elements[i] - except KeyError: - pass + offset = 0 + + for k in sorted(self.elements.keys()): + if k < indices[0]: + continue + elif offset < len(indices) and k > indices[offset]: + offset += 1 + + if offset: + self.elements[k - offset] = self.elements[k] + + del self.elements[k] + + self.size -= len(indices) + def __delslice__(self, start, stop): ''' @@ -184,7 +196,6 @@ class SparseList(object): raise IndexError('pop from empty SparseList') value = self[-1] del self[-1] - self.size -= 1 return value def remove(self, value): diff --git a/time_sparse_list.py b/time_sparse_list.py index 429097d..68dadef 100755 --- a/time_sparse_list.py +++ b/time_sparse_list.py @@ -37,5 +37,27 @@ class Benchmark_Retrieval(benchmark.Benchmark): def test_list(self): self.list[100] +class Benchmark_Slice_Deletion(benchmark.Benchmark): + def setUp(self): + self.sparse_list = sparse_list.SparseList(xrange(1000)) + self.list = list(xrange(1000)) + + def test_sparse_list(self): + del self.sparse_list[1::2] + + def test_list(self): + del self.list[1::2] + +class Benchmark_Deletion(benchmark.Benchmark): + def setUp(self): + self.sparse_list = sparse_list.SparseList(xrange(1000)) + self.list = list(xrange(1000)) + + def test_sparse_list(self): + del self.sparse_list[100] + + def test_list(self): + del self.list[100] + if __name__ == '__main__': benchmark.main(format="markdown", numberFormat="%.4g")
johnsyweb/python_sparse_list
a82747eb58797e0c249431ec794059bd7fb8f850
diff --git a/test_sparse_list.py b/test_sparse_list.py index ca22327..dc6feb7 100755 --- a/test_sparse_list.py +++ b/test_sparse_list.py @@ -141,32 +141,32 @@ class TestSparseList(unittest.TestCase): def test_present_item_removal(self): sl = sparse_list.SparseList({0: 1, 4: 1}, 0) del sl[0] - self.assertEqual([0, 0, 0, 0, 1], sl) + self.assertEqual([0, 0, 0, 1], sl) def test_missing_item_removal(self): sl = sparse_list.SparseList({0: 1, 4: 1}, 0) del sl[1] - self.assertEqual([1, 0, 0, 0, 1], sl) + self.assertEqual([1, 0, 0, 1], sl) def test_slice_removal(self): sl = sparse_list.SparseList(xrange(10), None) del sl[3:5] - self.assertEqual([0, 1, 2, None, None, 5, 6, 7, 8, 9], sl) + self.assertEqual([0, 1, 2, 5, 6, 7, 8, 9], sl) def test_unbounded_head_slice_removal(self): sl = sparse_list.SparseList(xrange(10), None) del sl[:3] - self.assertEqual([None, None, None, 3, 4, 5, 6, 7, 8, 9], sl) + self.assertEqual([3, 4, 5, 6, 7, 8, 9], sl) def test_unbounded_tail_slice_removal(self): sl = sparse_list.SparseList(xrange(10), None) del sl[5:] - self.assertEqual([0, 1, 2, 3, 4, None, None, None, None, None], sl) + self.assertEqual([0, 1, 2, 3, 4], sl) def test_stepped_slice_removal(self): sl = sparse_list.SparseList(xrange(6), None) del sl[::2] - self.assertEqual([None, 1, None, 3, None, 5], sl) + self.assertEqual([1, 3, 5], sl) def test_append(self): sl = sparse_list.SparseList(1, 0) @@ -330,23 +330,23 @@ class TestSparseList(unittest.TestCase): def test_set_slice_observes_stop(self): sl = sparse_list.SparseList(4, None) sl[0:2] = [1, 2, 3] - self.assertEquals([1, 2, None, None], sl) + self.assertEqual([1, 2, None, None], sl) def test_set_slice_resizes(self): sl = sparse_list.SparseList(0, None) sl[4:] = [4, 5] - self.assertEquals([None, None, None, None, 4, 5], sl) - self.assertEquals(len(sl), 6) + self.assertEqual([None, None, None, None, 4, 5], sl) + self.assertEqual(len(sl), 6) def test_set_slice_extends_past_end(self): sl = sparse_list.SparseList(5, None) sl[3:] = [6, 7, 8] - self.assertEquals([None, None, None, 6, 7, 8], sl) + self.assertEqual([None, None, None, 6, 7, 8], sl) def test_set_slice_with_step(self): sl = sparse_list.SparseList(6, None) sl[::2] = [1, 2, 3] - self.assertEquals([1, None, 2, None, 3, None], sl) + self.assertEqual([1, None, 2, None, 3, None], sl) if __name__ == '__main__': unittest.main()
Invalid implementation of `del my_list[a:b]` Deleting slices does not behave like Python's lists: ```python >>> standard_list = [1,2,3] >>> del standard_list[:2] >>> standard_list [3] >>> sparse_list = SparseList([1,2,3]) >>> del sparse_list[:2] >>> sparse_list [None, None, 3] ```
0.0
a82747eb58797e0c249431ec794059bd7fb8f850
[ "test_sparse_list.py::TestSparseList::test_missing_item_removal", "test_sparse_list.py::TestSparseList::test_present_item_removal", "test_sparse_list.py::TestSparseList::test_slice_removal", "test_sparse_list.py::TestSparseList::test_stepped_slice_removal", "test_sparse_list.py::TestSparseList::test_unbounded_head_slice_removal" ]
[ "test_sparse_list.py::TestSparseList::test_access_with_negative_index", "test_sparse_list.py::TestSparseList::test_access_with_negative_index_with_no_value", "test_sparse_list.py::TestSparseList::test_append", "test_sparse_list.py::TestSparseList::test_clone", "test_sparse_list.py::TestSparseList::test_concatenation", "test_sparse_list.py::TestSparseList::test_count_default_value", "test_sparse_list.py::TestSparseList::test_count_value", "test_sparse_list.py::TestSparseList::test_equality", "test_sparse_list.py::TestSparseList::test_extend", "test_sparse_list.py::TestSparseList::test_extended_slice", "test_sparse_list.py::TestSparseList::test_extended_slice_with_negative_stop", "test_sparse_list.py::TestSparseList::test_get_out_of_bounds", "test_sparse_list.py::TestSparseList::test_greater_than", "test_sparse_list.py::TestSparseList::test_in_place_concatenation", "test_sparse_list.py::TestSparseList::test_index_absent_default_value", "test_sparse_list.py::TestSparseList::test_index_absent_value", "test_sparse_list.py::TestSparseList::test_index_default_value", "test_sparse_list.py::TestSparseList::test_index_value", "test_sparse_list.py::TestSparseList::test_inequality_left_longer", "test_sparse_list.py::TestSparseList::test_inequality_same_length", "test_sparse_list.py::TestSparseList::test_init_default", "test_sparse_list.py::TestSparseList::test_init_no_default", "test_sparse_list.py::TestSparseList::test_init_non_zero", "test_sparse_list.py::TestSparseList::test_init_zero", "test_sparse_list.py::TestSparseList::test_initialisation_by_dict", "test_sparse_list.py::TestSparseList::test_initialisation_by_dict_with_non_numeric_key", "test_sparse_list.py::TestSparseList::test_initialisation_by_generator", "test_sparse_list.py::TestSparseList::test_initialisation_by_list", "test_sparse_list.py::TestSparseList::test_iteration_empty", "test_sparse_list.py::TestSparseList::test_iteration_populated", "test_sparse_list.py::TestSparseList::test_less_than", "test_sparse_list.py::TestSparseList::test_membership_absent", "test_sparse_list.py::TestSparseList::test_membership_present", "test_sparse_list.py::TestSparseList::test_multiply", "test_sparse_list.py::TestSparseList::test_multiply_in_place", "test_sparse_list.py::TestSparseList::test_pop_empty", "test_sparse_list.py::TestSparseList::test_pop_no_value", "test_sparse_list.py::TestSparseList::test_pop_value", "test_sparse_list.py::TestSparseList::test_push_value", "test_sparse_list.py::TestSparseList::test_random_access_read_absent", "test_sparse_list.py::TestSparseList::test_random_access_read_present", "test_sparse_list.py::TestSparseList::test_random_access_write", "test_sparse_list.py::TestSparseList::test_remove_default_value_does_nothing", "test_sparse_list.py::TestSparseList::test_remove_non_value", "test_sparse_list.py::TestSparseList::test_remove_only_first_value", "test_sparse_list.py::TestSparseList::test_remove_value", "test_sparse_list.py::TestSparseList::test_reversed", "test_sparse_list.py::TestSparseList::test_set_out_of_bounds", "test_sparse_list.py::TestSparseList::test_set_slice_extends_past_end", "test_sparse_list.py::TestSparseList::test_set_slice_observes_stop", "test_sparse_list.py::TestSparseList::test_set_slice_resizes", "test_sparse_list.py::TestSparseList::test_set_slice_with_step", "test_sparse_list.py::TestSparseList::test_slice", "test_sparse_list.py::TestSparseList::test_slice_list_size", "test_sparse_list.py::TestSparseList::test_slice_reversal_empty", "test_sparse_list.py::TestSparseList::test_slice_reversal_full", "test_sparse_list.py::TestSparseList::test_sorted", "test_sparse_list.py::TestSparseList::test_string_representations", "test_sparse_list.py::TestSparseList::test_unbounded_tail_slice_removal" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-07-29 11:30:17+00:00
mit
3,282
johnsyweb__python_sparse_list-17
diff --git a/sparse_list.py b/sparse_list.py index c7f6b56..e759c96 100644 --- a/sparse_list.py +++ b/sparse_list.py @@ -79,6 +79,9 @@ class SparseList(object): else: indices = (item, ) + if not indices: + return + offset = 0 for k in sorted(self.elements.keys()):
johnsyweb/python_sparse_list
21a04541305b929dd8203c491c5d98d27f454e50
diff --git a/test_sparse_list.py b/test_sparse_list.py index d45461f..ff82f80 100755 --- a/test_sparse_list.py +++ b/test_sparse_list.py @@ -176,6 +176,11 @@ class TestSparseList(unittest.TestCase): del sl[::2] self.assertEqual([1, 3, 5], sl) + def test_empty_removal(self): + sl = sparse_list.SparseList(xrange(5), None) + del sl[3:3] + self.assertEqual([0, 1, 2, 3, 4], sl) + def test_append(self): sl = sparse_list.SparseList(1, 0) sl.append(1)
Deleting an empty slice from a sparse list fails ``` sl = sparse_list.SparseList(xrange(5), None) del sl[3:3] ``` throws `IndexError: range object index out of range` whereas it should just leave the list untouched.
0.0
21a04541305b929dd8203c491c5d98d27f454e50
[ "test_sparse_list.py::TestSparseList::test_empty_removal" ]
[ "test_sparse_list.py::TestSparseList::test_access_with_negative_index", "test_sparse_list.py::TestSparseList::test_access_with_negative_index_with_no_value", "test_sparse_list.py::TestSparseList::test_append", "test_sparse_list.py::TestSparseList::test_clone", "test_sparse_list.py::TestSparseList::test_concatenation", "test_sparse_list.py::TestSparseList::test_count_default_value", "test_sparse_list.py::TestSparseList::test_count_value", "test_sparse_list.py::TestSparseList::test_equality", "test_sparse_list.py::TestSparseList::test_extend", "test_sparse_list.py::TestSparseList::test_extended_slice", "test_sparse_list.py::TestSparseList::test_extended_slice_is_sparse_list", "test_sparse_list.py::TestSparseList::test_extended_slice_with_negative_stop", "test_sparse_list.py::TestSparseList::test_get_out_of_bounds", "test_sparse_list.py::TestSparseList::test_greater_than", "test_sparse_list.py::TestSparseList::test_in_place_concatenation", "test_sparse_list.py::TestSparseList::test_index_absent_default_value", "test_sparse_list.py::TestSparseList::test_index_absent_value", "test_sparse_list.py::TestSparseList::test_index_default_value", "test_sparse_list.py::TestSparseList::test_index_value", "test_sparse_list.py::TestSparseList::test_inequality_left_longer", "test_sparse_list.py::TestSparseList::test_inequality_same_length", "test_sparse_list.py::TestSparseList::test_init_default", "test_sparse_list.py::TestSparseList::test_init_no_default", "test_sparse_list.py::TestSparseList::test_init_non_zero", "test_sparse_list.py::TestSparseList::test_init_zero", "test_sparse_list.py::TestSparseList::test_initialisation_by_dict", "test_sparse_list.py::TestSparseList::test_initialisation_by_dict_with_non_numeric_key", "test_sparse_list.py::TestSparseList::test_initialisation_by_generator", "test_sparse_list.py::TestSparseList::test_initialisation_by_list", "test_sparse_list.py::TestSparseList::test_iteration_empty", "test_sparse_list.py::TestSparseList::test_iteration_populated", "test_sparse_list.py::TestSparseList::test_less_than", "test_sparse_list.py::TestSparseList::test_membership_absent", "test_sparse_list.py::TestSparseList::test_membership_present", "test_sparse_list.py::TestSparseList::test_missing_item_removal", "test_sparse_list.py::TestSparseList::test_multiply", "test_sparse_list.py::TestSparseList::test_multiply_in_place", "test_sparse_list.py::TestSparseList::test_pop_empty", "test_sparse_list.py::TestSparseList::test_pop_no_value", "test_sparse_list.py::TestSparseList::test_pop_value", "test_sparse_list.py::TestSparseList::test_present_item_removal", "test_sparse_list.py::TestSparseList::test_push_value", "test_sparse_list.py::TestSparseList::test_random_access_read_absent", "test_sparse_list.py::TestSparseList::test_random_access_read_present", "test_sparse_list.py::TestSparseList::test_random_access_write", "test_sparse_list.py::TestSparseList::test_remove_default_value_does_nothing", "test_sparse_list.py::TestSparseList::test_remove_non_value", "test_sparse_list.py::TestSparseList::test_remove_only_first_value", "test_sparse_list.py::TestSparseList::test_remove_value", "test_sparse_list.py::TestSparseList::test_reversed", "test_sparse_list.py::TestSparseList::test_set_out_of_bounds", "test_sparse_list.py::TestSparseList::test_set_slice_extends_past_end", "test_sparse_list.py::TestSparseList::test_set_slice_observes_stop", "test_sparse_list.py::TestSparseList::test_set_slice_resizes", "test_sparse_list.py::TestSparseList::test_set_slice_with_step", "test_sparse_list.py::TestSparseList::test_slice", "test_sparse_list.py::TestSparseList::test_slice_is_sparse_list", "test_sparse_list.py::TestSparseList::test_slice_list_size", "test_sparse_list.py::TestSparseList::test_slice_removal", "test_sparse_list.py::TestSparseList::test_slice_reversal_empty", "test_sparse_list.py::TestSparseList::test_slice_reversal_full", "test_sparse_list.py::TestSparseList::test_sorted", "test_sparse_list.py::TestSparseList::test_stepped_slice_removal", "test_sparse_list.py::TestSparseList::test_string_representations", "test_sparse_list.py::TestSparseList::test_unbounded_head_slice_removal", "test_sparse_list.py::TestSparseList::test_unbounded_tail_slice_removal" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-19 08:00:40+00:00
mit
3,283
johnthagen__cppcheck-junit-6
diff --git a/cppcheck_junit.py b/cppcheck_junit.py index 87be9a5..9adfd7e 100755 --- a/cppcheck_junit.py +++ b/cppcheck_junit.py @@ -123,8 +123,9 @@ def generate_test_suite(errors): for file_name, errors in errors.items(): test_case = ElementTree.SubElement(test_suite, 'testcase', - name=os.path.relpath(file_name) if file_name else '', - classname='', + name=os.path.relpath( + file_name) if file_name else 'Cppcheck error', + classname='Cppcheck error', time=str(1)) for error in errors: ElementTree.SubElement(test_case, @@ -153,7 +154,7 @@ def generate_single_success_test_suite(): ElementTree.SubElement(test_suite, 'testcase', name='Cppcheck success', - classname='', + classname='Cppcheck success', time=str(1)) return ElementTree.ElementTree(test_suite)
johnthagen/cppcheck-junit
62cf03e4eee1ce80cccc1a9557417fb4b7f436f2
diff --git a/test.py b/test.py index e873733..18c3907 100644 --- a/test.py +++ b/test.py @@ -168,7 +168,8 @@ class GenerateTestSuiteTestCase(unittest.TestCase): self.assertTrue(required_attribute in testsuite_element.attrib.keys()) testcase_element = testsuite_element.find('testcase') - self.assertEqual(testcase_element.get('name'), '') + self.assertEqual(testcase_element.get('name'), 'Cppcheck error') + self.assertEqual(testcase_element.get('classname'), 'Cppcheck error') # Check that test_case is compliant with the spec for required_attribute in self.junit_testcase_attributes: self.assertTrue(required_attribute in testcase_element.attrib.keys()) @@ -207,6 +208,7 @@ class GenerateSingleSuccessTestSuite(unittest.TestCase): testcase_element = testsuite_element.find('testcase') self.assertEqual(testcase_element.get('name'), 'Cppcheck success') + self.assertEqual(testcase_element.get('classname'), 'Cppcheck success') # Check that test_case is compliant with the spec for required_attribute in self.junit_testcase_attributes: self.assertTrue(required_attribute in testcase_element.attrib.keys())
Failing tests not showing up on bamboo. I have added the following steps to my bamboo plan - `cppcheck ... 2> cppcheck-result.xml` - `cppcheck_junit cppcheck-result.xml cppcheck-junit.xml` - JUnit Parser I can see a passing test on the dashboard if cppcheck reports no errrors. If there are errors, however, I can only see that JUnit parser failed. No further information is available. Here are my logs: ```bash build 16-Oct-2017 10:21:36 Running cppcheck: cppcheck --xml --xml-version=2 --enable=all -- project=compile_commands.json 2> cppcheck-result.xml ``` ### cppcheck-result.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <results version="2"> <cppcheck version="1.80"/> <errors> <error id="missingInclude" severity="information" msg="Cppcheck cannot find all the include files (use --check-config for details)" verbose="Cppcheck cannot find all the include files. Cppcheck can check the code without the include files found. But the results will probably be more accurate if all the include files are found. Please check your project&apos;s include directories and add all of them as include directories for Cppcheck. To see what files Cppcheck cannot find use --check-config."/> </errors> </results> ``` ``` build 16-Oct-2017 10:21:36 Running cppcheck_junit: cppcheck_junit cppcheck-result.xml cppcheck-junit.xml ``` ### cppcheck-junit.xml: ```xml <?xml version='1.0' encoding='utf-8'?> <testsuite errors="1" failures="0" hostname="XXX" name="Cppcheck errors" tests="1" time="1" timestamp="2017-10-16T10:21:36.514058"> <testcase classname="" name="" time="1"> <error file="" line="0" message="0: (information) Cppcheck cannot find all the include files (use --check-config for details)" type="" /> </testcase> </testsuite> ``` ``` simple 16-Oct-2017 10:21:36 Finished task 'cppcheck' with result: Success simple 16-Oct-2017 10:21:36 Starting task 'JUnit Parser' of type 'com.atlassian.bamboo.plugins.testresultparser:task.testresultparser.junit' simple 16-Oct-2017 10:21:36 Parsing test results under <path> simple 16-Oct-2017 10:21:36 Failing task since 1 failing test cases were found. simple 16-Oct-2017 10:21:36 Finished task 'JUnit Parser' with result: Failed ```
0.0
62cf03e4eee1ce80cccc1a9557417fb4b7f436f2
[ "test.py::GenerateTestSuiteTestCase::test_missing_file", "test.py::GenerateSingleSuccessTestSuite::test" ]
[ "test.py::ParseCppcheckTestCase::test_all", "test.py::ParseCppcheckTestCase::test_bad", "test.py::ParseCppcheckTestCase::test_bad_large", "test.py::ParseCppcheckTestCase::test_file_not_found", "test.py::ParseCppcheckTestCase::test_good", "test.py::ParseCppcheckTestCase::test_malformed", "test.py::ParseCppcheckTestCase::test_missing_include_no_location_element", "test.py::ParseCppcheckTestCase::test_no_location_element", "test.py::ParseCppcheckTestCase::test_xml_version_1", "test.py::GenerateTestSuiteTestCase::test_single", "test.py::ParseArgumentsTestCase::test_no_arguments" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-10-17 21:53:41+00:00
mit
3,284
joke2k__django-environ-174
diff --git a/environ/environ.py b/environ/environ.py index 9a9f906..a1febab 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -422,8 +422,11 @@ class Env(object): if engine: config['ENGINE'] = engine - if url.scheme in Env.DB_SCHEMES: - config['ENGINE'] = Env.DB_SCHEMES[url.scheme] + else: + config['ENGINE'] = url.scheme + + if config['ENGINE'] in Env.DB_SCHEMES: + config['ENGINE'] = Env.DB_SCHEMES[config['ENGINE']] if not config.get('ENGINE', False): warnings.warn("Engine not recognized from url: {0}".format(config))
joke2k/django-environ
99d23c94769710009bf6630ac981e5ed0cdc461c
diff --git a/environ/test.py b/environ/test.py index 2a9e192..92f5c0f 100644 --- a/environ/test.py +++ b/environ/test.py @@ -18,6 +18,7 @@ class BaseTests(unittest.TestCase): SQLITE = 'sqlite:////full/path/to/your/database/file.sqlite' ORACLE_TNS = 'oracle://user:password@sid/' ORACLE = 'oracle://user:password@host:1521/sid' + CUSTOM_BACKEND = 'custom.backend://user:[email protected]:5430/database' REDSHIFT = 'redshift://user:password@examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev' MEMCACHE = 'memcache://127.0.0.1:11211' REDIS = 'rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=secret' @@ -52,6 +53,7 @@ class BaseTests(unittest.TestCase): DATABASE_ORACLE_URL=cls.ORACLE, DATABASE_ORACLE_TNS_URL=cls.ORACLE_TNS, DATABASE_REDSHIFT_URL=cls.REDSHIFT, + DATABASE_CUSTOM_BACKEND_URL=cls.CUSTOM_BACKEND, CACHE_URL=cls.MEMCACHE, CACHE_REDIS=cls.REDIS, EMAIL_URL=cls.EMAIL, @@ -220,6 +222,14 @@ class EnvTests(BaseTests): self.assertEqual(sqlite_config['ENGINE'], 'django.db.backends.sqlite3') self.assertEqual(sqlite_config['NAME'], '/full/path/to/your/database/file.sqlite') + custom_backend_config = self.env.db('DATABASE_CUSTOM_BACKEND_URL') + self.assertEqual(custom_backend_config['ENGINE'], 'custom.backend') + self.assertEqual(custom_backend_config['NAME'], 'database') + self.assertEqual(custom_backend_config['HOST'], 'example.com') + self.assertEqual(custom_backend_config['USER'], 'user') + self.assertEqual(custom_backend_config['PASSWORD'], 'password') + self.assertEqual(custom_backend_config['PORT'], 5430) + def test_cache_url_value(self): cache_config = self.env.cache_url() diff --git a/environ/test_env.txt b/environ/test_env.txt index c0112c3..a891138 100644 --- a/environ/test_env.txt +++ b/environ/test_env.txt @@ -28,4 +28,5 @@ INT_TUPLE=(42,33) DATABASE_ORACLE_TNS_URL=oracle://user:password@sid DATABASE_ORACLE_URL=oracle://user:password@host:1521/sid DATABASE_REDSHIFT_URL=redshift://user:password@examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev -export EXPORTED_VAR="exported var" \ No newline at end of file +DATABASE_CUSTOM_BACKEND_URL=custom.backend://user:[email protected]:5430/database +export EXPORTED_VAR="exported var"
Database url.scheme only works for built-in schemes (backends) I haven't find any issue related to this topic, so sorry in advance if it is something that has been already discussed. According to this code inside ```Env.db_url_config()```: ``` python class Env(object): # [...] @classmethod def db_url_config(cls, url, engine=None): # [...] if engine: config['ENGINE'] = engine if url.scheme in Env.DB_SCHEMES: config['ENGINE'] = Env.DB_SCHEMES[url.scheme] if not config.get('ENGINE', False): warnings.warn("Engine not recognized from url: {0}".format(config)) return {} ``` Actually, the only way to set up a custom backend for a database is using the ```engine``` parameter when we call ```Env.db()``` at the same time that we put an invalid ```url.scheme``` in ```DATABASE_URL``` (what is weird) or we put our custom one again (that it is going to be considered invalid anyway because it doesn't exist in ```Env.DB_SCHEMES```), what is redundant. ``` python import environ env = environ.Env() env.db('DATABASE_URL', engine='path.to.my.custom.backend') # Having DATABASE_URL=path.to.my.custom.backend://user:password@host:post/database ``` This code fix this situation, simply letting pass the custom scheme as a valid one if it doesn't match one of the built-in ```DB_SCHEMES```. ``` python if url.scheme in Env.DB_SCHEMES: config['ENGINE'] = Env.DB_SCHEMES[url.scheme] else: config['ENGINE'] = url.scheme ```
0.0
99d23c94769710009bf6630ac981e5ed0cdc461c
[ "environ/test.py::EnvTests::test_db_url_value", "environ/test.py::FileEnvTests::test_db_url_value", "environ/test.py::SubClassTests::test_db_url_value" ]
[ "environ/test.py::EnvTests::test_bool_false", "environ/test.py::EnvTests::test_bool_true", "environ/test.py::EnvTests::test_bytes", "environ/test.py::EnvTests::test_cache_url_value", "environ/test.py::EnvTests::test_contains", "environ/test.py::EnvTests::test_dict_parsing", "environ/test.py::EnvTests::test_dict_value", "environ/test.py::EnvTests::test_email_url_value", "environ/test.py::EnvTests::test_empty_list", "environ/test.py::EnvTests::test_exported", "environ/test.py::EnvTests::test_float", "environ/test.py::EnvTests::test_int", "environ/test.py::EnvTests::test_int_list", "environ/test.py::EnvTests::test_int_tuple", "environ/test.py::EnvTests::test_int_with_none_default", "environ/test.py::EnvTests::test_json_value", "environ/test.py::EnvTests::test_not_present_with_default", "environ/test.py::EnvTests::test_not_present_without_default", "environ/test.py::EnvTests::test_path", "environ/test.py::EnvTests::test_proxied_value", "environ/test.py::EnvTests::test_str", "environ/test.py::EnvTests::test_str_list_with_spaces", "environ/test.py::EnvTests::test_url_encoded_parts", "environ/test.py::EnvTests::test_url_value", "environ/test.py::FileEnvTests::test_bool_false", "environ/test.py::FileEnvTests::test_bool_true", "environ/test.py::FileEnvTests::test_bytes", "environ/test.py::FileEnvTests::test_cache_url_value", "environ/test.py::FileEnvTests::test_contains", "environ/test.py::FileEnvTests::test_dict_parsing", "environ/test.py::FileEnvTests::test_dict_value", "environ/test.py::FileEnvTests::test_email_url_value", "environ/test.py::FileEnvTests::test_empty_list", "environ/test.py::FileEnvTests::test_exported", "environ/test.py::FileEnvTests::test_float", "environ/test.py::FileEnvTests::test_int", "environ/test.py::FileEnvTests::test_int_list", "environ/test.py::FileEnvTests::test_int_tuple", "environ/test.py::FileEnvTests::test_int_with_none_default", "environ/test.py::FileEnvTests::test_json_value", "environ/test.py::FileEnvTests::test_not_present_with_default", "environ/test.py::FileEnvTests::test_not_present_without_default", "environ/test.py::FileEnvTests::test_path", "environ/test.py::FileEnvTests::test_proxied_value", "environ/test.py::FileEnvTests::test_str", "environ/test.py::FileEnvTests::test_str_list_with_spaces", "environ/test.py::FileEnvTests::test_url_encoded_parts", "environ/test.py::FileEnvTests::test_url_value", "environ/test.py::SubClassTests::test_bool_false", "environ/test.py::SubClassTests::test_bool_true", "environ/test.py::SubClassTests::test_bytes", "environ/test.py::SubClassTests::test_cache_url_value", "environ/test.py::SubClassTests::test_contains", "environ/test.py::SubClassTests::test_dict_parsing", "environ/test.py::SubClassTests::test_dict_value", "environ/test.py::SubClassTests::test_email_url_value", "environ/test.py::SubClassTests::test_empty_list", "environ/test.py::SubClassTests::test_exported", "environ/test.py::SubClassTests::test_float", "environ/test.py::SubClassTests::test_int", "environ/test.py::SubClassTests::test_int_list", "environ/test.py::SubClassTests::test_int_tuple", "environ/test.py::SubClassTests::test_int_with_none_default", "environ/test.py::SubClassTests::test_json_value", "environ/test.py::SubClassTests::test_not_present_with_default", "environ/test.py::SubClassTests::test_not_present_without_default", "environ/test.py::SubClassTests::test_path", "environ/test.py::SubClassTests::test_proxied_value", "environ/test.py::SubClassTests::test_singleton_environ", "environ/test.py::SubClassTests::test_str", "environ/test.py::SubClassTests::test_str_list_with_spaces", "environ/test.py::SubClassTests::test_url_encoded_parts", "environ/test.py::SubClassTests::test_url_value", "environ/test.py::SchemaEnvTests::test_schema", "environ/test.py::DatabaseTestSuite::test_cleardb_parsing", "environ/test.py::DatabaseTestSuite::test_database_ldap_url", "environ/test.py::DatabaseTestSuite::test_database_options_parsing", "environ/test.py::DatabaseTestSuite::test_empty_sqlite_url", "environ/test.py::DatabaseTestSuite::test_memory_sqlite_url", "environ/test.py::DatabaseTestSuite::test_mysql_gis_parsing", "environ/test.py::DatabaseTestSuite::test_mysql_no_password", "environ/test.py::DatabaseTestSuite::test_postgis_parsing", "environ/test.py::DatabaseTestSuite::test_postgres_parsing", "environ/test.py::CacheTestSuite::test_custom_backend", "environ/test.py::CacheTestSuite::test_dbcache_parsing", "environ/test.py::CacheTestSuite::test_dummycache_parsing", "environ/test.py::CacheTestSuite::test_filecache_parsing", "environ/test.py::CacheTestSuite::test_filecache_windows_parsing", "environ/test.py::CacheTestSuite::test_locmem_named_parsing", "environ/test.py::CacheTestSuite::test_locmem_parsing", "environ/test.py::CacheTestSuite::test_memcache_multiple_parsing", "environ/test.py::CacheTestSuite::test_memcache_parsing", "environ/test.py::CacheTestSuite::test_memcache_pylib_parsing", "environ/test.py::CacheTestSuite::test_memcache_socket_parsing", "environ/test.py::CacheTestSuite::test_options_parsing", "environ/test.py::CacheTestSuite::test_redis_multi_location_parsing", "environ/test.py::CacheTestSuite::test_redis_parsing", "environ/test.py::CacheTestSuite::test_redis_socket_parsing", "environ/test.py::CacheTestSuite::test_redis_socket_url", "environ/test.py::CacheTestSuite::test_redis_with_password_parsing", "environ/test.py::SearchTestSuite::test_common_args_parsing", "environ/test.py::SearchTestSuite::test_elasticsearch_parsing", "environ/test.py::SearchTestSuite::test_simple_parsing", "environ/test.py::SearchTestSuite::test_solr_multicore_parsing", "environ/test.py::SearchTestSuite::test_solr_parsing", "environ/test.py::SearchTestSuite::test_whoosh_parsing", "environ/test.py::SearchTestSuite::test_xapian_parsing", "environ/test.py::EmailTests::test_smtp_parsing", "environ/test.py::PathTests::test_comparison", "environ/test.py::PathTests::test_path_class", "environ/test.py::PathTests::test_required_path" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-02-15 17:50:14+00:00
mit
3,285
joke2k__django-environ-325
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0e4bd83..335a267 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -17,12 +17,13 @@ Added `#314 <https://github.com/joke2k/django-environ/pull/314>`_. - Provided ability to use ``bytes`` or ``str`` as a default value for ``Env.bytes()``. - Fixed +++++ -- Fixed links in the documentation +- Fixed links in the documentation. - Use default option in ``Env.bytes()`` `#206 <https://github.com/joke2k/django-environ/pull/206>`_. +- Safely evaluate a string containing an invalid Python literal + `#200 <https://github.com/joke2k/django-environ/issues/200>`_. Changed +++++++ diff --git a/environ/environ.py b/environ/environ.py index 0b97c5e..0267add 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -44,7 +44,7 @@ def _cast(value): # https://docs.python.org/3/library/ast.html#ast.literal_eval try: return ast.literal_eval(value) - except ValueError: + except (ValueError, SyntaxError): return value
joke2k/django-environ
192b813fc97fd395cb432eba5d0064a73d4ab9f0
diff --git a/tests/test_cache.py b/tests/test_cache.py index 13077a5..42c72bb 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -149,3 +149,80 @@ def test_unknown_backend(): def test_empty_url_is_mapped_to_empty_config(): assert Env.cache_url_config('') == {} assert Env.cache_url_config(None) == {} + + [email protected]( + 'chars', + ['!', '$', '&', "'", '(', ')', '*', '+', ';', '=', '-', '.', '-v1.2'] +) +def test_cache_url_password_using_sub_delims(monkeypatch, chars): + """Ensure CACHE_URL passwords may contains some unsafe characters. + + See: https://github.com/joke2k/django-environ/issues/200 for details.""" + url = 'rediss://enigma:secret{}@ondigitalocean.com:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + result = env.cache_url_config(url) + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + url = 'rediss://enigma:sec{}[email protected]:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + result = env.cache_url_config(url) + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + url = 'rediss://enigma:{}[email protected]:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + result = env.cache_url_config(url) + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + [email protected]( + 'chars', ['%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%2C'] +) +def test_cache_url_password_using_gen_delims(monkeypatch, chars): + """Ensure CACHE_URL passwords may contains %-encoded characters. + + See: https://github.com/joke2k/django-environ/issues/200 for details.""" + url = 'rediss://enigma:secret{}@ondigitalocean.com:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + url = 'rediss://enigma:sec{}[email protected]:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url + + url = 'rediss://enigma:{}[email protected]:25061/2'.format(chars) + monkeypatch.setenv('CACHE_URL', url) + env = Env() + + result = env.cache() + assert result['BACKEND'] == 'django_redis.cache.RedisCache' + assert result['LOCATION'] == url diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..523a72d --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,22 @@ +# This file is part of the django-environ. +# +# Copyright (c) 2021, Serghei Iakovlev <[email protected]> +# Copyright (c) 2013-2021, Daniele Faraglia <[email protected]> +# +# For the full copyright and license information, please view +# the LICENSE.txt file that was distributed with this source code. + +import pytest +from environ.environ import _cast + + [email protected]( + 'literal', + ['anything-', 'anything*', '*anything', 'anything.', + 'anything.1', '(anything', 'anything-v1.2', 'anything-1.2', 'anything='] +) +def test_cast(literal): + """Safely evaluate a string containing an invalid Python literal. + + See https://github.com/joke2k/django-environ/issues/200 for details.""" + assert _cast(literal) == literal
Error with CACHE_URL passwords that end with '=' This is somewhat similar to #194. A cache password that ends with the `=` character raises an error when calling `env.cache`. Even escaping it (`%3D`) will not work. It looks like the `cast` method works by trying to just convert to a value and if that fails with a `ValueError`, it assumes the value is string ([see code](https://github.com/joke2k/django-environ/blob/20a1b50/environ/environ.py#L27-L30)). However, a string that ends in a `=` will throw a `SyntaxError` instead of a `ValueError`: >>> import ast >>> ast.literal_eval('mypassword=') Traceback (most recent call last): ... SyntaxError: unexpected EOF while parsing If you think the solution is just to catch a `SyntaxError` in addition to a `ValueError`, I'm happy to make a PR. Normally I'd just change the password but on Azure the generated cache passwords always end with a `=` for some reason.
0.0
192b813fc97fd395cb432eba5d0064a73d4ab9f0
[ "tests/test_utils.py::test_cast[anything-]", "tests/test_utils.py::test_cast[anything*]", "tests/test_utils.py::test_cast[*anything]", "tests/test_utils.py::test_cast[anything.]", "tests/test_utils.py::test_cast[anything.1]", "tests/test_utils.py::test_cast[(anything]", "tests/test_utils.py::test_cast[anything-v1.2]", "tests/test_utils.py::test_cast[anything=]" ]
[ "tests/test_cache.py::test_base_options_parsing", "tests/test_cache.py::test_cache_parsing[dbcache]", "tests/test_cache.py::test_cache_parsing[filecache]", "tests/test_cache.py::test_cache_parsing[filecache_win]", "tests/test_cache.py::test_cache_parsing[locmemcache_empty]", "tests/test_cache.py::test_cache_parsing[locmemcache]", "tests/test_cache.py::test_cache_parsing[dummycache]", "tests/test_cache.py::test_cache_parsing[rediss]", "tests/test_cache.py::test_cache_parsing[redis_with_password]", "tests/test_cache.py::test_cache_parsing[redis_multiple]", "tests/test_cache.py::test_cache_parsing[redis_socket]", "tests/test_cache.py::test_cache_parsing[memcached_socket]", "tests/test_cache.py::test_cache_parsing[memcached_multiple]", "tests/test_cache.py::test_cache_parsing[memcached]", "tests/test_cache.py::test_cache_parsing[pylibmccache]", "tests/test_cache.py::test_redis_parsing", "tests/test_cache.py::test_redis_socket_url", "tests/test_cache.py::test_options_parsing", "tests/test_cache.py::test_custom_backend", "tests/test_cache.py::test_unknown_backend", "tests/test_cache.py::test_empty_url_is_mapped_to_empty_config", "tests/test_cache.py::test_cache_url_password_using_sub_delims[!]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[$]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[&]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[']", "tests/test_cache.py::test_cache_url_password_using_sub_delims[(]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[)]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[*]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[+]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[;]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[=]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[-]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[.]", "tests/test_cache.py::test_cache_url_password_using_sub_delims[-v1.2]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%3A]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%2F]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%3F]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%23]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%5B]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%5D]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%40]", "tests/test_cache.py::test_cache_url_password_using_gen_delims[%2C]", "tests/test_utils.py::test_cast[anything-1.2]" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-09-07 09:59:29+00:00
mit
3,286
joke2k__django-environ-329
diff --git a/docs/tips.rst b/docs/tips.rst index ab3161d..cff0d86 100644 --- a/docs/tips.rst +++ b/docs/tips.rst @@ -195,10 +195,13 @@ Values that being with a ``$`` may be interpolated. Pass ``interpolate=True`` to FOO +Reading env files +================= + .. _multiple-env-files-label: Multiple env files -================== +------------------ There is an ability point to the .env file location using an environment variable. This feature may be convenient in a production systems with a @@ -227,7 +230,7 @@ while ``./manage.py runserver`` uses ``.env``. Using Path objects when reading env -=================================== +----------------------------------- It is possible to use of ``pathlib.Path`` objects when reading environment file from the filesystem: @@ -249,3 +252,16 @@ It is possible to use of ``pathlib.Path`` objects when reading environment file env.read_env(os.path.join(BASE_DIR, '.env')) env.read_env(pathlib.Path(str(BASE_DIR)).joinpath('.env')) env.read_env(pathlib.Path(str(BASE_DIR)) / '.env') + + +Overwriting existing environment values from env files +------------------------------------------------------ + +If you want variables set within your env files to take higher precidence than +an existing set environment variable, use the ``overwrite=True`` argument of +``read_env``. For example: + +.. code-block:: python + + env = environ.Env() + env.read_env(BASE_DIR('.env'), overwrite=True) diff --git a/environ/environ.py b/environ/environ.py index 83642ff..a38324f 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -31,10 +31,10 @@ from .fileaware_mapping import FileAwareMapping try: from os import PathLike +except ImportError: # Python 3.5 support + from pathlib import PurePath as PathLike - Openable = (str, PathLike) -except ImportError: - Openable = (str,) +Openable = (str, PathLike) logger = logging.getLogger(__name__) @@ -732,13 +732,16 @@ class Env: return config @classmethod - def read_env(cls, env_file=None, **overrides): + def read_env(cls, env_file=None, overwrite=False, **overrides): """Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find the dotenv in the same directory as the file that called read_env. + By default, won't overwrite any existing environment variables. You can + enable this behaviour by setting ``overwrite=True``. + Refs: - https://wellfire.co/learn/easier-12-factor-django - https://gist.github.com/bennylope/2999704 @@ -757,7 +760,8 @@ class Env: try: if isinstance(env_file, Openable): - with open(env_file) as f: + # Python 3.5 support (wrap path with str). + with open(str(env_file)) as f: content = f.read() else: with env_file as f: @@ -788,13 +792,18 @@ class Env: if m3: val = re.sub(r'\\(.)', _keep_escaped_format_characters, m3.group(1)) - cls.ENVIRON.setdefault(key, str(val)) + overrides[key] = str(val) else: logger.warn('Invalid line: %s', line) - # set defaults + if overwrite: + def set_environ(key, value): + cls.ENVIRON[key] = value + else: + set_environ = cls.ENVIRON.setdefault + for key, value in overrides.items(): - cls.ENVIRON.setdefault(key, value) + set_environ(key, value) class FileAwareEnv(Env):
joke2k/django-environ
cbbd6d6d454352e4ff712947502466a84dd8faef
diff --git a/tests/test_env.py b/tests/test_env.py index afa6470..acd8dc4 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -152,6 +152,7 @@ class TestEnv: [ ('a=1', dict, {'a': '1'}), ('a=1', dict(value=int), {'a': 1}), + ('a=1', dict(value=float), {'a': 1.0}), ('a=1,2,3', dict(value=[str]), {'a': ['1', '2', '3']}), ('a=1,2,3', dict(value=[int]), {'a': [1, 2, 3]}), ('a=1;b=1.1,2.2;c=3', dict(value=int, cast=dict(b=[float])), @@ -163,6 +164,7 @@ class TestEnv: ids=[ 'dict', 'dict_int', + 'dict_float', 'dict_str_list', 'dict_int_list', 'dict_int_cast', @@ -307,34 +309,43 @@ class TestFileEnv(TestEnv): PATH_VAR=Path(__file__, is_file=True).__root__ ) - def test_read_env_path_like(self): + def create_temp_env_file(self, name): import pathlib import tempfile - path_like = (pathlib.Path(tempfile.gettempdir()) / 'test_pathlib.env') + env_file_path = (pathlib.Path(tempfile.gettempdir()) / name) try: - path_like.unlink() + env_file_path.unlink() except FileNotFoundError: pass - assert not path_like.exists() + assert not env_file_path.exists() + return env_file_path + + def test_read_env_path_like(self): + env_file_path = self.create_temp_env_file('test_pathlib.env') env_key = 'SECRET' env_val = 'enigma' env_str = env_key + '=' + env_val # open() doesn't take path-like on Python < 3.6 - try: - with open(path_like, 'w', encoding='utf-8') as f: - f.write(env_str + '\n') - except TypeError: - return + with open(str(env_file_path), 'w', encoding='utf-8') as f: + f.write(env_str + '\n') - assert path_like.exists() - self.env.read_env(path_like) + self.env.read_env(env_file_path) assert env_key in self.env.ENVIRON assert self.env.ENVIRON[env_key] == env_val + @pytest.mark.parametrize("overwrite", [True, False]) + def test_existing_overwrite(self, overwrite): + env_file_path = self.create_temp_env_file('test_existing.env') + with open(str(env_file_path), 'w') as f: + f.write("EXISTING=b") + self.env.ENVIRON['EXISTING'] = "a" + self.env.read_env(env_file_path, overwrite=overwrite) + assert self.env.ENVIRON["EXISTING"] == ("b" if overwrite else "a") + class TestSubClass(TestEnv): def setup_method(self, method):
Won't update environ key if it already set imagine a case when we need to update some of the production settings in `production.py` base on `base.py`. ```py from .base import * environ.Env.read_env(env_file="/etc/<app>/.env") DATABASES = { # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found "default": env.db(), } CELERY_BROKER_URL = env("REDIS_URL") CELERY_RESULT_BACKEND = env("REDIS_URL") CACHEOPS_REDIS = env("CACHE_URL") ... ``` since code used `setdefault` it will ignore to update that in `django-environ/environ/environ.py` ```py # line 654 cls.ENVIRON.setdefault(key, str(val)) ```
0.0
cbbd6d6d454352e4ff712947502466a84dd8faef
[ "tests/test_env.py::TestFileEnv::test_existing_overwrite[True]" ]
[ "tests/test_env.py::TestEnv::test_not_present_with_default", "tests/test_env.py::TestEnv::test_not_present_without_default", "tests/test_env.py::TestEnv::test_contains", "tests/test_env.py::TestEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_int", "tests/test_env.py::TestEnv::test_int_with_none_default", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestEnv::test_proxied_value", "tests/test_env.py::TestEnv::test_int_list", "tests/test_env.py::TestEnv::test_int_tuple", "tests/test_env.py::TestEnv::test_str_list_with_spaces", "tests/test_env.py::TestEnv::test_empty_list", "tests/test_env.py::TestEnv::test_dict_value", "tests/test_env.py::TestEnv::test_dict_parsing[dict]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestEnv::test_url_value", "tests/test_env.py::TestEnv::test_url_encoded_parts", "tests/test_env.py::TestEnv::test_db_url_value[postgres]", "tests/test_env.py::TestEnv::test_db_url_value[mysql]", "tests/test_env.py::TestEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestEnv::test_db_url_value[oracle]", "tests/test_env.py::TestEnv::test_db_url_value[redshift]", "tests/test_env.py::TestEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestEnv::test_db_url_value[custom]", "tests/test_env.py::TestEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestEnv::test_cache_url_value[redis]", "tests/test_env.py::TestEnv::test_email_url_value", "tests/test_env.py::TestEnv::test_json_value", "tests/test_env.py::TestEnv::test_path", "tests/test_env.py::TestEnv::test_smart_cast", "tests/test_env.py::TestEnv::test_exported", "tests/test_env.py::TestFileEnv::test_not_present_with_default", "tests/test_env.py::TestFileEnv::test_not_present_without_default", "tests/test_env.py::TestFileEnv::test_contains", "tests/test_env.py::TestFileEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestFileEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_int", "tests/test_env.py::TestFileEnv::test_int_with_none_default", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestFileEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestFileEnv::test_proxied_value", "tests/test_env.py::TestFileEnv::test_int_list", "tests/test_env.py::TestFileEnv::test_int_tuple", "tests/test_env.py::TestFileEnv::test_str_list_with_spaces", "tests/test_env.py::TestFileEnv::test_empty_list", "tests/test_env.py::TestFileEnv::test_dict_value", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestFileEnv::test_url_value", "tests/test_env.py::TestFileEnv::test_url_encoded_parts", "tests/test_env.py::TestFileEnv::test_db_url_value[postgres]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle]", "tests/test_env.py::TestFileEnv::test_db_url_value[redshift]", "tests/test_env.py::TestFileEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestFileEnv::test_db_url_value[custom]", "tests/test_env.py::TestFileEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestFileEnv::test_cache_url_value[redis]", "tests/test_env.py::TestFileEnv::test_email_url_value", "tests/test_env.py::TestFileEnv::test_json_value", "tests/test_env.py::TestFileEnv::test_path", "tests/test_env.py::TestFileEnv::test_smart_cast", "tests/test_env.py::TestFileEnv::test_exported", "tests/test_env.py::TestFileEnv::test_read_env_path_like", "tests/test_env.py::TestFileEnv::test_existing_overwrite[False]", "tests/test_env.py::TestSubClass::test_not_present_with_default", "tests/test_env.py::TestSubClass::test_not_present_without_default", "tests/test_env.py::TestSubClass::test_contains", "tests/test_env.py::TestSubClass::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestSubClass::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_int", "tests/test_env.py::TestSubClass::test_int_with_none_default", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestSubClass::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestSubClass::test_proxied_value", "tests/test_env.py::TestSubClass::test_int_list", "tests/test_env.py::TestSubClass::test_int_tuple", "tests/test_env.py::TestSubClass::test_str_list_with_spaces", "tests/test_env.py::TestSubClass::test_empty_list", "tests/test_env.py::TestSubClass::test_dict_value", "tests/test_env.py::TestSubClass::test_dict_parsing[dict]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_float]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestSubClass::test_url_value", "tests/test_env.py::TestSubClass::test_url_encoded_parts", "tests/test_env.py::TestSubClass::test_db_url_value[postgres]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql_gis]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle_tns]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle]", "tests/test_env.py::TestSubClass::test_db_url_value[redshift]", "tests/test_env.py::TestSubClass::test_db_url_value[sqlite]", "tests/test_env.py::TestSubClass::test_db_url_value[custom]", "tests/test_env.py::TestSubClass::test_cache_url_value[memcached]", "tests/test_env.py::TestSubClass::test_cache_url_value[redis]", "tests/test_env.py::TestSubClass::test_email_url_value", "tests/test_env.py::TestSubClass::test_json_value", "tests/test_env.py::TestSubClass::test_path", "tests/test_env.py::TestSubClass::test_smart_cast", "tests/test_env.py::TestSubClass::test_exported", "tests/test_env.py::TestSubClass::test_singleton_environ" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-09-24 04:49:00+00:00
mit
3,287
joke2k__django-environ-332
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 47d9673..c46d3ff 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -16,6 +16,8 @@ Added - Added option to override existing variables with ``read_env`` `#103 <https://github.com/joke2k/django-environ/issues/103>`_, `#249 <https://github.com/joke2k/django-environ/issues/249>`_. +- Added support for empty var with None default value + `#209 <https://github.com/joke2k/django-environ/issues/209>`_. Fixed diff --git a/environ/environ.py b/environ/environ.py index b678096..7cb2040 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -375,6 +375,8 @@ class Env: not isinstance(default, NoValue): cast = type(default) + value = None if default is None and value == '' else value + if value != default or (parse_default and value): value = self.parse_value(value, cast)
joke2k/django-environ
972b10392d42bf3688829c129b1cca6cfb558aa5
diff --git a/tests/test_env.py b/tests/test_env.py index acd8dc4..55147fb 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -86,6 +86,7 @@ class TestEnv: def test_int_with_none_default(self): assert self.env('NOT_PRESENT_VAR', cast=int, default=None) is None + assert self.env('EMPTY_INT_VAR', cast=int, default=None) is None @pytest.mark.parametrize( 'value,variable', diff --git a/tests/test_env.txt b/tests/test_env.txt index befeed7..a179a48 100644 --- a/tests/test_env.txt +++ b/tests/test_env.txt @@ -29,6 +29,7 @@ FLOAT_STRANGE_VAR2=123.420.333,3 FLOAT_NEGATIVE_VAR=-1.0 PROXIED_VAR=$STR_VAR EMPTY_LIST= +EMPTY_INT_VAR= INT_VAR=42 STR_LIST_WITH_SPACES= foo, bar STR_VAR=bar
Support for SOME_VAR=(int, None)? Is there a way to tell environ that `SOME_VAR=` in an env file is fine, and should lead to SOME_VAR being assigned the pythonic `None` when using the `SOME_VAR=(int, None)` format?
0.0
972b10392d42bf3688829c129b1cca6cfb558aa5
[ "tests/test_env.py::TestFileEnv::test_int_with_none_default" ]
[ "tests/test_env.py::TestEnv::test_not_present_with_default", "tests/test_env.py::TestEnv::test_not_present_without_default", "tests/test_env.py::TestEnv::test_contains", "tests/test_env.py::TestEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_int", "tests/test_env.py::TestEnv::test_int_with_none_default", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestEnv::test_proxied_value", "tests/test_env.py::TestEnv::test_int_list", "tests/test_env.py::TestEnv::test_int_tuple", "tests/test_env.py::TestEnv::test_str_list_with_spaces", "tests/test_env.py::TestEnv::test_empty_list", "tests/test_env.py::TestEnv::test_dict_value", "tests/test_env.py::TestEnv::test_dict_parsing[dict]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestEnv::test_url_value", "tests/test_env.py::TestEnv::test_url_encoded_parts", "tests/test_env.py::TestEnv::test_db_url_value[postgres]", "tests/test_env.py::TestEnv::test_db_url_value[mysql]", "tests/test_env.py::TestEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestEnv::test_db_url_value[oracle]", "tests/test_env.py::TestEnv::test_db_url_value[redshift]", "tests/test_env.py::TestEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestEnv::test_db_url_value[custom]", "tests/test_env.py::TestEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestEnv::test_cache_url_value[redis]", "tests/test_env.py::TestEnv::test_email_url_value", "tests/test_env.py::TestEnv::test_json_value", "tests/test_env.py::TestEnv::test_path", "tests/test_env.py::TestEnv::test_smart_cast", "tests/test_env.py::TestEnv::test_exported", "tests/test_env.py::TestFileEnv::test_not_present_with_default", "tests/test_env.py::TestFileEnv::test_not_present_without_default", "tests/test_env.py::TestFileEnv::test_contains", "tests/test_env.py::TestFileEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestFileEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_int", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestFileEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestFileEnv::test_proxied_value", "tests/test_env.py::TestFileEnv::test_int_list", "tests/test_env.py::TestFileEnv::test_int_tuple", "tests/test_env.py::TestFileEnv::test_str_list_with_spaces", "tests/test_env.py::TestFileEnv::test_empty_list", "tests/test_env.py::TestFileEnv::test_dict_value", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestFileEnv::test_url_value", "tests/test_env.py::TestFileEnv::test_url_encoded_parts", "tests/test_env.py::TestFileEnv::test_db_url_value[postgres]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle]", "tests/test_env.py::TestFileEnv::test_db_url_value[redshift]", "tests/test_env.py::TestFileEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestFileEnv::test_db_url_value[custom]", "tests/test_env.py::TestFileEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestFileEnv::test_cache_url_value[redis]", "tests/test_env.py::TestFileEnv::test_email_url_value", "tests/test_env.py::TestFileEnv::test_json_value", "tests/test_env.py::TestFileEnv::test_path", "tests/test_env.py::TestFileEnv::test_smart_cast", "tests/test_env.py::TestFileEnv::test_exported", "tests/test_env.py::TestFileEnv::test_read_env_path_like", "tests/test_env.py::TestFileEnv::test_existing_overwrite[True]", "tests/test_env.py::TestFileEnv::test_existing_overwrite[False]", "tests/test_env.py::TestSubClass::test_not_present_with_default", "tests/test_env.py::TestSubClass::test_not_present_without_default", "tests/test_env.py::TestSubClass::test_contains", "tests/test_env.py::TestSubClass::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestSubClass::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_int", "tests/test_env.py::TestSubClass::test_int_with_none_default", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestSubClass::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestSubClass::test_proxied_value", "tests/test_env.py::TestSubClass::test_int_list", "tests/test_env.py::TestSubClass::test_int_tuple", "tests/test_env.py::TestSubClass::test_str_list_with_spaces", "tests/test_env.py::TestSubClass::test_empty_list", "tests/test_env.py::TestSubClass::test_dict_value", "tests/test_env.py::TestSubClass::test_dict_parsing[dict]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_float]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestSubClass::test_url_value", "tests/test_env.py::TestSubClass::test_url_encoded_parts", "tests/test_env.py::TestSubClass::test_db_url_value[postgres]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql_gis]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle_tns]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle]", "tests/test_env.py::TestSubClass::test_db_url_value[redshift]", "tests/test_env.py::TestSubClass::test_db_url_value[sqlite]", "tests/test_env.py::TestSubClass::test_db_url_value[custom]", "tests/test_env.py::TestSubClass::test_cache_url_value[memcached]", "tests/test_env.py::TestSubClass::test_cache_url_value[redis]", "tests/test_env.py::TestSubClass::test_email_url_value", "tests/test_env.py::TestSubClass::test_json_value", "tests/test_env.py::TestSubClass::test_path", "tests/test_env.py::TestSubClass::test_smart_cast", "tests/test_env.py::TestSubClass::test_exported", "tests/test_env.py::TestSubClass::test_singleton_environ" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-10-05 19:23:51+00:00
mit
3,288
joke2k__django-environ-358
diff --git a/environ/environ.py b/environ/environ.py index acdfb15..0123c02 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -21,6 +21,7 @@ import warnings from urllib.parse import ( parse_qs, ParseResult, + unquote, unquote_plus, urlparse, urlunparse, @@ -61,7 +62,7 @@ def _cast_int(v): def _cast_urlstr(v): - return unquote_plus(v) if isinstance(v, str) else v + return unquote(v) if isinstance(v, str) else v class NoValue:
joke2k/django-environ
509cf7737363a56e4464962dbae4ab72b801c7b3
diff --git a/tests/test_utils.py b/tests/test_utils.py index 523a72d..f32d7cc 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -7,7 +7,7 @@ # the LICENSE.txt file that was distributed with this source code. import pytest -from environ.environ import _cast +from environ.environ import _cast, _cast_urlstr @pytest.mark.parametrize( @@ -20,3 +20,20 @@ def test_cast(literal): See https://github.com/joke2k/django-environ/issues/200 for details.""" assert _cast(literal) == literal + [email protected]( + "quoted_url_str,expected_unquoted_str", + [ + ("Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+", "Le-{FsIaYnaQw}a2B/[V8bS+"), + ("my_test-string+", "my_test-string+"), + ("my%20test%20string+", "my test string+") + ] +) +def test_cast_urlstr(quoted_url_str, expected_unquoted_str): + """Make sure that a url str that contains plus sign literals does not get unquoted incorrectly + Plus signs should not be converted to spaces, since spaces are encoded with %20 in URIs + + see https://github.com/joke2k/django-environ/issues/357 for details. + related to https://github.com/joke2k/django-environ/pull/69""" + + assert _cast_urlstr(quoted_url_str) == expected_unquoted_str
Fix _cast_urlstr to use unquote vs unquote_plus Currently, `Env.db_url_config` uses `_cast_urlstr` to url unquote the username and password from database connection URIs. The underlying problem occurs when you try to use a `+` in your postgres password. `_cast_urlstr` uses `unquote_plus`, ([introduced in this PR here](https://github.com/joke2k/django-environ/pull/69)), which which will turn plus signs into spaces when unquoted. This is undesired, as plus signs should only be replaced for spaces in HTML form values that are URL encoded, not in connection URIs. Unquote docs [unquote](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote) vs [unquote_plus](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote_plus) This bug was discovered when using [CrunchyData's PGO](https://access.crunchydata.com/documentation/postgres-operator/v5/) on kubernetes. The PGO autogenerates postgres URIs for users and stores them inside of a kubernetes secret. An example URI is shown below: ``` postgresql://myuser:Le-%7BFsIaYnaQw%7Da2B%2F%[email protected]:5432/mydb ``` Using the different unquotes to decode the password: ``` >>> unquote('Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+') 'Le-{FsIaYnaQw}a2B/[V8bS+' >>> unquote_plus('Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+') 'Le-{FsIaYnaQw}a2B/[V8bS ' ``` The first one can be used to sign into the database using both `psql` and `psycopg2.connect`, while the second gives an auth error. I ran the test suite for `django-environ` using both `unquote_plus` and `unquote` and all tests passed, regardless of which implementation is used, so I believe moving to `unquote` shouldn't be a huge change. I'll open a PR with changes and link them to this issue.
0.0
509cf7737363a56e4464962dbae4ab72b801c7b3
[ "tests/test_utils.py::test_cast_urlstr[Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+-Le-{FsIaYnaQw}a2B/[V8bS+]", "tests/test_utils.py::test_cast_urlstr[my_test-string+-my_test-string+]", "tests/test_utils.py::test_cast_urlstr[my%20test%20string+-my" ]
[ "tests/test_utils.py::test_cast[anything-]", "tests/test_utils.py::test_cast[anything*]", "tests/test_utils.py::test_cast[*anything]", "tests/test_utils.py::test_cast[anything.]", "tests/test_utils.py::test_cast[anything.1]", "tests/test_utils.py::test_cast[(anything]", "tests/test_utils.py::test_cast[anything-v1.2]", "tests/test_utils.py::test_cast[anything-1.2]", "tests/test_utils.py::test_cast[anything=]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-12-13 15:31:58+00:00
mit
3,289
joke2k__django-environ-361
diff --git a/environ/environ.py b/environ/environ.py index acdfb15..ccbca70 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -21,6 +21,7 @@ import warnings from urllib.parse import ( parse_qs, ParseResult, + unquote, unquote_plus, urlparse, urlunparse, @@ -61,7 +62,7 @@ def _cast_int(v): def _cast_urlstr(v): - return unquote_plus(v) if isinstance(v, str) else v + return unquote(v) if isinstance(v, str) else v class NoValue: @@ -365,10 +366,10 @@ class Env: try: value = self.ENVIRON[var] - except KeyError: + except KeyError as exc: if default is self.NOTSET: error_msg = "Set the {} environment variable".format(var) - raise ImproperlyConfigured(error_msg) + raise ImproperlyConfigured(error_msg) from exc value = default
joke2k/django-environ
509cf7737363a56e4464962dbae4ab72b801c7b3
diff --git a/tests/test_env.py b/tests/test_env.py index 59110e3..d154708 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -45,6 +45,7 @@ class TestEnv: with pytest.raises(ImproperlyConfigured) as excinfo: self.env('not_present') assert str(excinfo.value) == 'Set the not_present environment variable' + assert excinfo.value.__cause__ is not None def test_contains(self): assert 'STR_VAR' in self.env diff --git a/tests/test_utils.py b/tests/test_utils.py index 523a72d..f32d7cc 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -7,7 +7,7 @@ # the LICENSE.txt file that was distributed with this source code. import pytest -from environ.environ import _cast +from environ.environ import _cast, _cast_urlstr @pytest.mark.parametrize( @@ -20,3 +20,20 @@ def test_cast(literal): See https://github.com/joke2k/django-environ/issues/200 for details.""" assert _cast(literal) == literal + [email protected]( + "quoted_url_str,expected_unquoted_str", + [ + ("Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+", "Le-{FsIaYnaQw}a2B/[V8bS+"), + ("my_test-string+", "my_test-string+"), + ("my%20test%20string+", "my test string+") + ] +) +def test_cast_urlstr(quoted_url_str, expected_unquoted_str): + """Make sure that a url str that contains plus sign literals does not get unquoted incorrectly + Plus signs should not be converted to spaces, since spaces are encoded with %20 in URIs + + see https://github.com/joke2k/django-environ/issues/357 for details. + related to https://github.com/joke2k/django-environ/pull/69""" + + assert _cast_urlstr(quoted_url_str) == expected_unquoted_str
Attach cause to ImproperlyConfigured exception raised for missing environment variables I'd like to propose to add the original exception as the cause of the `ImproperlyConfigured` exception that's raised when an environment variable is missing using `raise ... from ...`: ```py try: value = self.ENVIRON[var] except KeyError as exc: if default is self.NOTSET: error_msg = "Set the {} environment variable".format(var) raise ImproperlyConfigured(error_msg) from exc ``` The original: https://github.com/joke2k/django-environ/blob/509cf7737363a56e4464962dbae4ab72b801c7b3/environ/environ.py#L366-L371 Note: Since it's a two-line change, I've opened #361 to introduce this change. I know that the proposal hasn't been discussed yet, but I figured not a lot of work is lost if it's rejected. ## Background The main difference is that this will mark the original `KeyError` as the explicit cause of the `ImproperlyConfigered`, instead of marking the `ImproperlyConfigured` as another exception that "happened to happen" during the handling of the `KeyError`. (A better explanation is given by Martijn Pieters [here](https://stackoverflow.com/questions/24752395/python-raise-from-usage/24752607#24752607)). ## Differences for end-users The most notable difference is the output. The proposed change would change the traceback output to: ```python-traceback Traceback (most recent call last): (...) KeyError: 'missing_key' The above exception was the direct cause of the following exception: Traceback (most recent call last): (...) environ.compat.ImproperlyConfigured: Set the missing_key environment variable ``` instead of ```python-traceback Traceback (most recent call last): (...) KeyError: 'missing_key' During handling of the above exception, another exception occurred: Traceback (most recent call last): (...) environ.compat.ImproperlyConfigured: Set the missing_key environment variable ``` Notice that the middle line that indicates the relationship between the two exceptions has changed. Additionally, the original exception will now be attached to the `ImproperlyConfigured` exception under the `__cause__` attribute instead of the `__context__` attribute.
0.0
509cf7737363a56e4464962dbae4ab72b801c7b3
[ "tests/test_env.py::TestEnv::test_not_present_without_default", "tests/test_env.py::TestFileEnv::test_not_present_without_default", "tests/test_env.py::TestSubClass::test_not_present_without_default", "tests/test_utils.py::test_cast_urlstr[Le-%7BFsIaYnaQw%7Da2B%2F%5BV8bS+-Le-{FsIaYnaQw}a2B/[V8bS+]", "tests/test_utils.py::test_cast_urlstr[my_test-string+-my_test-string+]", "tests/test_utils.py::test_cast_urlstr[my%20test%20string+-my" ]
[ "tests/test_env.py::TestEnv::test_not_present_with_default", "tests/test_env.py::TestEnv::test_contains", "tests/test_env.py::TestEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_int", "tests/test_env.py::TestEnv::test_int_with_none_default", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestEnv::test_proxied_value", "tests/test_env.py::TestEnv::test_escaped_dollar_sign", "tests/test_env.py::TestEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestEnv::test_int_list", "tests/test_env.py::TestEnv::test_int_tuple", "tests/test_env.py::TestEnv::test_str_list_with_spaces", "tests/test_env.py::TestEnv::test_empty_list", "tests/test_env.py::TestEnv::test_dict_value", "tests/test_env.py::TestEnv::test_complex_dict_value", "tests/test_env.py::TestEnv::test_dict_parsing[dict]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestEnv::test_url_value", "tests/test_env.py::TestEnv::test_url_encoded_parts", "tests/test_env.py::TestEnv::test_db_url_value[postgres]", "tests/test_env.py::TestEnv::test_db_url_value[mysql]", "tests/test_env.py::TestEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestEnv::test_db_url_value[oracle]", "tests/test_env.py::TestEnv::test_db_url_value[redshift]", "tests/test_env.py::TestEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestEnv::test_db_url_value[custom]", "tests/test_env.py::TestEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestEnv::test_cache_url_value[redis]", "tests/test_env.py::TestEnv::test_email_url_value", "tests/test_env.py::TestEnv::test_json_value", "tests/test_env.py::TestEnv::test_path", "tests/test_env.py::TestEnv::test_smart_cast", "tests/test_env.py::TestEnv::test_exported", "tests/test_env.py::TestFileEnv::test_not_present_with_default", "tests/test_env.py::TestFileEnv::test_contains", "tests/test_env.py::TestFileEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestFileEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_int", "tests/test_env.py::TestFileEnv::test_int_with_none_default", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestFileEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestFileEnv::test_proxied_value", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestFileEnv::test_int_list", "tests/test_env.py::TestFileEnv::test_int_tuple", "tests/test_env.py::TestFileEnv::test_str_list_with_spaces", "tests/test_env.py::TestFileEnv::test_empty_list", "tests/test_env.py::TestFileEnv::test_dict_value", "tests/test_env.py::TestFileEnv::test_complex_dict_value", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestFileEnv::test_url_value", "tests/test_env.py::TestFileEnv::test_url_encoded_parts", "tests/test_env.py::TestFileEnv::test_db_url_value[postgres]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle]", "tests/test_env.py::TestFileEnv::test_db_url_value[redshift]", "tests/test_env.py::TestFileEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestFileEnv::test_db_url_value[custom]", "tests/test_env.py::TestFileEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestFileEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestFileEnv::test_cache_url_value[redis]", "tests/test_env.py::TestFileEnv::test_email_url_value", "tests/test_env.py::TestFileEnv::test_json_value", "tests/test_env.py::TestFileEnv::test_path", "tests/test_env.py::TestFileEnv::test_smart_cast", "tests/test_env.py::TestFileEnv::test_exported", "tests/test_env.py::TestFileEnv::test_read_env_path_like", "tests/test_env.py::TestFileEnv::test_existing_overwrite[True]", "tests/test_env.py::TestFileEnv::test_existing_overwrite[False]", "tests/test_env.py::TestSubClass::test_not_present_with_default", "tests/test_env.py::TestSubClass::test_contains", "tests/test_env.py::TestSubClass::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestSubClass::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_int", "tests/test_env.py::TestSubClass::test_int_with_none_default", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestSubClass::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestSubClass::test_proxied_value", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestSubClass::test_int_list", "tests/test_env.py::TestSubClass::test_int_tuple", "tests/test_env.py::TestSubClass::test_str_list_with_spaces", "tests/test_env.py::TestSubClass::test_empty_list", "tests/test_env.py::TestSubClass::test_dict_value", "tests/test_env.py::TestSubClass::test_complex_dict_value", "tests/test_env.py::TestSubClass::test_dict_parsing[dict]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_float]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestSubClass::test_url_value", "tests/test_env.py::TestSubClass::test_url_encoded_parts", "tests/test_env.py::TestSubClass::test_db_url_value[postgres]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql_gis]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle_tns]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle]", "tests/test_env.py::TestSubClass::test_db_url_value[redshift]", "tests/test_env.py::TestSubClass::test_db_url_value[sqlite]", "tests/test_env.py::TestSubClass::test_db_url_value[custom]", "tests/test_env.py::TestSubClass::test_db_url_value[cloudsql]", "tests/test_env.py::TestSubClass::test_cache_url_value[memcached]", "tests/test_env.py::TestSubClass::test_cache_url_value[redis]", "tests/test_env.py::TestSubClass::test_email_url_value", "tests/test_env.py::TestSubClass::test_json_value", "tests/test_env.py::TestSubClass::test_path", "tests/test_env.py::TestSubClass::test_smart_cast", "tests/test_env.py::TestSubClass::test_exported", "tests/test_env.py::TestSubClass::test_singleton_environ", "tests/test_utils.py::test_cast[anything-]", "tests/test_utils.py::test_cast[anything*]", "tests/test_utils.py::test_cast[*anything]", "tests/test_utils.py::test_cast[anything.]", "tests/test_utils.py::test_cast[anything.1]", "tests/test_utils.py::test_cast[(anything]", "tests/test_utils.py::test_cast[anything-v1.2]", "tests/test_utils.py::test_cast[anything-1.2]", "tests/test_utils.py::test_cast[anything=]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-12-30 16:07:50+00:00
mit
3,290
joke2k__django-environ-419
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index aa7b3ff..8e181b1 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -17,6 +17,8 @@ Added `#468 <https://github.com/joke2k/django-environ/pull/468>`_. - Added capability to handle comments after #, after quoted values, like ``KEY= 'part1 # part2' # comment`` `#475 <https://github.com/joke2k/django-environ/pull/475>`_. +- Added support for ``interpolate`` parameter + `#419 <https://github.com/joke2k/django-environ/pull/419>`_. Changed +++++++ diff --git a/docs/tips.rst b/docs/tips.rst index 20b8c3e..ab59f69 100644 --- a/docs/tips.rst +++ b/docs/tips.rst @@ -226,7 +226,7 @@ Proxy value =========== Values that being with a ``$`` may be interpolated. Pass ``interpolate=True`` to -``environ.Env()`` to enable this feature: +``environ.Env()`` to enable this feature (``True`` by default): .. code-block:: python diff --git a/environ/environ.py b/environ/environ.py index 644286e..f35470c 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -197,11 +197,12 @@ class Env: VAR = re.compile(r'(?<!\\)\$\{?(?P<name>[A-Z_][0-9A-Z_]*)}?', re.IGNORECASE) - def __init__(self, **scheme): + def __init__(self, interpolate=True, **scheme): self._local = threading.local() self.smart_cast = True self.escape_proxy = False self.prefix = "" + self.interpolate = interpolate self.scheme = scheme def __call__(self, var, cast=None, default=NOTSET, parse_default=False): @@ -425,7 +426,8 @@ class Env: value = default # Expand variables - if isinstance(value, (bytes, str)) and var_name not in NOT_EXPANDED: + if self.interpolate and isinstance(value, (bytes, str)) \ + and var_name not in NOT_EXPANDED: def repl(match_): return self.get_value( match_.group('name'), cast=cast, default=default,
joke2k/django-environ
2750dd54e0e4b1b591a31409cfb1dc16a82b958d
diff --git a/tests/test_env.py b/tests/test_env.py index 0b105f5..1f2df15 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -134,6 +134,10 @@ class TestEnv: def test_proxied_value(self): assert self.env('PROXIED_VAR') == 'bar' + def test_not_interpolated_proxied_value(self): + env = Env(interpolate=False) + assert env('PROXIED_VAR') == '$STR_VAR' + def test_escaped_dollar_sign(self): self.env.escape_proxy = True assert self.env('ESCAPED_VAR') == '$baz'
`interpolate` flag functionality is not implemented I did `SECRET_KEY = env('DJANGO_SECRET_KEY')` and got the error: ``` django.core.exceptions.ImproperlyConfigured: Set the a&d3*0k#skh)!5o)$))zz9&%hr@-akid5zh--05ei790+wn0$r environment variable ``` This is becuase my `DJANGO_SECRET_KEY` starts with the dollar sign: ``` DJANGO_SECRET_KEY="$a&d3*0k#skh)!5o)$))zz9&%hr@-akid5zh--05ei790+wn0$r" ``` There was a number of issues for this problem: #284, #60, #271. Eventually, #333 somewhat solved the issue by allowing to escape the dollar sign. But this is not the best approach for generated values such as secret keys. The better option would be an ability to disable interpolation altogether. Ideally by default since the behaviour is unexpected. Interestingly, the `interpolation` flag is described in the docs: https://django-environ.readthedocs.io/en/latest/tips.html?highlight=Proxied%20Values#proxy-value. BUT it's not implemented! [This commit ](https://github.com/joke2k/django-environ/commit/f8c8a1ff50109e1b6de99e3f6ad51b326a794392) introduced the doc. Apparently, the implementation (#145) was not merged and closed in favor of #333. I don't know why. #145 seems like a proper solution.
0.0
2750dd54e0e4b1b591a31409cfb1dc16a82b958d
[ "tests/test_env.py::TestEnv::test_not_interpolated_proxied_value", "tests/test_env.py::TestFileEnv::test_not_interpolated_proxied_value", "tests/test_env.py::TestSubClass::test_not_interpolated_proxied_value" ]
[ "tests/test_env.py::TestEnv::test_not_present_with_default", "tests/test_env.py::TestEnv::test_not_present_without_default", "tests/test_env.py::TestEnv::test_contains", "tests/test_env.py::TestEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_int", "tests/test_env.py::TestEnv::test_int_with_none_default", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestEnv::test_proxied_value", "tests/test_env.py::TestEnv::test_escaped_dollar_sign", "tests/test_env.py::TestEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestEnv::test_int_list", "tests/test_env.py::TestEnv::test_int_list_cast_tuple", "tests/test_env.py::TestEnv::test_int_tuple", "tests/test_env.py::TestEnv::test_mix_tuple_issue_387", "tests/test_env.py::TestEnv::test_str_list_with_spaces", "tests/test_env.py::TestEnv::test_empty_list", "tests/test_env.py::TestEnv::test_dict_value", "tests/test_env.py::TestEnv::test_complex_dict_value", "tests/test_env.py::TestEnv::test_dict_parsing[dict]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestEnv::test_url_value", "tests/test_env.py::TestEnv::test_url_empty_string_default_value", "tests/test_env.py::TestEnv::test_url_encoded_parts", "tests/test_env.py::TestEnv::test_db_url_value[postgres]", "tests/test_env.py::TestEnv::test_db_url_value[mysql]", "tests/test_env.py::TestEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestEnv::test_db_url_value[oracle]", "tests/test_env.py::TestEnv::test_db_url_value[redshift]", "tests/test_env.py::TestEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestEnv::test_db_url_value[custom]", "tests/test_env.py::TestEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestEnv::test_cache_url_value[redis]", "tests/test_env.py::TestEnv::test_email_url_value", "tests/test_env.py::TestEnv::test_json_value", "tests/test_env.py::TestEnv::test_path", "tests/test_env.py::TestEnv::test_smart_cast", "tests/test_env.py::TestEnv::test_exported", "tests/test_env.py::TestEnv::test_prefix", "tests/test_env.py::TestFileEnv::test_not_present_with_default", "tests/test_env.py::TestFileEnv::test_not_present_without_default", "tests/test_env.py::TestFileEnv::test_contains", "tests/test_env.py::TestFileEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestFileEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_int", "tests/test_env.py::TestFileEnv::test_int_with_none_default", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestFileEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestFileEnv::test_proxied_value", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestFileEnv::test_int_list", "tests/test_env.py::TestFileEnv::test_int_list_cast_tuple", "tests/test_env.py::TestFileEnv::test_int_tuple", "tests/test_env.py::TestFileEnv::test_mix_tuple_issue_387", "tests/test_env.py::TestFileEnv::test_str_list_with_spaces", "tests/test_env.py::TestFileEnv::test_empty_list", "tests/test_env.py::TestFileEnv::test_dict_value", "tests/test_env.py::TestFileEnv::test_complex_dict_value", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestFileEnv::test_url_value", "tests/test_env.py::TestFileEnv::test_url_empty_string_default_value", "tests/test_env.py::TestFileEnv::test_url_encoded_parts", "tests/test_env.py::TestFileEnv::test_db_url_value[postgres]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle]", "tests/test_env.py::TestFileEnv::test_db_url_value[redshift]", "tests/test_env.py::TestFileEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestFileEnv::test_db_url_value[custom]", "tests/test_env.py::TestFileEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestFileEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestFileEnv::test_cache_url_value[redis]", "tests/test_env.py::TestFileEnv::test_email_url_value", "tests/test_env.py::TestFileEnv::test_json_value", "tests/test_env.py::TestFileEnv::test_path", "tests/test_env.py::TestFileEnv::test_smart_cast", "tests/test_env.py::TestFileEnv::test_exported", "tests/test_env.py::TestFileEnv::test_prefix", "tests/test_env.py::TestFileEnv::test_read_env_path_like", "tests/test_env.py::TestFileEnv::test_existing_overwrite[True]", "tests/test_env.py::TestFileEnv::test_existing_overwrite[False]", "tests/test_env.py::TestSubClass::test_not_present_with_default", "tests/test_env.py::TestSubClass::test_not_present_without_default", "tests/test_env.py::TestSubClass::test_contains", "tests/test_env.py::TestSubClass::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestSubClass::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_int", "tests/test_env.py::TestSubClass::test_int_with_none_default", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestSubClass::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL_WITH_COMMENT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestSubClass::test_proxied_value", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestSubClass::test_int_list", "tests/test_env.py::TestSubClass::test_int_list_cast_tuple", "tests/test_env.py::TestSubClass::test_int_tuple", "tests/test_env.py::TestSubClass::test_mix_tuple_issue_387", "tests/test_env.py::TestSubClass::test_str_list_with_spaces", "tests/test_env.py::TestSubClass::test_empty_list", "tests/test_env.py::TestSubClass::test_dict_value", "tests/test_env.py::TestSubClass::test_complex_dict_value", "tests/test_env.py::TestSubClass::test_dict_parsing[dict]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_float]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestSubClass::test_url_value", "tests/test_env.py::TestSubClass::test_url_empty_string_default_value", "tests/test_env.py::TestSubClass::test_url_encoded_parts", "tests/test_env.py::TestSubClass::test_db_url_value[postgres]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql_gis]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle_tns]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle]", "tests/test_env.py::TestSubClass::test_db_url_value[redshift]", "tests/test_env.py::TestSubClass::test_db_url_value[sqlite]", "tests/test_env.py::TestSubClass::test_db_url_value[custom]", "tests/test_env.py::TestSubClass::test_db_url_value[cloudsql]", "tests/test_env.py::TestSubClass::test_cache_url_value[memcached]", "tests/test_env.py::TestSubClass::test_cache_url_value[redis]", "tests/test_env.py::TestSubClass::test_email_url_value", "tests/test_env.py::TestSubClass::test_json_value", "tests/test_env.py::TestSubClass::test_path", "tests/test_env.py::TestSubClass::test_smart_cast", "tests/test_env.py::TestSubClass::test_exported", "tests/test_env.py::TestSubClass::test_prefix", "tests/test_env.py::TestSubClass::test_singleton_environ" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-26 13:23:32+00:00
mit
3,291
joke2k__django-environ-468
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 682b107..b8daeff 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -11,6 +11,8 @@ Added +++++ - Added support for secure Elasticsearch connections `#463 <https://github.com/joke2k/django-environ/pull/463>`_. +- Added variable expansion + `#468 <https://github.com/joke2k/django-environ/pull/468>`_. Changed +++++++ diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 6247383..2ab100f 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -23,6 +23,28 @@ And use it with ``settings.py`` as follows: :start-after: -code-begin- :end-before: -overview- +Variables can contain references to another variables: ``$VAR`` or ``${VAR}``. +Referenced variables are searched in the environment and within all definitions +in the ``.env`` file. References are checked for recursion (self-reference). +Exception is thrown if any reference results in infinite loop on any level +of recursion. Variable values are substituted similar to shell parameter +expansion. Example: + +.. code-block:: shell + + # shell + export POSTGRES_USERNAME='user' POSTGRES_PASSWORD='SECRET' + +.. code-block:: shell + + # .env + POSTGRES_HOSTNAME='example.com' + POSTGRES_DB='database' + DATABASE_URL="postgres://${POSTGRES_USERNAME}:${POSTGRES_PASSWORD}@${POSTGRES_HOSTNAME}:5432/${POSTGRES_DB}" + +The value of ``DATABASE_URL`` variable will become +``postgres://user:[email protected]:5432/database``. + The ``.env`` file should be specific to the environment and not checked into version control, it is best practice documenting the ``.env`` file with an example. For example, you can also add ``.env.dist`` with a template of your variables to diff --git a/environ/environ.py b/environ/environ.py index 8d09258..f045639 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -17,7 +17,9 @@ import logging import os import re import sys +import threading import warnings +from os.path import expandvars from urllib.parse import ( parse_qs, ParseResult, @@ -40,6 +42,9 @@ from .fileaware_mapping import FileAwareMapping Openable = (str, os.PathLike) logger = logging.getLogger(__name__) +# Variables which values should not be expanded +NOT_EXPANDED = 'DJANGO_SECRET_KEY', 'CACHE_URL' + def _cast(value): # Safely evaluate an expression node or a string containing a Python @@ -189,7 +194,11 @@ class Env: for s in ('', 's')] CLOUDSQL = 'cloudsql' + VAR = re.compile(r'(?<!\\)\$\{?(?P<name>[A-Z_][0-9A-Z_]*)}?', + re.IGNORECASE) + def __init__(self, **scheme): + self._local = threading.local() self.smart_cast = True self.escape_proxy = False self.prefix = "" @@ -343,9 +352,13 @@ class Env: """ return Path(self.get_value(var, default=default), **kwargs) - def get_value(self, var, cast=None, default=NOTSET, parse_default=False): + def get_value(self, var, cast=None, # pylint: disable=R0913 + default=NOTSET, parse_default=False, add_prefix=True): """Return value for given environment variable. + - Expand variables referenced as ``$VAR`` or ``${VAR}``. + - Detect infinite recursion in expansion (self-reference). + :param str var: Name of variable. :param collections.abc.Callable or None cast: @@ -354,15 +367,33 @@ class Env: If var not present in environ, return this instead. :param bool parse_default: Force to parse default. + :param bool add_prefix: + Whether to add prefix to variable name. :returns: Value from environment or default (if set). :rtype: typing.IO[typing.Any] """ - + var_name = f'{self.prefix}{var}' if add_prefix else var + if not hasattr(self._local, 'vars'): + self._local.vars = set() + if var_name in self._local.vars: + error_msg = f"Environment variable '{var_name}' recursively "\ + "references itself (eventually)" + raise ImproperlyConfigured(error_msg) + + self._local.vars.add(var_name) + try: + return self._get_value( + var_name, cast=cast, default=default, + parse_default=parse_default) + finally: + self._local.vars.remove(var_name) + + def _get_value(self, var_name, cast=None, default=NOTSET, + parse_default=False): logger.debug( "get '%s' casted as '%s' with default '%s'", - var, cast, default) + var_name, cast, default) - var_name = f'{self.prefix}{var}' if var_name in self.scheme: var_info = self.scheme[var_name] @@ -388,26 +419,37 @@ class Env: value = self.ENVIRON[var_name] except KeyError as exc: if default is self.NOTSET: - error_msg = f'Set the {var} environment variable' + error_msg = f'Set the {var_name} environment variable' raise ImproperlyConfigured(error_msg) from exc value = default + # Expand variables + if isinstance(value, (bytes, str)) and var_name not in NOT_EXPANDED: + def repl(match_): + return self.get_value( + match_.group('name'), cast=cast, default=default, + parse_default=parse_default, add_prefix=False) + + is_bytes = isinstance(value, bytes) + if is_bytes: + value = value.decode('utf-8') + value = self.VAR.sub(repl, value) + value = expandvars(value) + if is_bytes: + value = value.encode('utf-8') + # Resolve any proxied values prefix = b'$' if isinstance(value, bytes) else '$' escape = rb'\$' if isinstance(value, bytes) else r'\$' - if hasattr(value, 'startswith') and value.startswith(prefix): - value = value.lstrip(prefix) - value = self.get_value(value, cast=cast, default=default) if self.escape_proxy and hasattr(value, 'replace'): value = value.replace(escape, prefix) # Smart casting - if self.smart_cast: - if cast is None and default is not None and \ - not isinstance(default, NoValue): - cast = type(default) + if self.smart_cast and cast is None and default is not None \ + and not isinstance(default, NoValue): + cast = type(default) value = None if default is None and value == '' else value
joke2k/django-environ
69b4bc9a5aa855040ca9e8da19aea35a08dcd639
diff --git a/tests/test_expansion.py b/tests/test_expansion.py new file mode 100755 index 0000000..757ee9a --- /dev/null +++ b/tests/test_expansion.py @@ -0,0 +1,27 @@ +import pytest + +from environ import Env, Path +from environ.compat import ImproperlyConfigured + + +class TestExpansion: + def setup_method(self, method): + Env.ENVIRON = {} + self.env = Env() + self.env.read_env(Path(__file__, is_file=True)('test_expansion.txt')) + + def test_expansion(self): + assert self.env('HELLO') == 'Hello, world!' + + def test_braces(self): + assert self.env('BRACES') == 'Hello, world!' + + def test_recursion(self): + with pytest.raises(ImproperlyConfigured) as excinfo: + self.env('RECURSIVE') + assert str(excinfo.value) == "Environment variable 'RECURSIVE' recursively references itself (eventually)" + + def test_transitive(self): + with pytest.raises(ImproperlyConfigured) as excinfo: + self.env('R4') + assert str(excinfo.value) == "Environment variable 'R4' recursively references itself (eventually)" diff --git a/tests/test_expansion.txt b/tests/test_expansion.txt new file mode 100755 index 0000000..8290e45 --- /dev/null +++ b/tests/test_expansion.txt @@ -0,0 +1,9 @@ +VAR1='Hello' +VAR2='world' +HELLO="$VAR1, $VAR2!" +BRACES="${VAR1}, ${VAR2}!" +RECURSIVE="This variable is $RECURSIVE" +R1="$R2" +R2="$R3" +R3="$R4" +R4="$R1"
Any plan to support embedded variables? I was wondering if there has been discussions/plans to support embedded variables in .env file. For example, ``` # .env file with embedded variables LIB_PATH=/home/username/.lib GDAL_LIBRARY_PATH=${LIB_PATH}/osgeo/gdal304.dll GEOS_LIBRARY_PATH=${LIB_PATH}/osgeo/geos_c.dll ``` I got used to the ${VAR_NAME} syntax as it is supported by docker-compose and python-dotenv among others. It would be great to get the same support in django-environ. I'm aware of the interpolate feature which covers a more limited use case. Would that be useful to anyone else?
0.0
69b4bc9a5aa855040ca9e8da19aea35a08dcd639
[ "tests/test_expansion.py::TestExpansion::test_expansion", "tests/test_expansion.py::TestExpansion::test_braces", "tests/test_expansion.py::TestExpansion::test_recursion", "tests/test_expansion.py::TestExpansion::test_transitive" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-04-24 13:01:50+00:00
mit
3,292
joke2k__django-environ-500
diff --git a/.gitignore b/.gitignore index 5862901..0b4fa31 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ # This file is part of the django-environ. # -# Copyright (c) 2021, Serghei Iakovlev <[email protected]> +# Copyright (c) 2021-2023, Serghei Iakovlev <[email protected]> # Copyright (c) 2013-2021, Daniele Faraglia <[email protected]> # # For the full copyright and license information, please view diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 57c4c8d..ef00d40 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -5,8 +5,19 @@ All notable changes to this project will be documented in this file. The format is inspired by `Keep a Changelog <https://keepachangelog.com/en/1.0.0/>`_ and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_. +`v0.11.3`_ - 0-Undefined-2023 +----------------------------- +Changed ++++++++ +- Disabled inline comments handling by default due to potential side effects. + While the feature itself is useful, the project's philosophy dictates that + it should not be enabled by default for all users + `#499 <https://github.com/joke2k/django-environ/issues/499>`_. + + + `v0.11.2`_ - 1-September-2023 -------------------------------- +----------------------------- Fixed +++++ - Revert "Add variable expansion." feature @@ -31,7 +42,7 @@ Added `#463 <https://github.com/joke2k/django-environ/pull/463>`_. - Added variable expansion `#468 <https://github.com/joke2k/django-environ/pull/468>`_. -- Added capability to handle comments after #, after quoted values, +- Added capability to handle comments after ``#``, after quoted values, like ``KEY= 'part1 # part2' # comment`` `#475 <https://github.com/joke2k/django-environ/pull/475>`_. - Added support for ``interpolate`` parameter @@ -388,6 +399,7 @@ Added - Initial release. +.. _v0.11.3: https://github.com/joke2k/django-environ/compare/v0.11.2...v0.11.3 .. _v0.11.2: https://github.com/joke2k/django-environ/compare/v0.11.1...v0.11.2 .. _v0.11.1: https://github.com/joke2k/django-environ/compare/v0.11.0...v0.11.1 .. _v0.11.0: https://github.com/joke2k/django-environ/compare/v0.10.0...v0.11.0 diff --git a/LICENSE.txt b/LICENSE.txt index 0bd208d..8737f75 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2021, Serghei Iakovlev <[email protected]> +Copyright (c) 2021-2023, Serghei Iakovlev <[email protected]> Copyright (c) 2013-2021, Daniele Faraglia <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy diff --git a/docs/tips.rst b/docs/tips.rst index 20b8c3e..66538c4 100644 --- a/docs/tips.rst +++ b/docs/tips.rst @@ -2,6 +2,71 @@ Tips ==== +Handling Inline Comments in .env Files +====================================== + +``django-environ`` provides an optional feature to parse inline comments in ``.env`` +files. This is controlled by the ``parse_comments`` parameter in the ``read_env`` +method. + +Modes +----- + +- **Enabled (``parse_comments=True``)**: Inline comments starting with ``#`` will be ignored. +- **Disabled (``parse_comments=False``)**: The entire line, including comments, will be read as the value. +- **Default**: The behavior is the same as when ``parse_comments=False``. + +Side Effects +------------ + +While this feature can be useful for adding context to your ``.env`` files, +it can introduce unexpected behavior. For example, if your value includes +a ``#`` symbol, it will be truncated when ``parse_comments=True``. + +Why Disabled by Default? +------------------------ + +In line with the project's philosophy of being explicit and avoiding unexpected behavior, +this feature is disabled by default. If you understand the implications and find the feature +useful, you can enable it explicitly. + +Example +------- + +Here is an example demonstrating the different modes of handling inline comments. + +**.env file contents**: + +.. code-block:: shell + + # .env file contents + BOOL_TRUE_WITH_COMMENT=True # This is a comment + STR_WITH_HASH=foo#bar # This is also a comment + +**Python code**: + +.. code-block:: python + + import environ + + # Using parse_comments=True + env = environ.Env() + env.read_env(parse_comments=True) + print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True + print(env('STR_WITH_HASH')) # Output: foo + + # Using parse_comments=False + env = environ.Env() + env.read_env(parse_comments=False) + print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True # This is a comment + print(env('STR_WITH_HASH')) # Output: foo#bar # This is also a comment + + # Using default behavior + env = environ.Env() + env.read_env() + print(env('BOOL_TRUE_WITH_COMMENT')) # Output: True # This is a comment + print(env('STR_WITH_HASH')) # Output: foo#bar # This is also a comment + Docker-style file based variables ================================= diff --git a/environ/__init__.py b/environ/__init__.py index 28d4a5a..ddf05f9 100644 --- a/environ/__init__.py +++ b/environ/__init__.py @@ -21,7 +21,7 @@ from .environ import * __copyright__ = 'Copyright (C) 2013-2023 Daniele Faraglia' """The copyright notice of the package.""" -__version__ = '0.11.2' +__version__ = '0.11.3' """The version of the package.""" __license__ = 'MIT' diff --git a/environ/environ.py b/environ/environ.py index f74884b..a3d64f2 100644 --- a/environ/environ.py +++ b/environ/environ.py @@ -1,6 +1,6 @@ # This file is part of the django-environ. # -# Copyright (c) 2021-2022, Serghei Iakovlev <[email protected]> +# Copyright (c) 2021-2023, Serghei Iakovlev <[email protected]> # Copyright (c) 2013-2021, Daniele Faraglia <[email protected]> # # For the full copyright and license information, please view @@ -862,8 +862,8 @@ class Env: return config @classmethod - def read_env(cls, env_file=None, overwrite=False, encoding='utf8', - **overrides): + def read_env(cls, env_file=None, overwrite=False, parse_comments=False, + encoding='utf8', **overrides): r"""Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack @@ -883,6 +883,8 @@ class Env: the Django settings module from the Django project root. :param overwrite: ``overwrite=True`` will force an overwrite of existing environment variables. + :param parse_comments: Determines whether to recognize and ignore + inline comments in the .env file. Default is False. :param encoding: The encoding to use when reading the environment file. :param \**overrides: Any additional keyword arguments provided directly to read_env will be added to the environment. If the key matches an @@ -927,22 +929,40 @@ class Env: for line in content.splitlines(): m1 = re.match(r'\A(?:export )?([A-Za-z_0-9]+)=(.*)\Z', line) if m1: + + # Example: + # + # line: KEY_499=abc#def + # key: KEY_499 + # val: abc#def key, val = m1.group(1), m1.group(2) - # Look for value in quotes, ignore post-# comments - # (outside quotes) - m2 = re.match(r"\A\s*'(?<!\\)(.*)'\s*(#.*\s*)?\Z", val) - if m2: - val = m2.group(1) + + if not parse_comments: + # Default behavior + # + # Look for value in single quotes + m2 = re.match(r"\A'(.*)'\Z", val) + if m2: + val = m2.group(1) else: - # For no quotes, find value, ignore comments - # after the first # - m2a = re.match(r"\A(.*?)(#.*\s*)?\Z", val) - if m2a: - val = m2a.group(1) + # Ignore post-# comments (outside quotes). + # Something like ['val' # comment] becomes ['val']. + m2 = re.match(r"\A\s*'(?<!\\)(.*)'\s*(#.*\s*)?\Z", val) + if m2: + val = m2.group(1) + else: + # For no quotes, find value, ignore comments + # after the first # + m2a = re.match(r"\A(.*?)(#.*\s*)?\Z", val) + if m2a: + val = m2a.group(1) + + # Look for value in double quotes m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', _keep_escaped_format_characters, m3.group(1)) + overrides[key] = str(val) elif not line or line.startswith('#'): # ignore warnings for empty line-breaks or comments
joke2k/django-environ
7b5d7f933dc91fd43d744f06d2282860ee53aa38
diff --git a/tests/test_env.py b/tests/test_env.py index 0b105f5..85e0499 100644 --- a/tests/test_env.py +++ b/tests/test_env.py @@ -7,6 +7,7 @@ # the LICENSE.txt file that was distributed with this source code. import os +import tempfile from urllib.parse import quote import pytest @@ -21,6 +22,59 @@ from .asserts import assert_type_and_value from .fixtures import FakeEnv [email protected]( + 'variable,value,raw_value,parse_comments', + [ + # parse_comments=True + ('BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT', 'True', "'True' # comment\n", True), + ('BOOL_TRUE_BOOL_WITH_COMMENT', 'True ', "True # comment\n", True), + ('STR_QUOTED_IGNORE_COMMENT', 'foo', " 'foo' # comment\n", True), + ('STR_QUOTED_INCLUDE_HASH', 'foo # with hash', "'foo # with hash' # not comment\n", True), + ('SECRET_KEY_1', '"abc', '"abc#def"\n', True), + ('SECRET_KEY_2', 'abc', 'abc#def\n', True), + ('SECRET_KEY_3', 'abc#def', "'abc#def'\n", True), + + # parse_comments=False + ('BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT', "'True' # comment", "'True' # comment\n", False), + ('BOOL_TRUE_BOOL_WITH_COMMENT', 'True # comment', "True # comment\n", False), + ('STR_QUOTED_IGNORE_COMMENT', " 'foo' # comment", " 'foo' # comment\n", False), + ('STR_QUOTED_INCLUDE_HASH', "'foo # with hash' # not comment", "'foo # with hash' # not comment\n", False), + ('SECRET_KEY_1', 'abc#def', '"abc#def"\n', False), + ('SECRET_KEY_2', 'abc#def', 'abc#def\n', False), + ('SECRET_KEY_3', 'abc#def', "'abc#def'\n", False), + + # parse_comments is not defined (default behavior) + ('BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT', "'True' # comment", "'True' # comment\n", None), + ('BOOL_TRUE_BOOL_WITH_COMMENT', 'True # comment', "True # comment\n", None), + ('STR_QUOTED_IGNORE_COMMENT', " 'foo' # comment", " 'foo' # comment\n", None), + ('STR_QUOTED_INCLUDE_HASH', "'foo # with hash' # not comment", "'foo # with hash' # not comment\n", None), + ('SECRET_KEY_1', 'abc#def', '"abc#def"\n', None), + ('SECRET_KEY_2', 'abc#def', 'abc#def\n', None), + ('SECRET_KEY_3', 'abc#def', "'abc#def'\n", None), + ], + ) +def test_parse_comments(variable, value, raw_value, parse_comments): + old_environ = os.environ + + with tempfile.TemporaryDirectory() as temp_dir: + env_path = os.path.join(temp_dir, '.env') + + with open(env_path, 'w') as f: + f.write(f'{variable}={raw_value}\n') + f.flush() + + env = Env() + Env.ENVIRON = {} + if parse_comments is None: + env.read_env(env_path) + else: + env.read_env(env_path, parse_comments=parse_comments) + + assert env(variable) == value + + os.environ = old_environ + + class TestEnv: def setup_method(self, method): """ @@ -112,10 +166,8 @@ class TestEnv: [ (True, 'BOOL_TRUE_STRING_LIKE_INT'), (True, 'BOOL_TRUE_STRING_LIKE_BOOL'), - (True, 'BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT'), (True, 'BOOL_TRUE_INT'), (True, 'BOOL_TRUE_BOOL'), - (True, 'BOOL_TRUE_BOOL_WITH_COMMENT'), (True, 'BOOL_TRUE_STRING_1'), (True, 'BOOL_TRUE_STRING_2'), (True, 'BOOL_TRUE_STRING_3'), @@ -341,8 +393,6 @@ class TestEnv: def test_smart_cast(self): assert self.env.get_value('STR_VAR', default='string') == 'bar' - assert self.env.get_value('STR_QUOTED_IGNORE_COMMENT', default='string') == 'foo' - assert self.env.get_value('STR_QUOTED_INCLUDE_HASH', default='string') == 'foo # with hash' assert self.env.get_value('BOOL_TRUE_STRING_LIKE_INT', default=True) assert not self.env.get_value( 'BOOL_FALSE_STRING_LIKE_INT', diff --git a/tests/test_env.txt b/tests/test_env.txt index d5480bf..39ab896 100644 --- a/tests/test_env.txt +++ b/tests/test_env.txt @@ -25,8 +25,6 @@ BOOL_TRUE_STRING_3='yes' BOOL_TRUE_STRING_4='y' BOOL_TRUE_STRING_5='true' BOOL_TRUE_BOOL=True -BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT='True' # comment -BOOL_TRUE_BOOL_WITH_COMMENT=True # comment BOOL_FALSE_STRING_LIKE_INT='0' BOOL_FALSE_INT=0 BOOL_FALSE_STRING_LIKE_BOOL='False' @@ -47,8 +45,6 @@ INT_VAR=42 STR_LIST_WITH_SPACES= foo, spaces STR_LIST_WITH_SPACES_QUOTED=' foo',' quoted' STR_VAR=bar -STR_QUOTED_IGNORE_COMMENT= 'foo' # comment -STR_QUOTED_INCLUDE_HASH='foo # with hash' # not comment MULTILINE_STR_VAR=foo\nbar MULTILINE_QUOTED_STR_VAR="---BEGIN---\r\n---END---" MULTILINE_ESCAPED_STR_VAR=---BEGIN---\\n---END---
Hash sign inside double quotes is interpreted as the start of a comment Ran into this problem when updating to `0.11.2` for a project with an `.env` file like this: ``` SECRET_KEY="abc#def" ``` The `SECRET_KEY` used to be `abc#def` but now is read as `"abc`. Apparently the `#` is interpreted as the start of a comment now, except in *singly*-quoted strings. Looking at the tests for this new feature only the single-quoted case is tested, but the documentation contains examples with double quotes. It seems they are not treated the same in this case; is this intended behaviour?
0.0
7b5d7f933dc91fd43d744f06d2282860ee53aa38
[ "tests/test_env.py::test_parse_comments[BOOL_TRUE_BOOL_WITH_COMMENT-True", "tests/test_env.py::test_parse_comments[BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT-'True'", "tests/test_env.py::test_parse_comments[STR_QUOTED_IGNORE_COMMENT-", "tests/test_env.py::test_parse_comments[STR_QUOTED_INCLUDE_HASH-'foo", "tests/test_env.py::test_parse_comments[SECRET_KEY_1-abc#def-\"abc#def\"\\n-False]", "tests/test_env.py::test_parse_comments[SECRET_KEY_2-abc#def-abc#def\\n-False]", "tests/test_env.py::test_parse_comments[SECRET_KEY_1-abc#def-\"abc#def\"\\n-None]", "tests/test_env.py::test_parse_comments[SECRET_KEY_2-abc#def-abc#def\\n-None]" ]
[ "tests/test_env.py::test_parse_comments[BOOL_TRUE_STRING_LIKE_BOOL_WITH_COMMENT-True-'True'", "tests/test_env.py::test_parse_comments[STR_QUOTED_IGNORE_COMMENT-foo-", "tests/test_env.py::test_parse_comments[STR_QUOTED_INCLUDE_HASH-foo", "tests/test_env.py::test_parse_comments[SECRET_KEY_1-\"abc-\"abc#def\"\\n-True]", "tests/test_env.py::test_parse_comments[SECRET_KEY_2-abc-abc#def\\n-True]", "tests/test_env.py::test_parse_comments[SECRET_KEY_3-abc#def-'abc#def'\\n-True]", "tests/test_env.py::test_parse_comments[SECRET_KEY_3-abc#def-'abc#def'\\n-False]", "tests/test_env.py::test_parse_comments[SECRET_KEY_3-abc#def-'abc#def'\\n-None]", "tests/test_env.py::TestEnv::test_not_present_with_default", "tests/test_env.py::TestEnv::test_not_present_without_default", "tests/test_env.py::TestEnv::test_contains", "tests/test_env.py::TestEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestEnv::test_int", "tests/test_env.py::TestEnv::test_int_with_none_default", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestEnv::test_proxied_value", "tests/test_env.py::TestEnv::test_escaped_dollar_sign", "tests/test_env.py::TestEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestEnv::test_int_list", "tests/test_env.py::TestEnv::test_int_list_cast_tuple", "tests/test_env.py::TestEnv::test_int_tuple", "tests/test_env.py::TestEnv::test_mix_tuple_issue_387", "tests/test_env.py::TestEnv::test_str_list_with_spaces", "tests/test_env.py::TestEnv::test_empty_list", "tests/test_env.py::TestEnv::test_dict_value", "tests/test_env.py::TestEnv::test_complex_dict_value", "tests/test_env.py::TestEnv::test_dict_parsing[dict]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestEnv::test_url_value", "tests/test_env.py::TestEnv::test_url_empty_string_default_value", "tests/test_env.py::TestEnv::test_url_encoded_parts", "tests/test_env.py::TestEnv::test_db_url_value[postgres]", "tests/test_env.py::TestEnv::test_db_url_value[mysql]", "tests/test_env.py::TestEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestEnv::test_db_url_value[oracle]", "tests/test_env.py::TestEnv::test_db_url_value[redshift]", "tests/test_env.py::TestEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestEnv::test_db_url_value[custom]", "tests/test_env.py::TestEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestEnv::test_cache_url_value[redis]", "tests/test_env.py::TestEnv::test_email_url_value", "tests/test_env.py::TestEnv::test_json_value", "tests/test_env.py::TestEnv::test_path", "tests/test_env.py::TestEnv::test_smart_cast", "tests/test_env.py::TestEnv::test_exported", "tests/test_env.py::TestEnv::test_prefix", "tests/test_env.py::TestFileEnv::test_not_present_with_default", "tests/test_env.py::TestFileEnv::test_not_present_without_default", "tests/test_env.py::TestFileEnv::test_contains", "tests/test_env.py::TestFileEnv::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestFileEnv::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestFileEnv::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestFileEnv::test_int", "tests/test_env.py::TestFileEnv::test_int_with_none_default", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestFileEnv::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestFileEnv::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestFileEnv::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestFileEnv::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestFileEnv::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestFileEnv::test_proxied_value", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign", "tests/test_env.py::TestFileEnv::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestFileEnv::test_int_list", "tests/test_env.py::TestFileEnv::test_int_list_cast_tuple", "tests/test_env.py::TestFileEnv::test_int_tuple", "tests/test_env.py::TestFileEnv::test_mix_tuple_issue_387", "tests/test_env.py::TestFileEnv::test_str_list_with_spaces", "tests/test_env.py::TestFileEnv::test_empty_list", "tests/test_env.py::TestFileEnv::test_dict_value", "tests/test_env.py::TestFileEnv::test_complex_dict_value", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_float]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestFileEnv::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestFileEnv::test_url_value", "tests/test_env.py::TestFileEnv::test_url_empty_string_default_value", "tests/test_env.py::TestFileEnv::test_url_encoded_parts", "tests/test_env.py::TestFileEnv::test_db_url_value[postgres]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql]", "tests/test_env.py::TestFileEnv::test_db_url_value[mysql_gis]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle_tns]", "tests/test_env.py::TestFileEnv::test_db_url_value[oracle]", "tests/test_env.py::TestFileEnv::test_db_url_value[redshift]", "tests/test_env.py::TestFileEnv::test_db_url_value[sqlite]", "tests/test_env.py::TestFileEnv::test_db_url_value[custom]", "tests/test_env.py::TestFileEnv::test_db_url_value[cloudsql]", "tests/test_env.py::TestFileEnv::test_cache_url_value[memcached]", "tests/test_env.py::TestFileEnv::test_cache_url_value[redis]", "tests/test_env.py::TestFileEnv::test_email_url_value", "tests/test_env.py::TestFileEnv::test_json_value", "tests/test_env.py::TestFileEnv::test_path", "tests/test_env.py::TestFileEnv::test_smart_cast", "tests/test_env.py::TestFileEnv::test_exported", "tests/test_env.py::TestFileEnv::test_prefix", "tests/test_env.py::TestFileEnv::test_read_env_path_like", "tests/test_env.py::TestFileEnv::test_existing_overwrite[True]", "tests/test_env.py::TestFileEnv::test_existing_overwrite[False]", "tests/test_env.py::TestSubClass::test_not_present_with_default", "tests/test_env.py::TestSubClass::test_not_present_without_default", "tests/test_env.py::TestSubClass::test_contains", "tests/test_env.py::TestSubClass::test_str[STR_VAR-bar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\\\nbar-False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_STR_VAR-foo\\nbar-True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\\\r\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_QUOTED_STR_VAR----BEGIN---\\n---END----True]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\\\n---END----False]", "tests/test_env.py::TestSubClass::test_str[MULTILINE_ESCAPED_STR_VAR----BEGIN---\\\\\\n---END----True]", "tests/test_env.py::TestSubClass::test_bytes[STR_VAR-bar-default0]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_BYTES_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_bytes[NON_EXISTENT_STR_VAR-some-default-some-default]", "tests/test_env.py::TestSubClass::test_int", "tests/test_env.py::TestSubClass::test_int_with_none_default", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_VAR]", "tests/test_env.py::TestSubClass::test_float[33.3-FLOAT_COMMA_VAR]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR1]", "tests/test_env.py::TestSubClass::test_float[123420333.3-FLOAT_STRANGE_VAR2]", "tests/test_env.py::TestSubClass::test_float[-1.0-FLOAT_NEGATIVE_VAR]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_1]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_2]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_3]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_4]", "tests/test_env.py::TestSubClass::test_bool_true[True-BOOL_TRUE_STRING_5]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_INT]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_STRING_LIKE_BOOL]", "tests/test_env.py::TestSubClass::test_bool_true[False-BOOL_FALSE_BOOL]", "tests/test_env.py::TestSubClass::test_proxied_value", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign", "tests/test_env.py::TestSubClass::test_escaped_dollar_sign_disabled", "tests/test_env.py::TestSubClass::test_int_list", "tests/test_env.py::TestSubClass::test_int_list_cast_tuple", "tests/test_env.py::TestSubClass::test_int_tuple", "tests/test_env.py::TestSubClass::test_mix_tuple_issue_387", "tests/test_env.py::TestSubClass::test_str_list_with_spaces", "tests/test_env.py::TestSubClass::test_empty_list", "tests/test_env.py::TestSubClass::test_dict_value", "tests/test_env.py::TestSubClass::test_complex_dict_value", "tests/test_env.py::TestSubClass::test_dict_parsing[dict]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_float]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_list]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_int_cast]", "tests/test_env.py::TestSubClass::test_dict_parsing[dict_str_cast]", "tests/test_env.py::TestSubClass::test_url_value", "tests/test_env.py::TestSubClass::test_url_empty_string_default_value", "tests/test_env.py::TestSubClass::test_url_encoded_parts", "tests/test_env.py::TestSubClass::test_db_url_value[postgres]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql]", "tests/test_env.py::TestSubClass::test_db_url_value[mysql_gis]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle_tns]", "tests/test_env.py::TestSubClass::test_db_url_value[oracle]", "tests/test_env.py::TestSubClass::test_db_url_value[redshift]", "tests/test_env.py::TestSubClass::test_db_url_value[sqlite]", "tests/test_env.py::TestSubClass::test_db_url_value[custom]", "tests/test_env.py::TestSubClass::test_db_url_value[cloudsql]", "tests/test_env.py::TestSubClass::test_cache_url_value[memcached]", "tests/test_env.py::TestSubClass::test_cache_url_value[redis]", "tests/test_env.py::TestSubClass::test_email_url_value", "tests/test_env.py::TestSubClass::test_json_value", "tests/test_env.py::TestSubClass::test_path", "tests/test_env.py::TestSubClass::test_smart_cast", "tests/test_env.py::TestSubClass::test_exported", "tests/test_env.py::TestSubClass::test_prefix", "tests/test_env.py::TestSubClass::test_singleton_environ" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-08 20:18:09+00:00
mit
3,293
joke2k__faker-1037
diff --git a/faker/build_docs.py b/faker/build_docs.py index 3afc4714..17a96d3d 100644 --- a/faker/build_docs.py +++ b/faker/build_docs.py @@ -15,6 +15,12 @@ def write(fh, s): return fh.write(s.encode('utf-8')) +def write_base_provider(fh, doc, base_provider): + formatters = doc.get_provider_formatters(base_provider) + write(fh, ':github_url: hide\n\n') + write_provider(fh, doc, base_provider, formatters) + + def write_provider(fh, doc, provider, formatters, excludes=None): if excludes is None: @@ -47,16 +53,21 @@ def write_provider(fh, doc, provider, formatters, excludes=None): def write_docs(*args, **kwargs): from faker import Faker, documentor from faker.config import DEFAULT_LOCALE, AVAILABLE_LOCALES - - fake = Faker(locale=DEFAULT_LOCALE) - from faker.providers import BaseProvider - base_provider_formatters = [f for f in dir(BaseProvider)] + fake = Faker(locale=DEFAULT_LOCALE) doc = documentor.Documentor(fake) - formatters = doc.get_formatters(with_args=True, with_defaults=True) + # Write docs for fakers.providers.BaseProvider + base_provider = BaseProvider(fake) + fname = os.path.join(DOCS_ROOT, 'providers', 'BaseProvider.rst') + with open(fname, 'wb') as fh: + write_base_provider(fh, doc, base_provider) + # Write docs for default locale providers + base_provider_formatters = [f for f in dir(BaseProvider)] + formatters = doc.get_formatters(with_args=True, with_defaults=True, + excludes=base_provider_formatters) for provider, fakers in formatters: provider_name = doc.get_provider_name(provider) fname = os.path.join(DOCS_ROOT, 'providers', '%s.rst' % provider_name) @@ -64,15 +75,18 @@ def write_docs(*args, **kwargs): write(fh, ':github_url: hide\n\n') write_provider(fh, doc, provider, fakers) + # Write providers index page with open(os.path.join(DOCS_ROOT, 'providers.rst'), 'wb') as fh: write(fh, ':github_url: hide\n\n') write(fh, 'Providers\n') write(fh, '=========\n') write(fh, '.. toctree::\n') write(fh, ' :maxdepth: 2\n\n') + write(fh, ' providers/BaseProvider\n') [write(fh, ' providers/%s\n' % doc.get_provider_name(provider)) for provider, fakers in formatters] + # Write docs for locale-specific providers AVAILABLE_LOCALES = sorted(AVAILABLE_LOCALES) for lang in AVAILABLE_LOCALES: fname = os.path.join(DOCS_ROOT, 'locales', '%s.rst' % lang) @@ -90,6 +104,7 @@ def write_docs(*args, **kwargs): excludes=base_provider_formatters): write_provider(fh, d, p, fs) + # Write locales index page with open(os.path.join(DOCS_ROOT, 'locales.rst'), 'wb') as fh: write(fh, ':github_url: hide\n\n') write(fh, 'Locales\n') diff --git a/faker/documentor.py b/faker/documentor.py index 034c38f0..378104ae 100644 --- a/faker/documentor.py +++ b/faker/documentor.py @@ -22,7 +22,6 @@ class Documentor(object): self.already_generated = [] def get_formatters(self, locale=None, excludes=None, **kwargs): - self.max_name_len = 0 self.already_generated = [] if excludes is None else excludes[:] formatters = [] diff --git a/faker/providers/internet/__init__.py b/faker/providers/internet/__init__.py index 91bc9f2f..d7775597 100644 --- a/faker/providers/internet/__init__.py +++ b/faker/providers/internet/__init__.py @@ -10,6 +10,7 @@ from ipaddress import ip_address, ip_network, IPV4LENGTH, IPV6LENGTH # from faker.generator import random # from faker.providers.lorem.la import Provider as Lorem from faker.utils.decorators import lowercase, slugify, slugify_unicode +from faker.utils.distribution import choices_distribution localized = True @@ -29,12 +30,6 @@ class _IPv4Constants: 'c': ip_network('192.0.0.0/3'), } - _linklocal_network = ip_network('169.254.0.0/16') - - _loopback_network = ip_network('127.0.0.0/8') - - _multicast_network = ip_network('224.0.0.0/4') - # Three common private networks from class A, B and CIDR # to generate private addresses from. _private_networks = [ @@ -49,8 +44,8 @@ class _IPv4Constants: _excluded_networks = [ ip_network('0.0.0.0/8'), ip_network('100.64.0.0/10'), - ip_network('127.0.0.0/8'), - ip_network('169.254.0.0/16'), + ip_network('127.0.0.0/8'), # loopback network + ip_network('169.254.0.0/16'), # linklocal network ip_network('192.0.0.0/24'), ip_network('192.0.2.0/24'), ip_network('192.31.196.0/24'), @@ -60,12 +55,9 @@ class _IPv4Constants: ip_network('198.18.0.0/15'), ip_network('198.51.100.0/24'), ip_network('203.0.113.0/24'), + ip_network('224.0.0.0/4'), # multicast network ip_network('240.0.0.0/4'), ip_network('255.255.255.255/32'), - ] + [ - _linklocal_network, - _loopback_network, - _multicast_network, ] @@ -251,14 +243,123 @@ class Provider(BaseProvider): return self.generator.parse(pattern) - def _random_ipv4_address_from_subnet(self, subnet, network=False): + def _get_all_networks_and_weights(self, address_class=None): + """ + Produces a 2-tuple of valid IPv4 networks and corresponding relative weights + + :param address_class: IPv4 address class (a, b, or c) + """ + # If `address_class` has an unexpected value, use the whole IPv4 pool + if address_class in _IPv4Constants._network_classes.keys(): + networks_attr = '_cached_all_class_{}_networks'.format(address_class) + all_networks = [_IPv4Constants._network_classes[address_class]] + else: + networks_attr = '_cached_all_networks' + all_networks = [ip_network('0.0.0.0/0')] + + # Return cached network and weight data if available + weights_attr = '{}_weights'.format(networks_attr) + if hasattr(self, networks_attr) and hasattr(self, weights_attr): + return getattr(self, networks_attr), getattr(self, weights_attr) + + # Otherwise, compute for list of networks (excluding special networks) + all_networks = self._exclude_ipv4_networks( + all_networks, + _IPv4Constants._excluded_networks, + ) + + # Then compute for list of corresponding relative weights + weights = [network.num_addresses for network in all_networks] + + # Then cache and return results + setattr(self, networks_attr, all_networks) + setattr(self, weights_attr, weights) + return all_networks, weights + + def _get_private_networks_and_weights(self, address_class=None): + """ + Produces an OrderedDict of valid private IPv4 networks and corresponding relative weights + + :param address_class: IPv4 address class (a, b, or c) + """ + # If `address_class` has an unexpected value, choose a valid value at random + if address_class not in _IPv4Constants._network_classes.keys(): + address_class = self.ipv4_network_class() + + # Return cached network and weight data if available for a specific address class + networks_attr = '_cached_private_class_{}_networks'.format(address_class) + weights_attr = '{}_weights'.format(networks_attr) + if hasattr(self, networks_attr) and hasattr(self, weights_attr): + return getattr(self, networks_attr), getattr(self, weights_attr) + + # Otherwise, compute for list of private networks (excluding special networks) + supernet = _IPv4Constants._network_classes[address_class] + private_networks = [ + subnet for subnet in _IPv4Constants._private_networks + if subnet.overlaps(supernet) + ] + private_networks = self._exclude_ipv4_networks( + private_networks, + _IPv4Constants._excluded_networks, + ) + + # Then compute for list of corresponding relative weights + weights = [network.num_addresses for network in private_networks] + + # Then cache and return results + setattr(self, networks_attr, private_networks) + setattr(self, weights_attr, weights) + return private_networks, weights + + def _get_public_networks_and_weights(self, address_class=None): + """ + Produces a 2-tuple of valid public IPv4 networks and corresponding relative weights + + :param address_class: IPv4 address class (a, b, or c) + """ + # If `address_class` has an unexpected value, choose a valid value at random + if address_class not in _IPv4Constants._network_classes.keys(): + address_class = self.ipv4_network_class() + + # Return cached network and weight data if available for a specific address class + networks_attr = '_cached_public_class_{}_networks'.format(address_class) + weights_attr = '{}_weights'.format(networks_attr) + if hasattr(self, networks_attr) and hasattr(self, weights_attr): + return getattr(self, networks_attr), getattr(self, weights_attr) + + # Otherwise, compute for list of public networks (excluding private and special networks) + public_networks = [_IPv4Constants._network_classes[address_class]] + public_networks = self._exclude_ipv4_networks( + public_networks, + _IPv4Constants._private_networks + + _IPv4Constants._excluded_networks, + ) + + # Then compute for list of corresponding relative weights + weights = [network.num_addresses for network in public_networks] + + # Then cache and return results + setattr(self, networks_attr, public_networks) + setattr(self, weights_attr, weights) + return public_networks, weights + + def _random_ipv4_address_from_subnets(self, subnets, weights=None, network=False): """ Produces a random IPv4 address or network with a valid CIDR - from within a given subnet. + from within the given subnets using a distribution described + by weights. - :param subnet: IPv4Network to choose from within + :param subnets: List of IPv4Networks to choose from within + :param weights: List of weights corresponding to the individual IPv4Networks :param network: Return a network address, and not an IP address + :return: """ + # If the weights argument has an invalid value, default to equal distribution + try: + subnet = choices_distribution(subnets, weights, random=self.generator.random, length=1)[0] + except (AssertionError, TypeError): + subnet = self.generator.random.choice(subnets) + address = str( subnet[self.generator.random.randint( 0, subnet.num_addresses - 1, @@ -283,6 +384,7 @@ class Provider(BaseProvider): :param networks_to_exclude: List of IPv4 networks to exclude :returns: Flat list of IPv4 networks """ + networks_to_exclude.sort(key=lambda x: x.prefixlen) for network_to_exclude in networks_to_exclude: def _exclude_ipv4_network(network): """ @@ -327,7 +429,7 @@ class Provider(BaseProvider): def ipv4(self, network=False, address_class=None, private=None): """ - Produce a random IPv4 address or network with a valid CIDR. + Returns a random IPv4 address or network with a valid CIDR. :param network: Network address :param address_class: IPv4 address class (a, b, or c) @@ -340,25 +442,9 @@ class Provider(BaseProvider): elif private is False: return self.ipv4_public(address_class=address_class, network=network) - - # if neither private nor public is required explicitly, - # generate from whole requested address space - if address_class: - all_networks = [_IPv4Constants._network_classes[address_class]] else: - # if no address class is choosen, use whole IPv4 pool - all_networks = [ip_network('0.0.0.0/0')] - - # exclude special networks - all_networks = self._exclude_ipv4_networks( - all_networks, - _IPv4Constants._excluded_networks, - ) - - # choose random network from the list - random_network = self.generator.random.choice(all_networks) - - return self._random_ipv4_address_from_subnet(random_network, network) + all_networks, weights = self._get_all_networks_and_weights(address_class=address_class) + return self._random_ipv4_address_from_subnets(all_networks, weights=weights, network=network) def ipv4_private(self, network=False, address_class=None): """ @@ -368,26 +454,8 @@ class Provider(BaseProvider): :param address_class: IPv4 address class (a, b, or c) :returns: Private IPv4 """ - # compute private networks from given class - supernet = _IPv4Constants._network_classes[ - address_class or self.ipv4_network_class() - ] - - private_networks = [ - subnet for subnet in _IPv4Constants._private_networks - if subnet.overlaps(supernet) - ] - - # exclude special networks - private_networks = self._exclude_ipv4_networks( - private_networks, - _IPv4Constants._excluded_networks, - ) - - # choose random private network from the list - private_network = self.generator.random.choice(private_networks) - - return self._random_ipv4_address_from_subnet(private_network, network) + private_networks, weights = self._get_private_networks_and_weights(address_class=address_class) + return self._random_ipv4_address_from_subnets(private_networks, weights=weights, network=network) def ipv4_public(self, network=False, address_class=None): """ @@ -397,22 +465,8 @@ class Provider(BaseProvider): :param address_class: IPv4 address class (a, b, or c) :returns: Public IPv4 """ - # compute public networks - public_networks = [_IPv4Constants._network_classes[ - address_class or self.ipv4_network_class() - ]] - - # exclude private and excluded special networks - public_networks = self._exclude_ipv4_networks( - public_networks, - _IPv4Constants._private_networks + - _IPv4Constants._excluded_networks, - ) - - # choose random public network from the list - public_network = self.generator.random.choice(public_networks) - - return self._random_ipv4_address_from_subnet(public_network, network) + public_networks, weights = self._get_public_networks_and_weights(address_class=address_class) + return self._random_ipv4_address_from_subnets(public_networks, weights=weights, network=network) def ipv6(self, network=False): """Produce a random IPv6 address or network with a valid CIDR"""
joke2k/faker
8941a9f149405d0f7fedc509a8d54b3aec50e4a0
diff --git a/tests/test_factory.py b/tests/test_factory.py index 110728cb..a87fc3bd 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -6,6 +6,10 @@ import re import string import sys import unittest +try: + from unittest.mock import patch, PropertyMock +except ImportError: + from mock import patch, PropertyMock from collections import OrderedDict from ipaddress import ip_address, ip_network @@ -526,6 +530,41 @@ class FactoryTestCase(unittest.TestCase): email = factory.email() assert '@' in email + def test_ipv4_caching(self): + from faker.providers.internet import Provider, _IPv4Constants + + # The extra [None] here is to test code path involving whole IPv4 pool + for address_class in list(_IPv4Constants._network_classes.keys()) + [None]: + if address_class is None: + networks_attr = '_cached_all_networks' + else: + networks_attr = '_cached_all_class_{}_networks'.format(address_class) + weights_attr = '{}_weights'.format(networks_attr) + provider = Provider(self.generator) + + # First, test cache creation + assert not hasattr(provider, networks_attr) + assert not hasattr(provider, weights_attr) + provider.ipv4(address_class=address_class) + assert hasattr(provider, networks_attr) + assert hasattr(provider, weights_attr) + + # Then, test cache access on subsequent calls + with patch.object(Provider, networks_attr, create=True, + new_callable=PropertyMock) as mock_networks_cache: + with patch.object(Provider, weights_attr, create=True, + new_callable=PropertyMock) as mock_weights_cache: + # Keep test fast by patching the cache attributes to return something simple + mock_networks_cache.return_value = [ip_network('10.0.0.0/24')] + mock_weights_cache.return_value = [10] + for _ in range(100): + provider.ipv4(address_class=address_class) + + # Python's hasattr() internally calls getattr() + # So each call to ipv4() accesses the cache attributes twice + assert mock_networks_cache.call_count == 200 + assert mock_weights_cache.call_count == 200 + def test_ipv4(self): from faker.providers.internet import Provider @@ -565,6 +604,37 @@ class FactoryTestCase(unittest.TestCase): klass = provider.ipv4_network_class() assert klass in 'abc' + def test_ipv4_private_caching(self): + from faker.providers.internet import Provider, _IPv4Constants + + for address_class in _IPv4Constants._network_classes.keys(): + networks_attr = '_cached_private_class_{}_networks'.format(address_class) + weights_attr = '{}_weights'.format(networks_attr) + provider = Provider(self.generator) + + # First, test cache creation + assert not hasattr(provider, networks_attr) + assert not hasattr(provider, weights_attr) + provider.ipv4_private(address_class=address_class) + assert hasattr(provider, networks_attr) + assert hasattr(provider, weights_attr) + + # Then, test cache access on subsequent calls + with patch.object(Provider, networks_attr, create=True, + new_callable=PropertyMock) as mock_networks_cache: + with patch.object(Provider, weights_attr, create=True, + new_callable=PropertyMock) as mock_weights_cache: + # Keep test fast by patching the cache attributes to return something simple + mock_networks_cache.return_value = [ip_network('10.0.0.0/24')] + mock_weights_cache.return_value = [10] + for _ in range(100): + provider.ipv4_private(address_class=address_class) + + # Python's hasattr() internally calls getattr() + # So each call to ipv4_private() accesses the cache attributes twice + assert mock_networks_cache.call_count == 200 + assert mock_weights_cache.call_count == 200 + def test_ipv4_private(self): from faker.providers.internet import Provider provider = Provider(self.generator) @@ -638,6 +708,37 @@ class FactoryTestCase(unittest.TestCase): assert ip_address(address) >= class_min assert ip_address(address) <= class_max + def test_ipv4_public_caching(self): + from faker.providers.internet import Provider, _IPv4Constants + + for address_class in _IPv4Constants._network_classes.keys(): + networks_attr = '_cached_public_class_{}_networks'.format(address_class) + weights_attr = '{}_weights'.format(networks_attr) + provider = Provider(self.generator) + + # First, test cache creation + assert not hasattr(provider, networks_attr) + assert not hasattr(provider, weights_attr) + provider.ipv4_public(address_class=address_class) + assert hasattr(provider, networks_attr) + assert hasattr(provider, weights_attr) + + # Then, test cache access on subsequent calls + with patch.object(Provider, networks_attr, create=True, + new_callable=PropertyMock) as mock_networks_cache: + with patch.object(Provider, weights_attr, create=True, + new_callable=PropertyMock) as mock_weights_cache: + # Keep test fast by patching the cache attributes to return something simple + mock_networks_cache.return_value = [ip_network('10.0.0.0/24')] + mock_weights_cache.return_value = [10] + for _ in range(100): + provider.ipv4_public(address_class=address_class) + + # Python's hasattr() internally calls getattr() + # So each call to ipv4_public() accesses the cache attributes twice + assert mock_networks_cache.call_count == 200 + assert mock_weights_cache.call_count == 200 + def test_ipv4_public(self): from faker.providers.internet import Provider provider = Provider(self.generator) @@ -697,6 +798,39 @@ class FactoryTestCase(unittest.TestCase): assert len(address) <= 15 assert not ip_address(address).is_private, address + def test_ipv4_distribution_selection(self): + from faker.providers.internet import Provider + from faker.utils.distribution import choices_distribution + provider = Provider(self.generator) + + subnets = [ip_network('10.0.0.0/8'), ip_network('11.0.0.0/8')] + valid_weights = [1, 1] + list_of_invalid_weights = [ + [1, 2, 3], # List size does not match subnet list size + ['a', 'b'], # List size matches, but elements are invalid + None, # Not a list or valid iterable + ] + + with patch('faker.providers.internet.choices_distribution', + wraps=choices_distribution) as mock_choices_fn: + with patch('faker.generator.random.choice', + wraps=random.choice) as mock_random_choice: + # If weights argument is valid, only `choices_distribution` should be called + provider._random_ipv4_address_from_subnets(subnets, valid_weights) + assert mock_choices_fn.call_count == 1 + assert mock_random_choice.call_count == 0 + + # If weights argument is invalid, calls to `choices_distribution` will fail + # and calls to `random.choice` will be made as failover behavior + for invalid_weights in list_of_invalid_weights: + # Reset mock objects for each iteration + mock_random_choice.reset_mock() + mock_choices_fn.reset_mock() + + provider._random_ipv4_address_from_subnets(subnets, invalid_weights) + assert mock_choices_fn.call_count == 1 + assert mock_random_choice.call_count == 1 + def test_ipv6(self): from faker.providers.internet import Provider
ipv4 faker very slow Hi! We updated from Faker 0.9.0 to 0.9.2 and noticed our tests speed decreased by 5X. We tracked the bug to the changes in the ipv4 faker done in commit 3b847f48bbfc33aed3e86cffcedbcfd1c0cccec5 ### Steps to reproduce 1. checkout to commit 3b847f48bbfc33aed3e86cffcedbcfd1c0cccec5 1. run the following: `time python -c 'import faker; fake = faker.Faker(); [fake.ipv4() for _ in range(100)]'` 1. Check its output to see it was slow. in my laptop it took about 6 seconds. 1. Run `git checkout HEAD~1` to go to a working commit 1. Run the command of step 2 again and it will work much faster (in my case it took 0.4 seconds) ### Expected behavior Generating ivp4 addresses should be fast ### Actual behavior Generating ipv4 addresses is slow
0.0
8941a9f149405d0f7fedc509a8d54b3aec50e4a0
[ "tests/test_factory.py::FactoryTestCase::test_ipv4_caching", "tests/test_factory.py::FactoryTestCase::test_ipv4_distribution_selection", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_caching", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_caching" ]
[ "tests/test_factory.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "tests/test_factory.py::FactoryTestCase::test_binary", "tests/test_factory.py::FactoryTestCase::test_cli_seed", "tests/test_factory.py::FactoryTestCase::test_cli_seed_with_repeat", "tests/test_factory.py::FactoryTestCase::test_cli_verbosity", "tests/test_factory.py::FactoryTestCase::test_command", "tests/test_factory.py::FactoryTestCase::test_command_custom_provider", "tests/test_factory.py::FactoryTestCase::test_documentor", "tests/test_factory.py::FactoryTestCase::test_email", "tests/test_factory.py::FactoryTestCase::test_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_format_calls_formatter_on_provider", "tests/test_factory.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_callable", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "tests/test_factory.py::FactoryTestCase::test_instance_seed_chain", "tests/test_factory.py::FactoryTestCase::test_invalid_locale", "tests/test_factory.py::FactoryTestCase::test_ipv4", "tests/test_factory.py::FactoryTestCase::test_ipv4_network_class", "tests/test_factory.py::FactoryTestCase::test_ipv4_private", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv4_public", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv6", "tests/test_factory.py::FactoryTestCase::test_language_code", "tests/test_factory.py::FactoryTestCase::test_locale", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "tests/test_factory.py::FactoryTestCase::test_negative_pyfloat", "tests/test_factory.py::FactoryTestCase::test_nl_BE_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_no_words", "tests/test_factory.py::FactoryTestCase::test_no_words_paragraph", "tests/test_factory.py::FactoryTestCase::test_no_words_sentence", "tests/test_factory.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "tests/test_factory.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "tests/test_factory.py::FactoryTestCase::test_password", "tests/test_factory.py::FactoryTestCase::test_prefix_suffix_always_string", "tests/test_factory.py::FactoryTestCase::test_pyfloat_in_range", "tests/test_factory.py::FactoryTestCase::test_random_element", "tests/test_factory.py::FactoryTestCase::test_random_number", "tests/test_factory.py::FactoryTestCase::test_random_pyfloat", "tests/test_factory.py::FactoryTestCase::test_random_pystr_characters", "tests/test_factory.py::FactoryTestCase::test_random_sample_unique", "tests/test_factory.py::FactoryTestCase::test_slugify", "tests/test_factory.py::FactoryTestCase::test_some_words", "tests/test_factory.py::FactoryTestCase::test_texts_chars_count", "tests/test_factory.py::FactoryTestCase::test_texts_count", "tests/test_factory.py::FactoryTestCase::test_texts_word_list", "tests/test_factory.py::FactoryTestCase::test_unique_words", "tests/test_factory.py::FactoryTestCase::test_us_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list_unique", "tests/test_factory.py::FactoryTestCase::test_words_valueerror" ]
{ "failed_lite_validators": [ "has_git_commit_hash", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-11-05 12:56:40+00:00
mit
3,294
joke2k__faker-1043
diff --git a/faker/providers/bank/en_GB/__init__.py b/faker/providers/bank/en_GB/__init__.py index 9486de78..75daaf2e 100644 --- a/faker/providers/bank/en_GB/__init__.py +++ b/faker/providers/bank/en_GB/__init__.py @@ -2,5 +2,5 @@ from .. import Provider as BankProvider class Provider(BankProvider): - bban_format = '????#############' + bban_format = '????##############' country_code = 'GB'
joke2k/faker
e87a753f0463b259fffeacf2a33f0ed7f38ac023
diff --git a/tests/providers/test_bank.py b/tests/providers/test_bank.py index e3fc353e..c3333af1 100644 --- a/tests/providers/test_bank.py +++ b/tests/providers/test_bank.py @@ -45,3 +45,18 @@ class TestPlPL(unittest.TestCase): def test_iban(self): iban = self.factory.iban() assert re.match(r"PL\d{26}", iban) + + +class TestEnGB(unittest.TestCase): + """Tests the bank provider for en_GB locale""" + + def setUp(self): + self.factory = Faker('en_GB') + + def test_bban(self): + bban = self.factory.bban() + assert re.match(r"[A-Z]{4}\d{14}", bban) + + def test_iban(self): + iban = self.factory.iban() + assert re.match(r"GB\d{2}[A-Z]{4}\d{14}", iban)
BBAN for en_GB too short * Faker version: v2.0.3 * OS: linux Numeric part of the en_GB BBAN needs to be 14 digits long, it currently only returns 13, failing further validation. ### Steps to reproduce Invoke `fake.iban()` or `fake.bban()` with the en_GB locale, an IBAN or BBAN with 1 digit missing is returned. ### Expected behavior GB ibans should be 22 chars long: https://www.xe.com/ibancalculator/sample/?ibancountry=united kingdom
0.0
e87a753f0463b259fffeacf2a33f0ed7f38ac023
[ "tests/providers/test_bank.py::TestEnGB::test_bban", "tests/providers/test_bank.py::TestEnGB::test_iban" ]
[ "tests/providers/test_bank.py::TestNoNO::test_bban", "tests/providers/test_bank.py::TestFiFi::test_bban", "tests/providers/test_bank.py::TestFiFi::test_iban", "tests/providers/test_bank.py::TestPlPL::test_bban", "tests/providers/test_bank.py::TestPlPL::test_iban" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-11-08 08:32:14+00:00
mit
3,295
joke2k__faker-1046
diff --git a/faker/providers/isbn/__init__.py b/faker/providers/isbn/__init__.py index ada84898..2d6ace9c 100644 --- a/faker/providers/isbn/__init__.py +++ b/faker/providers/isbn/__init__.py @@ -52,7 +52,7 @@ class Provider(BaseProvider): :returns: A (registrant, publication) tuple of strings. """ for rule in rules: - if rule.min <= reg_pub <= rule.max: + if rule.min <= reg_pub[:-1] <= rule.max: reg_len = rule.registrant_length break else:
joke2k/faker
c284aa604b0fb931bdb7533714fe1ee386b8cedc
diff --git a/tests/providers/test_isbn.py b/tests/providers/test_isbn.py index 4d6fab06..fe01c4aa 100644 --- a/tests/providers/test_isbn.py +++ b/tests/providers/test_isbn.py @@ -43,8 +43,13 @@ class TestProvider(unittest.TestCase): def test_reg_pub_separation(self): r1 = RegistrantRule('0000000', '0000001', 1) r2 = RegistrantRule('0000002', '0000003', 2) - assert self.prov._registrant_publication('0000000', [r1, r2]) == ('0', '000000') - assert self.prov._registrant_publication('0000002', [r1, r2]) == ('00', '00002') + assert self.prov._registrant_publication('00000000', [r1, r2]) == ('0', '0000000') + assert self.prov._registrant_publication('00000010', [r1, r2]) == ('0', '0000010') + assert self.prov._registrant_publication('00000019', [r1, r2]) == ('0', '0000019') + assert self.prov._registrant_publication('00000020', [r1, r2]) == ('00', '000020') + assert self.prov._registrant_publication('00000030', [r1, r2]) == ('00', '000030') + assert self.prov._registrant_publication('00000031', [r1, r2]) == ('00', '000031') + assert self.prov._registrant_publication('00000039', [r1, r2]) == ('00', '000039') def test_rule_not_found(self): with pytest.raises(Exception):
Fake ISBN10 causes "Registrant/Publication not found" In rare cases the `fake.isbn10` method throws an exception with the following message: `Exception: Registrant/Publication not found in registrant rule list. ` A full exception message: ``` /usr/local/lib/python3.6/site-packages/faker/providers/isbn/__init__.py:70: in isbn10 ean, group, registrant, publication = self._body() /usr/local/lib/python3.6/site-packages/faker/providers/isbn/__init__.py:41: in _body registrant, publication = self._registrant_publication(reg_pub, rules) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ reg_pub = '64799998' rules = [RegistrantRule(min='0000000', max='1999999', registrant_length=2), RegistrantRule(min='2000000', max='2279999', regis...'6480000', max='6489999', registrant_length=7), RegistrantRule(min='6490000', max='6999999', registrant_length=3), ...] @staticmethod def _registrant_publication(reg_pub, rules): """ Separate the registration from the publication in a given string. :param reg_pub: A string of digits representing a registration and publication. :param rules: A list of RegistrantRules which designate where to separate the values in the string. :returns: A (registrant, publication) tuple of strings. """ for rule in rules: if rule.min <= reg_pub <= rule.max: reg_len = rule.registrant_length break else: > raise Exception('Registrant/Publication not found in registrant ' 'rule list.') E Exception: Registrant/Publication not found in registrant rule list. /usr/local/lib/python3.6/site-packages/faker/providers/isbn/__init__.py:59: Exception ``` ### Steps to reproduce Call `faker.providers.isbn.Provider._registrant_publication` with any of the following values for the `reg_pub` param: `64799998`, `39999999`. These values are valid randomly generated strings from [L34](https://github.com/joke2k/faker/blob/master/faker/providers/isbn/__init__.py#L37). Code: ```python from faker.providers.isbn import Provider from faker.providers.isbn.rules import RULES # Fails; throws an exception Provider._registrant_publication('64799998', RULES['978']['0']) Provider._registrant_publication('39999999', RULES['978']['1']) # Works; but may be invalid Provider._registrant_publication('64799998', RULES['978']['1']) Provider._registrant_publication('39999999', RULES['978']['0']) ``` ### Expected behavior The `faker.providers.isbn.Provider._body` should generate valid `reg_pub` values. ### Actual behavior It generates values for `reg_pub` that are not accepted by the rules defined in `faker.providers.isbn.rules`.
0.0
c284aa604b0fb931bdb7533714fe1ee386b8cedc
[ "tests/providers/test_isbn.py::TestProvider::test_reg_pub_separation" ]
[ "tests/providers/test_isbn.py::TestISBN10::test_check_digit_is_correct", "tests/providers/test_isbn.py::TestISBN10::test_format_length", "tests/providers/test_isbn.py::TestISBN13::test_check_digit_is_correct", "tests/providers/test_isbn.py::TestISBN13::test_format_length", "tests/providers/test_isbn.py::TestProvider::test_rule_not_found" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-11-09 18:31:05+00:00
mit
3,296
joke2k__faker-1047
diff --git a/faker/generator.py b/faker/generator.py index 40135a1b..b66b89bb 100644 --- a/faker/generator.py +++ b/faker/generator.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals import random as random_module import re +import six _re_token = re.compile(r'\{\{(\s?)(\w+)(\s?)\}\}') random = random_module.Random() @@ -108,5 +109,5 @@ class Generator(object): def __format_token(self, matches): formatter = list(matches.groups()) - formatter[1] = self.format(formatter[1]) + formatter[1] = six.text_type(self.format(formatter[1])) return ''.join(formatter) diff --git a/faker/providers/isbn/__init__.py b/faker/providers/isbn/__init__.py index ada84898..2d6ace9c 100644 --- a/faker/providers/isbn/__init__.py +++ b/faker/providers/isbn/__init__.py @@ -52,7 +52,7 @@ class Provider(BaseProvider): :returns: A (registrant, publication) tuple of strings. """ for rule in rules: - if rule.min <= reg_pub <= rule.max: + if rule.min <= reg_pub[:-1] <= rule.max: reg_len = rule.registrant_length break else: diff --git a/faker/providers/phone_number/fa_IR/__init__.py b/faker/providers/phone_number/fa_IR/__init__.py index 07f60d0b..ed6a1acb 100644 --- a/faker/providers/phone_number/fa_IR/__init__.py +++ b/faker/providers/phone_number/fa_IR/__init__.py @@ -5,14 +5,34 @@ from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( # Mobile + # Mci '+98 91# ### ####', '091# ### ####', + '+98 990 ### ####', + '0990 ### ####', + '+98 991 ### ####', + '0991 ### ####', + # Rightel Mobile prefixes '+98 920 ### ####', '0920 ### ####', '+98 921 ### ####', '0921 ### ####', + '+98 922 ### ####', + '0922 ### ####', + # Samantel Mobile prefixes + '+98 999 ### ####', + '0999 ### ####', + # Mtn and Talia '+98 93# ### ####', '093# ### ####', + '+98 901 ### ####', + '0901 ### ####', + '+98 902 ### ####', + '902 ### ####', + '+98 903 ### ####', + '0903 ### ####', + '+98 905 ### ####', + '0905 ### ####', # Land lines, # https://en.wikipedia.org/wiki/List_of_dialling_codes_in_Iran '+98 21 #### ####', diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index eb8a70a6..36317627 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from decimal import Decimal +import string import sys import six @@ -32,6 +33,9 @@ class Provider(BaseProvider): ), ) + def pystr_format(self, string_format='?#-###{{random_int}}{{random_letter}}', letters=string.ascii_letters): + return self.bothify(self.generator.parse(string_format), letters=letters) + def pyfloat(self, left_digits=None, right_digits=None, positive=False, min_value=None, max_value=None):
joke2k/faker
c284aa604b0fb931bdb7533714fe1ee386b8cedc
diff --git a/tests/providers/test_isbn.py b/tests/providers/test_isbn.py index 4d6fab06..fe01c4aa 100644 --- a/tests/providers/test_isbn.py +++ b/tests/providers/test_isbn.py @@ -43,8 +43,13 @@ class TestProvider(unittest.TestCase): def test_reg_pub_separation(self): r1 = RegistrantRule('0000000', '0000001', 1) r2 = RegistrantRule('0000002', '0000003', 2) - assert self.prov._registrant_publication('0000000', [r1, r2]) == ('0', '000000') - assert self.prov._registrant_publication('0000002', [r1, r2]) == ('00', '00002') + assert self.prov._registrant_publication('00000000', [r1, r2]) == ('0', '0000000') + assert self.prov._registrant_publication('00000010', [r1, r2]) == ('0', '0000010') + assert self.prov._registrant_publication('00000019', [r1, r2]) == ('0', '0000019') + assert self.prov._registrant_publication('00000020', [r1, r2]) == ('00', '000020') + assert self.prov._registrant_publication('00000030', [r1, r2]) == ('00', '000030') + assert self.prov._registrant_publication('00000031', [r1, r2]) == ('00', '000031') + assert self.prov._registrant_publication('00000039', [r1, r2]) == ('00', '000039') def test_rule_not_found(self): with pytest.raises(Exception): diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 61f5ca02..ccb93c79 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -1,6 +1,10 @@ # -*- coding: utf-8 -*- import unittest +try: + from unittest.mock import patch +except ImportError: + from mock import patch from faker import Faker @@ -87,3 +91,19 @@ class TestPyfloat(unittest.TestCase): message = str(raises.exception) self.assertEqual(message, expected_message) + + +class TestPystrFormat(unittest.TestCase): + + def setUp(self): + self.factory = Faker(includes=['tests.mymodule.en_US']) + + def test_formatter_invocation(self): + with patch.object(self.factory, 'foo') as mock_foo: + with patch('faker.providers.BaseProvider.bothify', + wraps=self.factory.bothify) as mock_bothify: + mock_foo.return_value = 'barbar' + value = self.factory.pystr_format('{{foo}}?#?{{foo}}?#?{{foo}}', letters='abcde') + assert value.count('barbar') == 3 + assert mock_foo.call_count == 3 + mock_bothify.assert_called_once_with('barbar?#?barbar?#?barbar', letters='abcde')
Would a faker.format() method make sense? It could enable the syntax: `print(faker.format('{name} considers a {catch_phrase} in {country}'))` A sample implementation show how simple it would be: ``` python def fake_fmt(fmt="{first_name}'s favorite number: {random_int}", fake=None): fake = fake or Faker() fields = [fld.split('}')[0].split(':')[0] for fld in fmt.split('{')[1:]] return fmt.format(**{field: getattr(fake, field)() for field in fields}) ``` More test cases at: https://github.com/cclauss/Ten-lines-or-less/blob/master/fake_format.py
0.0
c284aa604b0fb931bdb7533714fe1ee386b8cedc
[ "tests/providers/test_isbn.py::TestProvider::test_reg_pub_separation", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation" ]
[ "tests/providers/test_isbn.py::TestISBN10::test_check_digit_is_correct", "tests/providers/test_isbn.py::TestISBN10::test_format_length", "tests/providers/test_isbn.py::TestISBN13::test_check_digit_is_correct", "tests/providers/test_isbn.py::TestISBN13::test_format_length", "tests/providers/test_isbn.py::TestProvider::test_rule_not_found", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-11-11 12:24:39+00:00
mit
3,297
joke2k__faker-1050
diff --git a/build32bit.sh b/build32bit.sh index c493d7f3..c9df66f0 100755 --- a/build32bit.sh +++ b/build32bit.sh @@ -10,6 +10,7 @@ docker run -v ${PWD}:/code -e INSTALL_REQUIREMENTS=${INSTALL_REQUIREMENTS} i386/ && DEBIAN_FRONTEND=noninteractive apt-get install -yq python3 locales python3-pip debianutils \ && pip3 install tox coveralls \ && locale-gen en_US.UTF-8 \ + && export LANG='en_US.UTF-8' \ && cd /code \ && coverage run --source=faker setup.py test \ && coverage report" diff --git a/faker/generator.py b/faker/generator.py index 40135a1b..b66b89bb 100644 --- a/faker/generator.py +++ b/faker/generator.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals import random as random_module import re +import six _re_token = re.compile(r'\{\{(\s?)(\w+)(\s?)\}\}') random = random_module.Random() @@ -108,5 +109,5 @@ class Generator(object): def __format_token(self, matches): formatter = list(matches.groups()) - formatter[1] = self.format(formatter[1]) + formatter[1] = six.text_type(self.format(formatter[1])) return ''.join(formatter) diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index eb8a70a6..36317627 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from decimal import Decimal +import string import sys import six @@ -32,6 +33,9 @@ class Provider(BaseProvider): ), ) + def pystr_format(self, string_format='?#-###{{random_int}}{{random_letter}}', letters=string.ascii_letters): + return self.bothify(self.generator.parse(string_format), letters=letters) + def pyfloat(self, left_digits=None, right_digits=None, positive=False, min_value=None, max_value=None):
joke2k/faker
97b553654a54c159ccf1ad07b5e0b4dde50b1c79
diff --git a/tests/providers/test_misc.py b/tests/providers/test_misc.py index 1ee2476e..be2806f0 100644 --- a/tests/providers/test_misc.py +++ b/tests/providers/test_misc.py @@ -24,3 +24,15 @@ class TestMisc(unittest.TestCase): uuid4 = self.factory.uuid4(cast_to=lambda x: x) assert uuid4 assert isinstance(uuid4, uuid.UUID) + + def test_uuid4_seedability(self): + for _ in range(10): + random_seed = self.factory.random_int() + baseline_fake = Faker() + baseline_fake.seed(random_seed) + expected_uuids = [baseline_fake.uuid4() for i in range(1000)] + + new_fake = Faker() + new_fake.seed(random_seed) + new_uuids = [new_fake.uuid4() for i in range(1000)] + assert new_uuids == expected_uuids diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 61f5ca02..ccb93c79 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -1,6 +1,10 @@ # -*- coding: utf-8 -*- import unittest +try: + from unittest.mock import patch +except ImportError: + from mock import patch from faker import Faker @@ -87,3 +91,19 @@ class TestPyfloat(unittest.TestCase): message = str(raises.exception) self.assertEqual(message, expected_message) + + +class TestPystrFormat(unittest.TestCase): + + def setUp(self): + self.factory = Faker(includes=['tests.mymodule.en_US']) + + def test_formatter_invocation(self): + with patch.object(self.factory, 'foo') as mock_foo: + with patch('faker.providers.BaseProvider.bothify', + wraps=self.factory.bothify) as mock_bothify: + mock_foo.return_value = 'barbar' + value = self.factory.pystr_format('{{foo}}?#?{{foo}}?#?{{foo}}', letters='abcde') + assert value.count('barbar') == 3 + assert mock_foo.call_count == 3 + mock_bothify.assert_called_once_with('barbar?#?barbar?#?barbar', letters='abcde')
Not possible to seed uuid4 It is not possible to seed the uuid4 property. ``` >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) 4a6d35db-b61b-49ed-a225-e16bc164f7cc >>> f2 = Faker() >>> f2.seed(4321) >>> print(f2.uuid4()) b5f05be8-2f57-4a52-9b6f-5bcd03125278 ``` The solution is pretty much given in: http://stackoverflow.com/questions/41186818/how-to-generate-a-random-uuid-which-is-reproducible-with-a-seed-in-python
0.0
97b553654a54c159ccf1ad07b5e0b4dde50b1c79
[ "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation" ]
[ "tests/providers/test_misc.py::TestMisc::test_uuid4", "tests/providers/test_misc.py::TestMisc::test_uuid4_int", "tests/providers/test_misc.py::TestMisc::test_uuid4_seedability", "tests/providers/test_misc.py::TestMisc::test_uuid4_uuid_object", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-11-12 08:38:28+00:00
mit
3,298
joke2k__faker-1164
diff --git a/faker/providers/misc/__init__.py b/faker/providers/misc/__init__.py index c4906eff..39fb692f 100644 --- a/faker/providers/misc/__init__.py +++ b/faker/providers/misc/__init__.py @@ -87,12 +87,20 @@ class Provider(BaseProvider): return res.hexdigest() def uuid4(self, cast_to=str): - """Generate a random UUID4 object and cast it to another type using a callable ``cast_to``. + """Generate a random UUID4 object and cast it to another type if specified using a callable ``cast_to``. By default, ``cast_to`` is set to ``str``. + + May be called with ``cast_to=None`` to return a full-fledged ``UUID``. + + :sample: + :sample: cast_to=None """ # Based on http://stackoverflow.com/q/41186818 - return cast_to(uuid.UUID(int=self.generator.random.getrandbits(128), version=4)) + generated_uuid = uuid.UUID(int=self.generator.random.getrandbits(128), version=4) + if cast_to is not None: + generated_uuid = cast_to(generated_uuid) + return generated_uuid def password( self,
joke2k/faker
9f48a5c6a251b2b8d9f84f65472f946b85b9a923
diff --git a/tests/providers/test_misc.py b/tests/providers/test_misc.py index 16194c2a..f616db65 100644 --- a/tests/providers/test_misc.py +++ b/tests/providers/test_misc.py @@ -17,7 +17,7 @@ class TestMisc(unittest.TestCase): self.fake = Faker() Faker.seed(0) - def test_uuid4(self): + def test_uuid4_str(self): uuid4 = self.fake.uuid4() assert uuid4 assert isinstance(uuid4, str) @@ -28,7 +28,7 @@ class TestMisc(unittest.TestCase): assert isinstance(uuid4, int) def test_uuid4_uuid_object(self): - uuid4 = self.fake.uuid4(cast_to=lambda x: x) + uuid4 = self.fake.uuid4(cast_to=None) assert uuid4 assert isinstance(uuid4, uuid.UUID)
Why does faker.misc.uuid has `cast_to=str` by default? # I'm willing to open PR should this issue be accepted * Faker version: latest * OS: N/A `faker.misc.uuid` has a arg `cast_to` with `str` as default. So the returned value is always string. https://github.com/joke2k/faker/blob/9f48a5c6a251b2b8d9f84f65472f946b85b9a923/faker/providers/misc/__init__.py#L95 I want to have the `uuid.UUID` object returned. Calling with `cast_to=UUID` again raises a Error on UUID lib (of course it would). Since it's returned `UUID(UUID([...]))`from faker with this ![image](https://user-images.githubusercontent.com/3301060/80141445-f1113900-857f-11ea-85a2-2252c74acd00.png) So I would have to cast it like this `UUID(str(UUID([...])))` to be funcional. ### Steps to reproduce 1. `faker.uuid(cast_to=str)` 1. `faker.uuid(cast_to=uuid.UUID)` ### Expected behavior I should be able to call `faker.uuid(cast_to=None)` and have the pure `UUID` object returned. ### Actual behavior Faker forces object `UUID` to be cast.
0.0
9f48a5c6a251b2b8d9f84f65472f946b85b9a923
[ "tests/providers/test_misc.py::TestMisc::test_uuid4_uuid_object" ]
[ "tests/providers/test_misc.py::TestMisc::test_csv_helper_method", "tests/providers/test_misc.py::TestMisc::test_dsv_csvwriter_kwargs", "tests/providers/test_misc.py::TestMisc::test_dsv_data_columns", "tests/providers/test_misc.py::TestMisc::test_dsv_no_header", "tests/providers/test_misc.py::TestMisc::test_dsv_with_invalid_values", "tests/providers/test_misc.py::TestMisc::test_dsv_with_row_ids", "tests/providers/test_misc.py::TestMisc::test_dsv_with_valid_header", "tests/providers/test_misc.py::TestMisc::test_psv_helper_method", "tests/providers/test_misc.py::TestMisc::test_tar_compression_py3", "tests/providers/test_misc.py::TestMisc::test_tar_exact_minimum_size", "tests/providers/test_misc.py::TestMisc::test_tar_invalid_file", "tests/providers/test_misc.py::TestMisc::test_tar_one_byte_undersized", "tests/providers/test_misc.py::TestMisc::test_tar_over_minimum_size", "tests/providers/test_misc.py::TestMisc::test_tsv_helper_method", "tests/providers/test_misc.py::TestMisc::test_uuid4_int", "tests/providers/test_misc.py::TestMisc::test_uuid4_seedability", "tests/providers/test_misc.py::TestMisc::test_uuid4_str", "tests/providers/test_misc.py::TestMisc::test_zip_compression_py3", "tests/providers/test_misc.py::TestMisc::test_zip_exact_minimum_size", "tests/providers/test_misc.py::TestMisc::test_zip_invalid_file", "tests/providers/test_misc.py::TestMisc::test_zip_one_byte_undersized", "tests/providers/test_misc.py::TestMisc::test_zip_over_minimum_size" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false }
2020-04-23 22:55:54+00:00
mit
3,299
joke2k__faker-1193
diff --git a/faker/providers/person/__init__.py b/faker/providers/person/__init__.py index 05ecb61a..f19f9f71 100644 --- a/faker/providers/person/__init__.py +++ b/faker/providers/person/__init__.py @@ -10,6 +10,42 @@ class Provider(BaseProvider): last_names = ['Doe'] + # https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + language_names = [ + 'Afar', 'Abkhazian', 'Avestan', 'Afrikaans', 'Akan', 'Amharic', + 'Aragonese', 'Arabic', 'Assamese', 'Avaric', 'Aymara', 'Azerbaijani', + 'Bashkir', 'Belarusian', 'Bulgarian', 'Bihari languages', 'Bislama', + 'Bambara', 'Bengali', 'Tibetan', 'Breton', 'Bosnian', 'Catalan', + 'Chechen', 'Chamorro', 'Corsican', 'Cree', 'Czech', 'Church Slavic', + 'Chuvash', 'Welsh', 'Danish', 'German', 'Divehi', 'Dzongkha', 'Ewe', + 'Greek', 'English', 'Esperanto', 'Spanish', 'Estonian', 'Basque', + 'Persian', 'Fulah', 'Finnish', 'Fijian', 'Faroese', 'French', + 'Western Frisian', 'Irish', 'Gaelic', 'Galician', 'Guarani', + 'Gujarati', 'Manx', 'Hausa', 'Hebrew', 'Hindi', 'Hiri Motu', + 'Croatian', 'Haitian', 'Hungarian', 'Armenian', 'Herero', + 'Interlingua', 'Indonesian', 'Interlingue', 'Igbo', 'Sichuan Yi', + 'Inupiaq', 'Ido', 'Icelandic', 'Italian', 'Inuktitut', 'Japanese', + 'Javanese', 'Georgian', 'Kongo', 'Kikuyu', 'Kuanyama', 'Kazakh', + 'Kalaallisut', 'Central Khmer', 'Kannada', 'Korean', 'Kanuri', + 'Kashmiri', 'Kurdish', 'Komi', 'Cornish', 'Kirghiz', 'Latin', + 'Luxembourgish', 'Ganda', 'Limburgan', 'Lingala', 'Lao', 'Lithuanian', + 'Luba-Katanga', 'Latvian', 'Malagasy', 'Marshallese', 'Maori', + 'Macedonian', 'Malayalam', 'Mongolian', 'Marathi', 'Malay', 'Maltese', + 'Burmese', 'Nauru', 'North Ndebele', 'Nepali', + 'Ndonga', 'Dutch', 'Norwegian Nynorsk', 'Norwegian', 'South Ndebele', + 'Navajo', 'Chichewa', 'Occitan', 'Ojibwa', 'Oromo', 'Oriya', + 'Ossetian', 'Panjabi', 'Pali', 'Polish', 'Pushto', 'Portuguese', + 'Quechua', 'Romansh', 'Rundi', 'Romanian', 'Russian', 'Kinyarwanda', + 'Sanskrit', 'Sardinian', 'Sindhi', 'Northern Sami', 'Sango', 'Sinhala', + 'Slovak', 'Slovenian', 'Samoan', 'Shona', 'Somali', 'Albanian', + 'Serbian', 'Swati', 'Sotho, Southern', 'Sundanese', 'Swedish', + 'Swahili', 'Tamil', 'Telugu', 'Tajik', 'Thai', 'Tigrinya', 'Turkmen', + 'Tagalog', 'Tswana', 'Tonga', 'Turkish', 'Tsonga', 'Tatar', 'Twi', + 'Tahitian', 'Uighur', 'Ukrainian', 'Urdu', 'Uzbek', 'Venda', + 'Vietnamese', 'Walloon', 'Wolof', 'Xhosa', 'Yiddish', + 'Yoruba', 'Zhuang', 'Chinese', 'Zulu', + ] + def name(self): """ :example 'John Doe' @@ -96,3 +132,7 @@ class Provider(BaseProvider): if hasattr(self, 'suffixes_female'): return self.random_element(self.suffixes_female) return self.suffix() + + def language_name(self): + """Generate a random i18n language name (e.g. English).""" + return self.random_element(self.language_names) diff --git a/faker/providers/person/ru_RU/__init__.py b/faker/providers/person/ru_RU/__init__.py index b122f32c..44e213cd 100644 --- a/faker/providers/person/ru_RU/__init__.py +++ b/faker/providers/person/ru_RU/__init__.py @@ -272,6 +272,35 @@ class Provider(PersonProvider): middle_names = middle_names_male + middle_names_female + language_names = ( + 'Афарский', 'Абхазский', 'Авестийский', 'Африкаанс', 'Акан', + 'Амхарский', 'Арагонский', 'Арабский', 'Ассамский', 'Аварский', + 'Аймарский', 'Азербайджанский', 'Башкирский', 'Белорусский', + 'Болгарский', 'Бислама', 'Бенгальский', 'Тибетский', 'Бретонский', + 'Боснийский', 'Каталанский', 'Чеченский', 'Чаморро', 'Корсиканский', + 'Кри', 'Чешский', 'Чувашский', 'Валлийский', 'Датский', 'Немецкий', + 'Греческий', 'Английский', 'Эсперанто', 'Испанский', 'Эстонский', + 'Персидский', 'Финский', 'Фиджийский', 'Фарси', 'Французский', + 'Ирландский', 'Гэльский', 'Галийский', 'Иврит', 'Хинди', + 'Хорватский', 'Гавайский', 'Болгарский', 'Армянский', + 'Индонезийский', 'Исландский', 'Итальянский', 'Японский', + 'Яванский', 'Грузинский', 'Казахский', 'Корейский', 'Кашмири', + 'Курдский', 'Коми', 'Киргизский', 'Латинский', 'Люксембургский', + 'Лимбургский', 'Лингала', 'Лаосский', 'Литовский', 'Латвийский', + 'Малагасийский', 'Маршалльский', 'Маори', 'Македонский', 'Малаялам', + 'Монгольский', 'Маратхи', 'Малайский', 'Мальтийский', 'Непальский', + 'Нидерландский', 'Норвежский', 'Навахо', 'Оромо', 'Ория', + 'Осетинский', 'Пали', 'Польский', 'Пушту', 'Португальский', + 'Романшский', 'Румынский', 'Русский', 'Киньяруанда', + 'Санскрит', 'Сардинский', 'Санго', 'Сингальский', + 'Словацкий', 'Словенский', 'Самоанский', 'Сомалийский', 'Албанский', + 'Сербский', 'Сунданский', 'Шведский', 'Суахили', 'Тамильский', + 'Телугу', 'Таджикский', 'Тайский', 'Тигринья', 'Туркменский', + 'Тагальский', 'Тсвана', 'Тонга', 'Турецкий', 'Тсонга', 'Татарский', + 'Таитянский', 'Уйгурский', 'Украинский', 'Урду', 'Узбекский', 'Венда', + 'Вьетнамский', 'Идиш', 'Йоруба', 'Китайский', 'Зулу', + ) + prefixes_male = ('г-н', 'тов.') prefixes_female = ('г-жа', 'тов.')
joke2k/faker
5b8105a7576114e9ec8e2da771dcadaf6453b33b
diff --git a/tests/providers/test_person.py b/tests/providers/test_person.py index cbcb28bf..6a114d60 100644 --- a/tests/providers/test_person.py +++ b/tests/providers/test_person.py @@ -594,3 +594,7 @@ class TestRuRU(unittest.TestCase): assert middle_name in RuProvider.middle_names_male last_name = self.fake.last_name_male() assert last_name in RuProvider.last_names_male + + def test_language_name(self): + language_name = self.fake.language_name() + assert language_name in RuProvider.language_names
New feature: language_name Hi. I want to add a new method that would return random language name (e.g. English, Spanish, Dutch). I'm not sure where I should place this method. Initially I wanted to add this to BaseProvider near the language_code method, but this provider has no locale support. Any thoughts?
0.0
5b8105a7576114e9ec8e2da771dcadaf6453b33b
[ "tests/providers/test_person.py::TestRuRU::test_language_name" ]
[ "tests/providers/test_person.py::TestAr::test_first_name", "tests/providers/test_person.py::TestAr::test_last_name", "tests/providers/test_person.py::TestJaJP::test_person", "tests/providers/test_person.py::TestNeNP::test_names", "tests/providers/test_person.py::TestFiFI::test_gender_first_names", "tests/providers/test_person.py::TestFiFI::test_last_names", "tests/providers/test_person.py::TestSvSE::test_gender_first_names", "tests/providers/test_person.py::TestPlPL::test_identity_card_number", "tests/providers/test_person.py::TestPlPL::test_identity_card_number_checksum", "tests/providers/test_person.py::TestPlPL::test_nip", "tests/providers/test_person.py::TestPlPL::test_pesel_birth_date", "tests/providers/test_person.py::TestPlPL::test_pesel_sex_female", "tests/providers/test_person.py::TestPlPL::test_pesel_sex_male", "tests/providers/test_person.py::TestPlPL::test_pwz_doctor", "tests/providers/test_person.py::TestPlPL::test_pwz_doctor_check_digit_zero", "tests/providers/test_person.py::TestPlPL::test_pwz_nurse", "tests/providers/test_person.py::TestCsCZ::test_name_female", "tests/providers/test_person.py::TestCsCZ::test_name_male", "tests/providers/test_person.py::TestZhCN::test_first_name", "tests/providers/test_person.py::TestZhCN::test_last_name", "tests/providers/test_person.py::TestZhCN::test_name", "tests/providers/test_person.py::TestZhTW::test_first_name", "tests/providers/test_person.py::TestZhTW::test_last_name", "tests/providers/test_person.py::TestZhTW::test_name", "tests/providers/test_person.py::TestHyAM::test_first_name", "tests/providers/test_person.py::TestHyAM::test_last_name", "tests/providers/test_person.py::TestHyAM::test_name", "tests/providers/test_person.py::TestTaIN::test_gender_first_names", "tests/providers/test_person.py::TestRuRU::test_name_female", "tests/providers/test_person.py::TestRuRU::test_name_male", "tests/providers/test_person.py::TestRuRU::test_translit" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-06-02 07:11:05+00:00
mit
3,300
joke2k__faker-1368
diff --git a/faker/providers/lorem/__init__.py b/faker/providers/lorem/__init__.py index cc17fa47..42c4030f 100644 --- a/faker/providers/lorem/__init__.py +++ b/faker/providers/lorem/__init__.py @@ -22,7 +22,7 @@ class Provider(BaseProvider): sentence_punctuation = '.' def words(self, nb=3, ext_word_list=None, unique=False): - """Generate a list of words. + """Generate a tuple of words. The ``nb`` argument controls the number of words in the resulting list, and if ``ext_word_list`` is provided, words from that list will be used @@ -82,7 +82,7 @@ class Provider(BaseProvider): if variable_nb_words: nb_words = self.randomize_nb_elements(nb_words, min=1) - words = self.words(nb=nb_words, ext_word_list=ext_word_list) + words = list(self.words(nb=nb_words, ext_word_list=ext_word_list)) words[0] = words[0].title() return self.word_connector.join(words) + self.sentence_punctuation
joke2k/faker
434457ea74daf0d9c3c7380eb91af4ae34936725
diff --git a/tests/providers/test_lorem.py b/tests/providers/test_lorem.py index 7ba59859..be45e8b5 100644 --- a/tests/providers/test_lorem.py +++ b/tests/providers/test_lorem.py @@ -88,6 +88,10 @@ class TestLoremProvider: words = sentence.lower().replace('.', '').split() assert all(isinstance(word, str) and word in self.custom_word_list for word in words) + def test_sentence_single_word(self, faker): + word = faker.sentence(1) + assert str.isupper(word[0]) + def test_paragraph_no_sentences(self, faker, num_samples): for _ in range(num_samples): assert faker.paragraph(0) == ''
Random sentence of length 1 fails * Faker version: 5.5.0 * OS: Ubuntu 20.04.1 Creating a random sentence of length 1 fails because it attempts to titleize the first word of the sentence, but `random_choices` is returning a tuple which is immutable. This also occurs sometimes with 2 or 3 length sentences, although I presume that under the hood they are randomly selecting sentences of length 1. This works as expected in Faker version 5.4.1. ### Steps to reproduce ``` >>> import faker >>> thing = faker.Faker() >>> print(thing.sentence(1)) ``` ### Expected behavior A random titleized word is printed with a fullstop ### Actual behavior ``` Traceback (most recent call last): File "<input>", line 1, in <module> File "~/.../venv/lib/python3.6/site-packages/faker/providers/lorem/__init__.py", line 86, in sentence words[0] = words[0].title() TypeError: 'tuple' object does not support item assignment ```
0.0
434457ea74daf0d9c3c7380eb91af4ae34936725
[ "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_single_word" ]
[ "tests/providers/test_lorem.py::TestLoremProvider::test_word_with_defaults", "tests/providers/test_lorem.py::TestLoremProvider::test_word_with_custom_list", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_zero_nb", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_defaults", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_unique_sampling", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_no_words", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_inexact_word_count", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_exact_word_count", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_sentences", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_no_sentences", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_inexact_sentence_count", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_exact_sentence_count", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraphs", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_less_than_four_characters", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_valid_character_count[max_nb_chars", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_valid_character_count[25", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_texts" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-01-11 22:48:55+00:00
mit
3,301
joke2k__faker-1370
diff --git a/.bumpversion.cfg b/.bumpversion.cfg index cd0db80d..8c5bff51 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.5.0 +current_version = 5.5.1 files = VERSION faker/__init__.py docs/conf.py commit = True tag = True diff --git a/CHANGELOG.md b/CHANGELOG.md index eea29449..dd98dce2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Changelog +### [5.5.1 - 2021-01-12](https://github.com/joke2k/faker/compare/v5.5.0...v5.5.1) + +* Fix lorem provider ``sentence`` method. + ### [5.5.0 - 2021-01-11](https://github.com/joke2k/faker/compare/v5.4.1...v5.5.0) * Add elements caching and other optimizations. Thanks @prescod. diff --git a/VERSION b/VERSION index d50359de..7acd1cb0 100644 --- a/VERSION +++ b/VERSION @@ -1,1 +1,1 @@ -5.5.0 +5.5.1 diff --git a/docs/conf.py b/docs/conf.py index 5a21619d..27fb8200 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,9 +51,9 @@ copyright = '2014, Daniele Faraglia' # built documents. # # The short X.Y version. -version = '5.5.0' +version = '5.5.1' # The full version, including alpha/beta/rc tags. -release = '5.5.0' +release = '5.5.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/docs/fakerclass.rst b/docs/fakerclass.rst index 656b4c8b..0ef8b2be 100644 --- a/docs/fakerclass.rst +++ b/docs/fakerclass.rst @@ -183,10 +183,10 @@ OrderedDict with more than one valid locale, post-normalization. For example: ('ja-JP', 2), ('en_US', 2), ]) - fake2 = Faker(odict) + fake2 = Faker(locale_odict) # Will return ['en_US', 'ja_JP'] - fake1.locales + fake2.locales In this mode, calling a prospective provider method from the new ``Faker`` instance will run factory/selection logic in this order: diff --git a/faker/__init__.py b/faker/__init__.py index 3fd38102..b1af3b77 100644 --- a/faker/__init__.py +++ b/faker/__init__.py @@ -2,6 +2,6 @@ from faker.factory import Factory from faker.generator import Generator from faker.proxy import Faker -VERSION = '5.5.0' +VERSION = '5.5.1' __all__ = ('Factory', 'Generator', 'Faker') diff --git a/faker/providers/lorem/__init__.py b/faker/providers/lorem/__init__.py index cc17fa47..42c4030f 100644 --- a/faker/providers/lorem/__init__.py +++ b/faker/providers/lorem/__init__.py @@ -22,7 +22,7 @@ class Provider(BaseProvider): sentence_punctuation = '.' def words(self, nb=3, ext_word_list=None, unique=False): - """Generate a list of words. + """Generate a tuple of words. The ``nb`` argument controls the number of words in the resulting list, and if ``ext_word_list`` is provided, words from that list will be used @@ -82,7 +82,7 @@ class Provider(BaseProvider): if variable_nb_words: nb_words = self.randomize_nb_elements(nb_words, min=1) - words = self.words(nb=nb_words, ext_word_list=ext_word_list) + words = list(self.words(nb=nb_words, ext_word_list=ext_word_list)) words[0] = words[0].title() return self.word_connector.join(words) + self.sentence_punctuation
joke2k/faker
434457ea74daf0d9c3c7380eb91af4ae34936725
diff --git a/tests/providers/test_lorem.py b/tests/providers/test_lorem.py index 7ba59859..be45e8b5 100644 --- a/tests/providers/test_lorem.py +++ b/tests/providers/test_lorem.py @@ -88,6 +88,10 @@ class TestLoremProvider: words = sentence.lower().replace('.', '').split() assert all(isinstance(word, str) and word in self.custom_word_list for word in words) + def test_sentence_single_word(self, faker): + word = faker.sentence(1) + assert str.isupper(word[0]) + def test_paragraph_no_sentences(self, faker, num_samples): for _ in range(num_samples): assert faker.paragraph(0) == ''
Documentation mistype * Faker version:5.5.0 * OS: NA In [Multiple Locale Mode](https://faker.readthedocs.io/en/stable/fakerclass.html#multiple-locale-mode) session ``` from collections import OrderedDict from faker import Faker locale_list = ['en-US', 'ja-JP', 'en_US'] fake1 = Faker(locale_list) # Will return ['en_US', 'ja_JP'] fake1.locales locale_odict = OrderedDict([ ('en-US', 1), ('ja-JP', 2), ('en_US', 2), ]) fake2 = Faker(odict) # Will return ['en_US', 'ja_JP'] fake1.locales ``` ### Should be changed to ``` from collections import OrderedDict from faker import Faker locale_list = ['en-US', 'ja-JP', 'en_US'] fake1 = Faker(locale_list) # Will return ['en_US', 'ja_JP'] fake1.locales locale_odict = OrderedDict([ ('en-US', 1), ('ja-JP', 2), ('en_US', 2), ]) fake2 = Faker(locale_odict) ------------- Changed # Will return ['en_US', 'ja_JP'] fake2.locales ------------- Changed ```
0.0
434457ea74daf0d9c3c7380eb91af4ae34936725
[ "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_single_word" ]
[ "tests/providers/test_lorem.py::TestLoremProvider::test_word_with_defaults", "tests/providers/test_lorem.py::TestLoremProvider::test_word_with_custom_list", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_zero_nb", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_defaults", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_words_with_unique_sampling", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_no_words", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_inexact_word_count", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_exact_word_count", "tests/providers/test_lorem.py::TestLoremProvider::test_sentence_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_sentences", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_no_sentences", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_inexact_sentence_count", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_exact_sentence_count", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraph_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_paragraphs", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_less_than_four_characters", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_valid_character_count[max_nb_chars", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_valid_character_count[25", "tests/providers/test_lorem.py::TestLoremProvider::test_text_with_custom_word_list", "tests/providers/test_lorem.py::TestLoremProvider::test_texts" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-12 02:55:34+00:00
mit
3,302
joke2k__faker-1393
diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index 3f470e07..1febbeac 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -66,9 +66,9 @@ class Provider(BaseProvider): raise ValueError('Min value cannot be greater than max value') if None not in (min_value, max_value) and min_value == max_value: raise ValueError('Min and max value cannot be the same') - if positive and min_value is not None and min_value < 0: + if positive and min_value is not None and min_value <= 0: raise ValueError( - 'Cannot combine positive=True and negative min_value') + 'Cannot combine positive=True with negative or zero min_value') left_digits = left_digits if left_digits is not None else ( self.random_int(1, sys.float_info.dig)) @@ -87,7 +87,10 @@ class Provider(BaseProvider): sign = '+' if positive else self.random_element(('+', '-')) left_number = self.random_number(left_digits) - return float(f'{sign}{left_number}.{self.random_number(right_digits)}') + result = float(f'{sign}{left_number}.{self.random_number(right_digits)}') + if positive and result == 0: + result += sys.float_info.epsilon + return result def _safe_random_int(self, min_value, max_value, positive): orig_min_value = min_value
joke2k/faker
b2f787c669abcb6beeaea1b034109b90721195fa
diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 6a8fa981..7dee2b88 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -63,7 +63,7 @@ class TestPyfloat(unittest.TestCase): def test_positive(self): result = self.fake.pyfloat(positive=True) - self.assertGreaterEqual(result, 0) + self.assertGreater(result, 0) self.assertEqual(result, abs(result)) def test_min_value(self): @@ -99,7 +99,7 @@ class TestPyfloat(unittest.TestCase): result = self.fake.pyfloat(positive=True, max_value=100) self.assertLessEqual(result, 100) - self.assertGreaterEqual(result, 0) + self.assertGreater(result, 0) def test_positive_and_min_value_incompatible(self): """ @@ -108,7 +108,7 @@ class TestPyfloat(unittest.TestCase): """ expected_message = ( - "Cannot combine positive=True and negative min_value" + "Cannot combine positive=True with negative or zero min_value" ) with self.assertRaises(ValueError) as raises: self.fake.pyfloat(min_value=-100, positive=True) @@ -116,6 +116,14 @@ class TestPyfloat(unittest.TestCase): message = str(raises.exception) self.assertEqual(message, expected_message) + def test_positive_doesnt_return_zero(self): + """ + Choose the right_digits and max_value so it's guaranteed to return zero, + then watch as it doesn't because positive=True + """ + result = self.fake.pyfloat(positive=True, right_digits=0, max_value=1) + self.assertGreater(result, 0) + class TestPystrFormat(unittest.TestCase):
pyfloat provider with positive=True sometimes returns zero * Faker version: 5.8.0 * OS: macOS 11.1 Call pyfloat with positive=True, and it will sometimes return a zero. ### Steps to reproduce Here's an example: ``` import faker f=faker.Faker() are_zero = [f.pyfloat(positive=True, max_value=10)==0 for _ in range(100)] print(any(are_zero)) ``` ### Expected behavior It should always print `False` always. ### Actual behavior Sometimes it's `True` with f.pyfloat() returning zero.
0.0
b2f787c669abcb6beeaea1b034109b90721195fa
[ "tests/providers/test_python.py::TestPyfloat::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPyfloat::test_positive_doesnt_return_zero" ]
[ "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_and_positive", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation", "tests/providers/test_python.py::TestPython::test_pybool", "tests/providers/test_python.py::TestPython::test_pylist", "tests/providers/test_python.py::TestPython::test_pylist_types" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-03 04:34:54+00:00
mit
3,303
joke2k__faker-1416
diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index 2a0a4cc1..e6b2391f 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -123,7 +123,7 @@ class Provider(BaseProvider): def pytuple(self, nb_elements=10, variable_nb_elements=True, value_types=None, *allowed_types): return tuple( - self.pyset( + self._pyiterable( nb_elements, variable_nb_elements, value_types,
joke2k/faker
56e777f1ba0bab25bbd5049b56805bc89ac1d39a
diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index e42bc53f..263c0505 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -195,6 +195,21 @@ class TestPython(unittest.TestCase): with self.assertRaises(AssertionError): self.factory.pystr(min_chars=5, max_chars=5) + def test_pytuple(self): + with warnings.catch_warnings(record=True) as w: + some_tuple = Faker().pytuple() + assert len(w) == 0 + assert some_tuple + assert isinstance(some_tuple, tuple) + + def test_pytuple_size(self): + def mock_pyint(self, *args, **kwargs): + return 1 + + with patch('faker.providers.python.Provider.pyint', mock_pyint): + some_tuple = Faker().pytuple(nb_elements=3, variable_nb_elements=False, value_types=[int]) + assert some_tuple == (1, 1, 1) + def test_pylist(self): with warnings.catch_warnings(record=True) as w: some_list = self.factory.pylist()
pytuple can occassionally return fewer than expected elements * Faker version: 6.1.1 * OS: Mac OSX 10.15.5 Sporadically using pytuple may result in the tuple having less than the requested elements (`nb_elements`) even when `variable_nb_elements` is set to False. This happens because pytuple relies on pyset, returning `tuple(self.pyset(...))`. Because it delegates to a set rather than a list, any duplicate numbers generated will result in the set, and following that the tuple, having fewer numbers than expected. Suggest that the appropriate fix might be to use `pylist` instead of `pyset` ### Steps to reproduce 1. Specify `nb_elements = 3` in a call to pytuple, `variable_nb_elements= False` 2. Repeat until the tuple 'randomly' contains less than 3 elements ```python import faker fake = faker.Faker() for x in range(10000): random_tuple = fake.pytuple(nb_elements=3, variable_nb_elements=False, value_types=[int]) assert len(random_tuple) == 3, f"Tuple {random_tuple} not len 3 at iteration {x}" ``` ### Expected behavior When calling pytuple with `nb_elements = 3` and `variable_nb_elements = False` the tuple should always contain 3 elements, even if there are duplicate values. ### Actual behavior Sporadically the tuple contains less than 3 elements.
0.0
56e777f1ba0bab25bbd5049b56805bc89ac1d39a
[ "tests/providers/test_python.py::TestPython::test_pytuple_size" ]
[ "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-5-12345]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-0-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-1-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-2-12]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[0123-1-1]", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_and_positive", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPyfloat::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation", "tests/providers/test_python.py::TestPython::test_pybool", "tests/providers/test_python.py::TestPython::test_pylist", "tests/providers/test_python.py::TestPython::test_pylist_types", "tests/providers/test_python.py::TestPython::test_pytuple" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-03-24 13:51:18+00:00
mit
3,304
joke2k__faker-1475
diff --git a/faker/cli.py b/faker/cli.py index 786060a3..cef26c7e 100644 --- a/faker/cli.py +++ b/faker/cli.py @@ -7,7 +7,7 @@ import sys from pathlib import Path from typing import Any, Dict, List, Optional, TextIO -from faker import VERSION, Faker, documentor +from faker import VERSION, Faker, documentor, exceptions from faker.config import AVAILABLE_LOCALES, DEFAULT_LOCALE, META_PROVIDERS_MODULES __author__ = 'joke2k' @@ -86,8 +86,15 @@ def print_doc(provider_or_field=None, else: doc = documentor.Documentor(fake) + unsupported = [] - formatters = doc.get_formatters(with_args=True, with_defaults=True) + while True: + try: + formatters = doc.get_formatters(with_args=True, with_defaults=True, excludes=unsupported) + except exceptions.UnsupportedFeature as e: + unsupported.append(e.name) + else: + break for provider, fakers in formatters: @@ -104,7 +111,7 @@ def print_doc(provider_or_field=None, for p, fs in d.get_formatters(with_args=True, with_defaults=True, locale=language, - excludes=base_provider_formatters): + excludes=base_provider_formatters + unsupported): print_provider(d, p, fs, output=output) diff --git a/faker/exceptions.py b/faker/exceptions.py index 0feb4dd1..21bc606d 100644 --- a/faker/exceptions.py +++ b/faker/exceptions.py @@ -10,3 +10,6 @@ class UniquenessException(BaseFakerException): class UnsupportedFeature(BaseFakerException): """The requested feature is not available on this system.""" + def __init__(self, msg, name): + self.name = name + super().__init__(msg) diff --git a/faker/providers/misc/__init__.py b/faker/providers/misc/__init__.py index 5cf7822f..d6572080 100644 --- a/faker/providers/misc/__init__.py +++ b/faker/providers/misc/__init__.py @@ -305,7 +305,7 @@ class Provider(BaseProvider): import PIL.Image import PIL.ImageDraw except ImportError: - raise UnsupportedFeature("`image` requires the `Pillow` python library.") + raise UnsupportedFeature("`image` requires the `Pillow` python library.", "image") (width, height) = size image = PIL.Image.new('RGB', size, self.generator.color(hue=hue, luminosity=luminosity))
joke2k/faker
22017a42b36751b210b0d9b323d738d6fc091bc4
diff --git a/tests/providers/test_misc.py b/tests/providers/test_misc.py index 41de338d..35413597 100644 --- a/tests/providers/test_misc.py +++ b/tests/providers/test_misc.py @@ -326,9 +326,11 @@ class TestMiscProvider: def test_image_no_pillow(self, faker): with patch.dict("sys.modules", {"PIL": None}): - with pytest.raises(exceptions.UnsupportedFeature): + with pytest.raises(exceptions.UnsupportedFeature) as excinfo: faker.image() + assert excinfo.value.name == "image" + def test_dsv_with_invalid_values(self, faker): with pytest.raises(ValueError): faker.dsv(num_rows='1')
faker command line fails with "faker.exceptions.UnsupportedFeature: `image` requires the `Pillow` python library." * Faker version: 8.8.2 * OS: Ubuntu It looks like the image faker added in #1254 / 8.5.0 broke the faker command line? is the fix to catch `UnsupportedFeature` in cli.py, and maybe print a warning? ### Steps to reproduce 1. Install faker in a virtualenv 1. run in the terminal `faker` ### Expected behavior cli should output fake data ### Actual behavior Fails with exception: faker.exceptions.UnsupportedFeature: `image` requires the `Pillow` python library.
0.0
22017a42b36751b210b0d9b323d738d6fc091bc4
[ "tests/providers/test_misc.py::TestMiscProvider::test_image_no_pillow" ]
[ "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_str", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_int", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_uuid_object", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_seedability", "tests/providers/test_misc.py::TestMiscProvider::test_zip_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_zip_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_zip_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_tar_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_tar_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_tar_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_invalid_values", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_no_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_valid_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_row_ids", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_data_columns", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_csvwriter_kwargs", "tests/providers/test_misc.py::TestMiscProvider::test_csv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_tsv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_psv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_json_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_json_multiple_rows", "tests/providers/test_misc.py::TestMiscProvider::test_json_passthrough_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_int", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_float", "tests/providers/test_misc.py::TestMiscProvider::test_json_invalid_data_columns", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_md5", "tests/providers/test_misc.py::TestMiscProvider::test_sha1", "tests/providers/test_misc.py::TestMiscProvider::test_sha256" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-01 09:22:28+00:00
mit
3,305
joke2k__faker-1567
diff --git a/.bumpversion.cfg b/.bumpversion.cfg index b511b0b9..538a3a02 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 9.8.0 +current_version = 9.8.1 files = VERSION faker/__init__.py docs/conf.py commit = True tag = True diff --git a/CHANGELOG.md b/CHANGELOG.md index bd385890..967a9611 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Changelog +### [v9.8.1 - 2021-11-12](https://github.com/joke2k/faker/compare/v9.8.0...v9.8.1) + +* Fix ``pydecimal`` with ``left_digits=0`` not setting the left digit to 0. Thanks @ndrwkim. + ### [v9.8.0 - 2021-11-02](https://github.com/joke2k/faker/compare/v9.7.1...v9.8.0) * Add ``es_CO`` localized providers. Thank you @healarconr. diff --git a/VERSION b/VERSION index 834eb3fa..31476ce1 100644 --- a/VERSION +++ b/VERSION @@ -1,1 +1,1 @@ -9.8.0 +9.8.1 diff --git a/docs/conf.py b/docs/conf.py index 17466971..0a0138e8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,9 +51,9 @@ copyright = "2014, Daniele Faraglia" # built documents. # # The short X.Y version. -version = "9.8.0" +version = "9.8.1" # The full version, including alpha/beta/rc tags. -release = "9.8.0" +release = "9.8.1" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/faker/__init__.py b/faker/__init__.py index 7b64a32b..133b01e8 100644 --- a/faker/__init__.py +++ b/faker/__init__.py @@ -2,6 +2,6 @@ from faker.factory import Factory from faker.generator import Generator from faker.proxy import Faker -VERSION = "9.8.0" +VERSION = "9.8.1" __all__ = ("Factory", "Generator", "Faker") diff --git a/faker/providers/__init__.py b/faker/providers/__init__.py index 84e7b2f1..2a9e16ea 100644 --- a/faker/providers/__init__.py +++ b/faker/providers/__init__.py @@ -2,7 +2,7 @@ import re import string from collections import OrderedDict -from typing import Any, Dict, KeysView, List, Optional, Sequence, TypeVar, Union +from typing import Any, Collection, List, Optional, Sequence, TypeVar, Union from ..generator import Generator from ..utils.distribution import choices_distribution, choices_distribution_unique @@ -15,7 +15,7 @@ _re_qm = re.compile(r"\?") _re_cir = re.compile(r"\^") T = TypeVar("T") -ElementsType = Union[Sequence[T], Dict[T, float], KeysView[T]] +ElementsType = Collection[T] class BaseProvider: diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index bee5084d..bf989fdb 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -193,14 +193,16 @@ class Provider(BaseProvider): left_number = str(self.random_int(max(min_value or 0, 0), max_value)) else: min_left_digits = math.ceil(math.log10(max(min_value or 1, 1))) - left_digits = left_digits or self.random_int(min_left_digits, max_left_random_digits) + if left_digits is None: + left_digits = self.random_int(min_left_digits, max_left_random_digits) left_number = "".join([str(self.random_digit()) for i in range(0, left_digits)]) or "0" else: if min_value is not None: left_number = str(self.random_int(max(max_value or 0, 0), abs(min_value))) else: min_left_digits = math.ceil(math.log10(abs(min(max_value or 1, 1)))) - left_digits = left_digits or self.random_int(min_left_digits, max_left_random_digits) + if left_digits is None: + left_digits = self.random_int(min_left_digits, max_left_random_digits) left_number = "".join([str(self.random_digit()) for i in range(0, left_digits)]) or "0" if right_digits is None:
joke2k/faker
7093e5ab9b5e894e04807130b75dc940c7a9d53a
diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 68f2b1d4..ac8b0b4d 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -235,6 +235,14 @@ class TestPydecimal(unittest.TestCase): left_digits = len(str(abs(int(result)))) self.assertGreaterEqual(expected_left_digits, left_digits) + def test_left_digits_can_be_zero(self): + expected_left_digits = 0 + + result = self.fake.pydecimal(left_digits=expected_left_digits) + + left_digits = int(result) + self.assertEqual(expected_left_digits, left_digits) + def test_right_digits(self): expected_right_digits = 10
`ElementsType` requires `Sequence[T]`, not just `Iterable[T]`? The definition for `ElementsType` currently requires a sequence, or dict keys: https://github.com/joke2k/faker/blob/7093e5ab9b5e894e04807130b75dc940c7a9d53a/faker/providers/__init__.py#L18 I can't see why it needs to be a _sequence_ though, i.e. having any order - wouldn't `Iterable[T]` suffice? I hit this by using `random_element(elements)`, where `elements: Set[str]`. I can work around it for now as `random_element(tuple(elements))` of course.
0.0
7093e5ab9b5e894e04807130b75dc940c7a9d53a
[ "tests/providers/test_python.py::TestPydecimal::test_left_digits_can_be_zero" ]
[ "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-5-12345]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-0-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-1-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-2-12]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[0123-1-1]", "tests/providers/test_python.py::test_pyfloat_right_or_left_digit_overflow", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_and_positive", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPyfloat::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits", "tests/providers/test_python.py::TestPydecimal::test_left_digits", "tests/providers/test_python.py::TestPydecimal::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPydecimal::test_max_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_max_value_and_positive", "tests/providers/test_python.py::TestPydecimal::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value", "tests/providers/test_python.py::TestPydecimal::test_min_value_10_pow_1000_return_greater_number", "tests/providers/test_python.py::TestPydecimal::test_min_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_hundred_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_one_hundred_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_min_value_zero_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_positive", "tests/providers/test_python.py::TestPydecimal::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPydecimal::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPydecimal::test_pydecimal", "tests/providers/test_python.py::TestPydecimal::test_right_digits", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation", "tests/providers/test_python.py::TestPython::test_pybool", "tests/providers/test_python.py::TestPython::test_pylist", "tests/providers/test_python.py::TestPython::test_pylist_types", "tests/providers/test_python.py::TestPython::test_pytuple", "tests/providers/test_python.py::TestPython::test_pytuple_size" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-11-12 11:53:10+00:00
mit
3,306
joke2k__faker-1569
diff --git a/faker/providers/bank/pl_PL/__init__.py b/faker/providers/bank/pl_PL/__init__.py index 9d9b8f64..9cf6624d 100644 --- a/faker/providers/bank/pl_PL/__init__.py +++ b/faker/providers/bank/pl_PL/__init__.py @@ -4,5 +4,5 @@ from .. import Provider as BankProvider class Provider(BankProvider): """Implement bank provider for ``pl_PL`` locale.""" - bban_format = "#" * 26 + bban_format = "#" * 24 country_code = "PL"
joke2k/faker
e46676c5b2ec9a57f778a4f62cad0b9f21d4e444
diff --git a/tests/providers/test_bank.py b/tests/providers/test_bank.py index b71666d8..76d05ee0 100644 --- a/tests/providers/test_bank.py +++ b/tests/providers/test_bank.py @@ -73,14 +73,14 @@ class TestPlPl: def test_bban(self, faker, num_samples): for _ in range(num_samples): - assert re.fullmatch(r"\d{26}", faker.bban()) + assert re.fullmatch(r"\d{24}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() assert is_valid_iban(iban) assert iban[:2] == PlPlBankProvider.country_code - assert re.fullmatch(r"\d{2}\d{26}", iban[2:]) + assert re.fullmatch(r"\d{2}\d{24}", iban[2:]) class TestEnGb:
too long iban generated for pl-PL locale * Faker version: 9.8.2 * OS: MacOs 12.0.1 IBANs generated for pl_PL locales are 30 characters long. This is too many. Valid PL IBAN should have 28 characters (including country code). ### Steps to reproduce Generate a Polish IBAN with: ``` from faker import Faker fake=Faker('pl-PL') print(fake.iban()) ``` Copy paste generated string into IBAN Validator at https://www.ibancalculator.com/ ### Expected behavior IBAN should have the correct length and checksum ### Actual behavior There is an error message that IBAN have too many characters: "This IBAN cannot be correct because of its length. A Polish IBAN always contains exactly 28 digits and letters ("PL", a 2-digit checksum, and the 24-digit national account number, whose first 8 digits determine the bank and branch). The IBAN you entered is 30 characters long."
0.0
e46676c5b2ec9a57f778a4f62cad0b9f21d4e444
[ "tests/providers/test_bank.py::TestPlPl::test_bban", "tests/providers/test_bank.py::TestPlPl::test_iban" ]
[ "tests/providers/test_bank.py::TestNoNo::test_aba", "tests/providers/test_bank.py::TestNoNo::test_bban", "tests/providers/test_bank.py::TestNoNo::test_iban", "tests/providers/test_bank.py::TestFiFi::test_bban", "tests/providers/test_bank.py::TestFiFi::test_iban", "tests/providers/test_bank.py::TestEnGb::test_bban", "tests/providers/test_bank.py::TestEnGb::test_iban", "tests/providers/test_bank.py::TestEnIe::test_bban", "tests/providers/test_bank.py::TestEnIe::test_iban", "tests/providers/test_bank.py::TestRuRu::test_bic", "tests/providers/test_bank.py::TestRuRu::test_correspondent_account", "tests/providers/test_bank.py::TestRuRu::test_checking_account", "tests/providers/test_bank.py::TestRuRu::test_bank", "tests/providers/test_bank.py::TestPtPt::test_bban", "tests/providers/test_bank.py::TestPtPt::test_iban", "tests/providers/test_bank.py::TestEsEs::test_bban", "tests/providers/test_bank.py::TestEsEs::test_iban", "tests/providers/test_bank.py::TestFrFr::test_bban", "tests/providers/test_bank.py::TestFrFr::test_iban", "tests/providers/test_bank.py::TestEnPh::test_swift", "tests/providers/test_bank.py::TestEnPh::test_swift_invalid_length", "tests/providers/test_bank.py::TestEnPh::test_swift8_use_dataset", "tests/providers/test_bank.py::TestEnPh::test_swift11_use_dataset", "tests/providers/test_bank.py::TestEnPh::test_swift11_is_primary", "tests/providers/test_bank.py::TestFilPh::test_swift", "tests/providers/test_bank.py::TestFilPh::test_swift_invalid_length", "tests/providers/test_bank.py::TestFilPh::test_swift8_use_dataset", "tests/providers/test_bank.py::TestFilPh::test_swift11_use_dataset", "tests/providers/test_bank.py::TestFilPh::test_swift11_is_primary", "tests/providers/test_bank.py::TestTlPh::test_swift", "tests/providers/test_bank.py::TestTlPh::test_swift_invalid_length", "tests/providers/test_bank.py::TestTlPh::test_swift8_use_dataset", "tests/providers/test_bank.py::TestTlPh::test_swift11_use_dataset", "tests/providers/test_bank.py::TestTlPh::test_swift11_is_primary", "tests/providers/test_bank.py::TestTrTr::test_bban", "tests/providers/test_bank.py::TestTrTr::test_iban", "tests/providers/test_bank.py::TestDeCh::test_bban", "tests/providers/test_bank.py::TestDeCh::test_iban", "tests/providers/test_bank.py::TestFrCh::test_bban", "tests/providers/test_bank.py::TestFrCh::test_iban", "tests/providers/test_bank.py::TestItCh::test_bban", "tests/providers/test_bank.py::TestItCh::test_iban", "tests/providers/test_bank.py::TestThTh::test_bban", "tests/providers/test_bank.py::TestThTh::test_iban", "tests/providers/test_bank.py::TestElGr::test_bban", "tests/providers/test_bank.py::TestElGr::test_iban" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-11-22 20:44:49+00:00
mit
3,307
joke2k__faker-1600
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a5d9a99..1762e314 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,9 +128,16 @@ jobs: python-version: ${{ matrix.python }} - name: Install Tox and any other packages run: python -m pip install tox coveralls - - name: Run Tox - # Run tox using the version of Python in `PATH` - run: tox -e py + - name: pytest + uses: liskin/gh-problem-matcher-wrap@v1 + with: + linters: pytest + run: tox -e py + env: + COVERALLS_PARALLEL: true + COVERALLS_FLAG_NAME: run-ubuntu-${{ matrix.python }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COVERALLS_SERVICE_NAME: github - name: Publish coverage run: coveralls --service=github env: diff --git a/faker/documentor.py b/faker/documentor.py index ba72de21..5164bf7c 100644 --- a/faker/documentor.py +++ b/faker/documentor.py @@ -30,7 +30,7 @@ class Documentor: formatters = [] providers: List[BaseProvider] = self.generator.get_providers() for provider in providers[::-1]: # reverse - if locale and provider.__lang__ != locale: + if locale and provider.__lang__ and provider.__lang__ != locale: continue formatters.append( (provider, self.get_provider_formatters(provider, **kwargs)), diff --git a/faker/factory.py b/faker/factory.py index 4d1a66dd..56f47748 100644 --- a/faker/factory.py +++ b/faker/factory.py @@ -54,7 +54,7 @@ class Factory: if prov_name == "faker.providers": continue - prov_cls, lang_found = cls._get_provider_class(prov_name, locale) + prov_cls, lang_found, _ = cls._find_provider_class(prov_name, locale) provider = prov_cls(faker) provider.__use_weighting__ = use_weighting provider.__provider__ = prov_name @@ -64,31 +64,14 @@ class Factory: return faker @classmethod - def _get_provider_class(cls, provider: str, locale: Optional[str] = "") -> Tuple[Any, Optional[str]]: - - provider_class = cls._find_provider_class(provider, locale) - - if provider_class: - return provider_class, locale - - if locale and locale != DEFAULT_LOCALE: - # fallback to default locale - provider_class = cls._find_provider_class(provider, DEFAULT_LOCALE) - if provider_class: - return provider_class, DEFAULT_LOCALE - - # fallback to no locale - provider_class = cls._find_provider_class(provider) - if provider_class: - return provider_class, None - - msg = f"Unable to find provider `{provider}` with locale `{locale}`" - raise ValueError(msg) - - @classmethod - def _find_provider_class(cls, provider_path: str, locale: Optional[str] = None) -> Any: + def _find_provider_class( + cls, + provider_path: str, + locale: Optional[str] = None, + ) -> Tuple[Any, Optional[str], Optional[str]]: provider_module = import_module(provider_path) + default_locale = getattr(provider_module, "default_locale", "") if getattr(provider_module, "localized", False): @@ -101,7 +84,7 @@ class Factory: available_locales = list_module(provider_module) if not locale or locale not in available_locales: unavailable_locale = locale - locale = getattr(provider_module, "default_locale", DEFAULT_LOCALE) + locale = default_locale or DEFAULT_LOCALE logger.debug( "Specified locale `%s` is not available for " "provider `%s`. Locale reset to `%s` for this " @@ -122,15 +105,14 @@ class Factory: else: - logger.debug( - "Provider `%s` does not feature localization. " - "Specified locale `%s` is not utilized for this " - "provider.", - provider_module.__name__, - locale, - ) - - if locale is not None: - provider_module = import_module(provider_path) + if locale: + logger.debug( + "Provider `%s` does not feature localization. " + "Specified locale `%s` is not utilized for this " + "provider.", + provider_module.__name__, + locale, + ) + locale = default_locale = None - return provider_module.Provider # type: ignore + return provider_module.Provider, locale, default_locale # type: ignore
joke2k/faker
d1b3b83fe04ed6cf7be52ff50a8ecd99b3e67df8
diff --git a/tests/test_factory.py b/tests/test_factory.py index 1b119923..48c9015e 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -3,6 +3,8 @@ import string import sys import unittest +from unittest.mock import MagicMock, patch + import pytest from faker import Faker, Generator @@ -108,6 +110,74 @@ class FactoryTestCase(unittest.TestCase): finally: sys.stdout = orig_stdout + def test_unknown_provider(self): + with pytest.raises(ModuleNotFoundError) as excinfo: + Factory.create(providers=["dummy_provider"]) + assert str(excinfo.value) == "No module named 'dummy_provider'" + + with pytest.raises(ModuleNotFoundError) as excinfo: + Factory.create(providers=["dummy_provider"], locale="it_IT") + assert str(excinfo.value) == "No module named 'dummy_provider'" + + def test_unknown_locale(self): + with pytest.raises(AttributeError) as excinfo: + Factory.create(locale="77") + assert str(excinfo.value) == "Invalid configuration for faker locale `77`" + + with pytest.raises(AttributeError) as excinfo: + Factory.create(locale="77_US") + assert str(excinfo.value) == "Invalid configuration for faker locale `77_US`" + + def test_lang_unlocalized_provider(self): + for locale in (None, "", "en_GB", "it_IT"): + factory = Factory.create(providers=["faker.providers.file"], locale=locale) + assert len(factory.providers) == 1 + assert factory.providers[0].__provider__ == "faker.providers.file" + assert factory.providers[0].__lang__ is None + + def test_lang_localized_provider(self, with_default=True): + class DummyProviderModule: + localized = True + + def __init__(self): + if with_default: + self.default_locale = "ar_EG" + + @property + def __name__(self): + return self.__class__.__name__ + + class Provider: + def __init__(self, *args, **kwargs): + pass + + with patch.multiple( + "faker.factory", + import_module=MagicMock(return_value=DummyProviderModule()), + list_module=MagicMock(return_value=("en_GB", "it_IT")), + DEFAULT_LOCALE="ko_KR", + ): + test_cases = [ + (None, False), + ("", False), + ("ar", False), + ("es_CO", False), + ("en", False), + ("en_GB", True), + ("ar_EG", with_default), # True if module defines a default locale + ] + for locale, expected_used in test_cases: + factory = Factory.create(providers=["dummy"], locale=locale) + assert factory.providers[0].__provider__ == "dummy" + from faker.config import DEFAULT_LOCALE + + print(f"requested locale = {locale} , DEFAULT LOCALE {DEFAULT_LOCALE}") + expected_locale = locale if expected_used else ("ar_EG" if with_default else "ko_KR") + assert factory.providers[0].__lang__ == expected_locale + + def test_lang_localized_provider_without_default(self): + self.test_lang_localized_provider(with_default=False) + def test_slugify(self): slug = text.slugify("a'b/c") assert slug == "abc" diff --git a/tests/test_providers_formats.py b/tests/test_providers_formats.py index e4ebd4c2..8d0e0293 100644 --- a/tests/test_providers_formats.py +++ b/tests/test_providers_formats.py @@ -3,7 +3,7 @@ import re import pytest from faker import Factory -from faker.config import AVAILABLE_LOCALES, PROVIDERS +from faker.config import AVAILABLE_LOCALES, DEFAULT_LOCALE, PROVIDERS locales = AVAILABLE_LOCALES @@ -26,8 +26,16 @@ def test_no_invalid_formats(locale): for provider in PROVIDERS: if provider == "faker.providers": continue - prov_cls, lang = Factory._get_provider_class(provider, locale) - assert lang == locale + prov_cls, lang, default_lang = Factory._find_provider_class(provider, locale) + if default_lang is None: + # for non-localized providers, the discovered language will be None + assert lang is None + else: + # for localized providers, the discovered language will either be + # the requested one + # or the default language of the provider + # or the fallback locale + assert lang in (locale, default_lang or DEFAULT_LOCALE) attributes = set(dir(prov_cls))
Incorrect language set on Provider during locale fallback * Faker version: 11.3.0 When faker is initialised with a locale not implemented by some of the built-in providers, it falls back to the DEFAULT_LOCALE for these providers. However, the language set on the provider’s instance in `__lang__` is still the requested locale and not the locale in effect. This is due to `Factory._find_provider_class` not returning the locale it chose, in: https://github.com/joke2k/faker/blob/001ddee39c33b6b82196fe6a5ecc131bca3b964c/faker/factory.py#L102-L104 to `Factory._get_provider_class` which then proceeds to return the locale value as it was passed in at the first place. Thus, `provider.__lang__` does not contain the found locale (as the variable name `lang_found` would suggest): https://github.com/joke2k/faker/blob/001ddee39c33b6b82196fe6a5ecc131bca3b964c/faker/factory.py#L61 ### Expected behavior `provider.__lang__` should be set to the actual language / locale being used by the provider. ### Actual behavior `provider.__lang__` is set to the locale that was requested but is not offered by this provider.
0.0
d1b3b83fe04ed6cf7be52ff50a8ecd99b3e67df8
[ "tests/test_factory.py::FactoryTestCase::test_lang_localized_provider", "tests/test_factory.py::FactoryTestCase::test_lang_localized_provider_without_default", "tests/test_factory.py::FactoryTestCase::test_lang_unlocalized_provider", "tests/test_providers_formats.py::test_no_invalid_formats[ar_AA]", "tests/test_providers_formats.py::test_no_invalid_formats[ar_AE]", "tests/test_providers_formats.py::test_no_invalid_formats[ar_EG]", "tests/test_providers_formats.py::test_no_invalid_formats[ar_JO]", "tests/test_providers_formats.py::test_no_invalid_formats[ar_PS]", "tests/test_providers_formats.py::test_no_invalid_formats[ar_SA]", "tests/test_providers_formats.py::test_no_invalid_formats[az_AZ]", "tests/test_providers_formats.py::test_no_invalid_formats[bg_BG]", "tests/test_providers_formats.py::test_no_invalid_formats[bn_BD]", "tests/test_providers_formats.py::test_no_invalid_formats[bs_BA]", "tests/test_providers_formats.py::test_no_invalid_formats[cs_CZ]", "tests/test_providers_formats.py::test_no_invalid_formats[da_DK]", "tests/test_providers_formats.py::test_no_invalid_formats[de]", "tests/test_providers_formats.py::test_no_invalid_formats[de_AT]", "tests/test_providers_formats.py::test_no_invalid_formats[de_CH]", "tests/test_providers_formats.py::test_no_invalid_formats[de_DE]", "tests/test_providers_formats.py::test_no_invalid_formats[dk_DK]", "tests/test_providers_formats.py::test_no_invalid_formats[el_CY]", "tests/test_providers_formats.py::test_no_invalid_formats[el_GR]", "tests/test_providers_formats.py::test_no_invalid_formats[en]", "tests/test_providers_formats.py::test_no_invalid_formats[en_AU]", "tests/test_providers_formats.py::test_no_invalid_formats[en_CA]", "tests/test_providers_formats.py::test_no_invalid_formats[en_GB]", "tests/test_providers_formats.py::test_no_invalid_formats[en_IE]", "tests/test_providers_formats.py::test_no_invalid_formats[en_IN]", "tests/test_providers_formats.py::test_no_invalid_formats[en_NZ]", "tests/test_providers_formats.py::test_no_invalid_formats[en_PH]", "tests/test_providers_formats.py::test_no_invalid_formats[en_TH]", "tests/test_providers_formats.py::test_no_invalid_formats[en_US]", "tests/test_providers_formats.py::test_no_invalid_formats[es]", "tests/test_providers_formats.py::test_no_invalid_formats[es_CA]", "tests/test_providers_formats.py::test_no_invalid_formats[es_CO]", "tests/test_providers_formats.py::test_no_invalid_formats[es_ES]", "tests/test_providers_formats.py::test_no_invalid_formats[es_MX]", "tests/test_providers_formats.py::test_no_invalid_formats[et_EE]", "tests/test_providers_formats.py::test_no_invalid_formats[fa_IR]", "tests/test_providers_formats.py::test_no_invalid_formats[fi_FI]", "tests/test_providers_formats.py::test_no_invalid_formats[fil_PH]", "tests/test_providers_formats.py::test_no_invalid_formats[fr_CA]", "tests/test_providers_formats.py::test_no_invalid_formats[fr_CH]", "tests/test_providers_formats.py::test_no_invalid_formats[fr_FR]", "tests/test_providers_formats.py::test_no_invalid_formats[fr_QC]", "tests/test_providers_formats.py::test_no_invalid_formats[ga_IE]", "tests/test_providers_formats.py::test_no_invalid_formats[he_IL]", "tests/test_providers_formats.py::test_no_invalid_formats[hi_IN]", "tests/test_providers_formats.py::test_no_invalid_formats[hr_HR]", "tests/test_providers_formats.py::test_no_invalid_formats[hu_HU]", "tests/test_providers_formats.py::test_no_invalid_formats[hy_AM]", "tests/test_providers_formats.py::test_no_invalid_formats[id_ID]", "tests/test_providers_formats.py::test_no_invalid_formats[it_CH]", "tests/test_providers_formats.py::test_no_invalid_formats[it_IT]", "tests/test_providers_formats.py::test_no_invalid_formats[ja_JP]", "tests/test_providers_formats.py::test_no_invalid_formats[ka_GE]", "tests/test_providers_formats.py::test_no_invalid_formats[ko_KR]", "tests/test_providers_formats.py::test_no_invalid_formats[la]", "tests/test_providers_formats.py::test_no_invalid_formats[lb_LU]", "tests/test_providers_formats.py::test_no_invalid_formats[lt_LT]", "tests/test_providers_formats.py::test_no_invalid_formats[lv_LV]", "tests/test_providers_formats.py::test_no_invalid_formats[mt_MT]", "tests/test_providers_formats.py::test_no_invalid_formats[ne_NP]", "tests/test_providers_formats.py::test_no_invalid_formats[nl_BE]", "tests/test_providers_formats.py::test_no_invalid_formats[nl_NL]", "tests/test_providers_formats.py::test_no_invalid_formats[no_NO]", "tests/test_providers_formats.py::test_no_invalid_formats[or_IN]", "tests/test_providers_formats.py::test_no_invalid_formats[pl_PL]", "tests/test_providers_formats.py::test_no_invalid_formats[pt_BR]", "tests/test_providers_formats.py::test_no_invalid_formats[pt_PT]", "tests/test_providers_formats.py::test_no_invalid_formats[ro_RO]", "tests/test_providers_formats.py::test_no_invalid_formats[ru_RU]", "tests/test_providers_formats.py::test_no_invalid_formats[sk_SK]", "tests/test_providers_formats.py::test_no_invalid_formats[sl_SI]", "tests/test_providers_formats.py::test_no_invalid_formats[sv_SE]", "tests/test_providers_formats.py::test_no_invalid_formats[ta_IN]", "tests/test_providers_formats.py::test_no_invalid_formats[th]", "tests/test_providers_formats.py::test_no_invalid_formats[th_TH]", "tests/test_providers_formats.py::test_no_invalid_formats[tl_PH]", "tests/test_providers_formats.py::test_no_invalid_formats[tr_TR]", "tests/test_providers_formats.py::test_no_invalid_formats[tw_GH]", "tests/test_providers_formats.py::test_no_invalid_formats[uk_UA]", "tests/test_providers_formats.py::test_no_invalid_formats[zh_CN]", "tests/test_providers_formats.py::test_no_invalid_formats[zh_TW]" ]
[ "tests/test_factory.py::FactoryTestCase::test_arbitrary_digits_pydecimal", "tests/test_factory.py::FactoryTestCase::test_binary", "tests/test_factory.py::FactoryTestCase::test_cli_seed", "tests/test_factory.py::FactoryTestCase::test_cli_seed_with_repeat", "tests/test_factory.py::FactoryTestCase::test_cli_verbosity", "tests/test_factory.py::FactoryTestCase::test_command", "tests/test_factory.py::FactoryTestCase::test_command_custom_provider", "tests/test_factory.py::FactoryTestCase::test_documentor", "tests/test_factory.py::FactoryTestCase::test_instance_seed_chain", "tests/test_factory.py::FactoryTestCase::test_negative_pyfloat", "tests/test_factory.py::FactoryTestCase::test_password", "tests/test_factory.py::FactoryTestCase::test_prefix_suffix_always_string", "tests/test_factory.py::FactoryTestCase::test_pyfloat_empty_range_error", "tests/test_factory.py::FactoryTestCase::test_pyfloat_in_range", "tests/test_factory.py::FactoryTestCase::test_pyfloat_same_min_max", "tests/test_factory.py::FactoryTestCase::test_random_pyfloat", "tests/test_factory.py::FactoryTestCase::test_random_pystr_characters", "tests/test_factory.py::FactoryTestCase::test_slugify", "tests/test_factory.py::FactoryTestCase::test_unknown_locale", "tests/test_factory.py::FactoryTestCase::test_unknown_provider" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-01-30 18:32:51+00:00
mit
3,308
joke2k__faker-1741
diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 6d2394f1..037b8645 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 15.1.1 +current_version = 15.1.2 files = VERSION faker/__init__.py docs/conf.py commit = True tag = True diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d66f603..207f95ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Changelog +### [v15.1.2 - 2022-11-01](https://github.com/joke2k/faker/compare/v15.1.1...v15.1.2) + +* Fix missing return in `en_US` `state_abbr`. Thanks @AssenD. + ### [v15.1.1 - 2022-10-13](https://github.com/joke2k/faker/compare/v15.1.0...v15.1.1) * Fix ImportError on python <3.7.2. Thanks @matthewhughes934. diff --git a/VERSION b/VERSION index 68a28303..0a75ce5d 100644 --- a/VERSION +++ b/VERSION @@ -1,1 +1,1 @@ -15.1.1 +15.1.2 diff --git a/docs/conf.py b/docs/conf.py index 5e436041..278b69db 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -51,9 +51,9 @@ copyright = "2014, Daniele Faraglia" # built documents. # # The short X.Y version. -version = "15.1.1" +version = "15.1.2" # The full version, including alpha/beta/rc tags. -release = "15.1.1" +release = "15.1.2" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/faker/__init__.py b/faker/__init__.py index 12140975..1ce84021 100644 --- a/faker/__init__.py +++ b/faker/__init__.py @@ -2,6 +2,6 @@ from faker.factory import Factory from faker.generator import Generator from faker.proxy import Faker -VERSION = "15.1.1" +VERSION = "15.1.2" __all__ = ("Factory", "Generator", "Faker") diff --git a/faker/providers/address/en_US/__init__.py b/faker/providers/address/en_US/__init__.py index 82c1cac0..4242e781 100644 --- a/faker/providers/address/en_US/__init__.py +++ b/faker/providers/address/en_US/__init__.py @@ -493,7 +493,7 @@ class Provider(AddressProvider): If False, only states will be returned. """ if include_territories: - self.random_element(self.states_and_territories_abbr) + return self.random_element(self.states_and_territories_abbr) return self.random_element(self.states_abbr) def postcode(self) -> str: diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index 28128635..13926cf2 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -58,7 +58,13 @@ class Provider(BaseProvider): def pybool(self) -> bool: return self.random_int(0, 1) == 1 - def pystr(self, min_chars: Optional[int] = None, max_chars: int = 20, prefix: str = "", suffix: str = "") -> str: + def pystr( + self, + min_chars: Optional[int] = None, + max_chars: int = 20, + prefix: str = "", + suffix: str = "", + ) -> str: """ Generates a random string of upper and lowercase letters. :return: Random of random length between min and max characters. @@ -162,6 +168,11 @@ class Provider(BaseProvider): result = min(result, 10**left_digits - 1) result = max(result, -(10**left_digits + 1)) + # It's possible for the result to end up > than max_value + # This is a quick hack to ensure result is always smaller. + if max_value is not None: + if result > max_value: + result = result - (result - max_value) return result def _safe_random_int(self, min_value: float, max_value: float, positive: bool) -> int: @@ -178,7 +189,11 @@ class Provider(BaseProvider): if min_value == max_value: return self._safe_random_int(orig_min_value, orig_max_value, positive) else: - return self.random_int(int(min_value), int(max_value - 1)) + min_value = int(min_value) + max_value = int(max_value - 1) + if max_value < min_value: + max_value += 1 + return self.random_int(min_value, max_value) def pyint(self, min_value: int = 0, max_value: int = 9999, step: int = 1) -> int: return self.generator.random_int(min_value, max_value, step=step) @@ -385,7 +400,10 @@ class Provider(BaseProvider): ) def pystruct( - self, count: int = 10, value_types: Optional[TypesSpec] = None, allowed_types: Optional[TypesSpec] = None + self, + count: int = 10, + value_types: Optional[TypesSpec] = None, + allowed_types: Optional[TypesSpec] = None, ) -> Tuple[List, Dict, Dict]: value_types: TypesSpec = self._check_signature(value_types, allowed_types)
joke2k/faker
919a26ee1f97cf0dd41bce39bee3729110c736c5
diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 39c067b7..c3088a8e 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -228,6 +228,9 @@ class TestPyfloat(unittest.TestCase): """ self.fake.pyfloat(min_value=-1.0, max_value=1.0) + def test_float_min_and_max_value_with_same_whole(self): + self.fake.pyfloat(min_value=2.3, max_value=2.5) + class TestPydecimal(unittest.TestCase): def setUp(self):
ValueError: empty range for pyfloat * Faker version: 14.0.0 * OS: macOS 12.5 (Monterey) pyfloat throws ValueError when min_value and max_value have the same left digits. ### Steps to reproduce ``` from faker import Faker fake = Faker() fake.pyfloat(min_value=1.25, max_value=1.75) ``` ### Expected behavior pyfloat returns a float between min_value and max_value ### Actual behavior pyfloat throws exception ``` ValueError: empty range for randrange() (1, 1, 0) ```
0.0
919a26ee1f97cf0dd41bce39bee3729110c736c5
[ "tests/providers/test_python.py::TestPyfloat::test_float_min_and_max_value_with_same_whole" ]
[ "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-5-12345]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-0-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-1-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-2-12]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[0123-1-1]", "tests/providers/test_python.py::test_pyfloat_right_or_left_digit_overflow", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_and_positive", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPyfloat::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits", "tests/providers/test_python.py::TestPydecimal::test_left_digits", "tests/providers/test_python.py::TestPydecimal::test_left_digits_can_be_zero", "tests/providers/test_python.py::TestPydecimal::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPydecimal::test_max_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_max_value_and_positive", "tests/providers/test_python.py::TestPydecimal::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value", "tests/providers/test_python.py::TestPydecimal::test_min_value_10_pow_1000_return_greater_number", "tests/providers/test_python.py::TestPydecimal::test_min_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_hundred_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_one_hundred_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_min_value_zero_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_positive", "tests/providers/test_python.py::TestPydecimal::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPydecimal::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPydecimal::test_pydecimal", "tests/providers/test_python.py::TestPydecimal::test_right_digits", "tests/providers/test_python.py::TestPystr::test_exact_length", "tests/providers/test_python.py::TestPystr::test_invalid_length_limits", "tests/providers/test_python.py::TestPystr::test_lower_length_limit", "tests/providers/test_python.py::TestPystr::test_no_parameters", "tests/providers/test_python.py::TestPystr::test_prefix", "tests/providers/test_python.py::TestPystr::test_prefix_and_suffix", "tests/providers/test_python.py::TestPystr::test_suffix", "tests/providers/test_python.py::TestPystr::test_upper_length_limit", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation", "tests/providers/test_python.py::TestPython::test_pybool", "tests/providers/test_python.py::TestPython::test_pylist", "tests/providers/test_python.py::TestPython::test_pylist_types", "tests/providers/test_python.py::TestPython::test_pytuple", "tests/providers/test_python.py::TestPython::test_pytuple_size" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-28 19:06:24+00:00
mit
3,309
joke2k__faker-1821
diff --git a/faker/providers/address/en_US/__init__.py b/faker/providers/address/en_US/__init__.py index 4242e781..4bf14695 100644 --- a/faker/providers/address/en_US/__init__.py +++ b/faker/providers/address/en_US/__init__.py @@ -419,6 +419,15 @@ class Provider(AddressProvider): "WV": (24701, 26886), "WI": (53001, 54990), "WY": (82001, 83128), + # Territories - incomplete ranges with accurate subsets - https://www.geonames.org/postalcode-search.html + "AS": (96799, 96799), + "FM": (96941, 96944), + "GU": (96910, 96932), + "MH": (96960, 96970), + "MP": (96950, 96952), + "PW": (96940, 96940), + "PR": (600, 799), + "VI": (801, 805), } territories_abbr = ( @@ -511,7 +520,7 @@ class Provider(AddressProvider): if state_abbr is None: state_abbr = self.random_element(self.states_abbr) - if state_abbr in self.states_abbr: + if state_abbr in self.states_and_territories_abbr: postcode = "%d" % ( self.generator.random.randint( self.states_postcode[state_abbr][0], @@ -519,8 +528,12 @@ class Provider(AddressProvider): ) ) - if len(postcode) == 4: - postcode = "0%s" % postcode + # zero left pad up until desired length (some have length 3 or 4) + target_postcode_len = 5 + current_postcode_len = len(postcode) + if current_postcode_len < target_postcode_len: + pad = target_postcode_len - current_postcode_len + postcode = f"{'0'*pad}{postcode}" return postcode
joke2k/faker
5de6bf3fb811272b7e13b6da6623ee1fdfa3efe3
diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py index d9cf2e8b..0576484e 100644 --- a/tests/providers/test_address.py +++ b/tests/providers/test_address.py @@ -536,7 +536,7 @@ class TestEnUS: def test_postcode_in_state(self, faker, num_samples): for _ in range(num_samples): - for state_abbr in EnUsAddressProvider.states_abbr: + for state_abbr in EnUsAddressProvider.states_and_territories_abbr: code = faker.postcode_in_state(state_abbr) assert re.fullmatch(r"\d{5}", code) assert int(code) >= EnUsAddressProvider.states_postcode[state_abbr][0] @@ -553,7 +553,7 @@ class TestEnUS: def test_zipcode_in_state(self, faker, num_samples): for _ in range(num_samples): - for state_abbr in EnUsAddressProvider.states_abbr: + for state_abbr in EnUsAddressProvider.states_and_territories_abbr: code = faker.zipcode_in_state(state_abbr) assert re.fullmatch(r"\d{5}", code) assert int(code) >= EnUsAddressProvider.states_postcode[state_abbr][0]
states_postcode fails with territories * Faker version: since 15.1.2 * OS: All Brief summary of the issue goes here. en_US state fix in 15.1.2 added territories, which are not in states_postcode Looking up postcode by state fails with territories enabled, but didn't fail prior to 15.1.2. The fix made here: https://github.com/joke2k/faker/blob/master/faker/providers/address/en_US/__init__.py#L496 Combined with the default to include territories here: https://github.com/joke2k/faker/blob/master/faker/providers/address/en_US/__init__.py#L488 Causes this to fail whereas it did not prior to the correction made in 15.1.2. https://github.com/joke2k/faker/blob/master/faker/providers/address/en_US/__init__.py#L505 ### Steps to reproduce 1. fake.add_provider(providers.address.en_US.Provider) 2. state = fake.state_abbr() # include_territories=True is default. user can fix by setting to False? 3. repeatedly call fake.zipcode_in_state(state) # or alternatively pass in GU or other territory ### Expected behavior Ideally this would not give an error when combining these functions. It looks like territories to have zip codes, so best solution may be to update the state/postalcode mapping. --> from internet: "Within the U.S. Territories, American Samoa (postal abbreviation AS) uses zip code 96799, and Guam (postal abbreviation GU) uses zip codes in the range 96910–96932." ### Actual behavior Fails on Step 3 noted above.
0.0
5de6bf3fb811272b7e13b6da6623ee1fdfa3efe3
[ "tests/providers/test_address.py::TestEnUS::test_postcode_in_state", "tests/providers/test_address.py::TestEnUS::test_zipcode_in_state" ]
[ "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes_as_default", "tests/providers/test_address.py::TestBaseProvider::test_alpha_3_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_bad_country_code_representation", "tests/providers/test_address.py::TestBaseProvider::test_administrative_unit_all_locales", "tests/providers/test_address.py::TestBaseProvider::test_country_code_all_locales", "tests/providers/test_address.py::TestBaseProvider::test_current_country_errors", "tests/providers/test_address.py::TestAzAz::test_street_suffix_long", "tests/providers/test_address.py::TestAzAz::test_city_name", "tests/providers/test_address.py::TestAzAz::test_street_name", "tests/providers/test_address.py::TestAzAz::test_settlement_name", "tests/providers/test_address.py::TestAzAz::test_village_name", "tests/providers/test_address.py::TestAzAz::test_postcode", "tests/providers/test_address.py::TestCsCz::test_street_suffix_short", "tests/providers/test_address.py::TestCsCz::test_street_suffix_long", "tests/providers/test_address.py::TestCsCz::test_city_name", "tests/providers/test_address.py::TestCsCz::test_street_name", "tests/providers/test_address.py::TestCsCz::test_state", "tests/providers/test_address.py::TestCsCz::test_postcode", "tests/providers/test_address.py::TestCsCz::test_city_with_postcode", "tests/providers/test_address.py::TestDaDk::test_street_suffix", "tests/providers/test_address.py::TestDaDk::test_street_name", "tests/providers/test_address.py::TestDaDk::test_dk_street_name", "tests/providers/test_address.py::TestDaDk::test_city_name", "tests/providers/test_address.py::TestDaDk::test_state", "tests/providers/test_address.py::TestDaDk::test_postcode", "tests/providers/test_address.py::TestDeAt::test_city", "tests/providers/test_address.py::TestDeAt::test_state", "tests/providers/test_address.py::TestDeAt::test_street_suffix_short", "tests/providers/test_address.py::TestDeAt::test_street_suffix_long", "tests/providers/test_address.py::TestDeAt::test_country", "tests/providers/test_address.py::TestDeAt::test_postcode", "tests/providers/test_address.py::TestDeAt::test_city_with_postcode", "tests/providers/test_address.py::TestDeDe::test_city", "tests/providers/test_address.py::TestDeDe::test_state", "tests/providers/test_address.py::TestDeDe::test_street_suffix_short", "tests/providers/test_address.py::TestDeDe::test_street_suffix_long", "tests/providers/test_address.py::TestDeDe::test_country", "tests/providers/test_address.py::TestDeDe::test_postcode", "tests/providers/test_address.py::TestDeDe::test_city_with_postcode", "tests/providers/test_address.py::TestElGr::test_line_address", "tests/providers/test_address.py::TestElGr::test_street_prefix_short", "tests/providers/test_address.py::TestElGr::test_street_prefix_long", "tests/providers/test_address.py::TestElGr::test_street", "tests/providers/test_address.py::TestElGr::test_city", "tests/providers/test_address.py::TestElGr::test_region", "tests/providers/test_address.py::TestEnAu::test_postcode", "tests/providers/test_address.py::TestEnAu::test_state", "tests/providers/test_address.py::TestEnAu::test_city_prefix", "tests/providers/test_address.py::TestEnAu::test_state_abbr", "tests/providers/test_address.py::TestEnCa::test_postcode", "tests/providers/test_address.py::TestEnCa::test_postcode_in_province", "tests/providers/test_address.py::TestEnCa::test_postalcode", "tests/providers/test_address.py::TestEnCa::test_postal_code_letter", "tests/providers/test_address.py::TestEnCa::test_province", "tests/providers/test_address.py::TestEnCa::test_province_abbr", "tests/providers/test_address.py::TestEnCa::test_city_prefix", "tests/providers/test_address.py::TestEnCa::test_secondary_address", "tests/providers/test_address.py::TestEnGb::test_county", "tests/providers/test_address.py::TestEnIe::test_postcode", "tests/providers/test_address.py::TestEnIe::test_county", "tests/providers/test_address.py::TestEnUS::test_city_prefix", "tests/providers/test_address.py::TestEnUS::test_state", "tests/providers/test_address.py::TestEnUS::test_state_abbr", "tests/providers/test_address.py::TestEnUS::test_state_abbr_no_territories", "tests/providers/test_address.py::TestEnUS::test_postcode", "tests/providers/test_address.py::TestEnUS::test_zipcode", "tests/providers/test_address.py::TestEnUS::test_zipcode_plus4", "tests/providers/test_address.py::TestEnUS::test_military_ship", "tests/providers/test_address.py::TestEnUS::test_military_state", "tests/providers/test_address.py::TestEnUS::test_military_apo", "tests/providers/test_address.py::TestEnUS::test_military_dpo", "tests/providers/test_address.py::TestEnUS::test_postalcode", "tests/providers/test_address.py::TestEnUS::test_postalcode_in_state", "tests/providers/test_address.py::TestEsCo::test_department_code", "tests/providers/test_address.py::TestEsCo::test_department", "tests/providers/test_address.py::TestEsCo::test_municipality_code", "tests/providers/test_address.py::TestEsCo::test_municipality", "tests/providers/test_address.py::TestEsCo::test_street_prefix", "tests/providers/test_address.py::TestEsCo::test_street_suffix", "tests/providers/test_address.py::TestEsCo::test_street_name", "tests/providers/test_address.py::TestEsCo::test_building_number", "tests/providers/test_address.py::TestEsCo::test_secondary_address", "tests/providers/test_address.py::TestEsCo::test_street_address", "tests/providers/test_address.py::TestEsCo::test_postcode", "tests/providers/test_address.py::TestEsCo::test_address", "tests/providers/test_address.py::TestEsEs::test_state_name", "tests/providers/test_address.py::TestEsEs::test_street_prefix", "tests/providers/test_address.py::TestEsEs::test_secondary_address", "tests/providers/test_address.py::TestEsEs::test_regions", "tests/providers/test_address.py::TestEsEs::test_autonomous_community", "tests/providers/test_address.py::TestEsEs::test_postcode", "tests/providers/test_address.py::TestEsMx::test_city_prefix", "tests/providers/test_address.py::TestEsMx::test_city_suffix", "tests/providers/test_address.py::TestEsMx::test_city_adjective", "tests/providers/test_address.py::TestEsMx::test_street_prefix", "tests/providers/test_address.py::TestEsMx::test_secondary_address", "tests/providers/test_address.py::TestEsMx::test_state", "tests/providers/test_address.py::TestEsMx::test_state_abbr", "tests/providers/test_address.py::TestFaIr::test_city_prefix", "tests/providers/test_address.py::TestFaIr::test_secondary_address", "tests/providers/test_address.py::TestFaIr::test_state", "tests/providers/test_address.py::TestFrFr::test_street_prefix", "tests/providers/test_address.py::TestFrFr::test_city_prefix", "tests/providers/test_address.py::TestFrFr::test_region", "tests/providers/test_address.py::TestFrFr::test_department", "tests/providers/test_address.py::TestFrFr::test_department_name", "tests/providers/test_address.py::TestFrFr::test_department_number", "tests/providers/test_address.py::TestHeIl::test_city_name", "tests/providers/test_address.py::TestHeIl::test_street_title", "tests/providers/test_address.py::TestHiIn::test_city_name", "tests/providers/test_address.py::TestHiIn::test_state", "tests/providers/test_address.py::TestTaIn::test_city_name", "tests/providers/test_address.py::TestTaIn::test_state", "tests/providers/test_address.py::TestFiFi::test_city", "tests/providers/test_address.py::TestFiFi::test_street_suffix", "tests/providers/test_address.py::TestFiFi::test_state", "tests/providers/test_address.py::TestHrHr::test_city_name", "tests/providers/test_address.py::TestHrHr::test_street_name", "tests/providers/test_address.py::TestHrHr::test_state", "tests/providers/test_address.py::TestHyAm::test_address", "tests/providers/test_address.py::TestHyAm::test_building_number", "tests/providers/test_address.py::TestHyAm::test_city", "tests/providers/test_address.py::TestHyAm::test_city_prefix", "tests/providers/test_address.py::TestHyAm::test_country", "tests/providers/test_address.py::TestHyAm::test_postcode", "tests/providers/test_address.py::TestHyAm::test_postcode_in_state", "tests/providers/test_address.py::TestHyAm::test_secondary_address", "tests/providers/test_address.py::TestHyAm::test_state", "tests/providers/test_address.py::TestHyAm::test_state_abbr", "tests/providers/test_address.py::TestHyAm::test_street", "tests/providers/test_address.py::TestHyAm::test_street_address", "tests/providers/test_address.py::TestHyAm::test_street_name", "tests/providers/test_address.py::TestHyAm::test_street_prefix", "tests/providers/test_address.py::TestHyAm::test_street_suffix", "tests/providers/test_address.py::TestHyAm::test_village", "tests/providers/test_address.py::TestHyAm::test_village_prefix", "tests/providers/test_address.py::TestItIt::test_city", "tests/providers/test_address.py::TestItIt::test_postcode_city_province", "tests/providers/test_address.py::TestItIt::test_city_prefix", "tests/providers/test_address.py::TestItIt::test_secondary_address", "tests/providers/test_address.py::TestItIt::test_administrative_unit", "tests/providers/test_address.py::TestItIt::test_state_abbr", "tests/providers/test_address.py::TestJaJp::test_chome", "tests/providers/test_address.py::TestJaJp::test_ban", "tests/providers/test_address.py::TestJaJp::test_gou", "tests/providers/test_address.py::TestJaJp::test_town", "tests/providers/test_address.py::TestJaJp::test_prefecture", "tests/providers/test_address.py::TestJaJp::test_city", "tests/providers/test_address.py::TestJaJp::test_country", "tests/providers/test_address.py::TestJaJp::test_building_name", "tests/providers/test_address.py::TestJaJp::test_address", "tests/providers/test_address.py::TestJaJp::test_postcode", "tests/providers/test_address.py::TestJaJp::test_zipcode", "tests/providers/test_address.py::TestKoKr::test_old_postal_code", "tests/providers/test_address.py::TestKoKr::test_postal_code", "tests/providers/test_address.py::TestKoKr::test_postcode", "tests/providers/test_address.py::TestKoKr::test_city", "tests/providers/test_address.py::TestKoKr::test_borough", "tests/providers/test_address.py::TestKoKr::test_town", "tests/providers/test_address.py::TestKoKr::test_town_suffix", "tests/providers/test_address.py::TestKoKr::test_building_name", "tests/providers/test_address.py::TestKoKr::test_building_suffix", "tests/providers/test_address.py::TestKoKr::test_building_dong", "tests/providers/test_address.py::TestNeNp::test_province", "tests/providers/test_address.py::TestNeNp::test_district", "tests/providers/test_address.py::TestNeNp::test_city", "tests/providers/test_address.py::TestNeNp::test_country", "tests/providers/test_address.py::TestNoNo::test_postcode", "tests/providers/test_address.py::TestNoNo::test_city_suffix", "tests/providers/test_address.py::TestNoNo::test_street_suffix", "tests/providers/test_address.py::TestNoNo::test_address", "tests/providers/test_address.py::TestZhTw::test_postcode", "tests/providers/test_address.py::TestZhTw::test_city_name", "tests/providers/test_address.py::TestZhTw::test_city_suffix", "tests/providers/test_address.py::TestZhTw::test_city", "tests/providers/test_address.py::TestZhTw::test_country", "tests/providers/test_address.py::TestZhTw::test_street_name", "tests/providers/test_address.py::TestZhTw::test_address", "tests/providers/test_address.py::TestZhCn::test_postcode", "tests/providers/test_address.py::TestZhCn::test_city_name", "tests/providers/test_address.py::TestZhCn::test_city_suffix", "tests/providers/test_address.py::TestZhCn::test_city", "tests/providers/test_address.py::TestZhCn::test_province", "tests/providers/test_address.py::TestZhCn::test_district", "tests/providers/test_address.py::TestZhCn::test_country", "tests/providers/test_address.py::TestZhCn::test_street_name", "tests/providers/test_address.py::TestZhCn::test_address", "tests/providers/test_address.py::TestPtBr::test_country", "tests/providers/test_address.py::TestPtBr::test_bairro", "tests/providers/test_address.py::TestPtBr::test_neighborhood", "tests/providers/test_address.py::TestPtBr::test_estado", "tests/providers/test_address.py::TestPtBr::test_estado_nome", "tests/providers/test_address.py::TestPtBr::test_estado_sigla", "tests/providers/test_address.py::TestPtBr::test_address", "tests/providers/test_address.py::TestPtBr::test_raw_postcode", "tests/providers/test_address.py::TestPtBr::test_formatted_postcode", "tests/providers/test_address.py::TestPtPt::test_distrito", "tests/providers/test_address.py::TestPtPt::test_concelho", "tests/providers/test_address.py::TestPtPt::test_freguesia", "tests/providers/test_address.py::TestPtPt::test_place_name", "tests/providers/test_address.py::TestEnPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestEnPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestEnPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestEnPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestEnPh::test_postcode", "tests/providers/test_address.py::TestEnPh::test_building_number", "tests/providers/test_address.py::TestEnPh::test_floor_unit_number", "tests/providers/test_address.py::TestEnPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestEnPh::test_address", "tests/providers/test_address.py::TestFilPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestFilPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestFilPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestFilPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestFilPh::test_postcode", "tests/providers/test_address.py::TestFilPh::test_building_number", "tests/providers/test_address.py::TestFilPh::test_floor_unit_number", "tests/providers/test_address.py::TestFilPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestFilPh::test_address", "tests/providers/test_address.py::TestTlPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestTlPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestTlPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestTlPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestTlPh::test_postcode", "tests/providers/test_address.py::TestTlPh::test_building_number", "tests/providers/test_address.py::TestTlPh::test_floor_unit_number", "tests/providers/test_address.py::TestTlPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestTlPh::test_address", "tests/providers/test_address.py::TestRuRu::test_city_name", "tests/providers/test_address.py::TestRuRu::test_country", "tests/providers/test_address.py::TestRuRu::test_region", "tests/providers/test_address.py::TestRuRu::test_postcode", "tests/providers/test_address.py::TestRuRu::test_city_prefix", "tests/providers/test_address.py::TestRuRu::test_street_suffix", "tests/providers/test_address.py::TestRuRu::test_street_title", "tests/providers/test_address.py::TestRuRu::test_street_name", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[feminine_suffix_and_noflex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[feminine_suffix_and_flex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[non_feminine_suffix_and_noflex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_irregular_masc_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_ck_street_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_uk_street_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_other_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[neu_suffx_and_iregular_neu_street_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[neu_suffix_and_regular_street_title]", "tests/providers/test_address.py::TestThTh::test_country", "tests/providers/test_address.py::TestThTh::test_city_name", "tests/providers/test_address.py::TestThTh::test_province", "tests/providers/test_address.py::TestThTh::test_amphoe", "tests/providers/test_address.py::TestThTh::test_tambon", "tests/providers/test_address.py::TestThTh::test_postcode", "tests/providers/test_address.py::TestEnIn::test_city_name", "tests/providers/test_address.py::TestEnIn::test_state", "tests/providers/test_address.py::TestSkSk::test_street_suffix_short", "tests/providers/test_address.py::TestSkSk::test_street_suffix_long", "tests/providers/test_address.py::TestSkSk::test_city_name", "tests/providers/test_address.py::TestSkSk::test_street_name", "tests/providers/test_address.py::TestSkSk::test_state", "tests/providers/test_address.py::TestSkSk::test_postcode", "tests/providers/test_address.py::TestSkSk::test_city_with_postcode", "tests/providers/test_address.py::TestDeCh::test_canton_name", "tests/providers/test_address.py::TestDeCh::test_canton_code", "tests/providers/test_address.py::TestDeCh::test_canton", "tests/providers/test_address.py::TestDeCh::test_city", "tests/providers/test_address.py::TestRoRo::test_address", "tests/providers/test_address.py::TestRoRo::test_street_address", "tests/providers/test_address.py::TestRoRo::test_street_name", "tests/providers/test_address.py::TestRoRo::test_street_prefix", "tests/providers/test_address.py::TestRoRo::test_building_number", "tests/providers/test_address.py::TestRoRo::test_secondary_address", "tests/providers/test_address.py::TestRoRo::test_city", "tests/providers/test_address.py::TestRoRo::test_city_name", "tests/providers/test_address.py::TestRoRo::test_state", "tests/providers/test_address.py::TestRoRo::test_state_abbr", "tests/providers/test_address.py::TestRoRo::test_postcode", "tests/providers/test_address.py::TestRoRo::test_city_with_postcode", "tests/providers/test_address.py::TestEnNz::test_te_reo_part", "tests/providers/test_address.py::TestEnNz::test_reo_first", "tests/providers/test_address.py::TestEnNz::test_reo_ending", "tests/providers/test_address.py::TestEnNz::test_city_prefix", "tests/providers/test_address.py::TestEnNz::test_city_suffix", "tests/providers/test_address.py::TestEnNz::test_rd_number", "tests/providers/test_address.py::TestEnNz::test_secondary_address", "tests/providers/test_address.py::TestFrCh::test_canton_name", "tests/providers/test_address.py::TestFrCh::test_canton_code", "tests/providers/test_address.py::TestFrCh::test_canton", "tests/providers/test_address.py::TestHuHu::test_administrative_unit", "tests/providers/test_address.py::TestHuHu::test_street_address_with_county", "tests/providers/test_address.py::TestHuHu::test_city_prefix", "tests/providers/test_address.py::TestHuHu::test_city_part", "tests/providers/test_address.py::TestHuHu::test_real_city_name", "tests/providers/test_address.py::TestHuHu::test_frequent_street_name", "tests/providers/test_address.py::TestHuHu::test_postcode", "tests/providers/test_address.py::TestHuHu::test_street_name", "tests/providers/test_address.py::TestHuHu::test_building_number", "tests/providers/test_address.py::TestIdId::test_street", "tests/providers/test_address.py::TestIdId::test_street_prefix_short", "tests/providers/test_address.py::TestIdId::test_street_prefix_long", "tests/providers/test_address.py::TestIdId::test_city_name", "tests/providers/test_address.py::TestIdId::test_administrative_unit", "tests/providers/test_address.py::TestIdId::test_state_abbr", "tests/providers/test_address.py::TestIdId::test_country", "tests/providers/test_address.py::TestKaGe::test_street_title", "tests/providers/test_address.py::TestKaGe::test_city_name", "tests/providers/test_address.py::TestSlSi::test_city_name", "tests/providers/test_address.py::TestSlSi::test_street_name", "tests/providers/test_address.py::TestSlSi::test_administrative_unit", "tests/providers/test_address.py::TestSvSe::test_street_prefix", "tests/providers/test_address.py::TestSvSe::test_city_name", "tests/providers/test_address.py::TestSvSe::test_administrative_unit", "tests/providers/test_address.py::TestUkUa::test_city_prefix", "tests/providers/test_address.py::TestUkUa::test_city_name", "tests/providers/test_address.py::TestUkUa::test_postcode", "tests/providers/test_address.py::TestUkUa::test_street_prefix", "tests/providers/test_address.py::TestUkUa::test_street_name", "tests/providers/test_address.py::TestUkUa::test_street_title", "tests/providers/test_address.py::TestUkUa::test_region", "tests/providers/test_address.py::TestFrCa::test_province", "tests/providers/test_address.py::TestFrCa::test_province_abbr", "tests/providers/test_address.py::TestFrCa::test_city_prefixes", "tests/providers/test_address.py::TestFrCa::test_city_suffixes", "tests/providers/test_address.py::TestFrCa::test_street_prefixes", "tests/providers/test_address.py::TestFrCa::test_administrative_unit", "tests/providers/test_address.py::TestPlPl::test_postcode", "tests/providers/test_address.py::TestPlPl::test_zipcode", "tests/providers/test_address.py::TestPlPl::test_postalcode" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-03-13 21:57:50+00:00
mit
3,310
joke2k__faker-1869
diff --git a/faker/providers/address/fr_FR/__init__.py b/faker/providers/address/fr_FR/__init__.py index 1125716e..2ee23305 100644 --- a/faker/providers/address/fr_FR/__init__.py +++ b/faker/providers/address/fr_FR/__init__.py @@ -469,10 +469,10 @@ class Provider(AddressProvider): def postcode(self) -> str: """ - Randomly returns a postcode generated from existing french depertment number. + Randomly returns a postcode generated from existing french department number. exemple: '33260' """ department = self.department_number() if department in ["2A", "2B"]: department = "20" - return f"{department}{self.random_number(digits=5 - len(department))}" + return f"{department}{self.random_number(digits=5 - len(department), fix_len=True)}"
joke2k/faker
fa79c6b0c510274b08b46ad0f007fd1b517a9ab2
diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py index 0e5c47ef..0ecef674 100644 --- a/tests/providers/test_address.py +++ b/tests/providers/test_address.py @@ -870,6 +870,7 @@ class TestFrFr: for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) + assert len(postcode) == 5 assert ( postcode[:3] in department_numbers # for 3 digits deparments number or postcode[:2] == "20" # for Corsica : "2A" or "2B"
fr_FR address provider generates less than 5 digits postcode * Faker version: master (18.9.0), bug introduced by https://github.com/joke2k/faker/pull/1852 The new provider method can generate 4 or less digits values. But french postcodes must be 5 digits long (cf https://en.wikipedia.org/wiki/Postal_codes_in_France). Line to fix: https://github.com/joke2k/faker/blob/fa79c6b0c510274b08b46ad0f007fd1b517a9ab2/faker/providers/address/fr_FR/__init__.py#LL478C27-L478C27 ### Steps to reproduce 1. generate a few postcodes with `fr_FR` address provider ### Expected behavior 5 digits values ### Actual behavior From 3 to 5 digits values
0.0
fa79c6b0c510274b08b46ad0f007fd1b517a9ab2
[ "tests/providers/test_address.py::TestFrFr::test_postcode" ]
[ "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes_as_default", "tests/providers/test_address.py::TestBaseProvider::test_alpha_3_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_bad_country_code_representation", "tests/providers/test_address.py::TestBaseProvider::test_administrative_unit_all_locales", "tests/providers/test_address.py::TestBaseProvider::test_country_code_all_locales", "tests/providers/test_address.py::TestBaseProvider::test_current_country_errors", "tests/providers/test_address.py::TestAzAz::test_street_suffix_long", "tests/providers/test_address.py::TestAzAz::test_city_name", "tests/providers/test_address.py::TestAzAz::test_street_name", "tests/providers/test_address.py::TestAzAz::test_settlement_name", "tests/providers/test_address.py::TestAzAz::test_village_name", "tests/providers/test_address.py::TestAzAz::test_postcode", "tests/providers/test_address.py::TestCsCz::test_street_suffix_short", "tests/providers/test_address.py::TestCsCz::test_street_suffix_long", "tests/providers/test_address.py::TestCsCz::test_city_name", "tests/providers/test_address.py::TestCsCz::test_street_name", "tests/providers/test_address.py::TestCsCz::test_state", "tests/providers/test_address.py::TestCsCz::test_postcode", "tests/providers/test_address.py::TestCsCz::test_city_with_postcode", "tests/providers/test_address.py::TestDaDk::test_street_suffix", "tests/providers/test_address.py::TestDaDk::test_street_name", "tests/providers/test_address.py::TestDaDk::test_dk_street_name", "tests/providers/test_address.py::TestDaDk::test_city_name", "tests/providers/test_address.py::TestDaDk::test_state", "tests/providers/test_address.py::TestDaDk::test_postcode", "tests/providers/test_address.py::TestDeAt::test_city", "tests/providers/test_address.py::TestDeAt::test_state", "tests/providers/test_address.py::TestDeAt::test_street_suffix_short", "tests/providers/test_address.py::TestDeAt::test_street_suffix_long", "tests/providers/test_address.py::TestDeAt::test_country", "tests/providers/test_address.py::TestDeAt::test_postcode", "tests/providers/test_address.py::TestDeAt::test_city_with_postcode", "tests/providers/test_address.py::TestDeDe::test_city", "tests/providers/test_address.py::TestDeDe::test_state", "tests/providers/test_address.py::TestDeDe::test_street_suffix_short", "tests/providers/test_address.py::TestDeDe::test_street_suffix_long", "tests/providers/test_address.py::TestDeDe::test_country", "tests/providers/test_address.py::TestDeDe::test_postcode", "tests/providers/test_address.py::TestDeDe::test_city_with_postcode", "tests/providers/test_address.py::TestElGr::test_line_address", "tests/providers/test_address.py::TestElGr::test_street_prefix_short", "tests/providers/test_address.py::TestElGr::test_street_prefix_long", "tests/providers/test_address.py::TestElGr::test_street", "tests/providers/test_address.py::TestElGr::test_city", "tests/providers/test_address.py::TestElGr::test_region", "tests/providers/test_address.py::TestEnAu::test_postcode", "tests/providers/test_address.py::TestEnAu::test_state", "tests/providers/test_address.py::TestEnAu::test_city_prefix", "tests/providers/test_address.py::TestEnAu::test_state_abbr", "tests/providers/test_address.py::TestEnCa::test_postcode", "tests/providers/test_address.py::TestEnCa::test_postcode_in_province", "tests/providers/test_address.py::TestEnCa::test_postalcode", "tests/providers/test_address.py::TestEnCa::test_postal_code_letter", "tests/providers/test_address.py::TestEnCa::test_province", "tests/providers/test_address.py::TestEnCa::test_province_abbr", "tests/providers/test_address.py::TestEnCa::test_city_prefix", "tests/providers/test_address.py::TestEnCa::test_secondary_address", "tests/providers/test_address.py::TestEnGb::test_county", "tests/providers/test_address.py::TestEnIe::test_postcode", "tests/providers/test_address.py::TestEnIe::test_county", "tests/providers/test_address.py::TestEnUS::test_city_prefix", "tests/providers/test_address.py::TestEnUS::test_state", "tests/providers/test_address.py::TestEnUS::test_state_abbr", "tests/providers/test_address.py::TestEnUS::test_state_abbr_states_only", "tests/providers/test_address.py::TestEnUS::test_state_abbr_no_territories", "tests/providers/test_address.py::TestEnUS::test_state_abbr_no_freely_associated_states", "tests/providers/test_address.py::TestEnUS::test_postcode", "tests/providers/test_address.py::TestEnUS::test_postcode_in_state", "tests/providers/test_address.py::TestEnUS::test_zipcode", "tests/providers/test_address.py::TestEnUS::test_zipcode_in_state", "tests/providers/test_address.py::TestEnUS::test_zipcode_plus4", "tests/providers/test_address.py::TestEnUS::test_military_ship", "tests/providers/test_address.py::TestEnUS::test_military_state", "tests/providers/test_address.py::TestEnUS::test_military_apo", "tests/providers/test_address.py::TestEnUS::test_military_dpo", "tests/providers/test_address.py::TestEnUS::test_postalcode", "tests/providers/test_address.py::TestEnUS::test_postalcode_in_state", "tests/providers/test_address.py::TestEnUS::test_state_abbr_determinism", "tests/providers/test_address.py::TestEsCo::test_department_code", "tests/providers/test_address.py::TestEsCo::test_department", "tests/providers/test_address.py::TestEsCo::test_municipality_code", "tests/providers/test_address.py::TestEsCo::test_municipality", "tests/providers/test_address.py::TestEsCo::test_street_prefix", "tests/providers/test_address.py::TestEsCo::test_street_suffix", "tests/providers/test_address.py::TestEsCo::test_street_name", "tests/providers/test_address.py::TestEsCo::test_building_number", "tests/providers/test_address.py::TestEsCo::test_secondary_address", "tests/providers/test_address.py::TestEsCo::test_street_address", "tests/providers/test_address.py::TestEsCo::test_postcode", "tests/providers/test_address.py::TestEsCo::test_address", "tests/providers/test_address.py::TestEsEs::test_state_name", "tests/providers/test_address.py::TestEsEs::test_street_prefix", "tests/providers/test_address.py::TestEsEs::test_secondary_address", "tests/providers/test_address.py::TestEsEs::test_regions", "tests/providers/test_address.py::TestEsEs::test_autonomous_community", "tests/providers/test_address.py::TestEsEs::test_postcode", "tests/providers/test_address.py::TestEsMx::test_city_prefix", "tests/providers/test_address.py::TestEsMx::test_city_suffix", "tests/providers/test_address.py::TestEsMx::test_city_adjective", "tests/providers/test_address.py::TestEsMx::test_street_prefix", "tests/providers/test_address.py::TestEsMx::test_secondary_address", "tests/providers/test_address.py::TestEsMx::test_state", "tests/providers/test_address.py::TestEsMx::test_state_abbr", "tests/providers/test_address.py::TestFaIr::test_city_prefix", "tests/providers/test_address.py::TestFaIr::test_secondary_address", "tests/providers/test_address.py::TestFaIr::test_state", "tests/providers/test_address.py::TestFrFr::test_street_prefix", "tests/providers/test_address.py::TestFrFr::test_city_prefix", "tests/providers/test_address.py::TestFrFr::test_region", "tests/providers/test_address.py::TestFrFr::test_department", "tests/providers/test_address.py::TestFrFr::test_department_name", "tests/providers/test_address.py::TestFrFr::test_department_number", "tests/providers/test_address.py::TestHeIl::test_city_name", "tests/providers/test_address.py::TestHeIl::test_street_title", "tests/providers/test_address.py::TestHiIn::test_city_name", "tests/providers/test_address.py::TestHiIn::test_state", "tests/providers/test_address.py::TestTaIn::test_city_name", "tests/providers/test_address.py::TestTaIn::test_state", "tests/providers/test_address.py::TestFiFi::test_city", "tests/providers/test_address.py::TestFiFi::test_street_suffix", "tests/providers/test_address.py::TestFiFi::test_state", "tests/providers/test_address.py::TestHrHr::test_city_name", "tests/providers/test_address.py::TestHrHr::test_street_name", "tests/providers/test_address.py::TestHrHr::test_state", "tests/providers/test_address.py::TestHyAm::test_address", "tests/providers/test_address.py::TestHyAm::test_building_number", "tests/providers/test_address.py::TestHyAm::test_city", "tests/providers/test_address.py::TestHyAm::test_city_prefix", "tests/providers/test_address.py::TestHyAm::test_country", "tests/providers/test_address.py::TestHyAm::test_postcode", "tests/providers/test_address.py::TestHyAm::test_postcode_in_state", "tests/providers/test_address.py::TestHyAm::test_secondary_address", "tests/providers/test_address.py::TestHyAm::test_state", "tests/providers/test_address.py::TestHyAm::test_state_abbr", "tests/providers/test_address.py::TestHyAm::test_street", "tests/providers/test_address.py::TestHyAm::test_street_address", "tests/providers/test_address.py::TestHyAm::test_street_name", "tests/providers/test_address.py::TestHyAm::test_street_prefix", "tests/providers/test_address.py::TestHyAm::test_street_suffix", "tests/providers/test_address.py::TestHyAm::test_village", "tests/providers/test_address.py::TestHyAm::test_village_prefix", "tests/providers/test_address.py::TestItIt::test_city", "tests/providers/test_address.py::TestItIt::test_postcode_city_province", "tests/providers/test_address.py::TestItIt::test_city_prefix", "tests/providers/test_address.py::TestItIt::test_secondary_address", "tests/providers/test_address.py::TestItIt::test_administrative_unit", "tests/providers/test_address.py::TestItIt::test_state_abbr", "tests/providers/test_address.py::TestJaJp::test_chome", "tests/providers/test_address.py::TestJaJp::test_ban", "tests/providers/test_address.py::TestJaJp::test_gou", "tests/providers/test_address.py::TestJaJp::test_town", "tests/providers/test_address.py::TestJaJp::test_prefecture", "tests/providers/test_address.py::TestJaJp::test_city", "tests/providers/test_address.py::TestJaJp::test_country", "tests/providers/test_address.py::TestJaJp::test_building_name", "tests/providers/test_address.py::TestJaJp::test_address", "tests/providers/test_address.py::TestJaJp::test_postcode", "tests/providers/test_address.py::TestJaJp::test_zipcode", "tests/providers/test_address.py::TestKoKr::test_old_postal_code", "tests/providers/test_address.py::TestKoKr::test_postal_code", "tests/providers/test_address.py::TestKoKr::test_postcode", "tests/providers/test_address.py::TestKoKr::test_city", "tests/providers/test_address.py::TestKoKr::test_borough", "tests/providers/test_address.py::TestKoKr::test_town", "tests/providers/test_address.py::TestKoKr::test_town_suffix", "tests/providers/test_address.py::TestKoKr::test_building_name", "tests/providers/test_address.py::TestKoKr::test_building_suffix", "tests/providers/test_address.py::TestKoKr::test_building_dong", "tests/providers/test_address.py::TestNeNp::test_province", "tests/providers/test_address.py::TestNeNp::test_district", "tests/providers/test_address.py::TestNeNp::test_city", "tests/providers/test_address.py::TestNeNp::test_country", "tests/providers/test_address.py::TestNoNo::test_postcode", "tests/providers/test_address.py::TestNoNo::test_city_suffix", "tests/providers/test_address.py::TestNoNo::test_street_suffix", "tests/providers/test_address.py::TestNoNo::test_address", "tests/providers/test_address.py::TestZhTw::test_postcode", "tests/providers/test_address.py::TestZhTw::test_city_name", "tests/providers/test_address.py::TestZhTw::test_city_suffix", "tests/providers/test_address.py::TestZhTw::test_city", "tests/providers/test_address.py::TestZhTw::test_country", "tests/providers/test_address.py::TestZhTw::test_street_name", "tests/providers/test_address.py::TestZhTw::test_address", "tests/providers/test_address.py::TestZhCn::test_postcode", "tests/providers/test_address.py::TestZhCn::test_city_name", "tests/providers/test_address.py::TestZhCn::test_city_suffix", "tests/providers/test_address.py::TestZhCn::test_city", "tests/providers/test_address.py::TestZhCn::test_province", "tests/providers/test_address.py::TestZhCn::test_district", "tests/providers/test_address.py::TestZhCn::test_country", "tests/providers/test_address.py::TestZhCn::test_street_name", "tests/providers/test_address.py::TestZhCn::test_address", "tests/providers/test_address.py::TestPtBr::test_country", "tests/providers/test_address.py::TestPtBr::test_bairro", "tests/providers/test_address.py::TestPtBr::test_neighborhood", "tests/providers/test_address.py::TestPtBr::test_estado", "tests/providers/test_address.py::TestPtBr::test_estado_nome", "tests/providers/test_address.py::TestPtBr::test_estado_sigla", "tests/providers/test_address.py::TestPtBr::test_address", "tests/providers/test_address.py::TestPtBr::test_raw_postcode", "tests/providers/test_address.py::TestPtBr::test_formatted_postcode", "tests/providers/test_address.py::TestPtPt::test_distrito", "tests/providers/test_address.py::TestPtPt::test_concelho", "tests/providers/test_address.py::TestPtPt::test_freguesia", "tests/providers/test_address.py::TestPtPt::test_place_name", "tests/providers/test_address.py::TestEnPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestEnPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestEnPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestEnPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestEnPh::test_postcode", "tests/providers/test_address.py::TestEnPh::test_building_number", "tests/providers/test_address.py::TestEnPh::test_floor_unit_number", "tests/providers/test_address.py::TestEnPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestEnPh::test_address", "tests/providers/test_address.py::TestFilPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestFilPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestFilPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestFilPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestFilPh::test_postcode", "tests/providers/test_address.py::TestFilPh::test_building_number", "tests/providers/test_address.py::TestFilPh::test_floor_unit_number", "tests/providers/test_address.py::TestFilPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestFilPh::test_address", "tests/providers/test_address.py::TestTlPh::test_metro_manila_postcode", "tests/providers/test_address.py::TestTlPh::test_luzon_province_postcode", "tests/providers/test_address.py::TestTlPh::test_visayas_province_postcode", "tests/providers/test_address.py::TestTlPh::test_mindanao_province_postcode", "tests/providers/test_address.py::TestTlPh::test_postcode", "tests/providers/test_address.py::TestTlPh::test_building_number", "tests/providers/test_address.py::TestTlPh::test_floor_unit_number", "tests/providers/test_address.py::TestTlPh::test_ordinal_floor_number", "tests/providers/test_address.py::TestTlPh::test_address", "tests/providers/test_address.py::TestRuRu::test_city_name", "tests/providers/test_address.py::TestRuRu::test_country", "tests/providers/test_address.py::TestRuRu::test_region", "tests/providers/test_address.py::TestRuRu::test_postcode", "tests/providers/test_address.py::TestRuRu::test_city_prefix", "tests/providers/test_address.py::TestRuRu::test_street_suffix", "tests/providers/test_address.py::TestRuRu::test_street_title", "tests/providers/test_address.py::TestRuRu::test_street_name", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[feminine_suffix_and_noflex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[feminine_suffix_and_flex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[non_feminine_suffix_and_noflex_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_irregular_masc_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_ck_street_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_uk_street_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[masc_suffix_and_other_stem]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[neu_suffx_and_iregular_neu_street_title]", "tests/providers/test_address.py::TestRuRu::test_street_name_lexical[neu_suffix_and_regular_street_title]", "tests/providers/test_address.py::TestThTh::test_country", "tests/providers/test_address.py::TestThTh::test_city_name", "tests/providers/test_address.py::TestThTh::test_province", "tests/providers/test_address.py::TestThTh::test_amphoe", "tests/providers/test_address.py::TestThTh::test_tambon", "tests/providers/test_address.py::TestThTh::test_postcode", "tests/providers/test_address.py::TestEnIn::test_city_name", "tests/providers/test_address.py::TestEnIn::test_state", "tests/providers/test_address.py::TestSkSk::test_street_suffix_short", "tests/providers/test_address.py::TestSkSk::test_street_suffix_long", "tests/providers/test_address.py::TestSkSk::test_city_name", "tests/providers/test_address.py::TestSkSk::test_street_name", "tests/providers/test_address.py::TestSkSk::test_state", "tests/providers/test_address.py::TestSkSk::test_postcode", "tests/providers/test_address.py::TestSkSk::test_city_with_postcode", "tests/providers/test_address.py::TestDeCh::test_canton_name", "tests/providers/test_address.py::TestDeCh::test_canton_code", "tests/providers/test_address.py::TestDeCh::test_canton", "tests/providers/test_address.py::TestDeCh::test_city", "tests/providers/test_address.py::TestRoRo::test_address", "tests/providers/test_address.py::TestRoRo::test_street_address", "tests/providers/test_address.py::TestRoRo::test_street_name", "tests/providers/test_address.py::TestRoRo::test_street_prefix", "tests/providers/test_address.py::TestRoRo::test_building_number", "tests/providers/test_address.py::TestRoRo::test_secondary_address", "tests/providers/test_address.py::TestRoRo::test_city", "tests/providers/test_address.py::TestRoRo::test_city_name", "tests/providers/test_address.py::TestRoRo::test_state", "tests/providers/test_address.py::TestRoRo::test_state_abbr", "tests/providers/test_address.py::TestRoRo::test_postcode", "tests/providers/test_address.py::TestRoRo::test_city_with_postcode", "tests/providers/test_address.py::TestEnNz::test_te_reo_part", "tests/providers/test_address.py::TestEnNz::test_reo_first", "tests/providers/test_address.py::TestEnNz::test_reo_ending", "tests/providers/test_address.py::TestEnNz::test_city_prefix", "tests/providers/test_address.py::TestEnNz::test_city_suffix", "tests/providers/test_address.py::TestEnNz::test_rd_number", "tests/providers/test_address.py::TestEnNz::test_secondary_address", "tests/providers/test_address.py::TestFrCh::test_canton_name", "tests/providers/test_address.py::TestFrCh::test_canton_code", "tests/providers/test_address.py::TestFrCh::test_canton", "tests/providers/test_address.py::TestHuHu::test_administrative_unit", "tests/providers/test_address.py::TestHuHu::test_street_address_with_county", "tests/providers/test_address.py::TestHuHu::test_city_prefix", "tests/providers/test_address.py::TestHuHu::test_city_part", "tests/providers/test_address.py::TestHuHu::test_real_city_name", "tests/providers/test_address.py::TestHuHu::test_frequent_street_name", "tests/providers/test_address.py::TestHuHu::test_postcode", "tests/providers/test_address.py::TestHuHu::test_street_name", "tests/providers/test_address.py::TestHuHu::test_building_number", "tests/providers/test_address.py::TestIdId::test_street", "tests/providers/test_address.py::TestIdId::test_street_prefix_short", "tests/providers/test_address.py::TestIdId::test_street_prefix_long", "tests/providers/test_address.py::TestIdId::test_city_name", "tests/providers/test_address.py::TestIdId::test_administrative_unit", "tests/providers/test_address.py::TestIdId::test_state_abbr", "tests/providers/test_address.py::TestIdId::test_country", "tests/providers/test_address.py::TestKaGe::test_street_title", "tests/providers/test_address.py::TestKaGe::test_city_name", "tests/providers/test_address.py::TestSlSi::test_city_name", "tests/providers/test_address.py::TestSlSi::test_street_name", "tests/providers/test_address.py::TestSlSi::test_administrative_unit", "tests/providers/test_address.py::TestSvSe::test_street_prefix", "tests/providers/test_address.py::TestSvSe::test_city_name", "tests/providers/test_address.py::TestSvSe::test_administrative_unit", "tests/providers/test_address.py::TestUkUa::test_city_prefix", "tests/providers/test_address.py::TestUkUa::test_city_name", "tests/providers/test_address.py::TestUkUa::test_postcode", "tests/providers/test_address.py::TestUkUa::test_street_prefix", "tests/providers/test_address.py::TestUkUa::test_street_name", "tests/providers/test_address.py::TestUkUa::test_street_title", "tests/providers/test_address.py::TestUkUa::test_region", "tests/providers/test_address.py::TestFrCa::test_province", "tests/providers/test_address.py::TestFrCa::test_province_abbr", "tests/providers/test_address.py::TestFrCa::test_city_prefixes", "tests/providers/test_address.py::TestFrCa::test_city_suffixes", "tests/providers/test_address.py::TestFrCa::test_street_prefixes", "tests/providers/test_address.py::TestFrCa::test_administrative_unit", "tests/providers/test_address.py::TestPlPl::test_postcode", "tests/providers/test_address.py::TestPlPl::test_zipcode", "tests/providers/test_address.py::TestPlPl::test_postalcode" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-05-31 11:13:12+00:00
mit
3,311
joke2k__faker-1991
diff --git a/faker/proxy.py b/faker/proxy.py index 653a5943..03a6e42e 100644 --- a/faker/proxy.py +++ b/faker/proxy.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import copy import functools import re @@ -35,7 +37,7 @@ class Faker: use_weighting: bool = True, **config: Any, ) -> None: - self._factory_map = OrderedDict() + self._factory_map: OrderedDict[str, Generator | Faker] = OrderedDict() self._weights = None self._unique_proxy = UniqueProxy(self) self._optional_proxy = OptionalProxy(self) @@ -54,7 +56,7 @@ class Faker: if final_locale not in locales: locales.append(final_locale) - elif isinstance(locale, OrderedDict): + elif isinstance(locale, (OrderedDict, dict)): assert all(isinstance(v, (int, float)) for v in locale.values()) odict = OrderedDict() for k, v in locale.items(): @@ -66,15 +68,25 @@ class Faker: else: locales = [DEFAULT_LOCALE] - for locale in locales: - self._factory_map[locale] = Factory.create( - locale, + if len(locales) == 1: + self._factory_map[locales[0]] = Factory.create( + locales[0], providers, generator, includes, use_weighting=use_weighting, **config, ) + else: + for locale in locales: + self._factory_map[locale] = Faker( + locale, + providers, + generator, + includes, + use_weighting=use_weighting, + **config, + ) self._locales = locales self._factories = list(self._factory_map.values()) @@ -85,8 +97,12 @@ class Faker: attributes |= {attr for attr in dir(factory) if not attr.startswith("_")} return sorted(attributes) - def __getitem__(self, locale: str) -> Generator: - return self._factory_map[locale.replace("-", "_")] + def __getitem__(self, locale: str) -> Faker: + if locale.replace("-", "_") in self.locales and len(self.locales) == 1: + return self + instance = self._factory_map[locale.replace("-", "_")] + assert isinstance(instance, Faker) # for mypy + return instance def __getattribute__(self, attr: str) -> Any: """ @@ -273,10 +289,10 @@ class Faker: return self._weights @property - def factories(self) -> List[Generator]: + def factories(self) -> List[Generator | Faker]: return self._factories - def items(self) -> List[Tuple[str, Generator]]: + def items(self) -> List[Tuple[str, Generator | Faker]]: return list(self._factory_map.items())
joke2k/faker
17f22ba4cb5c158b63785c8e441597369dafdb61
diff --git a/tests/providers/test_misc.py b/tests/providers/test_misc.py index ec9fe57a..df735eee 100644 --- a/tests/providers/test_misc.py +++ b/tests/providers/test_misc.py @@ -423,7 +423,7 @@ class TestMiscProvider: def test_dsv_data_columns(self, faker): num_rows = 10 data_columns = ["{{name}}", "#??-####", "{{address}}", "{{phone_number}}"] - with patch.object(faker["en_US"], "pystr_format") as mock_pystr_format: + with patch.object(faker["en_US"].factories[0], "pystr_format") as mock_pystr_format: mock_pystr_format.assert_not_called() faker.dsv(data_columns=data_columns, num_rows=num_rows) diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py index 6342bfb9..4935528e 100644 --- a/tests/providers/test_python.py +++ b/tests/providers/test_python.py @@ -523,7 +523,7 @@ class TestPystrFormat(unittest.TestCase): Faker.seed(0) def test_formatter_invocation(self): - with patch.object(self.fake["en_US"], "foo") as mock_foo: + with patch.object(self.fake["en_US"].factories[0], "foo") as mock_foo: with patch("faker.providers.BaseProvider.bothify", wraps=self.fake.bothify) as mock_bothify: mock_foo.return_value = "barbar" value = self.fake.pystr_format("{{foo}}?#?{{foo}}?#?{{foo}}", letters="abcde") diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 322bc396..8b4b6d63 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -103,14 +103,14 @@ class TestFakerProxyClass: fake = Faker(locale) for locale_name, factory in fake.items(): assert locale_name in processed_locale - assert isinstance(factory, Generator) + assert isinstance(factory, (Generator, Faker)) def test_dunder_getitem(self): locale = ["de_DE", "en-US", "en-PH", "ja_JP"] fake = Faker(locale) for code in locale: - assert isinstance(fake[code], Generator) + assert isinstance(fake[code], (Generator, Faker)) with pytest.raises(KeyError): fake["en_GB"]
Unicity and localization * Faker version: 17.4.0 * OS: Archlinux It seems that uniqueness and localization cannot be used together: ```python >>> from faker import Faker ... fake = Faker(['it_IT', 'en_US', 'ja_JP']) >>> fake['it_IT'].name() 'Giuseppina Juvara' >>> fake['it_IT'].unique.name() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Generator' object has no attribute 'unique' >>> fake.unique.name() '石井 翔太' >>> fake.unique['it_IT'].name() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'UniqueProxy' object is not subscriptable ``` I would lo to be able to use both features at the same time!
0.0
17f22ba4cb5c158b63785c8e441597369dafdb61
[ "tests/providers/test_misc.py::TestMiscProvider::test_dsv_data_columns", "tests/providers/test_python.py::TestPystrFormat::test_formatter_invocation" ]
[ "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_str", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_int", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_uuid_object", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_seedability", "tests/providers/test_misc.py::TestMiscProvider::test_zip_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_zip_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_zip_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_tar_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_tar_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_tar_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_image_no_pillow", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_invalid_values", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_no_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_valid_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_row_ids", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_csvwriter_kwargs", "tests/providers/test_misc.py::TestMiscProvider::test_xml_no_xmltodict", "tests/providers/test_misc.py::TestMiscProvider::test_csv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_tsv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_psv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_json_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_json_multiple_rows", "tests/providers/test_misc.py::TestMiscProvider::test_json_passthrough_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_int", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_float", "tests/providers/test_misc.py::TestMiscProvider::test_json_invalid_data_columns", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_datetime_using_encoder", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_datetime_no_encoder", "tests/providers/test_misc.py::TestMiscProvider::test_json_bytes", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_md5", "tests/providers/test_misc.py::TestMiscProvider::test_sha1", "tests/providers/test_misc.py::TestMiscProvider::test_sha256", "tests/providers/test_python.py::test_pyobject[None]", "tests/providers/test_python.py::test_pyobject[bool]", "tests/providers/test_python.py::test_pyobject[str]", "tests/providers/test_python.py::test_pyobject[float]", "tests/providers/test_python.py::test_pyobject[int]", "tests/providers/test_python.py::test_pyobject[tuple]", "tests/providers/test_python.py::test_pyobject[set]", "tests/providers/test_python.py::test_pyobject[list]", "tests/providers/test_python.py::test_pyobject[object_type8]", "tests/providers/test_python.py::test_pyobject[dict]", "tests/providers/test_python.py::test_pyobject_with_unknown_object_type[object]", "tests/providers/test_python.py::test_pyobject_with_unknown_object_type[type]", "tests/providers/test_python.py::test_pyobject_with_unknown_object_type[callable]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-5-12345]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-0-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-1-1]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[1234567-2-12]", "tests/providers/test_python.py::test_pyfloat_right_and_left_digits_positive[0123-1-1]", "tests/providers/test_python.py::test_pyfloat_right_or_left_digit_overflow", "tests/providers/test_python.py::TestPyint::test_pyint", "tests/providers/test_python.py::TestPyint::test_pyint_bound_0", "tests/providers/test_python.py::TestPyint::test_pyint_bound_negative", "tests/providers/test_python.py::TestPyint::test_pyint_bound_positive", "tests/providers/test_python.py::TestPyint::test_pyint_bounds", "tests/providers/test_python.py::TestPyint::test_pyint_range", "tests/providers/test_python.py::TestPyint::test_pyint_step", "tests/providers/test_python.py::TestPyfloat::test_float_min_and_max_value_with_same_whole", "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPyfloat::test_max_and_min_value_negative_with_decimals", "tests/providers/test_python.py::TestPyfloat::test_max_and_min_value_positive_with_decimals", "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_and_positive", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPyfloat::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits", "tests/providers/test_python.py::TestPydecimal::test_left_digits", "tests/providers/test_python.py::TestPydecimal::test_left_digits_can_be_zero", "tests/providers/test_python.py::TestPydecimal::test_max_and_min_value_negative", "tests/providers/test_python.py::TestPydecimal::test_max_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_max_value_and_positive", "tests/providers/test_python.py::TestPydecimal::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPydecimal::test_max_value_zero_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value", "tests/providers/test_python.py::TestPydecimal::test_min_value_10_pow_1000_return_greater_number", "tests/providers/test_python.py::TestPydecimal::test_min_value_always_returns_a_decimal", "tests/providers/test_python.py::TestPydecimal::test_min_value_and_left_digits", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_minus_one_hundred_doesnt_return_positive", "tests/providers/test_python.py::TestPydecimal::test_min_value_one_hundred_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_min_value_zero_doesnt_return_negative", "tests/providers/test_python.py::TestPydecimal::test_positive", "tests/providers/test_python.py::TestPydecimal::test_positive_and_min_value_incompatible", "tests/providers/test_python.py::TestPydecimal::test_positive_doesnt_return_zero", "tests/providers/test_python.py::TestPydecimal::test_pydecimal", "tests/providers/test_python.py::TestPydecimal::test_right_digits", "tests/providers/test_python.py::TestPystr::test_exact_length", "tests/providers/test_python.py::TestPystr::test_invalid_length_limits", "tests/providers/test_python.py::TestPystr::test_lower_length_limit", "tests/providers/test_python.py::TestPystr::test_no_parameters", "tests/providers/test_python.py::TestPystr::test_prefix", "tests/providers/test_python.py::TestPystr::test_prefix_and_suffix", "tests/providers/test_python.py::TestPystr::test_suffix", "tests/providers/test_python.py::TestPystr::test_upper_length_limit", "tests/providers/test_python.py::TestPython::test_pybool_return_type", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_fifty", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_hundred", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_less_than_zero", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_more_than_hundred", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_seventy_five", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_twenty_five", "tests/providers/test_python.py::TestPython::test_pybool_truth_probability_zero", "tests/providers/test_python.py::TestPython::test_pylist", "tests/providers/test_python.py::TestPython::test_pylist_types", "tests/providers/test_python.py::TestPython::test_pytuple", "tests/providers/test_python.py::TestPython::test_pytuple_size", "tests/test_proxy.py::TestFakerProxyClass::test_unspecified_locale", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_string", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_list_invalid_value_type", "tests/test_proxy.py::TestFakerProxyClass::test_locale_as_ordereddict", "tests/test_proxy.py::TestFakerProxyClass::test_invalid_locale", "tests/test_proxy.py::TestFakerProxyClass::test_items", "tests/test_proxy.py::TestFakerProxyClass::test_dunder_getitem", "tests/test_proxy.py::TestFakerProxyClass::test_seed_classmethod", "tests/test_proxy.py::TestFakerProxyClass::test_seed_class_locales", "tests/test_proxy.py::TestFakerProxyClass::test_seed_instance", "tests/test_proxy.py::TestFakerProxyClass::test_seed_locale", "tests/test_proxy.py::TestFakerProxyClass::test_single_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_proxy_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_caching_behavior", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_no_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_with_weights", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_single_provider", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_shared_providers", "tests/test_proxy.py::TestFakerProxyClass::test_multiple_locale_factory_selection_unsupported_method", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_single_choice", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_with_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_locales", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_disabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_weighting_enabled_multiple_choices", "tests/test_proxy.py::TestFakerProxyClass::test_dir_include_all_providers_attribute_in_list", "tests/test_proxy.py::TestFakerProxyClass::test_copy", "tests/test_proxy.py::TestFakerProxyClass::test_pickle" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-11 16:00:25+00:00
mit
3,312
joke2k__faker-519
diff --git a/README.rst b/README.rst index 32de05e4..ada79958 100644 --- a/README.rst +++ b/README.rst @@ -136,6 +136,7 @@ Included localized providers: - `en\_US <https://faker.readthedocs.io/en/master/locales/en_US.html>`__ - English (United States) - `es\_ES <https://faker.readthedocs.io/en/master/locales/es_ES.html>`__ - Spanish (Spain) - `es\_MX <https://faker.readthedocs.io/en/master/locales/es_MX.html>`__ - Spanish (Mexico) +- `et\_EE <https://faker.readthedocs.io/en/master/locales/et_EE.html>`__ - Estonian - `fa\_IR <https://faker.readthedocs.io/en/master/locales/fa_IR.html>`__ - Persian (Iran) - `fi\_FI <https://faker.readthedocs.io/en/master/locales/fi_FI.html>`__ - Finnish - `fr\_FR <https://faker.readthedocs.io/en/master/locales/fr_FR.html>`__ - French diff --git a/docs/index.rst b/docs/index.rst index b1d8c097..44cac1ae 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -141,6 +141,7 @@ Included localized providers: - `en\_US <https://faker.readthedocs.io/en/master/locales/en_US.html>`__ - English (United States) - `es\_ES <https://faker.readthedocs.io/en/master/locales/es_ES.html>`__ - Spanish (Spain) - `es\_MX <https://faker.readthedocs.io/en/master/locales/es_MX.html>`__ - Spanish (Mexico) +- `et\_EE <https://faker.readthedocs.io/en/master/locales/et_EE.html>`__ - Estonian - `fa\_IR <https://faker.readthedocs.io/en/master/locales/fa_IR.html>`__ - Persian (Iran) - `fi\_FI <https://faker.readthedocs.io/en/master/locales/fi_FI.html>`__ - Finnish - `fr\_FR <https://faker.readthedocs.io/en/master/locales/fr_FR.html>`__ - French diff --git a/faker/providers/person/et_EE/__init__.py b/faker/providers/person/et_EE/__init__.py new file mode 100644 index 00000000..538897c4 --- /dev/null +++ b/faker/providers/person/et_EE/__init__.py @@ -0,0 +1,190 @@ +# coding=utf-8 +from __future__ import unicode_literals +from .. import Provider as PersonProvider + + +class Provider(PersonProvider): + # https://en.wikipedia.org/wiki/Demographics_of_Estonia#Ethnic_groups + # Main population groups in Estonia are Estonians and ethnic Russians: + # About 70% of the population are Estonians and about 25% are Russians + est_rat = 0.7 + rus_rat = 1.0 - est_rat + formats = {'{{first_name_est}} {{last_name_est}}': est_rat, + '{{first_name_rus}} {{last_name_rus}}': rus_rat} + + formats_male = {'{{first_name_male_est}} {{last_name_est}}': est_rat, + '{{first_name_male_rus}} {{last_name_rus}}': rus_rat} + formats_female = {'{{first_name_female_est}} {{last_name_est}}': est_rat, + '{{first_name_female_rus}} {{last_name_rus}}': rus_rat} + + prefixes_neutral = ('doktor', 'dr', 'prof') + prefixes_male = ('härra', 'hr') + prefixes_neutral + prefixes_female = ('proua', 'pr') + prefixes_neutral + prefixes = set(prefixes_male + prefixes_female) + + suffixes = ('PhD', 'MSc', 'BSc') + + # source: http://www.stat.ee/public/apps/nimed/TOP + # TOP 50 male names in 2017 according to the Statistics Estonia + first_names_male_est = ('Aivar', 'Aleksander', 'Alexander', 'Andres', + 'Andrus', 'Ants', 'Indrek', 'Jaan', 'Jaanus', + 'Jüri', 'Kristjan', 'Marek', 'Margus', 'Marko', + 'Martin', 'Mati', 'Meelis', 'Mihkel', 'Peeter', + 'Priit', 'Raivo', 'Rein', 'Sander', 'Siim', 'Tarmo', + 'Tiit', 'Toomas', 'Tõnu', 'Urmas', 'Vello') + + first_names_female_est = ('Aino', 'Anna', 'Anne', 'Anneli', 'Anu', 'Diana', + 'Ene', 'Eve', 'Kadri', 'Katrin', 'Kristi', + 'Kristiina', 'Kristina', 'Laura', 'Linda', 'Maie', + 'Malle', 'Mare', 'Maria', 'Marika', 'Merike', + 'Niina', 'Piret', 'Reet', 'Riina', 'Sirje', + 'Tiina', 'Tiiu', 'Triin', 'Ülle') + + first_names_est = first_names_male_est + first_names_female_est + + first_names_male_rus = ('Aleksander', 'Aleksandr', 'Aleksei', 'Alexander', + 'Andrei', 'Artur', 'Dmitri', 'Igor', 'Ivan', + 'Jevgeni', 'Juri', 'Maksim', 'Mihhail', 'Nikolai', + 'Oleg', 'Pavel', 'Roman', 'Sergei', 'Sergey', + 'Valeri', 'Viktor', 'Vladimir') + + first_names_female_rus = ('Aleksandra', 'Anna', 'Diana', 'Elena', 'Galina', + 'Irina', 'Jekaterina', 'Jelena', 'Julia', + 'Kristina', 'Ljubov', 'Ljudmila', 'Maria', + 'Marina', 'Nadežda', 'Natalia', 'Natalja', 'Nina', + 'Olga', 'Svetlana', 'Tamara', 'Tatiana', + 'Tatjana', 'Valentina', 'Viktoria') + + first_names_rus = first_names_male_rus + first_names_female_rus + + first_names_male = set(first_names_male_est + first_names_male_rus) + first_names_female = set(first_names_female_est + first_names_female_rus) + first_names = first_names_male | first_names_female + + # http://ekspress.delfi.ee/kuum/\ + # top-500-eesti-koige-levinumad-perekonnanimed?id=27677149 + last_names_est = ('Aas', 'Aasa', 'Aasmäe', 'Aavik', 'Abel', 'Adamson', + 'Ader', 'Alas', 'Allas', 'Allik', 'Anderson', 'Annus', + 'Anton', 'Arro', 'Aru', 'Arula', 'Aun', 'Aus', 'Eller', + 'Erik', 'Erm', 'Ernits', 'Gross', 'Hallik', 'Hansen', + 'Hanson', 'Hein', 'Heinsalu', 'Heinsoo', 'Holm', 'Hunt', + 'Härm', 'Ilves', 'Ivask','Jaakson', 'Jaanson', 'Jaanus', + 'Jakobson', 'Jalakas', 'Johanson', 'Juhanson', 'Juhkam', + 'Jänes', 'Järv', 'Järve', 'Jõe', 'Jõesaar', 'Jõgi', + 'Jürgens', 'Jürgenson', 'Jürisson', 'Kaasik', 'Kadak', + 'Kala', 'Kalamees', 'Kalda', 'Kaljula', 'Kaljurand', + 'Kaljuste', 'Kaljuvee', 'Kallas', 'Kallaste', 'Kalm', + 'Kalmus', 'Kangro', 'Kangur', 'Kapp', 'Karro', 'Karu', + 'Kasak', 'Kase', 'Kasemaa', 'Kasemets', 'Kask', 'Kass', + 'Kattai', 'Kaur', 'Kelder', 'Kesküla', 'Kiik', 'Kiil', + 'Kiis', 'Kiisk', 'Kikas', 'Kikkas', 'Kilk', 'Kink', + 'Kirs', 'Kirsipuu', 'Kirss', 'Kivi', 'Kivilo', 'Kivimäe', + 'Kivistik', 'Klaas', 'Klein', 'Koger', 'Kohv', 'Koit', + 'Koitla', 'Kokk', 'Kolk', 'Kont', 'Kool', 'Koort', + 'Koppel', 'Korol', 'Kotkas', 'Kotov', 'Koval', 'Kozlov', + 'Kriisa', 'Kroon', 'Krõlov', 'Kudrjavtsev', 'Kulikov', + 'Kuningas', 'Kurg', 'Kurm', 'Kurvits', 'Kutsar', 'Kuus', + 'Kuuse', 'Kuusik', 'Kuusk', 'Kärner', 'Käsper', 'Käär', + 'Käärik', 'Kõiv', 'Kütt', 'Laan', 'Laane', 'Laanemets', + 'Laas', 'Laht', 'Laine', 'Laks', 'Lang', 'Lass', 'Laur', + 'Lauri', 'Lehiste', 'Leht', 'Lehtla', 'Lehtmets', 'Leis', + 'Lember', 'Lepik', 'Lepp', 'Leppik', 'Liblik', 'Liiv', + 'Liiva', 'Liivak', 'Liivamägi', 'Lill', 'Lillemets', + 'Lind', 'Link', 'Lipp', 'Lokk', 'Lomp', 'Loorits', 'Luht', + 'Luik', 'Lukin', 'Lukk', 'Lumi', 'Lumiste', 'Luts', + 'Lätt', 'Lääne', 'Lääts', 'Lõhmus', 'Maasik', 'Madisson', + 'Maidla', 'Mandel', 'Maripuu', 'Mark', 'Markus', 'Martin', + 'Martinson', 'Meier', 'Meister', 'Melnik', 'Merila', + 'Mets', 'Michelson', 'Mikk', 'Miller', 'Mitt', 'Moor', + 'Muru', 'Must', 'Mäe', 'Mäeots', 'Mäesalu', 'Mägi', + 'Mänd', 'Mändla', 'Männik', 'Männiste', 'Mõttus', + 'Mölder', 'Mürk', 'Müür', 'Müürsepp', 'Niit', 'Nurk', + 'Nurm', 'Nuut', 'Nõmm', 'Nõmme', 'Nõmmik', 'Oja', 'Ojala', + 'Ojaste', 'Oks', 'Olesk', 'Oras', 'Orav', 'Org', 'Ots', + 'Ott', 'Paal', 'Paap', 'Paas', 'Paju', 'Pajula', 'Palm', + 'Palu', 'Parts', 'Pent', 'Peterson', 'Pettai', 'Pihelgas', + 'Pihlak', 'Piho', 'Piir', 'Piirsalu', 'Pikk', 'Ploom', + 'Poom', 'Post', 'Pruul', 'Pukk', 'Pulk', 'Puusepp', + 'Pärn', 'Pärna', 'Pärnpuu', 'Pärtel', 'Põder', 'Põdra', + 'Põld', 'Põldma', 'Põldmaa', 'Põllu', 'Püvi', 'Raadik', + 'Raag', 'Raamat', 'Raid', 'Raidma', 'Raja', 'Rand', + 'Randmaa', 'Randoja', 'Raud', 'Raudsepp', 'Rebane', + 'Reimann', 'Reinsalu', 'Remmel', 'Rohtla', 'Roos', + 'Roosileht', 'Roots', 'Rosenberg', 'Rosin', 'Ruus', + 'Rätsep', 'Rüütel', 'Saar', 'Saare', 'Saks', 'Salu', + 'Salumets', 'Salumäe', 'Sander', 'Sarap', 'Sarapuu', + 'Sarv', 'Saul', 'Schmidt', 'Sepp', 'Sibul', 'Siim', + 'Sikk', 'Sild', 'Sillaots', 'Sillaste', 'Silm', 'Simson', + 'Sirel', 'Sisask', 'Sokk', 'Soo', 'Soon', 'Soosaar', + 'Soosalu', 'Soots', 'Suits', 'Sulg', 'Susi', 'Sutt', + 'Suur', 'Suvi', 'Säde', 'Sööt', 'Taal', 'Tali', 'Talts', + 'Tamberg', 'Tamm', 'Tamme', 'Tammik', 'Teder', 'Teearu', + 'Teesalu', 'Teras', 'Tiik', 'Tiits', 'Tilk', 'Tomingas', + 'Tomson', 'Toom', 'Toome', 'Tooming', 'Toomsalu', 'Toots', + 'Trei', 'Treial', 'Treier', 'Truu', 'Tuisk', 'Tuul', + 'Tuulik', 'Täht', 'Tõnisson', 'Uibo', 'Unt', 'Urb', 'Uus', + 'Uustalu', 'Vaher', 'Vaht', 'Vahter', 'Vahtra', 'Vain', + 'Vaino', 'Valge', 'Valk', 'Vares', 'Varik', 'Veski', + 'Viik', 'Viira', 'Viks', 'Vill', 'Villemson', 'Visnapuu', + 'Vähi', 'Väli', 'Võsu', 'Õispuu', 'Õun', 'Õunapuu') + + last_names_rus = ('Abramov', 'Afanasjev', 'Aleksandrov', 'Alekseev', + 'Andreev', 'Anissimov', 'Antonov', 'Baranov', 'Beljajev', + 'Belov', 'Bogdanov', 'Bondarenko', 'Borissov', 'Bõstrov', + 'Danilov', 'Davõdov', 'Denissov', 'Dmitriev', 'Drozdov', + 'Egorov', 'Fedorov', 'Fedotov', 'Filatov', 'Filippov', + 'Fjodorov', 'Fomin', 'Frolov', 'Gavrilov', 'Gerassimov', + 'Golubev', 'Gontšarov', 'Gorbunov', 'Grigoriev', 'Gromov', + 'Gusev', 'Ignatjev', 'Iljin', 'Ivanov', 'Jakovlev', + 'Jefimov', 'Jegorov', 'Jermakov', 'Jeršov', 'Kalinin', + 'Karpov', 'Karpov', 'Kazakov', 'Kirillov', 'Kisseljov', + 'Klimov', 'Kolesnik', 'Komarov', 'Kondratjev', + 'Konovalov', 'Konstantinov', 'Korol', 'Kostin', 'Kotov', + 'Koval', 'Kozlov', 'Kruglov', 'Krõlov', 'Kudrjavtsev', + 'Kulikov', 'Kuzmin', 'Kuznetsov', 'Lebedev', 'Loginov', + 'Lukin', 'Makarov', 'Maksimov', 'Malõšev', 'Maslov', + 'Matvejev', 'Medvedev', 'Melnik', 'Mihhailov', 'Miller', + 'Mironov', 'Moroz', 'Naumov', 'Nazarov', 'Nikiforov', + 'Nikitin', 'Nikolaev', 'Novikov', 'Orlov', 'Ossipov', + 'Panov', 'Pavlov', 'Petrov', 'Poljakov', 'Popov', + 'Romanov', 'Rosenberg', 'Rumjantsev', 'Safronov', + 'Saveljev', 'Semenov', 'Sergejev', 'Sidorov', 'Smirnov', + 'Sobolev', 'Sokolov', 'Solovjov', 'Sorokin', 'Stepanov', + 'Suvorov', 'Tarassov', 'Tihhomirov', 'Timofejev', 'Titov', + 'Trofimov', 'Tsvetkov', 'Vasiliev', 'Vinogradov', + 'Vlassov', 'Volkov', 'Vorobjov', 'Voronin', 'Zahharov', + 'Zaitsev', 'Zujev', 'Ševtšenko', 'Štšerbakov', + 'Štšerbakov', 'Žukov', 'Žuravljov') + last_names = set(last_names_est + last_names_rus) + + @classmethod + def first_name_male_est(cls): + return cls.random_element(cls.first_names_male_est) + + @classmethod + def first_name_female_est(cls): + return cls.random_element(cls.first_names_female_est) + + @classmethod + def first_name_male_rus(cls): + return cls.random_element(cls.first_names_male_rus) + + @classmethod + def first_name_female_rus(cls): + return cls.random_element(cls.first_names_female_rus) + + @classmethod + def first_name_est(cls): + return cls.random_element(cls.first_names_est) + + @classmethod + def first_name_rus(cls): + return cls.random_element(cls.first_names_rus) + + @classmethod + def last_name_est(cls): + return cls.random_element(cls.last_names_est) + + @classmethod + def last_name_rus(cls): + return cls.random_element(cls.last_names_rus) diff --git a/faker/providers/person/pl_PL/__init__.py b/faker/providers/person/pl_PL/__init__.py index 56692129..aef9f9d1 100644 --- a/faker/providers/person/pl_PL/__init__.py +++ b/faker/providers/person/pl_PL/__init__.py @@ -10,9 +10,9 @@ class Provider(PersonProvider): '{{first_name}} {{last_name}}', '{{first_name}} {{last_name}}', '{{first_name}} {{last_name}}', - '{{prefix}} {{first_name}} {{last_name}}', + '{{prefix_female}} {{first_name_female}} {{last_name_female}}', '{{first_name}} {{last_name}}', - '{{prefix}} {{first_name}} {{last_name}}' + '{{prefix_male}} {{first_name_male}} {{last_name_male}}' ) first_names_male = ( @@ -519,7 +519,8 @@ class Provider(PersonProvider): 'Bukowski', 'Leśniak', ) - prefixes = ('pan', 'pani') + prefixes_male = ('pan',) + prefixes_female = ('pani',) first_names = first_names_male + first_names_female diff --git a/faker/providers/ssn/et_EE/__init__.py b/faker/providers/ssn/et_EE/__init__.py new file mode 100644 index 00000000..f1181b54 --- /dev/null +++ b/faker/providers/ssn/et_EE/__init__.py @@ -0,0 +1,67 @@ +# coding=utf-8 + +from __future__ import unicode_literals +from .. import Provider as SsnProvider +from faker.generator import random +import datetime +import operator + + +def checksum(digits): + """Calculate checksum of Estonian personal identity code. + + Checksum is calculated with "Modulo 11" method using level I or II scale: + Level I scale: 1 2 3 4 5 6 7 8 9 1 + Level II scale: 3 4 5 6 7 8 9 1 2 3 + + The digits of the personal code are multiplied by level I scale and summed; + if remainder of modulo 11 of the sum is less than 10, checksum is the + remainder. + If remainder is 10, then level II scale is used; checksum is remainder if + remainder < 10 or 0 if remainder is 10. + + See also https://et.wikipedia.org/wiki/Isikukood + """ + sum_mod11 = sum(map(operator.mul, digits, Provider.scale1)) % 11 + if sum_mod11 < 10: + return sum_mod11 + sum_mod11 = sum(map(operator.mul, digits, Provider.scale2)) % 11 + return 0 if sum_mod11 == 10 else sum_mod11 + + +class Provider(SsnProvider): + min_age = 16 * 365 + max_age = 90 * 365 + scale1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 1) + scale2 = (3, 4, 5, 6, 7, 8, 9, 1, 2, 3) + + @classmethod + def ssn(cls): + """ + Returns 11 character Estonian personal identity code (isikukood, IK). + + Age of person is between 16 and 90 years, based on local computer date. + This function assigns random sex to person. + An Estonian Personal identification code consists of 11 digits, + generally given without any whitespace or other delimiters. + The form is GYYMMDDSSSC, where G shows sex and century of birth (odd + number male, even number female, 1-2 19th century, 3-4 20th century, + 5-6 21st century), SSS is a serial number separating persons born on + the same date and C a checksum. + + https://en.wikipedia.org/wiki/National_identification_number#Estonia + """ + age = datetime.timedelta(days=random.randrange(Provider.min_age, + Provider.max_age)) + birthday = datetime.date.today() - age + if birthday.year < 2000: + ik = random.choice(('3', '4')) + elif birthday.year < 2100: + ik = random.choice(('5', '6')) + else: + ik = random.choice(('7', '8')) + + ik += "%02d%02d%02d" % ((birthday.year % 100), birthday.month, + birthday.day) + ik += str(random.randrange(0, 999)).zfill(3) + return ik + str(checksum([int(ch) for ch in ik]))
joke2k/faker
0ee26313099392f8b347c323d3c8eb294505ab58
diff --git a/tests/providers/ssn.py b/tests/providers/ssn.py index 37369aac..fe559113 100644 --- a/tests/providers/ssn.py +++ b/tests/providers/ssn.py @@ -6,10 +6,28 @@ import unittest import re from faker import Factory +from faker.providers.ssn.et_EE import Provider as EtProvider, checksum as et_checksum from faker.providers.ssn.hr_HR import Provider as HrProvider, checksum as hr_checksum from faker.providers.ssn.pt_BR import Provider as PtProvider, checksum as pt_checksum +class TestEtEE(unittest.TestCase): + """ Tests SSN in the et_EE locale """ + + def setUp(self): + self.factory = Factory.create('et_EE') + + def test_ssn_checksum(self): + self.assertEqual(et_checksum([4, 4, 1, 1, 1, 3, 0, 4, 9, 2]), 3) + self.assertEqual(et_checksum([3, 6, 7, 0, 1, 1, 6, 6, 2, 7]), 8) + self.assertEqual(et_checksum([4, 7, 0, 0, 4, 2, 1, 5, 0, 1]), 2) + self.assertEqual(et_checksum([3, 9, 7, 0, 3, 0, 4, 3, 3, 6]), 0) + + def test_ssn(self): + for i in range(100): + self.assertTrue(re.search(r'^\d{11}$', EtProvider.ssn())) + + class TestHrHR(unittest.TestCase): """ Tests SSN in the hr_HR locale """
Invalid gender spec in pl_PL ``` In [9]: fake.name() Out[9]: 'pani Mateusz Kiciak' ``` "pani" is female but "Mateusz" is male surname.
0.0
0ee26313099392f8b347c323d3c8eb294505ab58
[ "tests/providers/ssn.py::TestEtEE::test_ssn", "tests/providers/ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/ssn.py::TestHrHR::test_ssn", "tests/providers/ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/ssn.py::TestPtBR::test_pt_BR_ssn_checksum" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-05-29 07:17:37+00:00
mit
3,313
joke2k__faker-535
diff --git a/faker/providers/color/hr_HR/__init__.py b/faker/providers/color/hr_HR/__init__.py new file mode 100644 index 00000000..cf063762 --- /dev/null +++ b/faker/providers/color/hr_HR/__init__.py @@ -0,0 +1,160 @@ +# coding=utf-8 +from __future__ import unicode_literals + +from collections import OrderedDict + +from .. import Provider as ColorProvider + +localized = True + + +class Provider(ColorProvider): + all_colors = OrderedDict(( + ('Akvamarin', '#7FFFD4'), + ('Antikna bijela', '#FAEBD7'), + ('Azurna', '#F0FFFF'), + ('Bež', '#F5F5DC'), + ('Bijela', '#FFFFFF'), + ('Bijelo bilje', '#FFFAF0'), + ('Bjelokost', '#FFFFF0'), + ('Blijeda kudelja', '#EEE8AA'), + ('Blijedi badem', '#FFEBCD'), + ('Blijedoljubičasta', '#DB7093'), + ('Blijedotirkizna', '#AFEEEE'), + ('Blijedozelena', '#98FB98'), + ('Breskva', '#FFDAB9'), + ('Brončana', '#D2B48C'), + ('Čeličnoplava', '#4682B4'), + ('Čičak', '#D8BFD8'), + ('Cijan', '#00FFFF'), + ('Čipka', '#FDF5E6'), + ('Čokoladna', '#D2691E'), + ('Crna', '#000000'), + ('Crvena', '#FF0000'), + ('Dim', '#F5F5F5'), + ('Dodger plava', '#1E90FF'), + ('Duboko ružičasta', '#FF1493'), + ('Fuksija', '#FF00FF'), + ('Gainsboro', '#DCDCDC'), + ('Grimizna', '#DC143C'), + ('Indigo', '#4B0082'), + ('Jelenska koža', '#FFE4B5'), + ('Kadetski plava', '#5F9EA0'), + ('Kestenjasta', '#800000'), + ('Koraljna', '#FF7F50'), + ('Kraljevski plava', '#4169E1'), + ('Kudelja', '#DAA520'), + ('Lan', '#FAF0E6'), + ('Lavanda', '#E6E6FA'), + ('Limun', '#FFFACD'), + ('Lipa', '#00FF00'), + ('Ljubičasta', '#EE82EE'), + ('Magenta', '#FF00FF'), + ('Maslinasta', '#808000'), + ('Medljika', '#F0FFF0'), + ('Menta', '#F5FFFA'), + ('Modro nebo', '#00BFFF'), + ('Modrozelena', '#008080'), + ('Mornarska', '#000080'), + ('Morskozelena', '#2E8B57'), + ('Mračno siva', '#696969'), + ('Narančasta', '#FFA500'), + ('Narančastocrvena', '#FF4500'), + ('Narančastoružičasta', '#FA8072'), + ('Noćno plava', '#191970'), + ('Orhideja', '#DA70D6'), + ('Papaja', '#FFEFD5'), + ('Peru', '#CD853F'), + ('Plava', '#0000FF'), + ('Plavi prah', '#B0E0E6'), + ('Plavi škriljevac', '#6A5ACD'), + ('Plavkasta', '#F0F8FF'), + ('Plavo cvijeće', '#6495ED'), + ('Plavo nebo', '#87CEEB'), + ('Plavoljubičasta', '#8A2BE2'), + ('Porculanska', '#FFE4C4'), + ('Prljavomaslinasta', '#6B8E23'), + ('Proljetnozelena', '#00FF7F'), + ('Prozirno bijela', '#F8F8FF'), + ('Pšenica', '#F5DEB3'), + ('Purpurna', '#800080'), + ('Rajčica', '#FF6347'), + ('Rumena lavanda', '#FFF0F5'), + ('Ružičasta', '#FFC0CB'), + ('Ružičastosmeđa', '#BC8F8F'), + ('Siva', '#808080'), + ('Sivi škriljevac', '#708090'), + ('Sivožuta', '#F0E68C'), + ('Smeđa', '#A52A2A'), + ('Smeđe sedlo', '#8B4513'), + ('Smeđi pijesak', '#F4A460'), + ('Smeđkasto bijela', '#FFDEAD'), + ('Snijeg', '#FFFAFA'), + ('Srebrna', '#C0C0C0'), + ('Srednja akvamarin', '#66CDAA'), + ('Srednja crvenoljubičasta', '#C71585'), + ('Srednja morskozelena', '#3CB371'), + ('Srednja orhideja', '#BA55D3'), + ('Srednja plava', '#0000CD'), + ('Srednja proljetnozelena', '#00FA9A'), + ('Srednja purpurna', '#9370DB'), + ('Srednja tirkizna', '#48D1CC'), + ('Srednje plavi škriljevac', '#7B68EE'), + ('Svijetla čeličnoplava', '#B0C4DE'), + ('Svijetla narančastoružičasta', '#FFA07A'), + ('Svijetli cijan', '#E0FFFF'), + ('Svijetlo drvo', '#DEB887'), + ('Svijetlokoraljna', '#F08080'), + ('Svijetlomorskozelena', '#20B2AA'), + ('Svijetloplava', '#ADD8E6'), + ('Svijetloružičasta', '#FFB6C1'), + ('Svijetlosiva', '#D3D3D3'), + ('Svijetlosivi škriljevac', '#778899'), + ('Svijetlozelena', '#90EE90'), + ('Svijetložuta kudelja', '#FAFAD2'), + ('Svijetložuta', '#FFFFE0'), + ('Šamotna opeka', '#B22222'), + ('Školjka', '#FFF5EE'), + ('Šljiva', '#DDA0DD'), + ('Tamna kudelja', '#B8860B'), + ('Tamna magenta', '#8B008B'), + ('Tamna narančastoružičasta', '#E9967A'), + ('Tamna orhideja', '#9932CC'), + ('Tamna sivožuta', '#BDB76B'), + ('Tamni cijan', '#008B8B'), + ('Tamno zelena', '#006400'), + ('Tamnocrvena', '#8B0000'), + ('Tamnoljubičasta', '#9400D3'), + ('Tamnomaslinasta', '#556B2F'), + ('Tamnonarančasta', '#FF8C00'), + ('Tamnoplava', '#00008B'), + ('Tamnoplavi škriljevac', '#483D8B'), + ('Tamnosiva', '#A9A9A9'), + ('Tamnosivi škriljevac', '#2F4F4F'), + ('Tamnotirkizna', '#00CED1'), + ('Tamnozelena', '#8FBC8F'), + ('Tirkizna', '#40E0D0'), + ('Topla ružičasta', '#FF69B4'), + ('Vedro nebo', '#87CEFA'), + ('Voda', '#00FFFF'), + ('Zelena lipa', '#32CD32'), + ('Zelena šuma', '#228B22'), + ('Zelena tratina', '#7CFC00'), + ('Zelena', '#008000'), + ('Zeleni liker', '#7FFF00'), + ('Zelenožuta', '#ADFF2F'), + ('Zlatna', '#FFD700'), + ('Žućkastocrvena zemlja', '#CD5C5C'), + ('Žućkastoružičasta', '#FFE4E1'), + ('Žućkastosmeđa glina', '#A0522D'), + ('Žuta svila', '#FFF8DC'), + ('Žuta', '#FFFF00'), + ('Žutozelena', '#9ACD3'), + )) + + safe_colors = ( + 'crna', 'kestenjasta', 'zelena', 'mornarska', 'maslinasta', + 'purpurna', 'modrozelena', 'lipa', 'plava', 'srebrna', + 'siva', 'žuta', 'fuksija', 'voda', 'bijela', + ) + diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py index 8b76e429..f4d2626b 100644 --- a/faker/providers/date_time/__init__.py +++ b/faker/providers/date_time/__init__.py @@ -360,7 +360,7 @@ class Provider(BaseProvider): start_date = cls._parse_date_time(start_date, tzinfo=tzinfo) end_date = cls._parse_date_time(end_date, tzinfo=tzinfo) timestamp = random.randint(start_date, end_date) - return datetime.fromtimestamp(timestamp, tzinfo) + return datetime(1970, 1, 1,tzinfo=tzinfo) + timedelta(seconds=timestamp) @classmethod def future_datetime(cls, end_date='+30d', tzinfo=None): diff --git a/faker/providers/misc/__init__.py b/faker/providers/misc/__init__.py index d219e0c5..679f84b9 100644 --- a/faker/providers/misc/__init__.py +++ b/faker/providers/misc/__init__.py @@ -5,6 +5,7 @@ import hashlib import string import uuid import os +import sys from faker.generator import random from faker.providers.date_time import Provider as DatetimeProvider @@ -91,7 +92,8 @@ class Provider(BaseProvider): Default blob size is 1 Mb. """ - return os.urandom(length) + blob = [random.randrange(256) for o in range(length)] + return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob) @classmethod def md5(cls, raw_output=False):
joke2k/faker
bc645abe807a276bb6746472947047a748dea6c3
diff --git a/tests/factory.py b/tests/factory.py index 30e800ac..65aa47f9 100644 --- a/tests/factory.py +++ b/tests/factory.py @@ -171,13 +171,21 @@ class FactoryTestCase(unittest.TestCase): def test_binary(self): from faker.providers.misc import Provider - + for _ in range(999): length = random.randint(0, 2 ** 10) binary = Provider.binary(length) - self.assertTrue(isinstance(binary, six.binary_type)) + self.assertTrue(isinstance(binary, (bytes, bytearray))) self.assertTrue(len(binary) == length) + + for _ in range(999): + self.generator.seed(_) + binary1 = Provider.binary(_) + self.generator.seed(_) + binary2 = Provider.binary(_) + + self.assertTrue(binary1 == binary2) def test_language_code(self): from faker.providers.misc import Provider
Not possible to seed .binary() It is not possible to seed the method ``binary`` (see also issue #484) ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.binary()[0:100]) b'm\x17 ;\xca\x88\xb6\xb1\x8c/6Qmo\x02\xfa\xc3g\xf9R\xc5\xc6\x84\n\xac\xa3\x99\xb9Xs\xc3D\xa5g\xbb\xe5YU)\x95\tt\x0fsy\xe3\xaa\xfc\xaa\xb7\xb9\xfd\xac\x88\x13\xe2\xb1!\xbc\xea\x00\xd3]"\x9c;\xf2\xecx\xee\xe1\x06\xa6_\x9by\x97\xc3\xd7\xf6\x87&\x8fM\x90{\x18\xb0/\xdf\xcf$*\xde\x13\xc1\x96&\x12\xc2' >>> f2 = Faker() >>> f2.seed(4321) >>> print(f2.binary()[0:100]) b"\xc1Xf\x81\xba\xe8P\xcb\xb2\xfd\x8e\x8bz7'\xe0\x7f\xef\xdej\xf5\xb8\xf1\xe4\x97v\x7f\x9aM\xfb\xee\xabT\x17\x9c\xb7\xa6\x8f\xd1\x8c\x07l0\xc5&*\xd8\xf2B\xbf\xbe\xe8\xca\xbe\xe8\xdf\xec4\xd2\xc1\xff\xecI\xc9\xdc\xae\x92~|\xa1\x0ch\x08\\G\xd7\xd8\xf0I\xc0\xcaLR\xaa\xd6{%\xfa\x14\xd9C\x9f\x1fK\x14\xc0s?O)" ```
0.0
bc645abe807a276bb6746472947047a748dea6c3
[ "tests/factory.py::FactoryTestCase::test_binary" ]
[ "tests/factory.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "tests/factory.py::FactoryTestCase::test_command", "tests/factory.py::FactoryTestCase::test_command_custom_provider", "tests/factory.py::FactoryTestCase::test_documentor", "tests/factory.py::FactoryTestCase::test_email", "tests/factory.py::FactoryTestCase::test_ext_word_list", "tests/factory.py::FactoryTestCase::test_format_calls_formatter_on_provider", "tests/factory.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "tests/factory.py::FactoryTestCase::test_get_formatter_returns_callable", "tests/factory.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "tests/factory.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "tests/factory.py::FactoryTestCase::test_ipv4", "tests/factory.py::FactoryTestCase::test_ipv6", "tests/factory.py::FactoryTestCase::test_language_code", "tests/factory.py::FactoryTestCase::test_locale", "tests/factory.py::FactoryTestCase::test_magic_call_calls_format", "tests/factory.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "tests/factory.py::FactoryTestCase::test_nl_BE_ssn_valid", "tests/factory.py::FactoryTestCase::test_no_words_paragraph", "tests/factory.py::FactoryTestCase::test_no_words_sentence", "tests/factory.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "tests/factory.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "tests/factory.py::FactoryTestCase::test_password", "tests/factory.py::FactoryTestCase::test_prefix_suffix_always_string", "tests/factory.py::FactoryTestCase::test_random_element", "tests/factory.py::FactoryTestCase::test_random_number", "tests/factory.py::FactoryTestCase::test_random_pyfloat", "tests/factory.py::FactoryTestCase::test_random_pystr_characters", "tests/factory.py::FactoryTestCase::test_random_sample_unique", "tests/factory.py::FactoryTestCase::test_slugify", "tests/factory.py::FactoryTestCase::test_us_ssn_valid", "tests/factory.py::FactoryTestCase::test_words_valueerror" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-06-16 03:28:39+00:00
mit
3,314
joke2k__faker-568
diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py index f4d2626b..3bb3c28b 100644 --- a/faker/providers/date_time/__init__.py +++ b/faker/providers/date_time/__init__.py @@ -26,6 +26,20 @@ def datetime_to_timestamp(dt): return timegm(dt.timetuple()) +def timestamp_to_datetime(timestamp, tzinfo): + if tzinfo is None: + pick = datetime.fromtimestamp(timestamp, tzlocal()) + pick = pick.astimezone(tzutc()).replace(tzinfo=None) + else: + pick = datetime.fromtimestamp(timestamp, tzinfo) + + return pick + + +class ParseError(ValueError): + pass + + timedelta_pattern = r'' for name, sym in [('years', 'y'), ('weeks', 'w'), ('days', 'd'), ('hours', 'h'), ('minutes', 'm'), ('seconds', 's')]: timedelta_pattern += r'((?P<{0}>(?:\+|-)\d+?){1})?'.format(name, sym) @@ -316,6 +330,37 @@ class Provider(BaseProvider): """ return cls.date_time().time() + @classmethod + def _parse_date_string(cls, value): + parts = cls.regex.match(value) + if not parts: + raise ParseError("Can't parse date string `{}`.".format(value)) + parts = parts.groupdict() + time_params = {} + for (name, param) in parts.items(): + if param: + time_params[name] = int(param) + + if 'years' in time_params: + if 'days' not in time_params: + time_params['days'] = 0 + time_params['days'] += 365.24 * time_params.pop('years') + + if not time_params: + raise ParseError("Can't parse date string `{}`.".format(value)) + return time_params + + @classmethod + def _parse_timedelta(cls, value): + if isinstance(value, timedelta): + return value.total_seconds() + if is_string(value): + time_params = cls._parse_date_string(value) + return timedelta(**time_params).total_seconds() + if isinstance(value, (int, float)): + return value + raise ParseError("Invalid format for timedelta '{0}'".format(value)) + @classmethod def _parse_date_time(cls, text, tzinfo=None): if isinstance(text, (datetime, date, real_datetime, real_date)): @@ -326,24 +371,11 @@ class Provider(BaseProvider): if is_string(text): if text == 'now': return datetime_to_timestamp(datetime.now(tzinfo)) - parts = cls.regex.match(text) - if not parts: - return - parts = parts.groupdict() - time_params = {} - for (name, param) in parts.items(): - if param: - time_params[name] = int(param) - - if 'years' in time_params: - if 'days' not in time_params: - time_params['days'] = 0 - time_params['days'] += 365.24 * time_params.pop('years') - + time_params = cls._parse_date_string(text) return datetime_to_timestamp(now + timedelta(**time_params)) if isinstance(text, int): return datetime_to_timestamp(now + timedelta(text)) - raise ValueError("Invalid format for date '{0}'".format(text)) + raise ParseError("Invalid format for date '{0}'".format(text)) @classmethod def date_time_between(cls, start_date='-30y', end_date='now', tzinfo=None): @@ -552,6 +584,35 @@ class Provider(BaseProvider): else: return now + @classmethod + def time_series(cls, start_date='-30d', end_date='now', precision=None, distrib=None, tzinfo=None): + """ + Returns a generator yielding tuples of ``(<datetime>, <value>)``. + + The data points will start at ``start_date``, and be at every time interval specified by + ``precision``. + """ + start_date = cls._parse_date_time(start_date, tzinfo=tzinfo) + end_date = cls._parse_date_time(end_date, tzinfo=tzinfo) + + if end_date < start_date: + raise ValueError("`end_date` must be greater than `start_date`.") + + if precision is None: + precision = (end_date - start_date) / 30 + precision = cls._parse_timedelta(precision) + + if distrib is None: + distrib = lambda: random.uniform(0, precision) # noqa + + if not callable(distrib): + raise ValueError("`distrib` must be a callable. Got {} instead.".format(distrib)) + + datapoint = start_date + while datapoint < end_date: + datapoint += precision + yield (timestamp_to_datetime(datapoint, tzinfo), distrib()) + @classmethod def am_pm(cls): return cls.date('%p')
joke2k/faker
c12a23f112265bf051d720a3758f9919631734ab
diff --git a/tests/providers/date_time.py b/tests/providers/date_time.py index c132384e..a4d405bc 100644 --- a/tests/providers/date_time.py +++ b/tests/providers/date_time.py @@ -231,6 +231,51 @@ class TestDateTime(unittest.TestCase): datetime.now(utc).replace(second=0, microsecond=0) ) + def test_parse_timedelta(self): + from faker.providers.date_time import Provider + + td = timedelta(days=7) + seconds = Provider._parse_timedelta(td) + self.assertEqual(seconds, 604800.0) + + seconds = Provider._parse_timedelta('+1w') + self.assertEqual(seconds, 604800.0) + + seconds = Provider._parse_timedelta('+1y') + self.assertEqual(seconds, 31556736.0) + + with self.assertRaises(ValueError): + Provider._parse_timedelta('foobar') + + def test_time_series(self): + from faker.providers.date_time import Provider + + series = [i for i in Provider.time_series()] + self.assertTrue(len(series), 30) + self.assertTrue(series[1][0] - series[0][0], timedelta(days=1)) + + uniform = lambda: random.uniform(0, 5) # noqa + series = [i for i in Provider.time_series('now', '+1w', '+1d', uniform)] + self.assertTrue(len(series), 7) + self.assertTrue(series[1][0] - series[0][0], timedelta(days=1)) + + end = datetime.now() + timedelta(days=7) + series = [i for i in Provider.time_series('now', end, '+1d', uniform)] + self.assertTrue(len(series), 7) + self.assertTrue(series[1][0] - series[0][0], timedelta(days=1)) + + self.assertTrue(series[-1][0] <= end) + + with self.assertRaises(ValueError): + [i for i in Provider.time_series('+1w', 'now', '+1d', uniform)] + + with self.assertRaises(ValueError): + [i for i in Provider.time_series('now', '+1w', '+1d', 'uniform')] + + series = [i for i in Provider.time_series('now', end, '+1d', uniform, tzinfo=utc)] + self.assertTrue(len(series), 7) + self.assertTrue(series[1][0] - series[0][0], timedelta(days=1)) + class TestPlPL(unittest.TestCase):
is faking time series data in the scope of this project ? I wanted some fake time series data for a project and couldn't find anything suitable for my needs. Is something like [this](http://www.xaprb.com/blog/2014/01/24/methods-generate-realistic-time-series-data/) in the scope of this project ?
0.0
c12a23f112265bf051d720a3758f9919631734ab
[ "tests/providers/date_time.py::TestDateTime::test_parse_timedelta", "tests/providers/date_time.py::TestDateTime::test_time_series" ]
[ "tests/providers/date_time.py::TestDateTime::test_date_object", "tests/providers/date_time.py::TestDateTime::test_date_time_between_dates", "tests/providers/date_time.py::TestDateTime::test_date_time_between_dates_with_tzinfo", "tests/providers/date_time.py::TestDateTime::test_date_time_this_period", "tests/providers/date_time.py::TestDateTime::test_date_time_this_period_with_tzinfo", "tests/providers/date_time.py::TestDateTime::test_datetime_safe", "tests/providers/date_time.py::TestDateTime::test_datetime_safe_new_date", "tests/providers/date_time.py::TestDateTime::test_datetimes_with_and_without_tzinfo", "tests/providers/date_time.py::TestDateTime::test_day", "tests/providers/date_time.py::TestDateTime::test_future_date", "tests/providers/date_time.py::TestDateTime::test_future_datetime", "tests/providers/date_time.py::TestDateTime::test_month", "tests/providers/date_time.py::TestDateTime::test_parse_date_time", "tests/providers/date_time.py::TestDateTime::test_past_date", "tests/providers/date_time.py::TestDateTime::test_past_datetime", "tests/providers/date_time.py::TestDateTime::test_time_object", "tests/providers/date_time.py::TestDateTime::test_timezone_conversion", "tests/providers/date_time.py::TestPlPL::test_day", "tests/providers/date_time.py::TestPlPL::test_month" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2017-08-09 17:34:37+00:00
mit
3,315
joke2k__faker-764
diff --git a/faker/providers/ssn/en_CA/__init__.py b/faker/providers/ssn/en_CA/__init__.py index 0349b889..11f4acc6 100644 --- a/faker/providers/ssn/en_CA/__init__.py +++ b/faker/providers/ssn/en_CA/__init__.py @@ -2,36 +2,81 @@ from __future__ import unicode_literals from .. import Provider as SsnProvider +def checksum(sin): + """ + Determine validity of a Canadian Social Insurance Number. + Validation is performed using a modified Luhn Algorithm. To check + the Every second digit of the SIN is doubled and the result is + summed. If the result is a multiple of ten, the Social Insurance + Number is considered valid. + + https://en.wikipedia.org/wiki/Social_Insurance_Number + """ + + # Remove spaces and create a list of digits. + checksumCollection = list(sin.replace(' ', '')) + checksumCollection = [int(i) for i in checksumCollection] + + # Discard the last digit, we will be calculating it later. + checksumCollection[-1] = 0 + + # Iterate over the provided SIN and double every second digit. + # In the case that doubling that digit results in a two-digit + # number, then add the two digits together and keep that sum. + + for i in range(1, len(checksumCollection), 2): + result = checksumCollection[i] * 2 + if result < 10: + checksumCollection[i] = result + else: + checksumCollection[i] = result - 10 + 1 + + # The appropriate checksum digit is the value that, when summed + # with the first eight values, results in a value divisible by 10 + + check_digit = 10 - (sum(checksumCollection) % 10) + check_digit = (0 if check_digit == 10 else check_digit) + + return check_digit class Provider(SsnProvider): - # in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum - # this function essentially reverses the checksum steps to create a random - # valid SIN (Social Insurance Number) + # In order to create a valid SIN we need to provide a number that + # passes a simple modified Luhn Algorithm checksum. + # + # This function reverses the checksum steps to create a random + # valid nine-digit Canadian SIN (Social Insurance Number) in the + # format '### ### ###'. def ssn(self): - # create an array of 8 elements initialized randomly - digits = self.generator.random.sample(range(10), 8) + # Create an array of 8 elements initialized randomly. + digits = self.generator.random.sample(range(9), 8) + + # The final step of the validation requires that all of the + # digits sum to a multiple of 10. First, sum the first 8 and + # set the 9th to the value that results in a multiple of 10. + check_digit = 10 - (sum(digits) % 10) + check_digit = (0 if check_digit == 10 else check_digit) - # All of the digits must sum to a multiple of 10. - # sum the first 8 and set 9th to the value to get to a multiple of 10 - digits.append(10 - (sum(digits) % 10)) + digits.append(check_digit) - # digits is now the digital root of the number we want multiplied by the magic number 121 212 121 - # reverse the multiplication which occurred on every other element + # digits is now the digital root of the number we want + # multiplied by the magic number 121 212 121. The next step is + # to reverse the multiplication which occurred on every other + # element. for i in range(1, len(digits), 2): if digits[i] % 2 == 0: - digits[i] = (digits[i] / 2) + digits[i] = (digits[i] // 2) else: - digits[i] = (digits[i] + 9) / 2 + digits[i] = (digits[i] + 9) // 2 - # build the resulting SIN string + # Build the resulting SIN string. sin = "" - for i in range(0, len(digits), 1): + for i in range(0, len(digits)): sin += str(digits[i]) - # add a space to make it conform to normal standards in Canada - if i % 3 == 2: + # Add a space to make it conform to Canadian formatting. + if i in (2,5): sin += " " - # finally return our random but valid SIN + # Finally return our random but valid SIN. return sin
joke2k/faker
15a471fdbe357b80fa3baec8d14b646478b80a85
diff --git a/tests/providers/test_ssn.py b/tests/providers/test_ssn.py index abf33e63..439c1a4c 100644 --- a/tests/providers/test_ssn.py +++ b/tests/providers/test_ssn.py @@ -7,13 +7,29 @@ import re from datetime import datetime from faker import Faker +from faker.providers.ssn.en_CA import checksum as ca_checksum from faker.providers.ssn.et_EE import checksum as et_checksum from faker.providers.ssn.fi_FI import Provider as fi_Provider from faker.providers.ssn.hr_HR import checksum as hr_checksum from faker.providers.ssn.pt_BR import checksum as pt_checksum from faker.providers.ssn.pl_PL import checksum as pl_checksum, calculate_month as pl_calculate_mouth -from faker.providers.ssn.no_NO import checksum as no_checksum, Provider +from faker.providers.ssn.no_NO import checksum as no_checksum, Provider as no_Provider +class TestEnCA(unittest.TestCase): + def setUp(self): + self.factory = Faker('en_CA') + self.factory.seed(0) + + def test_ssn(self): + for _ in range(100): + sin = self.factory.ssn() + + # Ensure that generated SINs are 11 characters long + # including spaces, consist of spaces and digits only, and + # satisfy the validation algorithm. + assert len(sin) == 11 + assert sin.replace(' ','').isdigit() + assert ca_checksum(sin) == int(sin[-1]) class TestEtEE(unittest.TestCase): """ Tests SSN in the et_EE locale """ @@ -170,8 +186,8 @@ class TestNoNO(unittest.TestCase): self.factory = Faker('no_NO') def test_no_NO_ssn_checksum(self): - self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7], Provider.scale1), 6) - self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7, 6], Provider.scale2), 7) + self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7], no_Provider.scale1), 6) + self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7, 6], no_Provider.scale2), 7) def test_no_NO_ssn(self): for _ in range(100):
Canadian SSN Provider returns a string nothing like a Canadian SIN under python3 Canadian SSN Provider returns a string nothing like a Canadian SIN under python3. There are also no tests for this provider -- if there were, the change would have been detected. ### Steps to reproduce ``` Python 3.6.5 (default, Apr 25 2018, 14:23:58) [GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from faker import Faker >>> print(Faker('en-Ca').ssn()) 37.09 8.002.0 83.08 ``` ### Expected behavior An expected result follows the pattern `### ### ###`. ### Actual behavior Something else entirely. Here, it's `37.09 8.002.0 83.08`. ### Explanation This is due to the integer division operator change between python2 and python3.
0.0
15a471fdbe357b80fa3baec8d14b646478b80a85
[ "tests/providers/test_ssn.py::TestEnCA::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/test_ssn.py::TestFiFI::test_artifical_ssn", "tests/providers/test_ssn.py::TestFiFI::test_century_code", "tests/providers/test_ssn.py::TestFiFI::test_ssn_sanity", "tests/providers/test_ssn.py::TestFiFI::test_valid_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/test_ssn.py::TestHuHU::test_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn_checksum", "tests/providers/test_ssn.py::TestPlPL::test_calculate_month", "tests/providers/test_ssn.py::TestPlPL::test_ssn", "tests/providers/test_ssn.py::TestPlPL::test_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_gender_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_gender_passed" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-06-08 22:18:05+00:00
mit
3,316
joke2k__faker-767
diff --git a/faker/providers/ssn/en_CA/__init__.py b/faker/providers/ssn/en_CA/__init__.py index 0349b889..11f4acc6 100644 --- a/faker/providers/ssn/en_CA/__init__.py +++ b/faker/providers/ssn/en_CA/__init__.py @@ -2,36 +2,81 @@ from __future__ import unicode_literals from .. import Provider as SsnProvider +def checksum(sin): + """ + Determine validity of a Canadian Social Insurance Number. + Validation is performed using a modified Luhn Algorithm. To check + the Every second digit of the SIN is doubled and the result is + summed. If the result is a multiple of ten, the Social Insurance + Number is considered valid. + + https://en.wikipedia.org/wiki/Social_Insurance_Number + """ + + # Remove spaces and create a list of digits. + checksumCollection = list(sin.replace(' ', '')) + checksumCollection = [int(i) for i in checksumCollection] + + # Discard the last digit, we will be calculating it later. + checksumCollection[-1] = 0 + + # Iterate over the provided SIN and double every second digit. + # In the case that doubling that digit results in a two-digit + # number, then add the two digits together and keep that sum. + + for i in range(1, len(checksumCollection), 2): + result = checksumCollection[i] * 2 + if result < 10: + checksumCollection[i] = result + else: + checksumCollection[i] = result - 10 + 1 + + # The appropriate checksum digit is the value that, when summed + # with the first eight values, results in a value divisible by 10 + + check_digit = 10 - (sum(checksumCollection) % 10) + check_digit = (0 if check_digit == 10 else check_digit) + + return check_digit class Provider(SsnProvider): - # in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum - # this function essentially reverses the checksum steps to create a random - # valid SIN (Social Insurance Number) + # In order to create a valid SIN we need to provide a number that + # passes a simple modified Luhn Algorithm checksum. + # + # This function reverses the checksum steps to create a random + # valid nine-digit Canadian SIN (Social Insurance Number) in the + # format '### ### ###'. def ssn(self): - # create an array of 8 elements initialized randomly - digits = self.generator.random.sample(range(10), 8) + # Create an array of 8 elements initialized randomly. + digits = self.generator.random.sample(range(9), 8) + + # The final step of the validation requires that all of the + # digits sum to a multiple of 10. First, sum the first 8 and + # set the 9th to the value that results in a multiple of 10. + check_digit = 10 - (sum(digits) % 10) + check_digit = (0 if check_digit == 10 else check_digit) - # All of the digits must sum to a multiple of 10. - # sum the first 8 and set 9th to the value to get to a multiple of 10 - digits.append(10 - (sum(digits) % 10)) + digits.append(check_digit) - # digits is now the digital root of the number we want multiplied by the magic number 121 212 121 - # reverse the multiplication which occurred on every other element + # digits is now the digital root of the number we want + # multiplied by the magic number 121 212 121. The next step is + # to reverse the multiplication which occurred on every other + # element. for i in range(1, len(digits), 2): if digits[i] % 2 == 0: - digits[i] = (digits[i] / 2) + digits[i] = (digits[i] // 2) else: - digits[i] = (digits[i] + 9) / 2 + digits[i] = (digits[i] + 9) // 2 - # build the resulting SIN string + # Build the resulting SIN string. sin = "" - for i in range(0, len(digits), 1): + for i in range(0, len(digits)): sin += str(digits[i]) - # add a space to make it conform to normal standards in Canada - if i % 3 == 2: + # Add a space to make it conform to Canadian formatting. + if i in (2,5): sin += " " - # finally return our random but valid SIN + # Finally return our random but valid SIN. return sin diff --git a/faker/providers/ssn/no_NO/__init__.py b/faker/providers/ssn/no_NO/__init__.py index 207831b8..2f171d42 100644 --- a/faker/providers/ssn/no_NO/__init__.py +++ b/faker/providers/ssn/no_NO/__init__.py @@ -71,7 +71,7 @@ class Provider(SsnProvider): gender_num = self.generator.random.choice((0, 2, 4, 6, 8)) elif gender == 'M': gender_num = self.generator.random.choice((1, 3, 5, 7, 9)) - pnr = birthday.strftime('%y%m%d') + suffix.zfill(2) + str(gender_num) + pnr = birthday.strftime('%d%m%y') + suffix.zfill(2) + str(gender_num) pnr_nums = [int(ch) for ch in pnr] k1 = checksum(Provider.scale1, pnr_nums) k2 = checksum(Provider.scale2, pnr_nums + [k1])
joke2k/faker
15a471fdbe357b80fa3baec8d14b646478b80a85
diff --git a/tests/providers/test_ssn.py b/tests/providers/test_ssn.py index abf33e63..ea58fcf8 100644 --- a/tests/providers/test_ssn.py +++ b/tests/providers/test_ssn.py @@ -7,13 +7,29 @@ import re from datetime import datetime from faker import Faker +from faker.providers.ssn.en_CA import checksum as ca_checksum from faker.providers.ssn.et_EE import checksum as et_checksum from faker.providers.ssn.fi_FI import Provider as fi_Provider from faker.providers.ssn.hr_HR import checksum as hr_checksum from faker.providers.ssn.pt_BR import checksum as pt_checksum from faker.providers.ssn.pl_PL import checksum as pl_checksum, calculate_month as pl_calculate_mouth -from faker.providers.ssn.no_NO import checksum as no_checksum, Provider +from faker.providers.ssn.no_NO import checksum as no_checksum, Provider as no_Provider +class TestEnCA(unittest.TestCase): + def setUp(self): + self.factory = Faker('en_CA') + self.factory.seed(0) + + def test_ssn(self): + for _ in range(100): + sin = self.factory.ssn() + + # Ensure that generated SINs are 11 characters long + # including spaces, consist of spaces and digits only, and + # satisfy the validation algorithm. + assert len(sin) == 11 + assert sin.replace(' ','').isdigit() + assert ca_checksum(sin) == int(sin[-1]) class TestEtEE(unittest.TestCase): """ Tests SSN in the et_EE locale """ @@ -170,8 +186,8 @@ class TestNoNO(unittest.TestCase): self.factory = Faker('no_NO') def test_no_NO_ssn_checksum(self): - self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7], Provider.scale1), 6) - self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7, 6], Provider.scale2), 7) + self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7], no_Provider.scale1), 6) + self.assertEqual(no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7, 6], no_Provider.scale2), 7) def test_no_NO_ssn(self): for _ in range(100): @@ -180,9 +196,11 @@ class TestNoNO(unittest.TestCase): self.assertEqual(len(ssn), 11) def test_no_NO_ssn_dob_passed(self): - date_of_birth = '20010203' - ssn = self.factory.ssn(dob=date_of_birth) - self.assertEqual(ssn[:6], date_of_birth[2:]) + test_data = [('20010203', '030201'), + ('19991231', '311299')] + for date_of_birth, expected_dob_part in test_data: + ssn = self.factory.ssn(dob=date_of_birth) + self.assertEqual(ssn[:6], expected_dob_part) def test_no_NO_ssn_invalid_dob_passed(self): with self.assertRaises(ValueError):
Norwegian ssn returns the wrong format for the date part SSN for no_NO returns the wrong format of the date part. ### Steps to reproduce As @cloveras pointed out: Using December 31 1999 as the date of birth (YYYYMMDD): ssn('19991231','M') This results in SSNs like these: 99123145123 99123108724 99123127532 ### Expected behavior The correct format is DDMMYY. ### Actual behavior These start with the date of birth in YYMMDD format.
0.0
15a471fdbe357b80fa3baec8d14b646478b80a85
[ "tests/providers/test_ssn.py::TestEnCA::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/test_ssn.py::TestFiFI::test_artifical_ssn", "tests/providers/test_ssn.py::TestFiFI::test_century_code", "tests/providers/test_ssn.py::TestFiFI::test_ssn_sanity", "tests/providers/test_ssn.py::TestFiFI::test_valid_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/test_ssn.py::TestHuHU::test_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn_checksum", "tests/providers/test_ssn.py::TestPlPL::test_calculate_month", "tests/providers/test_ssn.py::TestPlPL::test_ssn", "tests/providers/test_ssn.py::TestPlPL::test_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_gender_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_gender_passed" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-06-10 10:31:30+00:00
mit
3,317
joke2k__faker-775
diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py index 11c7b8fc..8b10d4c3 100644 --- a/faker/providers/date_time/__init__.py +++ b/faker/providers/date_time/__init__.py @@ -1203,15 +1203,24 @@ class Provider(BaseProvider): return datetime(1970, 1, 1, tzinfo=tzinfo) + \ timedelta(seconds=self.unix_time(end_datetime=end_datetime)) - def date_time_ad(self, tzinfo=None, end_datetime=None): + def date_time_ad(self, tzinfo=None, end_datetime=None, start_datetime=None): """ Get a datetime object for a date between January 1, 001 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1265-03-22 21:15:52') :return datetime """ + + # 1970-01-01 00:00:00 UTC minus 62135596800 seconds is + # 0001-01-01 00:00:00 UTC. Since _parse_end_datetime() is used + # elsewhere where a default value of 0 is expected, we can't + # simply change that class method to use this magic number as a + # default value when None is provided. + + start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime) end_datetime = self._parse_end_datetime(end_datetime) - ts = self.generator.random.randint(-62135596800, end_datetime) + + ts = self.generator.random.randint(start_time, end_datetime) # NOTE: using datetime.fromtimestamp(ts) directly will raise # a "ValueError: timestamp out of range for platform time_t" # on some platforms due to system C functions; @@ -1747,3 +1756,44 @@ class Provider(BaseProvider): def timezone(self): return self.generator.random.choice( self.random_element(self.countries)['timezones']) + + def date_of_birth(self, tzinfo=None, minimum_age=0, maximum_age=115): + """ + Generate a random date of birth represented as a Date object, + constrained by optional miminimum_age and maximum_age + parameters. + + :param tzinfo Defaults to None. + :param minimum_age Defaults to 0. + :param maximum_age Defaults to 115. + + :example Date('1979-02-02') + :return Date + """ + + if not isinstance(minimum_age, int): + raise TypeError("minimum_age must be an integer.") + + if not isinstance(maximum_age, int): + raise TypeError("maximum_age must be an integer.") + + if (maximum_age < 0): + raise ValueError("maximum_age must be greater than or equal to zero.") + + if (minimum_age < 0): + raise ValueError("minimum_age must be greater than or equal to zero.") + + if (minimum_age > maximum_age): + raise ValueError("minimum_age must be less than or equal to maximum_age.") + + # In order to return the full range of possible dates of birth, add one + # year to the potential age cap and subtract one day if we land on the + # boundary. + + now = datetime.now(tzinfo).date() + start_date = now.replace(year=now.year - (maximum_age+1)) + end_date = now.replace(year=now.year - minimum_age) + + dob = self.date_time_ad(tzinfo=tzinfo, start_datetime=start_date, end_datetime=end_date).date() + + return dob if dob != start_date else dob + timedelta(days=1) diff --git a/faker/providers/profile/__init__.py b/faker/providers/profile/__init__.py index bcf5b5e5..a43622fd 100644 --- a/faker/providers/profile/__init__.py +++ b/faker/providers/profile/__init__.py @@ -29,7 +29,7 @@ class Provider(BaseProvider): "mail": self.generator.free_email(), #"password":self.generator.password() - "birthdate": self.generator.date(), + "birthdate": self.generator.date_of_birth(), }
joke2k/faker
6c83a263a589c031ef68244fa81d21c03c620100
diff --git a/tests/providers/test_date_time.py b/tests/providers/test_date_time.py index 6b912b96..3f011a79 100644 --- a/tests/providers/test_date_time.py +++ b/tests/providers/test_date_time.py @@ -471,3 +471,95 @@ class TestAr(unittest.TestCase): factory.month_name(), ArProvider.MONTH_NAMES.values() ) + + +class DatesOfBirth(unittest.TestCase): + from faker.providers.date_time import datetime_to_timestamp + + """ + Test Dates of Birth + """ + + def setUp(self): + self.factory = Faker() + self.factory.seed(0) + + def test_date_of_birth(self): + dob = self.factory.date_of_birth() + assert isinstance(dob, date) + + def test_value_errors(self): + with self.assertRaises(ValueError): + self.factory.date_of_birth(minimum_age=-1) + + with self.assertRaises(ValueError): + self.factory.date_of_birth(maximum_age=-1) + + with self.assertRaises(ValueError): + self.factory.date_of_birth(minimum_age=-2, maximum_age=-1) + + with self.assertRaises(ValueError): + self.factory.date_of_birth(minimum_age=5, maximum_age=4) + + def test_type_errors(self): + with self.assertRaises(TypeError): + self.factory.date_of_birth(minimum_age=0.5) + + with self.assertRaises(TypeError): + self.factory.date_of_birth(maximum_age='hello') + + def test_bad_age_range(self): + with self.assertRaises(ValueError): + self.factory.date_of_birth(minimum_age=5, maximum_age=0) + + def test_acceptable_age_range_five_years(self): + for _ in range(100): + now = datetime.now(utc).date() + + days_since_now = now - now + days_since_six_years_ago = now - now.replace(year=now.year-6) + + dob = self.factory.date_of_birth(tzinfo=utc, minimum_age=0, maximum_age=5) + days_since_dob = now - dob + + assert isinstance(dob, date) + assert days_since_six_years_ago > days_since_dob >= days_since_now + + def test_acceptable_age_range_eighteen_years(self): + for _ in range(100): + now = datetime.now(utc).date() + + days_since_now = now - now + days_since_nineteen_years_ago = now - now.replace(year=now.year-19) + + dob = self.factory.date_of_birth(tzinfo=utc, minimum_age=0, maximum_age=18) + days_since_dob = now - dob + + assert isinstance(dob, date) + assert days_since_nineteen_years_ago > days_since_dob >= days_since_now + + def test_identical_age_range(self): + for _ in range(100): + now = datetime.now(utc).date() + + days_since_five_years_ago = now - now.replace(year=now.year-5) + days_since_six_years_ago = now - now.replace(year=now.year-6) + + dob = self.factory.date_of_birth(minimum_age=5, maximum_age=5) + days_since_dob = now - dob + + assert isinstance(dob, date) + assert days_since_six_years_ago > days_since_dob >= days_since_five_years_ago + + def test_distant_age_range(self): + for _ in range(100): + now = datetime.now(utc).date() + + days_since_one_hundred_years_ago = now - now.replace(year=now.year-100) + days_since_one_hundred_eleven_years_ago = now - now.replace(year=now.year-111) + + dob = self.factory.date_of_birth(minimum_age=100, maximum_age=110) + days_since_dob = now - dob + + assert isinstance(dob, date) + assert days_since_one_hundred_eleven_years_ago > days_since_dob >= days_since_one_hundred_years_ago
Give the user the ability to generate adult vs. minor dates of birth Presently, dates of birth in the Profile provider are chosen randomly between unix epoch timestamp 0 and the present date and time. This isn't particularly useful from a testing perspective, as `0 <= age <= 48 years` isn't the most useful range. ### Expected behavior Users should be able to explicitly generate fake dates of birth for adults or minors.
0.0
6c83a263a589c031ef68244fa81d21c03c620100
[ "tests/providers/test_date_time.py::DatesOfBirth::test_acceptable_age_range_eighteen_years", "tests/providers/test_date_time.py::DatesOfBirth::test_acceptable_age_range_five_years", "tests/providers/test_date_time.py::DatesOfBirth::test_bad_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_date_of_birth", "tests/providers/test_date_time.py::DatesOfBirth::test_distant_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_identical_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_type_errors", "tests/providers/test_date_time.py::DatesOfBirth::test_value_errors" ]
[ "tests/providers/test_date_time.py::TestKoKR::test_day", "tests/providers/test_date_time.py::TestKoKR::test_month", "tests/providers/test_date_time.py::TestDateTime::test_date_between", "tests/providers/test_date_time.py::TestDateTime::test_date_between_dates", "tests/providers/test_date_time.py::TestDateTime::test_date_object", "tests/providers/test_date_time.py::TestDateTime::test_date_this_period", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between_dates", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between_dates_with_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_date_time_this_period", "tests/providers/test_date_time.py::TestDateTime::test_date_time_this_period_with_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_datetime_safe", "tests/providers/test_date_time.py::TestDateTime::test_datetime_safe_new_date", "tests/providers/test_date_time.py::TestDateTime::test_datetimes_with_and_without_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_day", "tests/providers/test_date_time.py::TestDateTime::test_future_date", "tests/providers/test_date_time.py::TestDateTime::test_future_datetime", "tests/providers/test_date_time.py::TestDateTime::test_month", "tests/providers/test_date_time.py::TestDateTime::test_parse_date", "tests/providers/test_date_time.py::TestDateTime::test_parse_date_time", "tests/providers/test_date_time.py::TestDateTime::test_parse_timedelta", "tests/providers/test_date_time.py::TestDateTime::test_past_date", "tests/providers/test_date_time.py::TestDateTime::test_past_datetime", "tests/providers/test_date_time.py::TestDateTime::test_past_datetime_within_second", "tests/providers/test_date_time.py::TestDateTime::test_time_object", "tests/providers/test_date_time.py::TestDateTime::test_time_series", "tests/providers/test_date_time.py::TestDateTime::test_timezone_conversion", "tests/providers/test_date_time.py::TestDateTime::test_unix_time", "tests/providers/test_date_time.py::TestPlPL::test_day", "tests/providers/test_date_time.py::TestPlPL::test_month", "tests/providers/test_date_time.py::TestAr::test_ar_aa", "tests/providers/test_date_time.py::TestAr::test_ar_eg" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-06-19 19:30:11+00:00
mit
3,318
joke2k__faker-808
diff --git a/faker/providers/lorem/__init__.py b/faker/providers/lorem/__init__.py index 48276aa5..55d25543 100644 --- a/faker/providers/lorem/__init__.py +++ b/faker/providers/lorem/__init__.py @@ -26,7 +26,7 @@ class Provider(BaseProvider): word_connector = ' ' sentence_punctuation = '.' - def words(self, nb=3, ext_word_list=None): + def words(self, nb=3, ext_word_list=None, unique=False): """ :returns: An array of random words. for example: ['Lorem', 'ipsum', 'dolor'] @@ -34,10 +34,13 @@ class Provider(BaseProvider): :param nb: how many words to return :param ext_word_list: a list of words you would like to have instead of 'Lorem ipsum' + :param unique: If True, the returned word list will contain unique words :rtype: list """ word_list = ext_word_list if ext_word_list else self.word_list + if unique: + return self.random_sample(word_list, length=nb) return self.random_choices(word_list, length=nb) def word(self, ext_word_list=None):
joke2k/faker
fc546bca9b4f411e8565aeb5ddd9ccee8de59494
diff --git a/tests/test_factory.py b/tests/test_factory.py index 39ed0084..7b28a767 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -330,6 +330,91 @@ class FactoryTestCase(unittest.TestCase): word = fake.word(ext_word_list=my_word_list) self.assertIn(word, my_word_list) + def test_no_words(self): + fake = Faker() + + words = fake.words(0) + self.assertEqual(words, []) + + def test_some_words(self): + fake = Faker() + + num_words = 5 + words = fake.words(num_words) + self.assertTrue(isinstance(words, list)) + self.assertEqual(len(words), num_words) + + for word in words: + self.assertTrue(isinstance(word, string_types)) + self.assertTrue(re.match(r'^[a-z].*$', word)) + + def test_words_ext_word_list(self): + fake = Faker() + + my_word_list = [ + 'danish', + 'cheesecake', + 'sugar', + 'Lollipop', + 'wafer', + 'Gummies', + 'Jelly', + 'pie', + ] + + num_words = 5 + words = fake.words(5, ext_word_list=my_word_list) + self.assertTrue(isinstance(words, list)) + self.assertEqual(len(words), num_words) + + for word in words: + self.assertTrue(isinstance(word, string_types)) + self.assertIn(word, my_word_list) + + def test_words_ext_word_list_unique(self): + fake = Faker() + + my_word_list = [ + 'danish', + 'cheesecake', + 'sugar', + 'Lollipop', + 'wafer', + 'Gummies', + 'Jelly', + 'pie', + ] + + num_words = 5 + words = fake.words(5, ext_word_list=my_word_list) + self.assertTrue(isinstance(words, list)) + self.assertEqual(len(words), num_words) + + checked_words = [] + for word in words: + self.assertTrue(isinstance(word, string_types)) + self.assertIn(word, my_word_list) + # Check that word is unique + self.assertTrue(word not in checked_words) + checked_words.append(word) + + def test_unique_words(self): + fake = Faker() + + num_words = 20 + words = fake.words(num_words, unique=True) + self.assertTrue(isinstance(words, list)) + self.assertEqual(len(words), num_words) + + checked_words = [] + for word in words: + self.assertTrue(isinstance(word, string_types)) + # Check that word is lowercase letters. No numbers, symbols, etc + self.assertTrue(re.match(r'^[a-z].*$', word)) + # Check that word list is unique + self.assertTrue(word not in checked_words) + checked_words.append(word) + def test_random_pystr_characters(self): from faker.providers.python import Provider provider = Provider(self.generator)
Ensure words() returns a unique list of words without duplicates When calling `words(10)` there is no guarantee that the returned list of elements is unique. While I could do `set(words(10))`, this may only return 9 items when I am in need of 10. If creating a list of words with potential duplicates is a useful feature to some, maybe adding an optional parameter called `unique` to the `words` generator could prove useful.
0.0
fc546bca9b4f411e8565aeb5ddd9ccee8de59494
[ "tests/test_factory.py::FactoryTestCase::test_unique_words", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list_unique" ]
[ "tests/test_factory.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "tests/test_factory.py::FactoryTestCase::test_binary", "tests/test_factory.py::FactoryTestCase::test_cli_seed", "tests/test_factory.py::FactoryTestCase::test_cli_seed_with_repeat", "tests/test_factory.py::FactoryTestCase::test_cli_verbosity", "tests/test_factory.py::FactoryTestCase::test_command", "tests/test_factory.py::FactoryTestCase::test_command_custom_provider", "tests/test_factory.py::FactoryTestCase::test_documentor", "tests/test_factory.py::FactoryTestCase::test_email", "tests/test_factory.py::FactoryTestCase::test_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_format_calls_formatter_on_provider", "tests/test_factory.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_callable", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "tests/test_factory.py::FactoryTestCase::test_instance_seed_chain", "tests/test_factory.py::FactoryTestCase::test_invalid_locale", "tests/test_factory.py::FactoryTestCase::test_ipv4", "tests/test_factory.py::FactoryTestCase::test_ipv4_network_class", "tests/test_factory.py::FactoryTestCase::test_ipv4_private", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv4_public", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv6", "tests/test_factory.py::FactoryTestCase::test_language_code", "tests/test_factory.py::FactoryTestCase::test_locale", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "tests/test_factory.py::FactoryTestCase::test_nl_BE_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_no_words", "tests/test_factory.py::FactoryTestCase::test_no_words_paragraph", "tests/test_factory.py::FactoryTestCase::test_no_words_sentence", "tests/test_factory.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "tests/test_factory.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "tests/test_factory.py::FactoryTestCase::test_password", "tests/test_factory.py::FactoryTestCase::test_prefix_suffix_always_string", "tests/test_factory.py::FactoryTestCase::test_random_element", "tests/test_factory.py::FactoryTestCase::test_random_number", "tests/test_factory.py::FactoryTestCase::test_random_pyfloat", "tests/test_factory.py::FactoryTestCase::test_random_pystr_characters", "tests/test_factory.py::FactoryTestCase::test_random_sample_unique", "tests/test_factory.py::FactoryTestCase::test_slugify", "tests/test_factory.py::FactoryTestCase::test_some_words", "tests/test_factory.py::FactoryTestCase::test_us_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_words_valueerror" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-09-08 12:56:41+00:00
mit
3,319
joke2k__faker-828
diff --git a/faker/providers/person/cs_CZ/__init__.py b/faker/providers/person/cs_CZ/__init__.py index 75376307..d256b82e 100644 --- a/faker/providers/person/cs_CZ/__init__.py +++ b/faker/providers/person/cs_CZ/__init__.py @@ -1,26 +1,26 @@ # coding=utf-8 from __future__ import unicode_literals +from collections import OrderedDict from .. import Provider as PersonProvider class Provider(PersonProvider): - formats = ( - '{{first_name_male}} {{last_name_male}}', - '{{first_name_male}} {{last_name_male}}', - '{{first_name_male}} {{last_name_male}}', - '{{first_name_male}} {{last_name_male}}', - '{{first_name_male}} {{last_name_male}}', - '{{first_name_female}} {{last_name_female}}', - '{{first_name_female}} {{last_name_female}}', - '{{first_name_female}} {{last_name_female}}', - '{{first_name_female}} {{last_name_female}}', - '{{first_name_female}} {{last_name_female}}', - '{{prefix_male}} {{first_name_male}} {{last_name_male}}', - '{{prefix_female}} {{first_name_female}} {{last_name_female}}', - '{{first_name_male}} {{last_name_male}} {{suffix}}', - '{{first_name_female}} {{last_name_female}} {{suffix}}', - '{{prefix_male}} {{first_name_male}} {{last_name_male}} {{suffix}}', - '{{prefix_female}} {{first_name_female}} {{last_name_female}} {{suffix}}') + formats_female = OrderedDict(( + ('{{first_name_female}} {{last_name_female}}', 0.97), + ('{{prefix_female}} {{first_name_female}} {{last_name_female}}', 0.015), + ('{{first_name_female}} {{last_name_female}} {{suffix}}', 0.02), + ('{{prefix_female}} {{first_name_female}} {{last_name_female}} {{suffix}}', 0.005) + )) + + formats_male = OrderedDict(( + ('{{first_name_male}} {{last_name_male}}', 0.97), + ('{{prefix_male}} {{first_name_male}} {{last_name_male}}', 0.015), + ('{{first_name_male}} {{last_name_male}} {{suffix}}', 0.02), + ('{{prefix_male}} {{first_name_male}} {{last_name_male}} {{suffix}}', 0.005) + )) + + formats = formats_male.copy() + formats.update(formats_female) first_names_male = ( 'Adam',
joke2k/faker
b350f46f0313ee41a91b9b416e5b3d6f16f721cd
diff --git a/tests/providers/test_person.py b/tests/providers/test_person.py index 94bf8fe1..6fc024cd 100644 --- a/tests/providers/test_person.py +++ b/tests/providers/test_person.py @@ -12,6 +12,7 @@ from faker.providers.person.ar_AA import Provider as ArProvider from faker.providers.person.fi_FI import Provider as FiProvider from faker.providers.person.ne_NP import Provider as NeProvider from faker.providers.person.sv_SE import Provider as SvSEProvider +from faker.providers.person.cs_CZ import Provider as CsCZProvider from faker.providers.person.pl_PL import ( checksum_identity_card_number as pl_checksum_identity_card_number, ) @@ -201,3 +202,49 @@ class TestPlPL(unittest.TestCase): def test_identity_card_number(self): for _ in range(100): self.assertTrue(re.search(r'^[A-Z]{3}\d{6}$', self.factory.identity_card_number())) + + +class TestCsCZ(unittest.TestCase): + + def setUp(self): + self.factory = Faker('cs_CZ') + + def test_name_male(self): + male_name = self.factory.name_male() + name_parts = male_name.split(" ") + first_name, last_name = "", "" + if len(name_parts) == 2: + first_name = name_parts[0] + last_name = name_parts[1] + elif len(name_parts) == 4: + first_name = name_parts[1] + last_name = name_parts[2] + elif len(name_parts) == 3: + if name_parts[-1] in CsCZProvider.suffixes: + first_name = name_parts[0] + last_name = name_parts[1] + else: + first_name = name_parts[1] + last_name = name_parts[2] + self.assertIn(first_name, CsCZProvider.first_names_male) + self.assertIn(last_name, CsCZProvider.last_names_male) + + def test_name_female(self): + female_name = self.factory.name_female() + name_parts = female_name.split(" ") + first_name, last_name = "", "" + if len(name_parts) == 2: + first_name = name_parts[0] + last_name = name_parts[1] + elif len(name_parts) == 4: + first_name = name_parts[1] + last_name = name_parts[2] + elif len(name_parts) == 3: + if name_parts[-1] in CsCZProvider.suffixes: + first_name = name_parts[0] + last_name = name_parts[1] + else: + first_name = name_parts[1] + last_name = name_parts[2] + self.assertIn(first_name, CsCZProvider.first_names_female) + self.assertIn(last_name, CsCZProvider.last_names_female)
Locales for cs_CZ fake.name_male() shows a female name Looking at the very last example [here](https://faker.readthedocs.io/en/latest/locales/cs_CZ.html#faker-providers-misc). The name is actually a female name. ``` fake.name_male() # 'Ing. Sára Mašková CSc.' ```
0.0
b350f46f0313ee41a91b9b416e5b3d6f16f721cd
[ "tests/providers/test_person.py::TestCsCZ::test_name_female" ]
[ "tests/providers/test_person.py::TestAr::test_first_name", "tests/providers/test_person.py::TestAr::test_last_name", "tests/providers/test_person.py::TestJaJP::test_person", "tests/providers/test_person.py::TestNeNP::test_names", "tests/providers/test_person.py::TestFiFI::test_gender_first_names", "tests/providers/test_person.py::TestFiFI::test_last_names", "tests/providers/test_person.py::TestSvSE::test_gender_first_names", "tests/providers/test_person.py::TestPlPL::test_identity_card_number", "tests/providers/test_person.py::TestPlPL::test_identity_card_number_checksum", "tests/providers/test_person.py::TestCsCZ::test_name_male" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-10-03 04:58:01+00:00
mit
3,320
joke2k__faker-836
diff --git a/faker/providers/internet/__init__.py b/faker/providers/internet/__init__.py index 30c1fed4..e256c8a5 100644 --- a/faker/providers/internet/__init__.py +++ b/faker/providers/internet/__init__.py @@ -111,7 +111,7 @@ class Provider(BaseProvider): '{{url}}{{uri_path}}/{{uri_page}}{{uri_extension}}', ) image_placeholder_services = ( - 'https://placeholdit.imgix.net/~text', + 'https://placeholdit.imgix.net/~text' '?txtsize=55&txt={width}x{height}&w={width}&h={height}', 'https://www.lorempixel.com/{width}/{height}', 'https://dummyimage.com/{width}x{height}', diff --git a/faker/providers/job/th_TH/__init__.py b/faker/providers/job/th_TH/__init__.py new file mode 100644 index 00000000..35ea47c6 --- /dev/null +++ b/faker/providers/job/th_TH/__init__.py @@ -0,0 +1,89 @@ +# coding=utf-8 +from __future__ import unicode_literals +from .. import Provider as BaseProvider + + +# Reference: +# https://th.wikipedia.org/wiki/หมวดหมู่:บุคคลแบ่งตามอาชีพ +# on 2018-10-16 +class Provider(BaseProvider): + jobs = [ + 'นักกฎหมาย', + 'กวี', + 'นักการทูต', + 'นักการเมือง', + 'นักการศึกษา', + 'นักกีฬา', + 'นักการกุศล', + 'เกษตรกร', + 'นักเขียน', + 'ข้าราชการ', + 'นักคณิตศาสตร์', + 'คนขับรถแท็กซี่', + 'โฆษก', + 'จ๊อกกี้', + 'นักจัดรายการวิทยุ', + 'จารชน', + 'จิตรกร', + 'นักจิตวิทยา', + 'เจ้าหน้าทีรักษาความปลอดภัย', + 'เจ้าหน้าที่รัฐบาล', + 'ช่างทำเครื่องดนตรี', + 'ช่างทำผม', + 'นักชีววิทยา', + 'นักดนตรี', + 'นักดาราศาสตร์', + 'นักแต่งเพลง', + 'ตำรวจ', + 'นักถ่ายภาพ', + 'ทนายความ', + 'ทหารบก', + 'นักธุรกิจ', + 'นักเคลื่อนไหว', + 'นักบวช', + 'นักบิน', + 'นักบินอวกาศ', + 'นักประชาสัมพันธ์', + 'นักผจญภัย', + 'นักสะสมศิลปะ', + 'นักแสดง', + 'นักหนังสือพิมพ์', + 'นางงาม', + 'นางแบบ', + 'นายแบบ', + 'บรรณาธิการ', + 'นักโบราณคดี', + 'นักแปล', + 'นักประดิษฐ์', + 'นักประวัติศาสตร์', + 'นักปรัชญา', + 'ผู้กำกับ', + 'ผู้กำกับภาพยนตร์', + 'ผู้กำกับละครโทรทัศน์', + 'ผู้จัดพิมพ์', + 'นักพจนานุกรม', + 'แพทย์', + 'นักพากย์', + 'พิธีกร', + 'นักโภชนาการ', + 'นักภาษาศาสตร์', + 'เภสัชกร', + 'มัคคุเทศก์', + 'นักมายากล', + 'นักวาดการ์ตูน', + 'นักวิทยาศาสตร์', + 'วิศวกร', + 'วีเจ', + 'นักเศรษฐศาสตร์', + 'ศิลปิน', + 'สถาปนิก', + 'นักสังคมวิทยา', + 'นักสังคมศาสตร์', + 'นักสัตววิทยา', + 'นักสำรวจ', + 'นักสืบ', + 'นักอนุรักษ์ธรรมชาติ', + 'นักออกแบบ', + 'อัยการ', + 'โปรแกรมเมอร์', + ] diff --git a/faker/providers/phone_number/pt_BR/__init__.py b/faker/providers/phone_number/pt_BR/__init__.py index 95707ba6..ca3efbd3 100644 --- a/faker/providers/phone_number/pt_BR/__init__.py +++ b/faker/providers/phone_number/pt_BR/__init__.py @@ -71,6 +71,7 @@ class Provider(PhoneNumberProvider): '#### ####', '####-####', ) + msisdn_formats = ( '5511#########', '5521#########', @@ -81,3 +82,11 @@ class Provider(PhoneNumberProvider): '5571#########', '5581#########', ) + + cellphone_formats = ( + '+55 9#### ####', + ) + + def cellphone_number(self): + pattern = self.random_element(self.cellphone_formats) + return self.numerify(self.generator.parse(pattern))
joke2k/faker
ba4994a9c1f84bab3aa3b21c7cc2a1e0e76d3f1c
diff --git a/tests/providers/test_phone_number.py b/tests/providers/test_phone_number.py index 156082cb..572e80d7 100644 --- a/tests/providers/test_phone_number.py +++ b/tests/providers/test_phone_number.py @@ -64,6 +64,12 @@ class TestPhoneNumber(unittest.TestCase): assert msisdn.isdigit() assert msisdn[0:4] in formats + def test_cellphone_pt_br(self): + factory = Faker('pt_BR') + cellphone = factory.cellphone_number() + assert cellphone is not None + assert len(cellphone) == 14 + class TestHuHU(unittest.TestCase):
Add method to generate a cell phone number to pt-BR Faker doesn't have a function to generate a cellphone to Brazilian. Steps to reproduce Create fake instance using localization "pt_BR" Call fake.msisdn() or fake.phone_number() Expected behavior It should generate a cell phone number. Actual behavior Sometimes these methods return a "residential" numbers. Reference difference between cell phones and residential numbers: http://www.teleco.com.br/num.asp
0.0
ba4994a9c1f84bab3aa3b21c7cc2a1e0e76d3f1c
[ "tests/providers/test_phone_number.py::TestPhoneNumber::test_cellphone_pt_br" ]
[ "tests/providers/test_phone_number.py::TestPhoneNumber::test_msisdn", "tests/providers/test_phone_number.py::TestPhoneNumber::test_msisdn_pt_br", "tests/providers/test_phone_number.py::TestPhoneNumber::test_phone_number", "tests/providers/test_phone_number.py::TestPhoneNumber::test_phone_number_ja", "tests/providers/test_phone_number.py::TestHuHU::test_phone_number" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-10-15 13:46:22+00:00
mit
3,321
joke2k__faker-907
diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py index f2048fa2..ed27c9f4 100644 --- a/faker/providers/date_time/__init__.py +++ b/faker/providers/date_time/__init__.py @@ -1379,8 +1379,11 @@ class Provider(BaseProvider): """ Get a timedelta object """ + start_datetime = self._parse_start_datetime('now') end_datetime = self._parse_end_datetime(end_datetime) - ts = self.generator.random.randint(0, end_datetime) + seconds = end_datetime - start_datetime + + ts = self.generator.random.randint(*sorted([0, seconds])) return timedelta(seconds=ts) def date_time(self, tzinfo=None, end_datetime=None): @@ -1507,20 +1510,20 @@ class Provider(BaseProvider): raise ParseError("Invalid format for timedelta '{0}'".format(value)) @classmethod - def _parse_date_time(cls, text, tzinfo=None): - if isinstance(text, (datetime, date, real_datetime, real_date)): - return datetime_to_timestamp(text) + def _parse_date_time(cls, value, tzinfo=None): + if isinstance(value, (datetime, date, real_datetime, real_date)): + return datetime_to_timestamp(value) now = datetime.now(tzinfo) - if isinstance(text, timedelta): - return datetime_to_timestamp(now - text) - if is_string(text): - if text == 'now': + if isinstance(value, timedelta): + return datetime_to_timestamp(now + value) + if is_string(value): + if value == 'now': return datetime_to_timestamp(datetime.now(tzinfo)) - time_params = cls._parse_date_string(text) + time_params = cls._parse_date_string(value) return datetime_to_timestamp(now + timedelta(**time_params)) - if isinstance(text, int): - return datetime_to_timestamp(now + timedelta(text)) - raise ParseError("Invalid format for date '{0}'".format(text)) + if isinstance(value, int): + return datetime_to_timestamp(now + timedelta(value)) + raise ParseError("Invalid format for date '{0}'".format(value)) @classmethod def _parse_date(cls, value): @@ -1530,7 +1533,7 @@ class Provider(BaseProvider): return value today = date.today() if isinstance(value, timedelta): - return today - value + return today + value if is_string(value): if value in ('today', 'now'): return today
joke2k/faker
4c9138f53b4a616f846900e87fa83fe0d309c613
diff --git a/tests/providers/test_date_time.py b/tests/providers/test_date_time.py index 479abba5..6f80ed54 100644 --- a/tests/providers/test_date_time.py +++ b/tests/providers/test_date_time.py @@ -91,7 +91,7 @@ class TestDateTime(unittest.TestCase): timestamp = DatetimeProvider._parse_date_time('+30d') now = DatetimeProvider._parse_date_time('now') assert timestamp > now - delta = timedelta(days=-30) + delta = timedelta(days=30) from_delta = DatetimeProvider._parse_date_time(delta) from_int = DatetimeProvider._parse_date_time(30) @@ -114,7 +114,7 @@ class TestDateTime(unittest.TestCase): assert DatetimeProvider._parse_date(datetime.now()) == today assert DatetimeProvider._parse_date(parsed) == parsed assert DatetimeProvider._parse_date(30) == parsed - assert DatetimeProvider._parse_date(timedelta(days=-30)) == parsed + assert DatetimeProvider._parse_date(timedelta(days=30)) == parsed def test_timezone_conversion(self): from faker.providers.date_time import datetime_to_timestamp @@ -168,6 +168,22 @@ class TestDateTime(unittest.TestCase): def test_time_object(self): assert isinstance(self.factory.time_object(), datetime_time) + def test_timedelta(self): + delta = self.factory.time_delta(end_datetime=timedelta(seconds=60)) + assert delta.seconds <= 60 + + delta = self.factory.time_delta(end_datetime=timedelta(seconds=-60)) + assert delta.seconds >= -60 + + delta = self.factory.time_delta(end_datetime='+60s') + assert delta.seconds <= 60 + + delta = self.factory.time_delta(end_datetime='-60s') + assert delta.seconds >= 60 + + delta = self.factory.time_delta(end_datetime='now') + assert delta.seconds <= 0 + def test_date_time_between_dates(self): timestamp_start = random.randint(0, 2000000000) timestamp_end = timestamp_start + 1
Can't produce a time_delta with a maximum value When using time_delta from the date_time provider it doesn't seem possible to provide a maximum value. The provider takes an `end_datetime` parameter but what it does with that is beyond me, certainly not what I'd expect. ### Steps to reproduce ``` >>> from faker import Faker >>> from datetime import timedelta >>> Faker().time_delta(end_datetime=timedelta(minutes=60)) datetime.timedelta(days=5892, seconds=74879) ``` ### Expected behavior I'd expect to receive a `datetime.timedelta` with a value no greater than 60 minutes. ### Actual behavior I receive a `datetime.timedelta` with seemingly unbounded value.
0.0
4c9138f53b4a616f846900e87fa83fe0d309c613
[ "tests/providers/test_date_time.py::TestDateTime::test_parse_date", "tests/providers/test_date_time.py::TestDateTime::test_parse_date_time", "tests/providers/test_date_time.py::TestDateTime::test_timedelta" ]
[ "tests/providers/test_date_time.py::TestKoKR::test_day", "tests/providers/test_date_time.py::TestKoKR::test_month", "tests/providers/test_date_time.py::TestDateTime::test_date_between", "tests/providers/test_date_time.py::TestDateTime::test_date_between_dates", "tests/providers/test_date_time.py::TestDateTime::test_date_object", "tests/providers/test_date_time.py::TestDateTime::test_date_this_period", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between_dates", "tests/providers/test_date_time.py::TestDateTime::test_date_time_between_dates_with_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_date_time_this_period", "tests/providers/test_date_time.py::TestDateTime::test_date_time_this_period_with_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_datetime_safe", "tests/providers/test_date_time.py::TestDateTime::test_datetime_safe_new_date", "tests/providers/test_date_time.py::TestDateTime::test_datetimes_with_and_without_tzinfo", "tests/providers/test_date_time.py::TestDateTime::test_day", "tests/providers/test_date_time.py::TestDateTime::test_future_date", "tests/providers/test_date_time.py::TestDateTime::test_future_datetime", "tests/providers/test_date_time.py::TestDateTime::test_month", "tests/providers/test_date_time.py::TestDateTime::test_parse_timedelta", "tests/providers/test_date_time.py::TestDateTime::test_past_date", "tests/providers/test_date_time.py::TestDateTime::test_past_datetime", "tests/providers/test_date_time.py::TestDateTime::test_past_datetime_within_second", "tests/providers/test_date_time.py::TestDateTime::test_time_object", "tests/providers/test_date_time.py::TestDateTime::test_time_series", "tests/providers/test_date_time.py::TestDateTime::test_timezone_conversion", "tests/providers/test_date_time.py::TestDateTime::test_unix_time", "tests/providers/test_date_time.py::TestPlPL::test_day", "tests/providers/test_date_time.py::TestPlPL::test_month", "tests/providers/test_date_time.py::TestAr::test_ar_aa", "tests/providers/test_date_time.py::TestAr::test_ar_eg", "tests/providers/test_date_time.py::DatesOfBirth::test_acceptable_age_range_eighteen_years", "tests/providers/test_date_time.py::DatesOfBirth::test_acceptable_age_range_five_years", "tests/providers/test_date_time.py::DatesOfBirth::test_bad_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_date_of_birth", "tests/providers/test_date_time.py::DatesOfBirth::test_distant_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_identical_age_range", "tests/providers/test_date_time.py::DatesOfBirth::test_type_errors", "tests/providers/test_date_time.py::DatesOfBirth::test_value_errors" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-02-06 16:35:38+00:00
mit
3,322
joke2k__faker-924
diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index c59c2960..6b2b2d6d 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -32,7 +32,9 @@ class Provider(BaseProvider): ), ) - def pyfloat(self, left_digits=None, right_digits=None, positive=False): + def pyfloat(self, left_digits=None, right_digits=None, positive=False, + min_value=None, max_value=None): + if left_digits is not None and left_digits < 0: raise ValueError( 'A float number cannot have less than 0 digits in its ' @@ -44,6 +46,8 @@ class Provider(BaseProvider): if left_digits == 0 and right_digits == 0: raise ValueError( 'A float number cannot have less than 0 digits in total') + if None not in (min_value, max_value) and min_value > max_value: + raise ValueError('Min value cannot be greater than max value') left_digits = left_digits if left_digits is not None else ( self.random_int(1, sys.float_info.dig)) @@ -51,16 +55,30 @@ class Provider(BaseProvider): self.random_int(0, sys.float_info.dig - left_digits)) sign = 1 if positive else self.random_element((-1, 1)) + if (min_value is not None) or (max_value is not None): + if min_value is None: + min_value = max_value - self.random_int() + if max_value is None: + max_value = min_value + self.random_int() + + left_number = self.random_int(min_value, max_value) + else: + left_number = sign * self.random_number(left_digits) + return float("{0}.{1}".format( - sign * self.random_number(left_digits), + left_number, self.random_number(right_digits), )) def pyint(self): return self.generator.random_int() - def pydecimal(self, left_digits=None, right_digits=None, positive=False): - return Decimal(str(self.pyfloat(left_digits, right_digits, positive))) + def pydecimal(self, left_digits=None, right_digits=None, positive=False, + min_value=None, max_value=None): + + float_ = self.pyfloat( + left_digits, right_digits, positive, min_value, max_value) + return Decimal(str(float_)) def pytuple(self, nb_elements=10, variable_nb_elements=True, *value_types): return tuple(
joke2k/faker
8fa3239b78cbdaac37ec478501571daa9dc55c29
diff --git a/tests/providers/test_python.py b/tests/providers/test_python.py new file mode 100644 index 00000000..bca66d33 --- /dev/null +++ b/tests/providers/test_python.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- + +import unittest + +from faker import Faker + + +class TestPyfloat(unittest.TestCase): + def setUp(self): + self.factory = Faker() + + def test_pyfloat(self): + result = self.factory.pyfloat() + + self.assertIsInstance(result, float) + + def test_left_digits(self): + expected_left_digits = 10 + + result = self.factory.pyfloat(left_digits=expected_left_digits) + + left_digits = len(str(abs(int(result)))) + self.assertGreaterEqual(expected_left_digits, left_digits) + + def test_right_digits(self): + expected_right_digits = 10 + + result = self.factory.pyfloat(right_digits=expected_right_digits) + + right_digits = len(str(result).split('.')[1]) + self.assertGreaterEqual(expected_right_digits, right_digits) + + def test_positive(self): + result = self.factory.pyfloat(positive=True) + + self.assertGreaterEqual(result, 0) + self.assertEqual(result, abs(result)) + + def test_min_value(self): + min_values = (0, 10, -1000, 1000, 999999) + + for min_value in min_values: + result = self.factory.pyfloat(min_value=min_value) + self.assertGreaterEqual(result, min_value) + + def test_max_value(self): + max_values = (0, 10, -1000, 1000, 999999) + + for max_value in max_values: + result = self.factory.pyfloat(max_value=max_value) + self.assertLessEqual(result, max_value) + + def test_max_value_should_be_greater_than_min_value(self): + """ + An exception should be raised if min_value is greater than max_value + """ + expected_message = 'Min value cannot be greater than max value' + with self.assertRaises(ValueError) as raises: + self.factory.pyfloat(min_value=100, max_value=0) + + message = str(raises.exception) + self.assertEqual(message, expected_message)
Enables min and max values for pydecimal Currently is not possible to set min or max values to `pydecimal` or `pyfloat`. It would be nice if we could pass these parameters. If it makes senses I can open a PR.
0.0
8fa3239b78cbdaac37ec478501571daa9dc55c29
[ "tests/providers/test_python.py::TestPyfloat::test_max_value", "tests/providers/test_python.py::TestPyfloat::test_max_value_should_be_greater_than_min_value", "tests/providers/test_python.py::TestPyfloat::test_min_value" ]
[ "tests/providers/test_python.py::TestPyfloat::test_left_digits", "tests/providers/test_python.py::TestPyfloat::test_positive", "tests/providers/test_python.py::TestPyfloat::test_pyfloat", "tests/providers/test_python.py::TestPyfloat::test_right_digits" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-03-13 01:56:45+00:00
mit
3,323
joke2k__faker-930
diff --git a/faker/providers/company/nl_NL/__init__.py b/faker/providers/company/nl_NL/__init__.py new file mode 100644 index 00000000..67993034 --- /dev/null +++ b/faker/providers/company/nl_NL/__init__.py @@ -0,0 +1,109 @@ +# coding=utf-8 + +from __future__ import unicode_literals +from .. import Provider as CompanyProvider + + +class Provider(CompanyProvider): + + formats = ( + '{{last_name}} {{company_suffix}}', + '{{last_name}} & {{last_name}}', + '{{company_prefix}} {{last_name}}', + '{{large_company}}', + ) + + company_prefixes = ( + 'Stichting', 'Koninklijke', 'Royal', + ) + + company_suffixes = ( + 'BV', 'NV', 'Groep', + ) + + # Source: https://www.mt.nl/management/reputatie/mt-500-2018-de-lijst/559930 + large_companies = ( + 'Shell', 'Coolblue', 'ASML', 'Ahold', 'Tata Steel', 'KLM', 'Bol.com', 'BP Nederland', 'De Efteling', 'Eneco', + 'De Persgroep', 'ING', 'Royal HaskoningDHV', 'Randstad', 'Google', 'Ikea', 'Rockwool', 'BAM', 'Achmea', + 'Damen Shipyard', 'ABN Amro', 'Remeha Group', 'TenneT', 'Coca-Cola', 'Van Leeuwen Buizen', 'Wavin', 'Rabobank', + 'AkzoNobel', 'Arcadis', 'AFAS', 'Cisco', 'DAF Trucks', 'DHL', 'Hanos', 'Boon Edam', 'BMW Nederland', + 'The Greenery', 'Dutch Flower Group', 'Koninklijke Mosa', 'Yacht', 'Rituals', 'Microsoft', 'Esso', + '3W Vastgoed', 'Deloitte', 'Corio', 'Voortman Steel Group', 'Agrifirm', 'Makro Nederland', + 'Nederlandse Publieke Omroep', 'De Alliantie', 'Heijmans', 'McDonalds', 'ANWB', 'Mediamarkt', 'Kruidvat' + 'Van Merksteijn Steel', 'Dura Vermeer', 'Alliander', 'Unilever', 'Enexis', 'Berenschot', 'Jumbo', + 'Technische Unie', 'Havenbedrijf Rotterdam', 'Ballast Nedam', 'RTL Nederland', 'Talpa Media', + 'Blauwhoed Vastgoed', 'DSM', 'Ymere', 'Witteveen+Bos', 'NS', 'Action', 'FloraHolland', 'Heineken', 'Nuon', 'EY', + 'Dow Benelux', 'Bavaria', 'Schiphol', 'Holland Casino', 'Binck bank', 'BDO', 'HEMA', 'Alphabet Nederland', + 'Croon Elektrotechniek', 'ASR Vastgoed ontwikkeling', 'PwC', 'Mammoet', 'KEMA', 'IBM', 'A.S. Watson', + 'KPMG', 'VodafoneZiggo', 'YoungCapital', 'Triodos Bank', 'Aviko', 'AgruniekRijnvallei', 'Heerema', 'Accenture', + 'Aegon', 'NXP', 'Breman Installatiegroep', 'Movares Groep', 'Q-Park', 'FleuraMetz', 'Sanoma', + 'Bakker Logistiek', 'VDL Group', 'Bayer', 'Boskalis', 'Nutreco', 'Dell', 'Brunel', 'Exact', 'Manpower', + 'Essent', 'Canon', 'ONVZ Zorgverzekeraar', 'Telegraaf Media Group', 'Nationale Nederlanden', 'Andus Group', + 'Den Braven Group', 'ADP', 'ASR', 'ArboNed', 'Plieger', 'De Heus Diervoeders', 'USG People', 'Bidvest Deli XL', + 'Apollo Vredestein', 'Tempo-Team', 'Trespa', 'Janssen Biologics', 'Starbucks', 'PostNL', 'Vanderlande', + 'FrieslandCampina', 'Constellium', 'Huisman', 'Abbott', 'Koninklijke Boom Uitgevers', 'Bosch Rexroth', 'BASF', + 'Audax', 'VolkerWessels', 'Hunkemöller', 'Athlon Car Lease', 'DSW Zorgverzekeraar', 'Mars', + 'De Brauw Blackstone Westbroek', 'NDC Mediagroep', 'Bluewater', 'Stedin', 'Feenstra', + 'Wuppermann Staal Nederland', 'Kramp', 'SABIC', 'Iv-Groep', 'Bejo Zaden', 'Wolters Kluwer', 'Nyrstar holding', + 'Adecco', 'Tauw', 'Robeco', 'Eriks', 'Allianz Nederland Groep', 'Driessen', 'Burger King', 'Lekkerland', + 'Van Lanschot', 'Brocacef', 'Bureau Veritas', 'Relx', 'Pathé Bioscopen', 'Bosal', + 'Ardagh Group', 'Maandag', 'Inalfa', 'Atradius', 'Capgemini', 'Greenchoice', 'Q8 (Kuwait Petroleum Europe)', + 'ASM International', 'Van der Valk', 'Delta Lloyd', 'GlaxoSmithKline', 'ABB', + 'Fabory, a Grainger company', 'Veen Bosch & Keuning Uitgeversgroep', 'CZ', 'Plus', 'RET Rotterdam', + 'Loyens & Loeff', 'Holland Trading', 'Archer Daniels Midland Nederland', 'Ten Brinke', 'NAM', 'DAS', + 'Samsung Electronics Benelux', 'Koopman International', 'TUI', 'Lannoo Meulenhoff', 'AC Restaurants', + 'Stage Entertainment', 'Acer', 'HDI Global SE', 'Detailresult', 'Nestle', 'GVB Amsterdam', 'Dekamarkt', 'Dirk', + 'MSD', 'Arriva', 'Baker Tilly Berk', 'SBM Offshore', 'TomTom', 'Fujifilm', 'B&S', 'BCC', 'Gasunie', + 'Oracle Nederland', 'Astellas Pharma', 'SKF', 'Woningstichting Eigen Haard', 'Rijk Zwaan', 'Chubb', 'Fugro', + 'Total', 'Rochdale', 'ASVB', 'Atos', 'Acomo', 'KPN', 'Van Drie Group', 'Olympia uitzendbureau', + 'Bacardi Nederland', 'JMW Horeca Uitzendbureau', 'Warner Bros/Eyeworks', 'Aalberts Industries', 'SNS Bank', + 'Amtrada Holding', 'VGZ', 'Grolsch', 'Office Depot', 'De Rijke Group', 'Bovemij Verzekeringsgroep', + 'Coop Nederland', 'Eaton Industries', 'ASN', 'Yara Sluiskil', 'HSF Logistics', 'Fokker', 'Deutsche Bank', + 'Sweco', 'Univé Groep', 'Koninklijke Wagenborg', 'Strukton', 'Conclusion', 'Philips', 'In Person', + 'Fluor', 'Vroegop-Windig', 'ArboUnie', 'Centraal Boekhuis', 'Siemens', 'Connexxion', 'Fujitsu', 'Consolid', + 'AVR Afvalverwerking', 'Brabant Alucast', 'Centric', 'Havensteder', 'Novartis', 'Booking.com', 'Menzis', + 'Frankort & Koning Groep', 'Jan de Rijk', 'Brand Loyalty Group', 'Ohra Verzekeringen', 'Terberg Group', + 'Cloetta', 'Holland & Barrett', 'Enza Zaden', 'VION', 'Woonzorg Nederland', + 'T-Mobile', 'Crucell', 'NautaDutilh', 'BNP Paribas', 'NIBC Bank', 'VastNed', 'CCV Holland', + 'IHC Merwede', 'Neways', 'NSI N.V.', 'Deen', 'Accor', 'HTM', 'ITM Group', 'Ordina', 'Dümmen Orange', 'Optiver', + 'Zara', 'L\'Oreal Nederland B.V.', 'Vinci Energies', 'Suit Supply Topco', 'Sita', 'Vos Logistics', + 'Altran', 'St. Clair', 'BESI', 'Fiat Chrysler Automobiles', 'UPS', 'Jacobs', 'Emté', 'TBI', 'De Bijenkorf', + 'Aldi Nederland', 'Van Wijnen', 'Vitens', 'De Goudse Verzekeringen', 'SBS Broadcasting', + 'Sandd', 'Omron', 'Sogeti', 'Alfa Accountants & Adviseurs', 'Harvey Nash', 'Stork', 'Glencore Grain', + 'Meijburg & Co', 'Honeywell', 'Meyn', 'Ericsson Telecommunicatie', 'Hurks', 'Mitsubishi', 'GGN', + 'CGI Nederland', 'Staples Nederland', 'Denkavit International', 'Ecorys', 'Rexel Nederland', + 'A. Hakpark', 'DuPont Nederland', 'CBRE Group', 'Bolsius', 'Marel', 'Metro', + 'Flynth Adviseurs en Accountants', 'Kropman Installatietechniek', 'Kuijpers', 'Medtronic', 'Cefetra', + 'Simon Loos', 'Citadel Enterprises', 'Intergamma', 'Ceva Logistics', 'Beter Bed', 'Subway', 'Gamma', 'Karwei' + 'Varo Energy', 'APM Terminals', 'Center Parcs', 'Brenntag Nederland', 'NFI', 'Hoogvliet', + 'Van Gansewinkel', 'Nedap', 'Blokker', 'Perfetti Van Melle', 'Vestia', 'Kuehne + Nagel Logistics', + 'Rensa Group', 'NTS Group', 'Joh. Mourik & Co. Holding', 'Mercedes-Benz', 'DIT Personeel', 'Verkade', + 'Hametha', 'Vopak', 'IFF', 'Pearle', 'Mainfreight', 'De Jong & Laan', 'DSV', 'P4People', 'Mazars', 'Cargill', + 'Ten Brinke Groep', 'Alewijnse', 'Agio Cigars', 'Peter Appel Transport', 'Syngenta', 'Avery Dennison', + 'Accon AVM', 'Vitol', 'Vermaat Groep', 'BMC', 'Alcatel-Lucent', 'Maxeda DIY', 'Equens', + 'Van Gelder Groep', 'Emerson Electric Nederland', 'Bakkersland', 'Specsavers', 'E.On', 'Landal Greenparks', + 'IMC Trading', 'Barentz Group', 'Epson', 'Raet', 'Van Oord', 'Thomas Cook Nederland', 'SDU uitgevers', + 'Nedschroef', 'Linde Gas', 'Ewals Cargo Care', 'Theodoor Gilissen', 'TMF Group', 'Cornelis Vrolijk', + 'Jan Linders Supermarkten', 'SIF group', 'BT Nederland', 'Kinepolis', 'Pink Elephant', + 'General Motors Nederland', 'Carlson Wagonlit', 'Bruna', 'Docdata', 'Schenk Tanktransport', 'WPG', 'Peak-IT', + 'Martinair', 'Reesink', 'Elopak Nederland', 'Fagron N.V.', 'OVG Groep', 'Ford Nederland', 'Multi Corporation', + 'Simac', 'Primark', 'Tech Data Nederland', 'Vleesgroothandel Zandbergen', 'Raben Group', 'Farm Frites', + 'Libéma', 'Caldic', 'Portaal', 'Syntus', 'Jacobs DE', 'Stena Line', 'The Phone House', 'Interfood Group', + 'Thales', 'Teva Pharmaceuticals', 'RFS Holland', 'Aebi Schmidt Nederland', + 'Rockwell Automation Nederland', 'Engie Services', 'Hendrix Genetics', 'Qbuzz', 'Unica', + '2SistersFoodGroup', 'Ziut', 'Munckhof Groep', 'Spar Holding', 'Samskip', 'Continental Bakeries', 'Sligro', + 'Merck', 'Foot Locker Europe', 'Unit4', 'PepsiCo', 'Sulzer', 'Tebodin', 'Value8', 'Boels', + 'DKG Groep', 'Bruynzeel Keukens', 'Janssen de Jong Groep', 'ProRail', 'Solid Professionals', 'Hermes Partners', + ) + + def large_company(self): + """ + :example: 'Bol.com' + """ + return self.random_element(self.large_companies) + + def company_prefix(self): + """ + :example 'Stichting' + """ + return self.random_element(self.company_prefixes)
joke2k/faker
eb7d9c838cd297c70730c43f2728ce86fe7320d9
diff --git a/tests/providers/test_company.py b/tests/providers/test_company.py index 0334a087..ed2ea4a7 100644 --- a/tests/providers/test_company.py +++ b/tests/providers/test_company.py @@ -13,6 +13,7 @@ from faker.providers.company.pt_BR import company_id_checksum from faker.providers.company.pl_PL import ( company_vat_checksum, regon_checksum, local_regon_checksum, Provider as PlProvider, ) +from faker.providers.company.nl_NL import Provider as NlProvider class TestFiFI(unittest.TestCase): @@ -140,3 +141,28 @@ class TestPlPL(unittest.TestCase): suffix = self.factory.company_suffix() assert isinstance(suffix, six.string_types) assert suffix in suffixes + + +class TestNlNL(unittest.TestCase): + """ Tests company in the nl_NL locale """ + + def setUp(self): + self.factory = Faker('nl_NL') + + def test_company_prefix(self): + prefixes = NlProvider.company_prefixes + prefix = self.factory.company_prefix() + assert isinstance(prefix, six.string_types) + assert prefix in prefixes + + def test_company_suffix(self): + suffixes = NlProvider.company_suffixes + suffix = self.factory.company_suffix() + assert isinstance(suffix, six.string_types) + assert suffix in suffixes + + def test_large_companies(self): + companies = NlProvider.large_companies + company = self.factory.large_company() + assert isinstance(company, six.string_types) + assert company in companies
Support for companies for the nl_NL locale I'm currently using faker in a project and would love to use Dutch company namers. I already made changes to do this and would like to commit these. Can you make a branch avaiable for me so I can ask for a merge request?
0.0
eb7d9c838cd297c70730c43f2728ce86fe7320d9
[ "tests/providers/test_company.py::TestFiFI::test_company_business_id", "tests/providers/test_company.py::TestJaJP::test_company", "tests/providers/test_company.py::TestPtBR::test_pt_BR_cnpj", "tests/providers/test_company.py::TestPtBR::test_pt_BR_company_id", "tests/providers/test_company.py::TestPtBR::test_pt_BR_company_id_checksum", "tests/providers/test_company.py::TestHuHU::test_company", "tests/providers/test_company.py::TestHuHU::test_company_suffix", "tests/providers/test_company.py::TestPlPL::test_company_prefix", "tests/providers/test_company.py::TestPlPL::test_company_suffix", "tests/providers/test_company.py::TestPlPL::test_company_vat", "tests/providers/test_company.py::TestPlPL::test_company_vat_checksum", "tests/providers/test_company.py::TestPlPL::test_local_regon", "tests/providers/test_company.py::TestPlPL::test_local_regon_checksum", "tests/providers/test_company.py::TestPlPL::test_regon", "tests/providers/test_company.py::TestPlPL::test_regon_checksum", "tests/providers/test_company.py::TestNlNL::test_company_prefix", "tests/providers/test_company.py::TestNlNL::test_company_suffix", "tests/providers/test_company.py::TestNlNL::test_large_companies" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-03-20 16:04:43+00:00
mit
3,324
joke2k__faker-995
diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index 7b1bd6f8..eb8a70a6 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -60,7 +60,7 @@ class Provider(BaseProvider): if max_value is None: max_value = min_value + self.random_int() - left_number = self.random_int(min_value, max_value) + left_number = self.random_int(min_value, max_value - 1) else: sign = '+' if positive else self.random_element(('+', '-')) left_number = self.random_number(left_digits)
joke2k/faker
78bf434d76d536553fb07777b41be0731d25b45e
diff --git a/tests/test_factory.py b/tests/test_factory.py index ddc8f3b0..110728cb 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -466,6 +466,16 @@ class FactoryTestCase(unittest.TestCase): with pytest.raises(ValueError): provider.pyfloat(left_digits=0, right_digits=0) + def test_pyfloat_in_range(self): + # tests for https://github.com/joke2k/faker/issues/994 + factory = Faker() + + factory.seed_instance(5) + result = factory.pyfloat(min_value=0, max_value=1) + + assert result >= 0.0 + assert result <= 1.0 + def test_negative_pyfloat(self): # tests for https://github.com/joke2k/faker/issues/813 factory = Faker()
pyfloat producing values above max_value * Faker version: 2.0.1 * OS: Windows 10 Calling `pyfloat` with the `max_value` set can produce values above `max_value` leading to issues. ### Steps to reproduce Run my example code below. ### Expected behavior Given my following example, I would expect to _only_ see numbers in the range `1 <= x <= 2`. ``` for _ in range(25): print(faker.pyfloat(min_value=1, max_value=2)) ``` ### Actual behavior However, my example will produce values in the range `1 <= x < 3`. This behavior is very confusing and unexpected. Output I got from running my above example: ``` 1.200055 2.709 2.319785 2.773763416717 1.521 1.9 2.52454 2.91 1.87016 2.35457 1.92215 1.7 2.461453 1.922252943 1.416632 1.448 2.0 1.5 2.31 2.5114 2.18 1.8 2.12503540581 2.0 ```
0.0
78bf434d76d536553fb07777b41be0731d25b45e
[ "tests/test_factory.py::FactoryTestCase::test_pyfloat_in_range" ]
[ "tests/test_factory.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "tests/test_factory.py::FactoryTestCase::test_binary", "tests/test_factory.py::FactoryTestCase::test_cli_seed", "tests/test_factory.py::FactoryTestCase::test_cli_seed_with_repeat", "tests/test_factory.py::FactoryTestCase::test_cli_verbosity", "tests/test_factory.py::FactoryTestCase::test_command", "tests/test_factory.py::FactoryTestCase::test_command_custom_provider", "tests/test_factory.py::FactoryTestCase::test_documentor", "tests/test_factory.py::FactoryTestCase::test_email", "tests/test_factory.py::FactoryTestCase::test_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_format_calls_formatter_on_provider", "tests/test_factory.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_callable", "tests/test_factory.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "tests/test_factory.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "tests/test_factory.py::FactoryTestCase::test_instance_seed_chain", "tests/test_factory.py::FactoryTestCase::test_invalid_locale", "tests/test_factory.py::FactoryTestCase::test_ipv4", "tests/test_factory.py::FactoryTestCase::test_ipv4_network_class", "tests/test_factory.py::FactoryTestCase::test_ipv4_private", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_private_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv4_public", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_a", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_b", "tests/test_factory.py::FactoryTestCase::test_ipv4_public_class_c", "tests/test_factory.py::FactoryTestCase::test_ipv6", "tests/test_factory.py::FactoryTestCase::test_language_code", "tests/test_factory.py::FactoryTestCase::test_locale", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format", "tests/test_factory.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "tests/test_factory.py::FactoryTestCase::test_negative_pyfloat", "tests/test_factory.py::FactoryTestCase::test_nl_BE_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_no_words", "tests/test_factory.py::FactoryTestCase::test_no_words_paragraph", "tests/test_factory.py::FactoryTestCase::test_no_words_sentence", "tests/test_factory.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "tests/test_factory.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "tests/test_factory.py::FactoryTestCase::test_password", "tests/test_factory.py::FactoryTestCase::test_prefix_suffix_always_string", "tests/test_factory.py::FactoryTestCase::test_random_element", "tests/test_factory.py::FactoryTestCase::test_random_number", "tests/test_factory.py::FactoryTestCase::test_random_pyfloat", "tests/test_factory.py::FactoryTestCase::test_random_pystr_characters", "tests/test_factory.py::FactoryTestCase::test_random_sample_unique", "tests/test_factory.py::FactoryTestCase::test_slugify", "tests/test_factory.py::FactoryTestCase::test_some_words", "tests/test_factory.py::FactoryTestCase::test_texts_chars_count", "tests/test_factory.py::FactoryTestCase::test_texts_count", "tests/test_factory.py::FactoryTestCase::test_texts_word_list", "tests/test_factory.py::FactoryTestCase::test_unique_words", "tests/test_factory.py::FactoryTestCase::test_us_ssn_valid", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list", "tests/test_factory.py::FactoryTestCase::test_words_ext_word_list_unique", "tests/test_factory.py::FactoryTestCase::test_words_valueerror" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-09-06 15:00:55+00:00
mit
3,325
jonaswitt__stripe-datev-exporter-5
diff --git a/stripe_datev/recognition.py b/stripe_datev/recognition.py index a4c1d83..a8852f7 100644 --- a/stripe_datev/recognition.py +++ b/stripe_datev/recognition.py @@ -39,7 +39,7 @@ def split_months(start, end, amounts): months[-1]["amounts"] = [month_amount + remaining_amounts[idx] for idx, month_amount in enumerate(months[-1]["amounts"])] - if not any(amount > 0 for amount in months[-1]["amounts"]): + if not any(amount != 0 for amount in months[-1]["amounts"]): months = months[:-1] for idx, amount in enumerate(amounts):
jonaswitt/stripe-datev-exporter
d185cfc89a52d82e0aba23fdd578abf765cf4919
diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_recognition.py b/tests/test_recognition.py new file mode 100644 index 0000000..8daea9e --- /dev/null +++ b/tests/test_recognition.py @@ -0,0 +1,18 @@ +from stripe_datev import config, recognition +import unittest +import decimal +import datetime + +class RecognitionTest(unittest.TestCase): + + def test_split_months_simple(self): + months = recognition.split_months(config.accounting_tz.localize(datetime.datetime(2020, 4, 1)), config.accounting_tz.localize(datetime.datetime(2020, 6, 30, 23, 59, 59)), [decimal.Decimal('100')]) + + self.assertEqual(len(months), 3) + self.assertEqual(months[0]["amounts"], [decimal.Decimal('32.97')]) + + def test_split_months_negative(self): + months = recognition.split_months(datetime.datetime(2022, 11, 15, 17, 3, 22, tzinfo=config.accounting_tz), datetime.datetime(2023, 8, 16, 11, 52, 12, tzinfo=config.accounting_tz), [decimal.Decimal('-14.11')]) + + self.assertEqual(len(months), 10) + self.assertEqual(months[-1]["amounts"], [decimal.Decimal('-0.78')])
AssertionError when downloading data First of all, thanks for the awesome tool! I can download the data for all months of the previous year 2022 except for November. For this single month I get the following error: ``` (venv) porcupine:stripe-datev-exporter tom$ python stripe-datev-cli.py download 2022 11 Retrieving data between 2022-11-01 and 2022-11-30 Retrieved 6 invoice(s), total -66.94 EUR Retrieved 2 charge(s), total 21.42 EUR Wrote 6 invoices to out/overview/overview-2022-11.csv Wrote 6 revenue items to out/monthly_recognition/monthly_recognition-2022-11.csv Traceback (most recent call last): File "/Users/tom/Development/stripe-datev-exporter/stripe-datev-cli.py", line 249, in <module> StripeDatevCli().run(sys.argv) File "/Users/tom/Development/stripe-datev-exporter/stripe-datev-cli.py", line 49, in run getattr(self, args.command)(argv[2:]) File "/Users/tom/Development/stripe-datev-exporter/stripe-datev-cli.py", line 105, in download records += stripe_datev.invoices.createAccountingRecords(revenue_item) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/tom/Development/stripe-datev-exporter/stripe_datev/invoices.py", line 287, in createAccountingRecords months = recognition.split_months(recognition_start, recognition_end, [amount_with_tax]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/tom/Development/stripe-datev-exporter/stripe_datev/recognition.py", line 46, in split_months assert amount == sum(month["amounts"][idx] for month in months) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError (venv) porcupine:stripe-datev-exporter tom$ ``` I am happy to provide more info in order to debug the problem, should that be necessary.
0.0
d185cfc89a52d82e0aba23fdd578abf765cf4919
[ "tests/test_recognition.py::RecognitionTest::test_split_months_negative" ]
[ "tests/test_recognition.py::RecognitionTest::test_split_months_simple" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-10-13 11:26:12+00:00
mit
3,326
jonathanhaigh__multiconfparse-96
diff --git a/multiconfparse/__init__.py b/multiconfparse/__init__.py index 0d0f524..60aedc0 100644 --- a/multiconfparse/__init__.py +++ b/multiconfparse/__init__.py @@ -418,11 +418,10 @@ class EnvironmentSource(Source): environment variable names that the source will look for. The default value is ``""``. - Note that: + * ``env_var_force_upper`` (optional, keyword): force the environment + variable name to be in upper case. Default is ``True``. - * The name of the environment variable for a config item is the config - item's name, converted to upper case, then prefixed with - ``env_var_prefix``. + Note that: * Values in environment variables for config items with ``nargs == 0`` or ``nargs == "?"`` (where the ``const`` value should be used rather than @@ -438,7 +437,12 @@ class EnvironmentSource(Source): source_name = "environment" def __init__( - self, actions, none_values=None, priority=10, env_var_prefix="", + self, + actions, + none_values=None, + priority=10, + env_var_prefix="", + env_var_force_upper=True, ): super().__init__(actions, priority=priority) @@ -446,6 +450,7 @@ class EnvironmentSource(Source): none_values = [""] self._none_values = none_values self._env_var_prefix = env_var_prefix + self._env_var_force_upper = env_var_force_upper def parse_config(self): mentions = [] @@ -466,7 +471,9 @@ class EnvironmentSource(Source): return mentions def _config_name_to_env_name(self, config_name): - return f"{self._env_var_prefix}{config_name.upper()}" + if self._env_var_force_upper: + config_name = config_name.upper() + return f"{self._env_var_prefix}{config_name}" class ArgparseSource(Source):
jonathanhaigh/multiconfparse
7a29d5c44311b7ec9015a772c4013824eae3c5a5
diff --git a/tests/test_multiconfparse.py b/tests/test_multiconfparse.py index f58d3f4..faadf53 100644 --- a/tests/test_multiconfparse.py +++ b/tests/test_multiconfparse.py @@ -495,38 +495,6 @@ def test_priorities_stable_sort(): ) -def test_dict_source_none_values(): - mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c", action="store", nargs="?", const="cv") - mcp_parser.add_source( - "dict", {"c": "none_value"}, none_values=["none_value"] - ) - values = mcp_parser.parse_config() - assert values == mcp._namespace_from_dict({"c": "cv"}) - - -def test_env_source_none_values(): - mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c", action="store", nargs="?", const="cv") - mcp_parser.add_source( - "environment", env_var_prefix="TEST_", none_values=["none_value"], - ) - with utm.patch.object(os, "environ", {"TEST_C": "none_value"}): - values = mcp_parser.parse_config() - assert values == mcp._namespace_from_dict({"c": "cv"}) - - -def test_json_source_none_values(): - mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c", action="store", nargs="?", const="cv") - fileobj = io.StringIO('{"c": "none_value"}') - mcp_parser.add_source( - "json", fileobj=fileobj, none_values=["none_value"], - ) - values = mcp_parser.parse_config() - assert values == mcp._namespace_from_dict({"c": "cv"}) - - def test_config_name_clash(): mcp_parser = mcp.ConfigParser() mcp_parser.add_config("c") @@ -595,19 +563,6 @@ def test_dest_with_extend(): assert values == expected -def test_dest_with_simple_argparse(): - mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c1", action="extend", dest="d") - mcp_parser.add_config("c2", action="extend", dest="d") - mcp_parser.add_config("c3", action="extend", dest="d") - mcp_parser.add_source("simple_argparse") - argv = "prog --c1 v1 v2 --c2 v3 --c3 v4 v5".split() - with utm.patch.object(sys, "argv", argv): - values = mcp_parser.parse_config() - expected = mcp._namespace_from_dict({"d": ["v1", "v2", "v3", "v4", "v5"]}) - assert values == expected - - def test_suppress_help(capfd): mcp_parser = mcp.ConfigParser() mcp_parser.add_config("config_item1") @@ -1461,24 +1416,17 @@ def test_simple_argparse_source_with_count_with_default(): assert values == expected_values -def test_simple_argparse_source_with_count_missing(): +def test_simple_argparse_source_with_dest(): mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c1", action="count") - mcp_parser.add_source("simple_argparse") - with utm.patch.object(sys, "argv", "prog".split()): - values = mcp_parser.parse_config() - expected_values = mcp._namespace_from_dict({"c1": None}) - assert values == expected_values - - -def test_simple_argparse_source_with_count_missing_with_default(): - mcp_parser = mcp.ConfigParser() - mcp_parser.add_config("c1", action="count", default=10) + mcp_parser.add_config("c1", action="extend", dest="d") + mcp_parser.add_config("c2", action="extend", dest="d") + mcp_parser.add_config("c3", action="extend", dest="d") mcp_parser.add_source("simple_argparse") - with utm.patch.object(sys, "argv", "prog".split()): + argv = "prog --c1 v1 v2 --c2 v3 --c3 v4 v5".split() + with utm.patch.object(sys, "argv", argv): values = mcp_parser.parse_config() - expected_values = mcp._namespace_from_dict({"c1": 10}) - assert values == expected_values + expected = mcp._namespace_from_dict({"d": ["v1", "v2", "v3", "v4", "v5"]}) + assert values == expected # ------------------------------------------------------------------------------ @@ -1506,6 +1454,72 @@ def test_json_source_with_config_added_after_source(): assert values == expected_values +def test_json_source_none_values(): + mcp_parser = mcp.ConfigParser() + mcp_parser.add_config("c", action="store", nargs="?", const="cv") + fileobj = io.StringIO('{"c": "none_value"}') + mcp_parser.add_source( + "json", fileobj=fileobj, none_values=["none_value"], + ) + values = mcp_parser.parse_config() + assert values == mcp._namespace_from_dict({"c": "cv"}) + + +# ------------------------------------------------------------------------------ +# environment source tests +# ------------------------------------------------------------------------------ + + +def test_env_source_none_values(): + mcp_parser = mcp.ConfigParser() + mcp_parser.add_config("c", action="store", nargs="?", const="cv") + mcp_parser.add_source( + "environment", env_var_prefix="TEST_", none_values=["none_value"], + ) + with utm.patch.object(os, "environ", {"TEST_C": "none_value"}): + values = mcp_parser.parse_config() + assert values == mcp._namespace_from_dict({"c": "cv"}) + + +def test_env_source_force_upper_true(): + mcp_parser = mcp.ConfigParser() + mcp_parser.add_config("c1") + mcp_parser.add_config("c2") + mcp_parser.add_source( + "environment", env_var_prefix="TEST_", env_var_force_upper=True + ) + with utm.patch.object(os, "environ", {"TEST_C1": "v1", "TEST_c2": "v2"}): + values = mcp_parser.parse_config() + assert values == mcp._namespace_from_dict({"c1": "v1", "c2": None}) + + +def test_env_source_force_upper_false(): + mcp_parser = mcp.ConfigParser() + mcp_parser.add_config("c1") + mcp_parser.add_config("c2") + mcp_parser.add_source( + "environment", env_var_prefix="TEST_", env_var_force_upper=False + ) + with utm.patch.object(os, "environ", {"TEST_C1": "v1", "TEST_c2": "v2"}): + values = mcp_parser.parse_config() + assert values == mcp._namespace_from_dict({"c1": None, "c2": "v2"}) + + +# ------------------------------------------------------------------------------ +# dict source tests +# ------------------------------------------------------------------------------ + + +def test_dict_source_none_values(): + mcp_parser = mcp.ConfigParser() + mcp_parser.add_config("c", action="store", nargs="?", const="cv") + mcp_parser.add_source( + "dict", {"c": "none_value"}, none_values=["none_value"] + ) + values = mcp_parser.parse_config() + assert values == mcp._namespace_from_dict({"c": "cv"}) + + # ------------------------------------------------------------------------------ # Multiple source tests # ------------------------------------------------------------------------------
Add option to turn off upper casing of env var names
0.0
7a29d5c44311b7ec9015a772c4013824eae3c5a5
[ "tests/test_multiconfparse.py::test_env_source_force_upper_true", "tests/test_multiconfparse.py::test_env_source_force_upper_false" ]
[ "tests/test_multiconfparse.py::test_partially_parse_config", "tests/test_multiconfparse.py::test_types", "tests/test_multiconfparse.py::test_file_opening", "tests/test_multiconfparse.py::test_valid_name[c1]", "tests/test_multiconfparse.py::test_valid_name[c_]", "tests/test_multiconfparse.py::test_valid_name[C]", "tests/test_multiconfparse.py::test_valid_name[_c]", "tests/test_multiconfparse.py::test_invalid_name[-c]", "tests/test_multiconfparse.py::test_invalid_name[c-]", "tests/test_multiconfparse.py::test_invalid_name[1c]", "tests/test_multiconfparse.py::test_validate_type", "tests/test_multiconfparse.py::test_custom_action", "tests/test_multiconfparse.py::test_source_as_class", "tests/test_multiconfparse.py::test_count", "tests/test_multiconfparse.py::test_count_with_default", "tests/test_multiconfparse.py::test_count_missing", "tests/test_multiconfparse.py::test_count_with_required", "tests/test_multiconfparse.py::test_count_missing_with_default", "tests/test_multiconfparse.py::test_priorities", "tests/test_multiconfparse.py::test_priorities_with_default", "tests/test_multiconfparse.py::test_priorities_with_multiple_values_from_source", "tests/test_multiconfparse.py::test_priorities_stable_sort", "tests/test_multiconfparse.py::test_config_name_clash", "tests/test_multiconfparse.py::test_dest_with_store", "tests/test_multiconfparse.py::test_dest_with_store_const", "tests/test_multiconfparse.py::test_dest_with_count", "tests/test_multiconfparse.py::test_dest_with_append", "tests/test_multiconfparse.py::test_dest_with_extend", "tests/test_multiconfparse.py::test_suppress_help", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_valid_input,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_invalid_input,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_invalid_const,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_default,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_global_default,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_with_default_and_global_default,", "tests/test_multiconfparse.py::test_spec_with_dict[nargs_0_or_1_with_const,", "tests/test_multiconfparse.py::test_spec_with_dict[store_const,", "tests/test_multiconfparse.py::test_spec_with_dict[store_true,", "tests/test_multiconfparse.py::test_spec_with_dict[store_false,", "tests/test_multiconfparse.py::test_spec_with_dict[suppress,", "tests/test_multiconfparse.py::test_spec_with_dict[required,", "tests/test_multiconfparse.py::test_spec_with_dict[choices,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_valid_input,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_invalid_input,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_invalid_const,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_default,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_global_default,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_with_default_and_global_default,", "tests/test_multiconfparse.py::test_spec_with_env[nargs_0_or_1_with_const,", "tests/test_multiconfparse.py::test_spec_with_env[store_const,", "tests/test_multiconfparse.py::test_spec_with_env[store_true,", "tests/test_multiconfparse.py::test_spec_with_env[store_false,", "tests/test_multiconfparse.py::test_spec_with_env[suppress,", "tests/test_multiconfparse.py::test_spec_with_env[required,", "tests/test_multiconfparse.py::test_spec_with_env[choices,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_valid_input,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_invalid_input,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_invalid_const,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_default,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_global_default,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_with_default_and_global_default,", "tests/test_multiconfparse.py::test_spec_with_json[nargs_0_or_1_with_const,", "tests/test_multiconfparse.py::test_spec_with_json[store_const,", "tests/test_multiconfparse.py::test_spec_with_json[store_true,", "tests/test_multiconfparse.py::test_spec_with_json[store_false,", "tests/test_multiconfparse.py::test_spec_with_json[suppress,", "tests/test_multiconfparse.py::test_spec_with_json[required,", "tests/test_multiconfparse.py::test_spec_with_json[choices,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_valid_input,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_invalid_input,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_invalid_const,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_default,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_global_default,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_with_default_and_global_default,", "tests/test_multiconfparse.py::test_spec_with_argparse[nargs_0_or_1_with_const,", "tests/test_multiconfparse.py::test_spec_with_argparse[store_const,", "tests/test_multiconfparse.py::test_spec_with_argparse[store_true,", "tests/test_multiconfparse.py::test_spec_with_argparse[store_false,", "tests/test_multiconfparse.py::test_spec_with_argparse[suppress,", "tests/test_multiconfparse.py::test_spec_with_argparse[required,", "tests/test_multiconfparse.py::test_spec_with_argparse[choices,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_valid_input,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_invalid_input,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_invalid_const,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_default,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_global_default,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_with_default_and_global_default,", "tests/test_multiconfparse.py::test_spec_against_argparse[nargs_0_or_1_with_const,", "tests/test_multiconfparse.py::test_spec_against_argparse[store_const,", "tests/test_multiconfparse.py::test_spec_against_argparse[store_true,", "tests/test_multiconfparse.py::test_spec_against_argparse[store_false,", "tests/test_multiconfparse.py::test_spec_against_argparse[suppress,", "tests/test_multiconfparse.py::test_spec_against_argparse[required,", "tests/test_multiconfparse.py::test_spec_against_argparse[choices,", "tests/test_multiconfparse.py::test_simple_argparse_source_with_config_added_after_source", "tests/test_multiconfparse.py::test_simple_argparse_source_with_prog", "tests/test_multiconfparse.py::test_simple_argparse_source_with_count", "tests/test_multiconfparse.py::test_simple_argparse_source_with_count_with_default", "tests/test_multiconfparse.py::test_simple_argparse_source_with_dest", "tests/test_multiconfparse.py::test_json_source_with_config_added_after_source", "tests/test_multiconfparse.py::test_json_source_none_values", "tests/test_multiconfparse.py::test_env_source_none_values", "tests/test_multiconfparse.py::test_dict_source_none_values", "tests/test_multiconfparse.py::test_multiple_sources", "tests/test_multiconfparse.py::test_include_exclude", "tests/test_multiconfparse.py::test_getattr_or_none", "tests/test_multiconfparse.py::test_has_nonnone_attr" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-22 10:45:42+00:00
mit
3,327
jonathanj__cacofonix-12
diff --git a/src/cacofonix/_app.py b/src/cacofonix/_app.py index 6b1e7cd..5f867dc 100644 --- a/src/cacofonix/_app.py +++ b/src/cacofonix/_app.py @@ -37,7 +37,9 @@ class Application(object): """ Parse and validate a fragment from a stream. """ - return self.validate_fragment(_yaml.load(fd)) + fragment = _yaml.load(fd) + fragment['issues'] = {str(k): v for k, v in fragment.get('issues', {}).items()} + return self.validate_fragment(fragment) def find_fragments( self, @@ -157,12 +159,12 @@ class Application(object): def compile_fragment_files( self, write_fs: FS, - found_fragments: Iterable[FoundFragment]) -> int: + found_fragments: Iterable[FoundFragment]) -> List[str]: """ Compile fragment files into `parent_dir`. """ - n = 0 - for n, (version_fs, filename) in enumerate(found_fragments, 1): + outputs = [] + for version_fs, filename in found_fragments: try: fragment = self.load_fragment(version_fs.readtext(filename)) fragment_type = fragment.get('type') @@ -186,9 +188,10 @@ class Application(object): if parent_dir: write_fs.makedirs(parent_dir, recreate=True) write_fs.writetext(output_path, rendered_content) + outputs.append(output_path) except Exception: raise FragmentCompilationError(filename) - return n + return outputs def render_changelog( self, diff --git a/src/cacofonix/_config.py b/src/cacofonix/_config.py index 46d4528..3c9c3a5 100644 --- a/src/cacofonix/_config.py +++ b/src/cacofonix/_config.py @@ -10,11 +10,12 @@ T = TypeVar('T') default_sections = OrderedDict([('', '')]) default_fragment_types = OrderedDict([ - (u'feature', {'name': u'Added', 'showcontent': True}), - (u'bugfix', {'name': u'Fixed', 'showcontent': True}), - (u'doc', {'name': u'Documentation', 'showcontent': True}), - (u'removal', {'name': u'Removed', 'showcontent': True}), - (u'misc', {'name': u'Misc', 'showcontent': False}), + (u'feature', {'title': u'Added', 'showcontent': True}), + (u'change', {'title': u'Changed', 'showcontent': True}), + (u'bugfix', {'title': u'Fixed', 'showcontent': True}), + (u'doc', {'title': u'Documentation', 'showcontent': True}), + (u'removal', {'title': u'Removed', 'showcontent': True}), + (u'misc', {'title': u'Misc', 'showcontent': False}), ]) diff --git a/src/cacofonix/main.py b/src/cacofonix/main.py index 47417d9..84bd8f5 100644 --- a/src/cacofonix/main.py +++ b/src/cacofonix/main.py @@ -231,7 +231,7 @@ def compile(app: Application, new_fragments = list(app.find_new_fragments()) with open_fs('temp://') as tmp_fs: - n = app.compile_fragment_files(tmp_fs, new_fragments) + n = len(app.compile_fragment_files(tmp_fs, new_fragments)) echo('Found {} new changelog fragments'.format(n)) changelog = app.render_changelog( fs=tmp_fs,
jonathanj/cacofonix
984d93c51f954266a82a4447a1a6b3cd5644d0f6
diff --git a/src/cacofonix/test/data/config.yaml b/src/cacofonix/test/data/config.yaml new file mode 100644 index 0000000..3570806 --- /dev/null +++ b/src/cacofonix/test/data/config.yaml @@ -0,0 +1,10 @@ +# Path in which to find fragments. +change_fragments_path: fragments +# Path to the changelog to merge into. +changelog_path: CHANGELOG.md +# Marker to add new changes below. +changelog_marker: | + <!-- Generated release notes start. --> + +# Type of document to output, valid values are: markdown, rest +changelog_output_type: markdown diff --git a/src/cacofonix/test/data/fragments/numeric_issue_number.yaml b/src/cacofonix/test/data/fragments/numeric_issue_number.yaml new file mode 100644 index 0000000..545e1dc --- /dev/null +++ b/src/cacofonix/test/data/fragments/numeric_issue_number.yaml @@ -0,0 +1,7 @@ +type: bugfix +section: '' +issues: + 1234: https://example.com/ +feature_flags: [] +description: |- + An issue description. diff --git a/src/cacofonix/test/test_app.py b/src/cacofonix/test/test_app.py new file mode 100644 index 0000000..83d8f72 --- /dev/null +++ b/src/cacofonix/test/test_app.py @@ -0,0 +1,66 @@ +import os.path +import pytest +from fs import open_fs +from fs.base import FS +from fs.wrap import read_only + +from cacofonix._app import Application +from cacofonix._config import Config +from cacofonix._effects import SideEffects + + +class MockSideEffects(SideEffects): + def __init__(self, root_fs, config): + self.root_fs = root_fs + self.fragments_fs = self.root_fs.opendir(config.change_fragments_path) + + def archive_fs(self, path: str) -> FS: + raise NotImplementedError() + + def changelog_fs(self, path: str) -> FS: + raise NotImplementedError() + + def git_mv(self, path: str) -> FS: + raise NotImplementedError() + + def git_stage(self, path: str) -> FS: + raise NotImplementedError() + + +def open_test_root_fs() -> FS: + """ + Open the filesystem root for the tests. + """ + cwd = os.path.dirname(__file__) + return read_only(open_fs('data', cwd=cwd)) + + +def load_test_config(root_fs) -> Config: + """ + Load the config files for the tests. + """ + with root_fs.open('config.yaml') as fd: + return Config.parse(fd) + + +class TestCompileFragmentFiles: + """ + Tests for `Application.compile_fragment_files`. + """ + def test_numeric_issue_key(self): + """ + Issues with numeric keys can be compiled. + """ + with open_test_root_fs() as root_fs: + config = load_test_config(root_fs) + effects = MockSideEffects(root_fs, config) + app = Application(config, effects) + found_fragments = [ + (effects.fragments_fs, 'numeric_issue_number.yaml'), + ] + with open_fs('temp://') as write_fs: + outputs = app.compile_fragment_files( + write_fs, + found_fragments) + assert len(outputs) == 1 + assert '#1234' in write_fs.readtext(outputs[0])
Coerce issue keys to strings Towncrier expects issues to be strings and throws an exception if this isn't the case: ``` Traceback (most recent call last): │ts after you do a transaction. It takes 12 minutes and your Yoco will restart.", "endDate": "2019-04-05T09:19:00.000Z", "friendlyName": "NFC Announcement - Ba File "/usr/local/lib/python3.7/site-packages/cacofonix/_app.py", line 172, in compile_fragment_files │tch 12 & 13", "heading": "Yoco Tap Update", "imageFileUUID": "1554182327949-7e2239ae-ba89-4081-8b4b-a4a5024a06d0", "imageURL": "https://s3-eu-west-1.amazonaws self.config.changelog_output_type) │.com/yoco-dev/production/sysadmin-bus-uuid/announcement/1554182327949-7e2239ae-ba89-4081-8b4b-a4a5024a06d0/yoco_tap_icon.png", "isDeleted": false, "isGlobal": File "/usr/local/lib/python3.7/site-packages/cacofonix/_towncrier.py", line 63, in render_fragment │ false, "lastUpdated": "2019-04-02T05:19:46.504Z", "nonDismissible": false, "primaryButtonLink": "http://bit.ly/yocotapbatch6", "primaryButtonText": "Read Mor for ticket, url in sorted(issues.items()))) │e", "showIfAndroidVersionLessThan": "9.9.9", "showIfIOSVersionLessThan": "9.9.9", "startDate": "2019-04-02T11:30:00.000Z", "targetingCriteria": {"dismissibleA File "/usr/local/lib/python3.7/site-packages/cacofonix/_towncrier.py", line 63, in <genexpr> │tUserLevel": false}, "uuid": "1554182386490-5097b263-23db-4460-9610-83e928f425ba", "wasImmutable": true} for ticket, url in sorted(issues.items()))) │ LOG Announcements> Selector> Announcement after its end date File "/usr/local/lib/python3.7/site-packages/cacofonix/_towncrier.py", line 35, in _ticket_prefix │ LOG Announcements> announcement> {"created": "2019-09-19T13:21:38.531Z", "description": "Thank you for purchasing a Yoco Go card machine. Please update you if ticket.isdigit(): │r app in order to use your new card machine. Happy transacting!", "endDate": "2019-09-27T13:17:00.000Z", "friendlyName": "New Go Force Update - test", "headin AttributeError: 'int' object has no attribute 'isdigit'```
0.0
984d93c51f954266a82a4447a1a6b3cd5644d0f6
[ "src/cacofonix/test/test_app.py::TestCompileFragmentFiles::test_numeric_issue_key" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-05-28 11:37:25+00:00
mit
3,328
jonathanj__cacofonix-8
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml new file mode 100644 index 0000000..e837306 --- /dev/null +++ b/.github/workflows/main.yaml @@ -0,0 +1,42 @@ +name: Python package + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.6, 3.7] + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install .[test] + - name: Lint with flake8 + run: | + pip install flake8 + # stop the build if there are Python syntax errors or undefined names + flake8 src setup.py --show-source --statistics + - name: Test with pytest + run: | + pip install pytest + pip install pytest-cov + pytest --cov=./ --cov-report=xml + - uses: codecov/[email protected] + with: + token: ${{ secrets.CODECOV_TOKEN }} + file: ./coverage.xml + flags: unittests + name: gh-${{ matrix.python }} diff --git a/setup.py b/setup.py index 28e702f..df669f8 100644 --- a/setup.py +++ b/setup.py @@ -42,12 +42,17 @@ setup( 'Topic :: Software Development :: Build Tools', ], install_requires=[ - 'towncrier @ git+https://github.com/hawkowl/towncrier.git#egg=towncrier', + 'towncrier @ git+https://github.com/hawkowl/towncrier.git#egg=towncrier', # noqa 'pyyaml >= 5.3', 'aniso8601 >= 8.0.0', - 'prompt_toolkit >= 3.0.3', + 'prompt-toolkit >= 3.0.3', 'Pygments >= 2.5.2', 'semver >= 2.9.0', 'fs >= 2.4.11', ], + extras_require={ + 'test': [ + 'pytest >= 5.3.5', + ], + }, ) diff --git a/src/cacofonix/_app.py b/src/cacofonix/_app.py index dd23792..86663f4 100644 --- a/src/cacofonix/_app.py +++ b/src/cacofonix/_app.py @@ -20,7 +20,7 @@ from ._towncrier import ( render_fragment, render_changelog, merge_with_existing_changelog) -from ._types import Fragment, FoundFragment +from ._types import Fragment, FoundFragment, GuessPair from ._effects import SideEffects @@ -161,7 +161,7 @@ class Application(object): n = 0 for n, (version_fs, filename) in enumerate(found_fragments, 1): try: - fragment = self.load_fragment(version_fs.gettext(filename)) + fragment = self.load_fragment(version_fs.readtext(filename)) fragment_type = fragment.get('type') showcontent = self.config.fragment_types.get( fragment_type, {}).get('showcontent', True) @@ -219,16 +219,11 @@ class Application(object): changelog) self.effects.git_stage(changelog_path) - def guess_version(self, cwd_fs) -> Optional[str]: + def guess_version(self, cwd_fs: FS) -> Optional[str]: """ Attempt to guess the software version. """ - guesses = [package_json] - for guess in guesses: - result = guess(cwd_fs) - if result is not None: - return result - return None + return detect_version(cwd_fs) def known_versions(self) -> List[VersionInfo]: """ @@ -252,8 +247,24 @@ def package_json(cwd_fs: FS): if cwd_fs.exists('package.json'): log.debug('Guessing version with package.json') try: - return ('package.json', - json.load(cwd_fs.gettext('package.json')).get('version')) + with cwd_fs.open('package.json', 'r') as fd: + return json.load(fd).get('version') except json.JSONDecodeError: pass return None + + +_default_guesses = [ + ('package.json', package_json), +] + + +def detect_version(cwd_fs: FS, _guesses: List[GuessPair]) -> Optional[str]: + """ + Make several attempts to guess the version of the package. + """ + for kind, guess in _guesses: + result = guess(cwd_fs) + if result is not None: + return kind, result + return None diff --git a/src/cacofonix/_effects.py b/src/cacofonix/_effects.py index 0cdb8c5..fe8ad58 100644 --- a/src/cacofonix/_effects.py +++ b/src/cacofonix/_effects.py @@ -108,8 +108,8 @@ def _dry_run_method(name: str): class DryRunSideEffects(SideEffects): """ - Dry run side effects that change only temporary files or log actions instead - of performing them. + Dry run side effects that change only temporary files or log actions + instead of performing them. """ git_mv = _dry_run_method('git_mv') git_stage = _dry_run_method('git_stage') diff --git a/src/cacofonix/_log.py b/src/cacofonix/_log.py index 6d90c95..52feea0 100644 --- a/src/cacofonix/_log.py +++ b/src/cacofonix/_log.py @@ -13,7 +13,8 @@ def setup_logging(level): def _log_method(name): def __log_method(*a, **kw): global _logger - assert _logger is not None + if _logger is None: + _logger = logging return getattr(_logger, name)(*a, **kw) return __log_method diff --git a/src/cacofonix/_types.py b/src/cacofonix/_types.py index 2c5c2db..097ff87 100644 --- a/src/cacofonix/_types.py +++ b/src/cacofonix/_types.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, Tuple +from typing import Any, Dict, Tuple, Callable, Optional from fs.base import FS @@ -8,3 +8,4 @@ Fragment = Dict[str, Any] # OutputType = Literal['markdown', 'rest'] OutputType = str FoundFragment = Tuple[FS, str] +GuessPair = Tuple[str, Callable[[FS], Optional[str]]]
jonathanj/cacofonix
f7599ac8d1b8770a2c7844d45572cc97bf27c036
diff --git a/src/cacofonix/test/__init__.py b/src/cacofonix/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/cacofonix/test/test_version_detection.py b/src/cacofonix/test/test_version_detection.py new file mode 100644 index 0000000..f521b74 --- /dev/null +++ b/src/cacofonix/test/test_version_detection.py @@ -0,0 +1,50 @@ +import json +import pytest +from fs import open_fs +from fs.wrap import read_only + +from cacofonix._app import detect_version, package_json + + +class TestDetectVersion: + """ + Tests for `detect_version`. + """ + never = ('never', lambda _: None) + always = ('always', lambda _: '1.2.3') + + def test_detect_nothing(self): + _guesses = [self.never] + with open_fs('mem://') as cwd_fs: + assert detect_version(cwd_fs, _guesses) is None + + def test_detect_something(self): + _guesses = [self.always] + with open_fs('mem://') as cwd_fs: + assert detect_version(cwd_fs, _guesses) == ( + 'always', '1.2.3') + + [email protected]('tmpdir') +class TestPackageJson: + """ + Tests for ``package.json`` version detection. + """ + def test_nonexistent_file(self, tmpdir): + with tmpdir.as_cwd(): + with open_fs('.') as cwd_fs: + assert package_json(read_only(cwd_fs)) is None + + def test_missing_version(self, tmpdir): + with tmpdir.as_cwd(): + with open_fs('.') as cwd_fs: + content = json.dumps({'name': 'Test'}) + cwd_fs.writetext('package.json', content) + assert package_json(read_only(cwd_fs)) is None + + def test_version(self, tmpdir): + with tmpdir.as_cwd(): + with open_fs('.') as cwd_fs: + content = json.dumps({'name': 'Test', 'version': '1.2.3'}) + cwd_fs.writetext('package.json', content) + assert package_json(read_only(cwd_fs)) == '1.2.3'
Version guessing from package.json is broken ``` Traceback (most recent call last): File "/usr/local/bin/cacofonix", line 10, in <module> sys.exit(main()) File "/usr/local/lib/python3.7/site-packages/cacofonix/main.py", line 298, in main cli() File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1135, in invoke sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 641, in make_context self.parse_args(ctx, args) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 940, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1477, in handle_parse_result self.callback, ctx, self, value) File "/usr/local/lib/python3.7/site-packages/click/core.py", line 96, in invoke_param_callback return callback(ctx, param, value) File "/usr/local/lib/python3.7/site-packages/cacofonix/_cli.py", line 112, in guess_version value = app.guess_version(app.effects.cwd_fs()) File "/usr/local/lib/python3.7/site-packages/cacofonix/_app.py", line 228, in guess_version result = guess(cwd_fs) File "/usr/local/lib/python3.7/site-packages/cacofonix/_app.py", line 256, in package_json json.load(cwd_fs.gettext('package.json')).get('version')) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 293, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read' ```
0.0
f7599ac8d1b8770a2c7844d45572cc97bf27c036
[ "src/cacofonix/test/test_version_detection.py::TestDetectVersion::test_detect_nothing", "src/cacofonix/test/test_version_detection.py::TestDetectVersion::test_detect_something", "src/cacofonix/test/test_version_detection.py::TestPackageJson::test_nonexistent_file", "src/cacofonix/test/test_version_detection.py::TestPackageJson::test_missing_version", "src/cacofonix/test/test_version_detection.py::TestPackageJson::test_version" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-04 20:14:22+00:00
mit
3,329
jonathanj__eliottree-61
diff --git a/eliottree/filter.py b/eliottree/filter.py index a3f48ea..9fd5f8f 100644 --- a/eliottree/filter.py +++ b/eliottree/filter.py @@ -1,7 +1,7 @@ from datetime import datetime import jmespath -from iso8601.iso8601 import Utc +from iso8601.iso8601 import UTC def filter_by_jmespath(query): @@ -25,7 +25,7 @@ def _parse_timestamp(timestamp): """ Parse a timestamp into a UTC L{datetime}. """ - return datetime.utcfromtimestamp(timestamp).replace(tzinfo=Utc()) + return datetime.utcfromtimestamp(timestamp).replace(tzinfo=UTC) def filter_by_start_date(start_date):
jonathanj/eliottree
c2ae5b0d4ae14d18691ea3fd89e378ecd4fce535
diff --git a/eliottree/test/test_filter.py b/eliottree/test/test_filter.py index 023cb02..495b4fa 100644 --- a/eliottree/test/test_filter.py +++ b/eliottree/test/test_filter.py @@ -1,7 +1,7 @@ from calendar import timegm from datetime import datetime -from iso8601.iso8601 import Utc +from iso8601.iso8601 import UTC from testtools import TestCase from testtools.matchers import Equals @@ -63,7 +63,7 @@ class FilterByStartDate(TestCase): Return ``False`` if the input task's timestamp is before the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 1, 0).utctimetuple())) @@ -75,7 +75,7 @@ class FilterByStartDate(TestCase): """ Return ``True`` if the input task's timestamp is after the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 2).utctimetuple())) @@ -88,7 +88,7 @@ class FilterByStartDate(TestCase): Return ``True`` if the input task's timestamp is the same as the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 1, 15).utctimetuple())) @@ -106,7 +106,7 @@ class FilterByEndDate(TestCase): Return ``False`` if the input task's timestamp is after the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 2).utctimetuple())) @@ -119,7 +119,7 @@ class FilterByEndDate(TestCase): Return ``False`` if the input task's timestamp is the same as the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 1, 15).utctimetuple())) @@ -131,7 +131,7 @@ class FilterByEndDate(TestCase): """ Return ``True`` if the input task's timestamp is before the start date. """ - now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=Utc()) + now = datetime(2015, 10, 30, 22, 1, 15).replace(tzinfo=UTC) task = dict( message_task, timestamp=timegm(datetime(2015, 10, 30, 22, 1).utctimetuple()))
`iso8601.iso8601.Utc` is not reliably available Version 0.1.12 doesn't expose this for Python 3.2.0 and newer, it looks like this is not really a public export anyway and we ought to be using `UTC` which is an instance of a UTC tzinfo implementation.
0.0
c2ae5b0d4ae14d18691ea3fd89e378ecd4fce535
[ "eliottree/test/test_filter.py::FilterByJmespath::test_match", "eliottree/test/test_filter.py::FilterByJmespath::test_no_match", "eliottree/test/test_filter.py::FilterByUUID::test_match", "eliottree/test/test_filter.py::FilterByUUID::test_no_match", "eliottree/test/test_filter.py::FilterByStartDate::test_match", "eliottree/test/test_filter.py::FilterByStartDate::test_match_moment", "eliottree/test/test_filter.py::FilterByStartDate::test_no_match", "eliottree/test/test_filter.py::FilterByEndDate::test_match", "eliottree/test/test_filter.py::FilterByEndDate::test_no_match", "eliottree/test/test_filter.py::FilterByEndDate::test_no_match_moment" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-09-01 13:23:01+00:00
mit
3,330
jonathanj__eliottree-89
diff --git a/README.rst b/README.rst index a09aa73..5715dd8 100644 --- a/README.rst +++ b/README.rst @@ -78,9 +78,10 @@ Usage from the command-line $ eliot-tree usage: eliot-tree [-h] [-u UUID] [-i KEY] [--raw] [--local-timezone] - [--color {always,auto,never}] [--ascii] [--no-color-tree] - [-l LENGTH] [--select QUERY] [--start START] [--end END] - [FILE [FILE ...]] + [--color {always,auto,never}] [--ascii] [--no-color-tree] + [--theme {auto,dark,light}] [-l LENGTH] [--select QUERY] + [--start START] [--end END] + [FILE [FILE ...]] Display an Eliot log as a tree of tasks. @@ -103,6 +104,8 @@ Usage from the command-line is a TTY. --ascii Use ASCII for tree drawing characters. --no-color-tree Do not color the tree lines. + --theme {auto,dark,light} + Select a color theme to use. -l LENGTH, --field-limit LENGTH Limit the length of field values to LENGTH or a newline, whichever comes first. Use a length of 0 to diff --git a/src/eliottree/_cli.py b/src/eliottree/_cli.py index da4f27a..3df68a5 100644 --- a/src/eliottree/_cli.py +++ b/src/eliottree/_cli.py @@ -1,9 +1,11 @@ import argparse import codecs import json +import os import platform import sys from pprint import pformat +from termcolor import colored import iso8601 from six import PY3, binary_type, reraise @@ -13,6 +15,7 @@ from toolz import compose from eliottree import ( EliotParseError, JSONParseError, filter_by_end_date, filter_by_jmespath, filter_by_start_date, filter_by_uuid, render_tasks, tasks_from_iterable) +from eliottree._theme import get_theme def text_writer(fd): @@ -92,7 +95,7 @@ def setup_platform(colorize): colorama.init() -def display_tasks(tasks, color, colorize_tree, ascii, ignored_fields, +def display_tasks(tasks, color, colorize_tree, ascii, theme_name, ignored_fields, field_limit, human_readable, utc_timestamps): """ Render Eliot tasks, apply any command-line-specified behaviour and render @@ -106,6 +109,13 @@ def display_tasks(tasks, color, colorize_tree, ascii, ignored_fields, setup_platform(colorize=colorize) write = text_writer(sys.stdout).write write_err = text_writer(sys.stderr).write + if theme_name == 'auto': + dark_background = is_dark_terminal_background(default=True) + else: + dark_background = theme_name == 'dark' + theme = get_theme( + dark_background=dark_background, + colored=colored if colorize else None) render_tasks( write=write, @@ -114,10 +124,10 @@ def display_tasks(tasks, color, colorize_tree, ascii, ignored_fields, ignored_fields=set(ignored_fields) or None, field_limit=field_limit, human_readable=human_readable, - colorize=colorize, colorize_tree=colorize and colorize_tree, ascii=ascii, - utc_timestamps=utc_timestamps) + utc_timestamps=utc_timestamps, + theme=theme) def _decode_command_line(value, encoding='utf-8'): @@ -129,6 +139,29 @@ def _decode_command_line(value, encoding='utf-8'): return value +def is_dark_terminal_background(default=True): + """ + Does the terminal use a dark background color? + + Currently just checks the `COLORFGBG` environment variable, if it exists, + which some terminals define as `fg:bg`. + + :rtype: bool + """ + colorfgbg = os.environ.get('COLORFGBG', None) + if colorfgbg is not None: + parts = os.environ['COLORFGBG'].split(';') + try: + last_number = int(parts[-1]) + if 0 <= last_number <= 6 or last_number == 8: + return True + else: + return False + except ValueError: + pass + return default + + def main(): parser = argparse.ArgumentParser( description='Display an Eliot log as a tree of tasks.') @@ -176,6 +209,11 @@ def main(): default=True, dest='colorize_tree', help='''Do not color the tree lines.''') + parser.add_argument('--theme', + default='auto', + choices=['auto', 'dark', 'light'], + dest='theme_name', + help='''Select a color theme to use.'''), parser.add_argument('-l', '--field-limit', metavar='LENGTH', type=int, @@ -216,6 +254,7 @@ def main(): tasks=tasks, color=args.color, colorize_tree=args.colorize_tree, + theme_name=args.theme_name, ascii=args.ascii, ignored_fields=args.ignored_fields, field_limit=args.field_limit, diff --git a/src/eliottree/_render.py b/src/eliottree/_render.py index 4e660cf..17bdb83 100644 --- a/src/eliottree/_render.py +++ b/src/eliottree/_render.py @@ -4,12 +4,12 @@ from functools import partial from eliot.parse import WrittenAction, WrittenMessage, Task from six import text_type -from termcolor import colored from toolz import compose, excepts, identity from eliottree import format from eliottree.tree_format import format_tree, Options, ASCII_OPTIONS from eliottree._util import eliot_ns, format_namespace, is_namespace +from eliottree._theme import get_theme RIGHT_DOUBLE_ARROW = u'\N{RIGHTWARDS DOUBLE ARROW}' @@ -20,41 +20,6 @@ DEFAULT_IGNORED_KEYS = set([ u'message_type']) -class Color(object): - def __init__(self, color, attrs=[]): - self.color = color - self.attrs = attrs - - def __get__(self, instance, owner): - return lambda text: instance.colored( - text, self.color, attrs=self.attrs) - - -class COLORS(object): - root = Color('white', ['bold']) - parent = Color('magenta') - success = Color('green') - failure = Color('red') - prop = Color('blue') - error = Color('red', ['bold']) - timestamp = Color('white', ['dark']) - duration = Color('blue', ['dark']) - tree_failed = Color('red', ['dark']) - tree_color0 = Color('white', ['dark']) - tree_color1 = Color('blue', ['dark']) - tree_color2 = Color('magenta', ['dark']) - - def __init__(self, colored): - self.colored = colored - - -def _no_color(text, *a, **kw): - """ - Colorizer that does not colorize. - """ - return text - - def _default_value_formatter( human_readable, field_limit, @@ -84,7 +49,7 @@ def _default_value_formatter( format.anything(encoding))) -def message_name(colors, format_value, message, end_message=None): +def message_name(theme, format_value, message, end_message=None): """ Derive the name for a message. @@ -94,7 +59,7 @@ def message_name(colors, format_value, message, end_message=None): otherwise no name will be derived. """ if message is not None: - timestamp = colors.timestamp( + timestamp = theme.timestamp( format_value( message.timestamp, field_name=eliot_ns('timestamp'))) if u'action_type' in message.contents: @@ -105,7 +70,7 @@ def message_name(colors, format_value, message, end_message=None): duration_seconds = end_message.timestamp - message.timestamp duration = u' {} {}'.format( HOURGLASS, - colors.duration( + theme.duration( format_value( duration_seconds, field_name=eliot_ns('duration')))) @@ -114,11 +79,11 @@ def message_name(colors, format_value, message, end_message=None): action_status = message.contents.action_status status_color = identity if action_status == u'succeeded': - status_color = colors.success + status_color = theme.success elif action_status == u'failed': - status_color = colors.failure + status_color = theme.failure return u'{}{} {} {} {}{}'.format( - colors.parent(action_type), + theme.parent(action_type), message.task_level.to_string(), RIGHT_DOUBLE_ARROW, status_color(message.contents.action_status), @@ -128,13 +93,13 @@ def message_name(colors, format_value, message, end_message=None): message_type = format.escape_control_characters( message.contents.message_type) return u'{}{} {}'.format( - colors.parent(message_type), + theme.parent(message_type), message.task_level.to_string(), timestamp) return u'<unnamed>' -def format_node(format_value, colors, node): +def format_node(format_value, theme, node): """ Format a node for display purposes. @@ -146,17 +111,17 @@ def format_node(format_value, colors, node): """ if isinstance(node, Task): return u'{}'.format( - colors.root( + theme.root( format.escape_control_characters(node.root().task_uuid))) elif isinstance(node, WrittenAction): return message_name( - colors, + theme, format_value, node.start_message, node.end_message) elif isinstance(node, WrittenMessage): return message_name( - colors, + theme, format_value, node) elif isinstance(node, tuple): @@ -168,7 +133,7 @@ def format_node(format_value, colors, node): if is_namespace(key): key = format_namespace(key) return u'{}: {}'.format( - colors.prop(format.escape_control_characters(key)), + theme.prop(format.escape_control_characters(key)), value) raise NotImplementedError() @@ -228,7 +193,7 @@ def track_exceptions(f, caught, default=None): return excepts(Exception, f, _catch) -class ColorizedOptions(): +class ColorizedOptions(object): """ `Options` for `format_tree` that colorizes sub-trees. """ @@ -249,9 +214,10 @@ class ColorizedOptions(): def render_tasks(write, tasks, field_limit=0, ignored_fields=None, - human_readable=False, colorize=False, write_err=None, + human_readable=False, write_err=None, format_node=format_node, format_value=None, - utc_timestamps=True, colorize_tree=False, ascii=False): + utc_timestamps=True, colorize_tree=False, ascii=False, + theme=None): """ Render Eliot tasks as an ASCII tree. @@ -275,10 +241,12 @@ def render_tasks(write, tasks, field_limit=0, ignored_fields=None, :param bool utc_timestamps: Format timestamps as UTC? :param int colorize_tree: Colorizing the tree output? :param bool ascii: Render the tree as plain ASCII instead of Unicode? + :param Theme theme: Theme to use for rendering. """ if ignored_fields is None: ignored_fields = DEFAULT_IGNORED_KEYS - colors = COLORS(colored if colorize else _no_color) + if theme is None: + theme = get_theme(dark_background=True) caught_exceptions = [] if format_value is None: format_value = _default_value_formatter( @@ -290,7 +258,7 @@ def render_tasks(write, tasks, field_limit=0, ignored_fields=None, caught_exceptions, u'<value formatting exception>') _format_node = track_exceptions( - partial(format_node, _format_value, colors), + partial(format_node, _format_value, theme), caught_exceptions, u'<node formatting exception>') _get_children = partial(get_children, ignored_fields) @@ -302,8 +270,8 @@ def render_tasks(write, tasks, field_limit=0, ignored_fields=None, options = Options() if colorize_tree: return ColorizedOptions( - failed_color=colors.tree_failed, - depth_colors=[colors.tree_color0, colors.tree_color1, colors.tree_color2], + failed_color=theme.tree_failed, + depth_colors=[theme.tree_color0, theme.tree_color1, theme.tree_color2], options=options) return options @@ -313,7 +281,7 @@ def render_tasks(write, tasks, field_limit=0, ignored_fields=None, if write_err and caught_exceptions: write_err( - colors.error( + theme.error( u'Exceptions ({}) occurred during processing:\n'.format( len(caught_exceptions)))) for exc in caught_exceptions: diff --git a/src/eliottree/_theme.py b/src/eliottree/_theme.py new file mode 100644 index 0000000..d73a69b --- /dev/null +++ b/src/eliottree/_theme.py @@ -0,0 +1,93 @@ +def color_factory(colored): + """ + Factory for making text color-wrappers. + """ + def _color(color, attrs=[]): + def __color(text): + return colored(text, color, attrs=attrs) + return __color + return _color + + +class Theme(object): + """ + Theme base class. + """ + __slots__ = [ + 'root', + 'parent', + 'success', + 'failure', + 'prop', + 'error', + 'timestamp', + 'duration', + 'tree_failed', + 'tree_color0', + 'tree_color1', + 'tree_color2', + ] + def __init__(self, **theme): + super(Theme, self).__init__() + for k, v in theme.items(): + setattr(self, k, v) + + +class DarkBackgroundTheme(Theme): + """ + Color theme for dark backgrounds. + """ + def __init__(self, colored): + color = color_factory(colored) + super(DarkBackgroundTheme, self).__init__( + root=color('white', ['bold']), + parent=color('magenta'), + success=color('green'), + failure=color('red'), + prop=color('blue'), + error=color('red', ['bold']), + timestamp=color('white', ['dark']), + duration=color('blue', ['dark']), + tree_failed=color('red'), + tree_color0=color('white', ['dark']), + tree_color1=color('blue', ['dark']), + tree_color2=color('magenta', ['dark']), + ) + + +class LightBackgroundTheme(Theme): + """ + Color theme for light backgrounds. + """ + def __init__(self, colored): + color = color_factory(colored) + super(LightBackgroundTheme, self).__init__( + root=color('grey', ['bold']), + parent=color('magenta'), + success=color('green'), + failure=color('red'), + prop=color('blue'), + error=color('red', ['bold']), + timestamp=color('grey'), + duration=color('blue', ['dark']), + tree_failed=color('red'), + tree_color0=color('grey', ['dark']), + tree_color1=color('blue', ['dark']), + tree_color2=color('magenta', ['dark']), + ) + + +def _no_color(text, *a, **kw): + """ + Colorizer that does not colorize. + """ + return text + + +def get_theme(dark_background, colored=None): + """ + Create an appropriate theme. + """ + if colored is None: + colored = _no_color + return DarkBackgroundTheme(colored) if dark_background else LightBackgroundTheme(colored)
jonathanj/eliottree
ddac8b4ea05f0320cb4f3a8e10d08436d86c651c
diff --git a/src/eliottree/test/test_render.py b/src/eliottree/test/test_render.py index 8547ed9..e0002b0 100644 --- a/src/eliottree/test/test_render.py +++ b/src/eliottree/test/test_render.py @@ -10,8 +10,9 @@ from testtools.matchers import ( from eliottree import ( render_tasks, tasks_from_iterable) from eliottree._render import ( - COLORS, HOURGLASS, RIGHT_DOUBLE_ARROW, _default_value_formatter, _no_color, - format_node, get_children, message_fields, message_name) + HOURGLASS, RIGHT_DOUBLE_ARROW, _default_value_formatter, format_node, + get_children, message_fields, message_name) +from eliottree._theme import get_theme from eliottree._util import eliot_ns from eliottree.test.matchers import ExactlyEquals from eliottree.test.tasks import ( @@ -131,8 +132,8 @@ class DefaultValueFormatterTests(TestCase): ExactlyEquals(text_type(now))) -colors = COLORS(colored) -no_colors = COLORS(_no_color) +colors = get_theme(dark_background=True, colored=colored) +no_colors = get_theme(dark_background=True, colored=None) def no_formatting(value, field_name=None): @@ -704,11 +705,11 @@ class RenderTasksTests(TestCase): def test_colorize(self): """ - Passing ``colorize=True`` will colorize the output. + Passing ``theme`` will colorize the output. """ self.assertThat( self.render_tasks([action_task, action_task_end], - colorize=True), + theme=colors), ExactlyEquals( u'\n'.join([ colors.root(u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4'),
On my terminal, prints white-on-white text On my terminal, eliot-tree output looks like: ![image](https://user-images.githubusercontent.com/609896/56775876-02154780-677e-11e9-98e7-bb233a2cbf1d.png) I find that UUID somewhat hard to read :-)
0.0
ddac8b4ea05f0320cb4f3a8e10d08436d86c651c
[ "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_anything", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_bytes", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_not_eliot_timestamp_field", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_timestamp_field", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_timestamp_field_local", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_timestamp_field_not_human", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_unicode", "src/eliottree/test/test_render.py::DefaultValueFormatterTests::test_unicode_control_characters", "src/eliottree/test/test_render.py::MessageNameTests::test_action_status", "src/eliottree/test/test_render.py::MessageNameTests::test_action_status_failed", "src/eliottree/test/test_render.py::MessageNameTests::test_action_status_success", "src/eliottree/test/test_render.py::MessageNameTests::test_action_task_level", "src/eliottree/test/test_render.py::MessageNameTests::test_action_type", "src/eliottree/test/test_render.py::MessageNameTests::test_message_task_level", "src/eliottree/test/test_render.py::MessageNameTests::test_message_type", "src/eliottree/test/test_render.py::MessageNameTests::test_unknown", "src/eliottree/test/test_render.py::FormatNodeTests::test_other", "src/eliottree/test/test_render.py::FormatNodeTests::test_task", "src/eliottree/test/test_render.py::FormatNodeTests::test_tuple_dict", "src/eliottree/test/test_render.py::FormatNodeTests::test_tuple_list", "src/eliottree/test/test_render.py::FormatNodeTests::test_tuple_other", "src/eliottree/test/test_render.py::FormatNodeTests::test_written_action", "src/eliottree/test/test_render.py::MessageFieldsTests::test_empty", "src/eliottree/test/test_render.py::MessageFieldsTests::test_fields", "src/eliottree/test/test_render.py::MessageFieldsTests::test_ignored_fields", "src/eliottree/test/test_render.py::GetChildrenTests::test_other", "src/eliottree/test/test_render.py::GetChildrenTests::test_task_action", "src/eliottree/test/test_render.py::GetChildrenTests::test_tuple_dict", "src/eliottree/test/test_render.py::GetChildrenTests::test_tuple_list", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_children", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_end", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_ignored_fields", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_no_children", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_no_end", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_action_start", "src/eliottree/test/test_render.py::GetChildrenTests::test_written_message", "src/eliottree/test/test_render.py::RenderTasksTests::test_colorize", "src/eliottree/test/test_render.py::RenderTasksTests::test_dict_data", "src/eliottree/test/test_render.py::RenderTasksTests::test_field_limit", "src/eliottree/test/test_render.py::RenderTasksTests::test_format_node_failures", "src/eliottree/test/test_render.py::RenderTasksTests::test_format_value_failures", "src/eliottree/test/test_render.py::RenderTasksTests::test_ignored_keys", "src/eliottree/test/test_render.py::RenderTasksTests::test_janky_action", "src/eliottree/test/test_render.py::RenderTasksTests::test_janky_message", "src/eliottree/test/test_render.py::RenderTasksTests::test_list_data", "src/eliottree/test/test_render.py::RenderTasksTests::test_multiline_field", "src/eliottree/test/test_render.py::RenderTasksTests::test_multiline_field_limit", "src/eliottree/test/test_render.py::RenderTasksTests::test_nested", "src/eliottree/test/test_render.py::RenderTasksTests::test_task_data", "src/eliottree/test/test_render.py::RenderTasksTests::test_tasks", "src/eliottree/test/test_render.py::RenderTasksTests::test_tasks_human_readable" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_media", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-10 08:42:40+00:00
mit
3,331
jordaneremieff__mangum-182
diff --git a/mangum/handlers/aws_alb.py b/mangum/handlers/aws_alb.py index b2c6470..33e0968 100644 --- a/mangum/handlers/aws_alb.py +++ b/mangum/handlers/aws_alb.py @@ -57,9 +57,13 @@ class AwsAlb(AbstractHandler): @property def body(self) -> bytes: - body = self.trigger_event.get("body", b"") + body = self.trigger_event.get("body", b"") or b"" + if self.trigger_event.get("isBase64Encoded", False): - body = base64.b64decode(body) + return base64.b64decode(body) + if not isinstance(body, bytes): + body = body.encode() + return body def transform_response(self, response: Response) -> Dict[str, Any]: diff --git a/mangum/handlers/aws_api_gateway.py b/mangum/handlers/aws_api_gateway.py index 6267ffa..2e239d4 100644 --- a/mangum/handlers/aws_api_gateway.py +++ b/mangum/handlers/aws_api_gateway.py @@ -95,9 +95,13 @@ class AwsApiGateway(AbstractHandler): @property def body(self) -> bytes: - body = self.trigger_event.get("body", b"") + body = self.trigger_event.get("body", b"") or b"" + if self.trigger_event.get("isBase64Encoded", False): - body = base64.b64decode(body) + return base64.b64decode(body) + if not isinstance(body, bytes): + body = body.encode() + return body def transform_response(self, response: Response) -> Dict[str, Any]: diff --git a/mangum/handlers/aws_cf_lambda_at_edge.py b/mangum/handlers/aws_cf_lambda_at_edge.py index 85013bd..b43132c 100644 --- a/mangum/handlers/aws_cf_lambda_at_edge.py +++ b/mangum/handlers/aws_cf_lambda_at_edge.py @@ -55,9 +55,13 @@ class AwsCfLambdaAtEdge(AbstractHandler): @property def body(self) -> bytes: request = self.trigger_event["Records"][0]["cf"]["request"] - body = request.get("body", {}).get("data", None) + body = request.get("body", {}).get("data", None) or b"" + if request.get("body", {}).get("encoding", "") == "base64": - body = base64.b64decode(body) + return base64.b64decode(body) + if not isinstance(body, bytes): + body = body.encode() + return body def transform_response(self, response: Response) -> Dict[str, Any]: diff --git a/mangum/handlers/aws_http_gateway.py b/mangum/handlers/aws_http_gateway.py index 6ff783c..513c494 100644 --- a/mangum/handlers/aws_http_gateway.py +++ b/mangum/handlers/aws_http_gateway.py @@ -102,9 +102,13 @@ class AwsHttpGateway(AbstractHandler): @property def body(self) -> bytes: - body = self.trigger_event.get("body", b"") + body = self.trigger_event.get("body", b"") or b"" + if self.trigger_event.get("isBase64Encoded", False): - body = base64.b64decode(body) + return base64.b64decode(body) + if not isinstance(body, bytes): + body = body.encode() + return body def transform_response(self, response: Response) -> Dict[str, Any]:
jordaneremieff/mangum
3f312acb67aac30c07dfb305d3cd1881c59755c4
diff --git a/tests/handlers/test_aws_alb.py b/tests/handlers/test_aws_alb.py index 216d8a8..d922c37 100644 --- a/tests/handlers/test_aws_alb.py +++ b/tests/handlers/test_aws_alb.py @@ -74,6 +74,8 @@ def test_aws_alb_basic(): example_context = {} handler = AwsAlb(example_event, example_context) + + assert type(handler.body) == bytes assert handler.request.scope == { "asgi": {"version": "3.0"}, "aws.context": {}, @@ -119,7 +121,15 @@ def test_aws_alb_basic(): "query_string,scope_body", [ ("GET", "/hello/world", None, None, False, b"", None), - ("POST", "/", {"name": ["me"]}, None, False, b"name=me", None), + ( + "POST", + "/", + {"name": ["me"]}, + "field1=value1&field2=value2", + False, + b"name=me", + b"field1=value1&field2=value2", + ), ( "GET", "/my/resource", @@ -210,7 +220,10 @@ def test_aws_alb_scope_real( "type": "http", } - assert handler.body == scope_body + if handler.body: + assert handler.body == scope_body + else: + assert handler.body == b"" def test_aws_alb_set_cookies() -> None: diff --git a/tests/handlers/test_aws_api_gateway.py b/tests/handlers/test_aws_api_gateway.py index bc07d08..e35bf4e 100644 --- a/tests/handlers/test_aws_api_gateway.py +++ b/tests/handlers/test_aws_api_gateway.py @@ -96,6 +96,8 @@ def test_aws_api_gateway_scope_basic(): } example_context = {} handler = AwsApiGateway(example_event, example_context) + + assert type(handler.body) == bytes assert handler.request.scope == { "asgi": {"version": "3.0"}, "aws.context": {}, @@ -128,7 +130,15 @@ def test_aws_api_gateway_scope_basic(): "query_string,scope_body", [ ("GET", "/hello/world", None, None, False, b"", None), - ("POST", "/", {"name": ["me"]}, None, False, b"name=me", None), + ( + "POST", + "/", + {"name": ["me"]}, + "field1=value1&field2=value2", + False, + b"name=me", + b"field1=value1&field2=value2", + ), ( "GET", "/my/resource", @@ -218,7 +228,10 @@ def test_aws_api_gateway_scope_real( "type": "http", } - assert handler.body == scope_body + if handler.body: + assert handler.body == scope_body + else: + assert handler.body == b"" @pytest.mark.parametrize( diff --git a/tests/handlers/test_aws_cf_lambda_at_edge.py b/tests/handlers/test_aws_cf_lambda_at_edge.py index 650e4e2..4692e79 100644 --- a/tests/handlers/test_aws_cf_lambda_at_edge.py +++ b/tests/handlers/test_aws_cf_lambda_at_edge.py @@ -136,6 +136,7 @@ def test_aws_cf_lambda_at_edge_scope_basic(): example_context = {} handler = AwsCfLambdaAtEdge(example_event, example_context) + assert type(handler.body) == bytes assert handler.request.scope == { "asgi": {"version": "3.0"}, "aws.context": {}, @@ -169,7 +170,15 @@ def test_aws_cf_lambda_at_edge_scope_basic(): "body_base64_encoded,query_string,scope_body", [ ("GET", "/hello/world", None, None, False, b"", None), - ("POST", "/", {"name": ["me"]}, None, False, b"name=me", None), + ( + "POST", + "/", + {"name": ["me"]}, + "field1=value1&field2=value2", + False, + b"name=me", + b"field1=value1&field2=value2", + ), ( "GET", "/my/resource", @@ -241,7 +250,10 @@ def test_aws_api_gateway_scope_real( "type": "http", } - assert handler.body == scope_body + if handler.body: + assert handler.body == scope_body + else: + assert handler.body == b"" @pytest.mark.parametrize( diff --git a/tests/handlers/test_aws_http_gateway.py b/tests/handlers/test_aws_http_gateway.py index 56b9115..4e87f9d 100644 --- a/tests/handlers/test_aws_http_gateway.py +++ b/tests/handlers/test_aws_http_gateway.py @@ -195,6 +195,8 @@ def test_aws_http_gateway_scope_basic_v1(): } example_context = {} handler = AwsHttpGateway(example_event, example_context) + + assert type(handler.body) == bytes assert handler.request.scope == { "asgi": {"version": "3.0"}, "aws.context": {}, @@ -297,6 +299,8 @@ def test_aws_http_gateway_scope_basic_v2(): } example_context = {} handler = AwsHttpGateway(example_event, example_context) + + assert type(handler.body) == bytes assert handler.request.scope == { "asgi": {"version": "3.0"}, "aws.context": {}, @@ -396,7 +400,10 @@ def test_aws_http_gateway_scope_real_v1( "type": "http", } - assert handler.body == scope_body + if handler.body: + assert handler.body == scope_body + else: + assert handler.body == b"" @pytest.mark.parametrize( @@ -461,7 +468,10 @@ def test_aws_http_gateway_scope_real_v2( "type": "http", } - assert handler.body == scope_body + if handler.body: + assert handler.body == scope_body + else: + assert handler.body == b"" @pytest.mark.parametrize(
Bug - handler.body returns a str resulting in TypeError: a bytes-like object is required, not 'str' First this bug was introduced post 0.11.0 when the handlers were refactored. **Traceback** ``` Exception in 'http' protocol. -- Traceback (most recent call last): File "/function/src/mangum/mangum/protocols/http.py", line 81, in run await app(self.request.scope, self.receive, self.send) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/asgi.py", line 149, in __call__ body_file = await self.read_body(receive) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/asgi.py", line 181, in read_body body_file.write(message['body']) File "/usr/lib/python3.8/tempfile.py", line 896, in write rv = file.write(s) TypeError: a bytes-like object is required, not 'str' ``` --- I was able to trace the issue down to the `def body()` method in the handler classes. Adding `assert type(handler.body) == bytes` to the `_basic` tests will reveal the error. ```python handler = AwsAlb(example_event, example_context) > assert type(handler.body) == bytes E AssertionError: assert <class 'str'> == <class 'bytes'> E +<class 'str'> E -<class 'bytes'> ``` In 0.11.0 the body was guaranteed to be bytes because of the following snippet: ```python is_binary = event.get("isBase64Encoded", False) initial_body = event.get("body") or b"" if is_binary: initial_body = base64.b64decode(initial_body) elif not isinstance(initial_body, bytes): # forces strings to be bytes. initial_body = initial_body.encode() ``` For most handlers the refactored code looks like this: ```python @property def body(self) -> bytes: body = self.trigger_event.get("body", b"") if self.trigger_event.get("isBase64Encoded", False): body = base64.b64decode(body) return body ``` If `self.trigger_event` has a `body` key than the body returned will be whatever the type of the value is, which might not be bytes. The solution I believe is to add the code from 0.11.0 to the `body` function.: ```python if not isinstance(body, bytes): body = body.encode() ``` I'll work on updating the tests and putting a PR with the fix if the above seems correct.
0.0
3f312acb67aac30c07dfb305d3cd1881c59755c4
[ "tests/handlers/test_aws_alb.py::test_aws_alb_basic", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_basic", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_cf_lambda_at_edge_scope_basic", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_basic_v1", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_basic_v2", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v1[GET-/my/test/path-None-None-False--None]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v1[GET--query_parameters1-None-False-name=me-None]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v2[GET-/my/test/path-None-None-False--None]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v2[GET--query_parameters1-None-False-name=me-None]" ]
[ "[", "[100%]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_alb.py::test_aws_alb_set_cookies", "tests/handlers/test_aws_alb.py::test_aws_alb_response[GET-text/plain;", "tests/handlers/test_aws_alb.py::test_aws_alb_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_base_path[GET-/test/hello-None-None-False--None]", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_response[GET-text/plain;", "tests/handlers/test_aws_api_gateway.py::test_aws_api_gateway_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_lambda_at_edge_response[GET-text/plain;", "tests/handlers/test_aws_cf_lambda_at_edge.py::test_aws_lambda_at_edge_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_v1_only_non_multi_headers", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_v1_no_headers", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_bad_version", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v1[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v1[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v2[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_scope_real_v2[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v1[GET-text/plain;", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v1[GET-application/json-{\"hello\":", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v1[GET-None-Hello", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v1[GET-None-{\"hello\":", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v1[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v2[GET-text/plain;", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v2[GET-application/json-{\"hello\":", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v2[GET-None-Hello", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v2[GET-None-{\"hello\":", "tests/handlers/test_aws_http_gateway.py::test_aws_http_gateway_response_v2[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-04-15 23:32:53+00:00
mit
3,332
jordaneremieff__mangum-186
diff --git a/mangum/handlers/aws_alb.py b/mangum/handlers/aws_alb.py index 33e0968..6fef8b5 100644 --- a/mangum/handlers/aws_alb.py +++ b/mangum/handlers/aws_alb.py @@ -1,11 +1,30 @@ import base64 import urllib.parse -from typing import Dict, Any +from typing import Any, Dict, Generator, List, Tuple from .abstract_handler import AbstractHandler from .. import Response, Request +def all_casings(input_string: str) -> Generator: + """ + Permute all casings of a given string. + A pretty algoritm, via @Amber + http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python + """ + if not input_string: + yield "" + else: + first = input_string[:1] + if first.lower() == first.upper(): + for sub_casing in all_casings(input_string[1:]): + yield first + sub_casing + else: + for sub_casing in all_casings(input_string[1:]): + yield first.lower() + sub_casing + yield first.upper() + sub_casing + + class AwsAlb(AbstractHandler): """ Handles AWS Elastic Load Balancer, really Application Load Balancer events @@ -66,10 +85,27 @@ class AwsAlb(AbstractHandler): return body - def transform_response(self, response: Response) -> Dict[str, Any]: + def handle_headers( + self, + response_headers: List[List[bytes]], + ) -> Tuple[Dict[str, str], Dict[str, List[str]]]: headers, multi_value_headers = self._handle_multi_value_headers( - response.headers + response_headers ) + if "multiValueHeaders" not in self.trigger_event: + # If there are multiple occurrences of headers, create case-mutated + # variations: https://github.com/logandk/serverless-wsgi/issues/11 + for key, values in multi_value_headers.items(): + if len(values) > 1: + for value, cased_key in zip(values, all_casings(key)): + headers[cased_key] = value + + multi_value_headers = {} + + return headers, multi_value_headers + + def transform_response(self, response: Response) -> Dict[str, Any]: + headers, multi_value_headers = self.handle_headers(response.headers) body, is_base64_encoded = self._handle_base64_response_body( response.body, headers
jordaneremieff/mangum
619790e206be2d4d1e27e878a803e1d33429eea6
diff --git a/tests/handlers/test_aws_alb.py b/tests/handlers/test_aws_alb.py index d922c37..712b52b 100644 --- a/tests/handlers/test_aws_alb.py +++ b/tests/handlers/test_aws_alb.py @@ -5,9 +5,14 @@ from mangum.handlers import AwsAlb def get_mock_aws_alb_event( - method, path, multi_value_query_parameters, body, body_base64_encoded + method, + path, + multi_value_query_parameters, + body, + body_base64_encoded, + multi_value_headers=True, ): - return { + event = { "requestContext": { "elb": { "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a" # noqa: E501 @@ -38,6 +43,10 @@ def get_mock_aws_alb_event( "body": body, "isBase64Encoded": body_base64_encoded, } + if multi_value_headers: + event["multiValueHeaders"] = {} + + return event def test_aws_alb_basic(): @@ -226,7 +235,7 @@ def test_aws_alb_scope_real( assert handler.body == b"" -def test_aws_alb_set_cookies() -> None: +def test_aws_alb_set_cookies_multiValueHeaders() -> None: async def app(scope, receive, send): await send( { @@ -255,6 +264,39 @@ def test_aws_alb_set_cookies() -> None: } +def test_aws_alb_set_cookies_headers() -> None: + async def app(scope, receive, send): + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [b"content-type", b"text/plain; charset=utf-8"], + [b"set-cookie", b"cookie1=cookie1; Secure"], + [b"set-cookie", b"cookie2=cookie2; Secure"], + ], + } + ) + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + handler = Mangum(app, lifespan="off") + event = get_mock_aws_alb_event( + "GET", "/test", {}, None, False, multi_value_headers=False + ) + response = handler(event, {}) + assert response == { + "statusCode": 200, + "isBase64Encoded": False, + "headers": { + "content-type": "text/plain; charset=utf-8", + "set-cookie": "cookie1=cookie1; Secure", + "Set-cookie": "cookie2=cookie2; Secure", + }, + "multiValueHeaders": {}, + "body": "Hello, world!", + } + + @pytest.mark.parametrize( "method,content_type,raw_res_body,res_body,res_base64_encoded", [
0.11.0 Regression - ALB/ELB - Properly handle multiple set cookies in output when multiValueHeaders is not set This is a regression from 0.11.0. The 0.11.0 ALB/ELB code handled when there were multiple set-cookies headers in the response, but multiValueHeaders was not set on the load balancer. ```python if "elb" in event["requestContext"]: for key, value in message.get("headers", []): lower_key = key.decode().lower() if lower_key in multi_value_headers: multi_value_headers[lower_key].append(value.decode()) else: multi_value_headers[lower_key] = [value.decode()] if "multiValueHeaders" not in event: # If there are multiple occurrences of headers, create case-mutated # variations: https://github.com/logandk/serverless-wsgi/issues/11 for key, values in multi_value_headers.items(): if len(values) > 1: for value, cased_key in zip(values, all_casings(key)): headers[cased_key] = value elif len(values) == 1: headers[key] = values[0] multi_value_headers = {} ``` https://github.com/jordaneremieff/mangum/blob/0.11.0/mangum/protocols/http.py#L148-L157 Original issue in serverless-wsgi that this fix is based on: https://github.com/logandk/serverless-wsgi/issues/11. In the recent refactor this case mutation code was removed, resulting in the following bug: Headers returned by asgi application ```python [ (b'Content-Type', b'text/html; charset=utf-8'), (b'Location', b'/app/'), (b'X-Frame-Options', b'DENY'), (b'Vary', b'Cookie'), (b'Content-Length', b'0'), (b'X-Content-Type-Options', b'nosniff'), (b'Referrer-Policy', b'same-origin'), (b'Set-Cookie', b'csrftoken=abc; expires=Fri, 15 Apr 2022 18:44:11 GMT; Max-Age=31449600; Path=/; SameSite=Lax'), (b'Set-Cookie', b'sessionid=xyz; expires=Sat, 17 Apr 2021 18:44:11 GMT; HttpOnly; Max-Age=86400; Path=/; SameSite=Lax') ] ``` Headers returned by mangum ```python { 'content-type': 'text/html; charset=utf-8', 'location': '/app/', 'x-frame-options': 'DENY', 'vary': 'Cookie', 'content-length': '0', 'x-content-type-options': 'nosniff', 'referrer-policy': 'same-origin' } ``` I suggest adding back the original fix if that seems appropriate to the alb handler.
0.0
619790e206be2d4d1e27e878a803e1d33429eea6
[ "tests/handlers/test_aws_alb.py::test_aws_alb_set_cookies_headers" ]
[ "[", "[100%]", "tests/handlers/test_aws_alb.py::test_aws_alb_basic", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_aws_alb.py::test_aws_alb_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_aws_alb.py::test_aws_alb_set_cookies_multiValueHeaders", "tests/handlers/test_aws_alb.py::test_aws_alb_response[GET-text/plain;", "tests/handlers/test_aws_alb.py::test_aws_alb_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-04-18 01:42:12+00:00
mit
3,333
jordaneremieff__mangum-280
diff --git a/docs/external-links.md b/docs/external-links.md index fab77ec..2dc4f91 100644 --- a/docs/external-links.md +++ b/docs/external-links.md @@ -2,6 +2,7 @@ External links related to using Mangum. -- [Deploying Python web apps as AWS Lambda functions](https://til.simonwillison.net/awslambda/asgi-mangum) is a tutorial that goes through every step involved in packaging and deploying a Python web application to AWS Lambda, including how to use Mangum to wrap an ASGI application. +- [Deploying Python web apps as AWS Lambda functions](https://til.simonwillison.net/awslambda/asgi-mangum) is a tutorial that goes through every step involved in packaging and deploying a Python web application to AWS Lambda, including how to use Mangum to wrap an ASGI application. +- [Deploy FastAPI applications to AWS Lambda](https://aminalaee.dev/posts/2022/fastapi-aws-lambda/) is a quick tutorial about how to deploy FastAPI and Starlette applications to AWS Lambda using Mangum, including also a suggested approach by AWS about how to manage larger applications. If you're interested in contributing to this page, please reference this [issue](https://github.com/jordaneremieff/mangum/issues/104) in a PR. diff --git a/mangum/adapter.py b/mangum/adapter.py index 31d2d1f..bb99cfb 100644 --- a/mangum/adapter.py +++ b/mangum/adapter.py @@ -44,6 +44,7 @@ class Mangum: api_gateway_base_path: str = "/", custom_handlers: Optional[List[Type[LambdaHandler]]] = None, text_mime_types: Optional[List[str]] = None, + exclude_headers: Optional[List[str]] = None, ) -> None: if lifespan not in ("auto", "on", "off"): raise ConfigurationError( @@ -53,9 +54,11 @@ class Mangum: self.app = app self.lifespan = lifespan self.custom_handlers = custom_handlers or [] + exclude_headers = exclude_headers or [] self.config = LambdaConfig( api_gateway_base_path=api_gateway_base_path or "/", text_mime_types=text_mime_types or [*DEFAULT_TEXT_MIME_TYPES], + exclude_headers=[header.lower() for header in exclude_headers], ) def infer(self, event: LambdaEvent, context: LambdaContext) -> LambdaHandler: diff --git a/mangum/handlers/alb.py b/mangum/handlers/alb.py index 41378ed..875c4ee 100644 --- a/mangum/handlers/alb.py +++ b/mangum/handlers/alb.py @@ -5,6 +5,7 @@ from urllib.parse import urlencode, unquote, unquote_plus from mangum.handlers.utils import ( get_server_and_port, handle_base64_response_body, + handle_exclude_headers, maybe_encode_body, ) from mangum.types import ( @@ -166,8 +167,10 @@ class ALB: # headers otherwise. multi_value_headers_enabled = "multiValueHeaders" in self.scope["aws.event"] if multi_value_headers_enabled: - out["multiValueHeaders"] = multi_value_headers + out["multiValueHeaders"] = handle_exclude_headers( + multi_value_headers, self.config + ) else: - out["headers"] = finalized_headers + out["headers"] = handle_exclude_headers(finalized_headers, self.config) return out diff --git a/mangum/handlers/api_gateway.py b/mangum/handlers/api_gateway.py index bd58a7d..d9b30c0 100644 --- a/mangum/handlers/api_gateway.py +++ b/mangum/handlers/api_gateway.py @@ -4,6 +4,7 @@ from urllib.parse import urlencode from mangum.handlers.utils import ( get_server_and_port, handle_base64_response_body, + handle_exclude_headers, handle_multi_value_headers, maybe_encode_body, strip_api_gateway_path, @@ -120,8 +121,10 @@ class APIGateway: return { "statusCode": response["status"], - "headers": finalized_headers, - "multiValueHeaders": multi_value_headers, + "headers": handle_exclude_headers(finalized_headers, self.config), + "multiValueHeaders": handle_exclude_headers( + multi_value_headers, self.config + ), "body": finalized_body, "isBase64Encoded": is_base64_encoded, } diff --git a/mangum/handlers/lambda_at_edge.py b/mangum/handlers/lambda_at_edge.py index 6737967..89a3709 100644 --- a/mangum/handlers/lambda_at_edge.py +++ b/mangum/handlers/lambda_at_edge.py @@ -2,6 +2,7 @@ from typing import Dict, List from mangum.handlers.utils import ( handle_base64_response_body, + handle_exclude_headers, handle_multi_value_headers, maybe_encode_body, ) @@ -88,7 +89,7 @@ class LambdaAtEdge: return { "status": response["status"], - "headers": finalized_headers, + "headers": handle_exclude_headers(finalized_headers, self.config), "body": response_body, "isBase64Encoded": is_base64_encoded, } diff --git a/mangum/handlers/utils.py b/mangum/handlers/utils.py index c1cce0b..7e3e7b3 100644 --- a/mangum/handlers/utils.py +++ b/mangum/handlers/utils.py @@ -1,8 +1,8 @@ import base64 -from typing import Dict, List, Tuple, Union +from typing import Any, Dict, List, Tuple, Union from urllib.parse import unquote -from mangum.types import Headers +from mangum.types import Headers, LambdaConfig def maybe_encode_body(body: Union[str, bytes], *, is_base64: bool) -> bytes: @@ -81,3 +81,15 @@ def handle_base64_response_body( is_base64_encoded = True return output_body, is_base64_encoded + + +def handle_exclude_headers( + headers: Dict[str, Any], config: LambdaConfig +) -> Dict[str, Any]: + finalized_headers = {} + for header_key, header_value in headers.items(): + if header_key in config["exclude_headers"]: + continue + finalized_headers[header_key] = header_value + + return finalized_headers diff --git a/mangum/types.py b/mangum/types.py index b50b0b2..0ff436c 100644 --- a/mangum/types.py +++ b/mangum/types.py @@ -117,6 +117,7 @@ class Response(TypedDict): class LambdaConfig(TypedDict): api_gateway_base_path: str text_mime_types: List[str] + exclude_headers: List[str] class LambdaHandler(Protocol):
jordaneremieff/mangum
20653dc0dddb6eecfe4a8cef8ad3edcdc174d4b4
diff --git a/tests/handlers/test_alb.py b/tests/handlers/test_alb.py index 3804f9d..e75d2d9 100644 --- a/tests/handlers/test_alb.py +++ b/tests/handlers/test_alb.py @@ -372,3 +372,40 @@ def test_aws_alb_response_extra_mime_types(): "headers": {"content-type": content_type.decode()}, "body": utf_res_body, } + + [email protected]("multi_value_headers_enabled", (True, False)) +def test_aws_alb_exclude_headers(multi_value_headers_enabled) -> None: + async def app(scope, receive, send): + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [b"content-type", b"text/plain; charset=utf-8"], + [b"x-custom-header", b"test"], + ], + } + ) + await send({"type": "http.response.body", "body": b"Hello, world!"}) + + handler = Mangum(app, lifespan="off", exclude_headers=["x-custom-header"]) + event = get_mock_aws_alb_event( + "GET", "/test", {}, None, None, False, multi_value_headers_enabled + ) + response = handler(event, {}) + + expected_response = { + "statusCode": 200, + "isBase64Encoded": False, + "body": "Hello, world!", + } + if multi_value_headers_enabled: + expected_response["multiValueHeaders"] = { + "content-type": ["text/plain; charset=utf-8"], + } + else: + expected_response["headers"] = { + "content-type": "text/plain; charset=utf-8", + } + assert response == expected_response diff --git a/tests/handlers/test_api_gateway.py b/tests/handlers/test_api_gateway.py index 1231bb0..e2458c2 100644 --- a/tests/handlers/test_api_gateway.py +++ b/tests/handlers/test_api_gateway.py @@ -401,3 +401,31 @@ def test_aws_api_gateway_response_extra_mime_types(): "multiValueHeaders": {}, "body": utf_res_body, } + + +def test_aws_api_gateway_exclude_headers(): + async def app(scope, receive, send): + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [b"content-type", b"text/plain; charset=utf-8"], + [b"x-custom-header", b"test"], + ], + } + ) + await send({"type": "http.response.body", "body": b"Hello world"}) + + event = get_mock_aws_api_gateway_event("GET", "/test", {}, None, False) + + handler = Mangum(app, lifespan="off", exclude_headers=["X-CUSTOM-HEADER"]) + + response = handler(event, {}) + assert response == { + "statusCode": 200, + "isBase64Encoded": False, + "headers": {"content-type": b"text/plain; charset=utf-8".decode()}, + "multiValueHeaders": {}, + "body": "Hello world", + } diff --git a/tests/handlers/test_lambda_at_edge.py b/tests/handlers/test_lambda_at_edge.py index ffeb9bc..563e144 100644 --- a/tests/handlers/test_lambda_at_edge.py +++ b/tests/handlers/test_lambda_at_edge.py @@ -342,3 +342,34 @@ def test_aws_lambda_at_edge_response_extra_mime_types(): }, "body": utf_res_body, } + + +def test_aws_lambda_at_edge_exclude_(): + async def app(scope, receive, send): + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [b"content-type", b"text/plain; charset=utf-8"], + [b"x-custom-header", b"test"], + ], + } + ) + await send({"type": "http.response.body", "body": b"Hello world"}) + + event = mock_lambda_at_edge_event("GET", "/test", {}, None, False) + + handler = Mangum(app, lifespan="off", exclude_headers=["x-custom-header"]) + + response = handler(event, {}) + assert response == { + "status": 200, + "isBase64Encoded": False, + "headers": { + "content-type": [ + {"key": "content-type", "value": b"text/plain; charset=utf-8".decode()} + ] + }, + "body": "Hello world", + } diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 6b50fd6..de36049 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -14,6 +14,7 @@ def test_default_settings(): assert handler.lifespan == "auto" assert handler.config["api_gateway_base_path"] == "/" assert sorted(handler.config["text_mime_types"]) == sorted(DEFAULT_TEXT_MIME_TYPES) + assert handler.config["exclude_headers"] == [] @pytest.mark.parametrize(
Allow Mangum to remove certain aws reponse headers from api gateway response Problem: Currently `Mangum` injects the following headers in the api gateway response for an aws lambda integration ``` x-amz-apigw-id x-amzn-requestid x-amzn-trace-id ``` This exposes additional information that the client doesn't need to know. Proposal: Allow Mangum to take optional parameter say `exclude_header_keys=[]` at the application mounting step. An Example of that would look like. ```python from fastapi import FastAPI app = FastAPI() handler = Mangum(app, exclude_header_keys=[] ```
0.0
20653dc0dddb6eecfe4a8cef8ad3edcdc174d4b4
[ "tests/handlers/test_alb.py::test_aws_alb_exclude_headers[True]", "tests/handlers/test_alb.py::test_aws_alb_exclude_headers[False]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_exclude_headers", "tests/handlers/test_lambda_at_edge.py::test_aws_lambda_at_edge_exclude_", "tests/test_adapter.py::test_default_settings" ]
[ "[", "tests/handlers/test_alb.py::test_aws_alb_scope_real[GET-/hello/world-None-None-None-False--None-False]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[GET-/lambda-query_parameters1-None--False-q1=1234ABCD&q2=b+c&q3=b+c&q4=%2Fsome%2Fpath%2F&q5=%2Fsome%2Fpath%2F--False]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[POST-/-query_parameters2-None-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2-False]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[POST-/-query_parameters3-None-None-False-name=you-None-False]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[GET-/my/resource-query_parameters4-None-None-False-name=me&name=you-None-True]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[GET--query_parameters5-None-None-False-name=me&name=you&pet=dog-None-True]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[POST-/img-None-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-False]", "tests/handlers/test_alb.py::test_aws_alb_scope_real[POST-/form-submit-None-None-say=Hi&to=Mom-False--say=Hi&to=Mom-False]", "tests/handlers/test_alb.py::test_aws_alb_set_cookies[True]", "tests/handlers/test_alb.py::test_aws_alb_set_cookies[False]", "tests/handlers/test_alb.py::test_aws_alb_response[GET-text/plain;", "tests/handlers/test_alb.py::test_aws_alb_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_alb.py::test_aws_alb_response_extra_mime_types", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_basic", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_base_path[GET-/test/hello-None-None-False--None]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_response[GET-text/plain;", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_api_gateway.py::test_aws_api_gateway_response_extra_mime_types", "tests/handlers/test_lambda_at_edge.py::test_aws_cf_lambda_at_edge_scope_basic", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET-/hello/world-None-None-False--None]", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/-multi_value_query_parameters1-field1=value1&field2=value2-False-name=me-field1=value1&field2=value2]", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET-/my/resource-multi_value_query_parameters2-None-False-name=me&name=you-None]", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[GET--multi_value_query_parameters3-None-False-name=me&name=you&pet=dog-None]", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/img-None-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True--GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;]", "tests/handlers/test_lambda_at_edge.py::test_aws_api_gateway_scope_real[POST-/form-submit-None-say=Hi&to=Mom-False--say=Hi&to=Mom]", "tests/handlers/test_lambda_at_edge.py::test_aws_lambda_at_edge_response[GET-text/plain;", "tests/handlers/test_lambda_at_edge.py::test_aws_lambda_at_edge_response[POST-image/gif-GIF87a\\x01\\x00\\x01\\x00\\x80\\x01\\x00\\xff\\x00\\x00\\x00\\x00\\x00,\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02\\x02D\\x01\\x00;-R0lGODdhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=-True]", "tests/handlers/test_lambda_at_edge.py::test_aws_lambda_at_edge_response_extra_mime_types", "tests/test_adapter.py::test_invalid_options[arguments0-Invalid" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-11-07 07:12:30+00:00
mit
3,334