rover: use Pydantic for Vector and Rover classes

Pydantic is similar to Dataclasses, but enables run-time type-checking.
This commit is contained in:
Bruno BELANYI 2019-11-15 21:04:16 +01:00
parent 0f1b861eee
commit add6940dce
4 changed files with 28 additions and 15 deletions

View file

@ -8,6 +8,7 @@ pytest = "*"
pytest-cov = "*" pytest-cov = "*"
[packages] [packages]
pydantic = "*"
[requires] [requires]
python_version = "3.8" python_version = "3.8"

17
rover/Pipfile.lock generated
View file

@ -1,7 +1,7 @@
{ {
"_meta": { "_meta": {
"hash": { "hash": {
"sha256": "4e6c8e77ff1a48b470f5c8aa479b97d87225ac2cd2fb9b9f9ebceae1713e3adb" "sha256": "afeb69259202b698c70d288232d6bd89a36b75720f9efeb8f0360d5f8a5217dd"
}, },
"pipfile-spec": 6, "pipfile-spec": 6,
"requires": { "requires": {
@ -15,7 +15,20 @@
} }
] ]
}, },
"default": {}, "default": {
"pydantic": {
"hashes": [
"sha256:2588e5c68b7927fd44c4bf2c5768cdaff7948fc4ae0e3f602376b76b1913c3b0",
"sha256:2d8d8c14b6349066e27aca9bfd3fb973fb2c45a860a6ba83fbea16ee42efbfd1",
"sha256:40b62f5e8db4957221e4aa06cea015c4a74740405edea0e11def4c6418e7c62c",
"sha256:43f8ac74e114aaac0d844040fea971fc6c53434f24cee2e1aa0486e6601817b4",
"sha256:4f3baf0b4ef8f68021186448efddbcc259ed473e18acf4433ef75dd13d795594",
"sha256:f85a63028003d8778dc3bf27c5c5cd25da64593422ab82a696cca32b1ce3e750"
],
"index": "pypi",
"version": "==1.1"
}
},
"develop": { "develop": {
"atomicwrites": { "atomicwrites": {
"hashes": [ "hashes": [

View file

@ -1,11 +1,11 @@
import enum import enum
from dataclasses import dataclass
from pydantic import BaseModel
@dataclass class Vector(BaseModel):
class Vector: x: int = 0
x: int y: int = 0
y: int
class Direction(enum.Enum): class Direction(enum.Enum):
@ -15,8 +15,7 @@ class Direction(enum.Enum):
WEST = "W" WEST = "W"
@dataclass class Rover(BaseModel):
class Rover: pos: Vector = Vector(x=0, y=0)
pos: Vector = (0, 0) planet_size: Vector = Vector(x=100, y=100)
planet_size: Vector = (100, 100)
dir: Direction = Direction.NORTH dir: Direction = Direction.NORTH

View file

@ -1,14 +1,14 @@
from rover import Direction, Rover from rover import Direction, Rover, Vector
def test_rover_constructor(): def test_rover_constructor():
rov = Rover(pos=(0, 0), planet_size=(100, 100)) rov = Rover(pos={"x": 0, "y": 0}, planet_size={"x": 100, "y": 100})
assert rov.pos == (0, 0) and rov.planet_size == (100, 100) assert rov.pos == Vector(x=0, y=0) and rov.planet_size == Vector(x=100, y=100)
def test_rover_default_values(): def test_rover_default_values():
rov = Rover() rov = Rover()
assert rov.pos == (0, 0) and rov.planet_size == (100, 100) assert rov.pos == Vector(x=0, y=0) and rov.planet_size == Vector(x=100, y=100)
def test_rover_has_direction(): def test_rover_has_direction():