Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix zero division error #2674

Merged
merged 2 commits into from
May 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## Unreleased


### Fixed

- Fixed zero division error https://github.com/Textualize/textual/issues/2673

### Added

- `work` decorator accepts `description` parameter to add debug string https://github.com/Textualize/textual/issues/2597
Expand Down
6 changes: 4 additions & 2 deletions src/textual/_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ def resolve_fraction_unit(
if not remaining_space or not widget_styles:
return Fraction(1)

initial_space = remaining_space

def resolve_scalar(
scalar: Scalar | None, fraction_unit: Fraction = Fraction(1)
) -> Fraction | None:
Expand Down Expand Up @@ -166,8 +168,8 @@ def resolve_scalar(

return (
Fraction(remaining_space, remaining_fraction)
if remaining_space > 0
else Fraction(1)
if remaining_fraction > 0
else initial_space
)


Expand Down
25 changes: 25 additions & 0 deletions tests/test_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from textual._resolve import resolve, resolve_fraction_unit
from textual.css.scalar import Scalar
from textual.css.styles import Styles
from textual.geometry import Size
from textual.widget import Widget

Expand Down Expand Up @@ -125,6 +126,30 @@ def test_resolve_fraction_unit():
) == Fraction(2)


def test_resolve_fraction_unit_stress_test():
"""Check for zero division errors."""
# https://github.com/Textualize/textual/issues/2673
widget = Widget()
styles = widget.styles
styles.width = "1fr"

# We're mainly checking for the absence of zero division errors,
# which is a reoccurring theme for this code.
for remaining_space in range(1, 101, 10):
for max_width in range(1, remaining_space):
styles.max_width = max_width

for width in range(1, remaining_space):
resolved_unit = resolve_fraction_unit(
[styles, styles, styles],
Size(width, 24),
Size(width, 24),
Fraction(remaining_space),
"width",
)
assert resolved_unit <= remaining_space


def test_resolve_issue_2502():
"""Test https://github.com/Textualize/textual/issues/2502"""

Expand Down