From 1fbf7ece7c709eb39dc8d064ca438ce9001d8da0 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 16 Nov 2019 04:24:02 +0100 Subject: [PATCH] rover: add non-negative coordinate validation --- rover/rover.py | 14 +++++++++++++- rover/test_rover.py | 12 ++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/rover/rover.py b/rover/rover.py index 2cf29e9..56d4453 100644 --- a/rover/rover.py +++ b/rover/rover.py @@ -2,13 +2,25 @@ import enum from copy import deepcopy from typing import List -from pydantic import BaseModel +from pydantic import BaseModel, validator class Vector(BaseModel): x: int = 0 y: int = 0 + @validator("x") + def _x_must_be_positive(x): + if x < 0: + raise ValueError("x must be positive") + return x + + @validator("y") + def _y_must_be_positive(y): + if y < 0: + raise ValueError("y must be positive") + return y + class Direction(enum.Enum): NORTH = "N" diff --git a/rover/test_rover.py b/rover/test_rover.py index 99e886d..9b92447 100644 --- a/rover/test_rover.py +++ b/rover/test_rover.py @@ -1,4 +1,6 @@ import pytest +from pydantic import ValidationError + from rover import Commander, Direction, ObstacleError, Rover, Vector @@ -225,3 +227,13 @@ def test_commander_command_with_obstacles(): with pytest.raises(ObstacleError): com.parse_execute("FFRF") assert com.rover == Rover(pos=Vector(x=0, y=2), dir=Direction.EAST) + + +def test_rover_negative_x_construction(): + with pytest.raises(ValidationError): + _ = Rover(pos=Vector(x=-1, y=0)) + + +def test_rover_negative_y_construction(): + with pytest.raises(ValidationError): + _ = Rover(pos=Vector(x=0, y=-1))