Pluralize filter sometimes returns singular form instead of an empty string for invalid inputs
|Reported by:||Aymeric Augustin||Owned by:||Jorge C. Leitão|
|Cc:||Jorge C. Leitão||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||yes||Patch needs improvement:||yes|
Filters are documented to return either their input unchanged, or the empty string, whatever makes most sense, when they're used incorrectly. The
pluralize filter returns the empty string in such cases, for instance when it receives more than two forms (singular, plural).
However, it returns the singular form instead of the empty string when it's passed an object that isn't a number, a string or a list.
Failing test case:
--- a/tests/defaultfilters/tests.py +++ b/tests/defaultfilters/tests.py @@ -622,6 +622,9 @@ class DefaultFiltersTests(TestCase): self.assertEqual(pluralize(2,'y,ies'), 'ies') self.assertEqual(pluralize(0,'y,ies,error'), '') + def test_pluralize_error(self): + self.assertEqual(pluralize(object, 'y,ies'), '') + def test_phone2numeric(self): self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
I understand that the implementation is crafted to avoid
isinstance checks, but in this case we really want different logic depending on the type of the input. I think the filter should be rewritten with the following pseudo-code:
if the value is a number: return singular if value is 1 else plural if the value is a string: return singular if value is '1' else plural if the value has a length (needs a try/except TypeError): return singular if length is 1 else plural return ''
I discovered this while working on #16723.
Change History (7)
comment:3 Changed 4 years ago by
|Cc:||Jorge C. Leitão added|
|Owner:||changed from nobody to Jorge C. Leitão|
|Status:||new → assigned|