Skip to content

Commit

Permalink
Merge pull request #81 from nbraud/hypothesis/scale_to
Browse files Browse the repository at this point in the history
Vector2.scale_to: Add Hypothesis tests, fix exposed bugs
  • Loading branch information
AstraLuma authored Dec 9, 2018
2 parents 47be1bf + 1b003f2 commit 513be47
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 32 deletions.
9 changes: 4 additions & 5 deletions ppb_vector/vector2.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,11 +269,10 @@ def scale_to(self: VectorOrSub, length: Realish) -> VectorOrSub:
"""
Scale the vector to the given length
"""
try:
scale = length / self.length
except ZeroDivisionError:
scale = 1
return self.scale_by(scale)
if length < 0:
raise ValueError("Vector2.scale_to takes non-negative lengths.")

return (length / self.length) * self

scale = scale_to

Expand Down
15 changes: 7 additions & 8 deletions tests/test_vector2_normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
import ppb_vector


@pytest.mark.parametrize("x, y, expected", [
(3, 4, 1),
(6, 8, 1),
(0, 1, 1),
(1, 0, 1),
(0, 0, 0)
@pytest.mark.parametrize("x, y", [
(3, 4),
(6, 8),
(0, 1),
(1, 0),
])
def test_normalize(x, y, expected):
def test_normalize(x, y):
vector = ppb_vector.Vector2(x, y).normalize()
assert vector.length == expected
assert vector.length == 1
39 changes: 20 additions & 19 deletions tests/test_vector2_scale.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import pytest # type: ignore
from math import hypot
from hypothesis import assume, given
from hypothesis.strategies import floats
from math import isclose
from utils import vectors

from ppb_vector import Vector2


@pytest.fixture()
def vector():
return Vector2(10, 20)
@given(x=vectors(), l=floats(min_value=-1e150, max_value=1e150))
def test_scale_to_length(x: Vector2, l: float):
"""Test that the length of x.scale_to(l) is l."""
try:
assert isclose(x.scale_to(l).length, l)
except ZeroDivisionError:
assert x == (0, 0)
except ValueError:
assert l < 0


def test_calculate_scale(vector):
x, y = 10, 20
length = hypot(x, y)
scale = 4
vector_scale_calculated = vector * (scale / length)
assert vector.scale(scale) == vector_scale_calculated


def test_scale_is_equivalent_to_truncate():
"""
Vector2.scale is equivalent to Vector2.truncate
when scalar is less than length
@given(x=vectors(), l=floats(min_value=1e150, max_value=1e150))
def test_scale_is_equivalent_to_truncate(x: Vector2, l: float):
"""
Vector2.scale_to is equivalent to Vector2.truncate
when the scalar is less than length
"""
vector_scale = Vector2(3, 4).scale(4)
vector_truncate = Vector2(3, 4).truncate(4)
assert vector_scale == vector_truncate
assume(l <= x.length)
assert x.scale_to(l) == x.truncate(l)

0 comments on commit 513be47

Please sign in to comment.