diff --git a/rover/rover.py b/rover/rover.py index 56d4453..e49843e 100644 --- a/rover/rover.py +++ b/rover/rover.py @@ -2,7 +2,7 @@ import enum from copy import deepcopy from typing import List -from pydantic import BaseModel, validator +from pydantic import BaseModel, root_validator, validator class Vector(BaseModel): @@ -41,6 +41,19 @@ class Rover(BaseModel): planet_size: Vector = Vector(x=100, y=100) dir: Direction = Direction.NORTH + @root_validator() + def _validate_pos(cls, values) -> None: + pos, planet_size = values.get("pos"), values.get("planet_size") + if pos.x > planet_size.x: + raise ValueError( + f"pos.x (= {pos.x}) should be under planet_size.x (= {planet_size.x})" + ) + if pos.y > planet_size.y: + raise ValueError( + f"pos.y (= {pos.y}) should be under planet_size.y (= {planet_size.y})" + ) + return values + def _translate(self, value): if self.dir == Direction.NORTH: self.pos.y += value diff --git a/rover/test_rover.py b/rover/test_rover.py index 9b92447..2264006 100644 --- a/rover/test_rover.py +++ b/rover/test_rover.py @@ -237,3 +237,13 @@ def test_rover_negative_x_construction(): def test_rover_negative_y_construction(): with pytest.raises(ValidationError): _ = Rover(pos=Vector(x=0, y=-1)) + + +def test_rover_oversize_x_construction(): + with pytest.raises(ValidationError): + _ = Rover(pos=Vector(x=11, y=0), planet_size=Vector(x=10, y=10)) + + +def test_rover_oversize_y_construction(): + with pytest.raises(ValidationError): + _ = Rover(pos=Vector(x=0, y=11), planet_size=Vector(x=10, y=10))