pydantic / pydantic-extra-types

Extra Pydantic types.
MIT License
181 stars 48 forks source link

chore(feat): Support Money as Type #22

Closed yezz123 closed 1 year ago

yezz123 commented 1 year ago
from pydantic import BaseModel, ValidationError
from pydantic_extra_types import CurrencyCode
import pytest

class Product(BaseModel):
    name: str
    price: float
    code: CurrencyCode

example = [
     {
          "name": "Apple",
          "price": 1.99,
          "code": "USD"
     },
     {
          "name": "Banana",
          "price": 2.99,
          "code": "EUR"
     },
     {
          "name": "Orange",
          "price": 3.99,
          "code": "GBP"
     },
     {
          "name": "Pineapple",
          "price": 4.99,
          "code": "Us"
     },
]

assert Product(**example[0]).code == "USD"
assert Product(**example[1]).code == "EUR"
assert Product(**example[2]).code == "GBP"

def test_invalid():
     with pytest.raises(ValidationError):
          Product(**example[3])

print(f"This currency code is not valide: {example[3]['code']}")

cc @samuelcolvin this following one also ready for review 👍🏻

yezz123 commented 1 year ago

Similar to this one's logic https://github.com/pydantic/pydantic-extra-types/pull/14

yezz123 commented 1 year ago

I will close this and support pycountry as we have currencies also supported