rover: add non-oversize position validation
This commit is contained in:
parent
1fbf7ece7c
commit
39d1fcd5ac
|
@ -2,7 +2,7 @@ import enum
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from pydantic import BaseModel, validator
|
from pydantic import BaseModel, root_validator, validator
|
||||||
|
|
||||||
|
|
||||||
class Vector(BaseModel):
|
class Vector(BaseModel):
|
||||||
|
@ -41,6 +41,19 @@ class Rover(BaseModel):
|
||||||
planet_size: Vector = Vector(x=100, y=100)
|
planet_size: Vector = Vector(x=100, y=100)
|
||||||
dir: Direction = Direction.NORTH
|
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):
|
def _translate(self, value):
|
||||||
if self.dir == Direction.NORTH:
|
if self.dir == Direction.NORTH:
|
||||||
self.pos.y += value
|
self.pos.y += value
|
||||||
|
|
|
@ -237,3 +237,13 @@ def test_rover_negative_x_construction():
|
||||||
def test_rover_negative_y_construction():
|
def test_rover_negative_y_construction():
|
||||||
with pytest.raises(ValidationError):
|
with pytest.raises(ValidationError):
|
||||||
_ = Rover(pos=Vector(x=0, y=-1))
|
_ = 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))
|
||||||
|
|
Loading…
Reference in a new issue