22import pytest
33from pydantic import BaseModel , ValidationError
44
5- from pydantic_extra_types .pendulum_dt import Date , DateTime
5+ from pydantic_extra_types .pendulum_dt import Date , DateTime , Duration
66
77
88class DtModel (BaseModel ):
@@ -13,6 +13,10 @@ class DateModel(BaseModel):
1313 d : Date
1414
1515
16+ class DurationModel (BaseModel ):
17+ delta_t : Duration
18+
19+
1620def test_pendulum_dt_existing_instance ():
1721 """
1822 Verifies that constructing a model with an existing pendulum dt doesn't throw.
@@ -31,8 +35,23 @@ def test_pendulum_date_existing_instance():
3135 assert model .d == today
3236
3337
38+ def test_pendulum_duration_existing_instance ():
39+ """
40+ Verifies that constructing a model with an existing pendulum duration doesn't throw.
41+ """
42+ delta_t = pendulum .duration (days = 42 , hours = 13 , minutes = 37 )
43+ model = DurationModel (delta_t = delta_t )
44+
45+ assert model .delta_t .total_seconds () == delta_t .total_seconds ()
46+
47+
3448@pytest .mark .parametrize (
35- 'dt' , [pendulum .now ().to_iso8601_string (), pendulum .now ().to_w3c_string (), pendulum .now ().to_iso8601_string ()]
49+ 'dt' ,
50+ [
51+ pendulum .now ().to_iso8601_string (),
52+ pendulum .now ().to_w3c_string (),
53+ pendulum .now ().to_iso8601_string (),
54+ ],
3655)
3756def test_pendulum_dt_from_serialized (dt ):
3857 """
@@ -52,6 +71,25 @@ def test_pendulum_date_from_serialized():
5271 assert model .d == date_actual
5372
5473
74+ @pytest .mark .parametrize (
75+ 'delta_t_str' ,
76+ [
77+ 'P3.14D' ,
78+ 'PT404H' ,
79+ 'P1DT25H' ,
80+ 'P2W' ,
81+ 'P10Y10M10D' ,
82+ ],
83+ )
84+ def test_pendulum_duration_from_serialized (delta_t_str ):
85+ """
86+ Verifies that building an instance from serialized, well-formed strings decode properly.
87+ """
88+ true_delta_t = pendulum .parse (delta_t_str )
89+ model = DurationModel (delta_t = delta_t_str )
90+ assert model .delta_t == true_delta_t
91+
92+
5593@pytest .mark .parametrize ('dt' , [None , 'malformed' , pendulum .now ().to_iso8601_string ()[:5 ], 42 ])
5694def test_pendulum_dt_malformed (dt ):
5795 """
@@ -68,3 +106,15 @@ def test_pendulum_date_malformed(date):
68106 """
69107 with pytest .raises (ValidationError ):
70108 DateModel (d = date )
109+
110+
111+ @pytest .mark .parametrize (
112+ 'delta_t' ,
113+ [None , 'malformed' , pendulum .today ().to_iso8601_string ()[:5 ], 42 , '12m' ],
114+ )
115+ def test_pendulum_duration_malformed (delta_t ):
116+ """
117+ Verifies that the instance fails to validate if malformed durations are passed.
118+ """
119+ with pytest .raises (ValidationError ):
120+ DurationModel (delta_t = delta_t )
0 commit comments