Skip to content

Commit 56d2432

Browse files
author
Henry Walshaw
committed
Add a failing test for computed properties on export
1 parent 3afc80f commit 56d2432

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

tests/models.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Optional
33

44
import pydantic
5-
from pydantic import Field
5+
from pydantic import Field, computed_field
66

77

88
class User(pydantic.BaseModel):
@@ -56,3 +56,19 @@ def parse_end_date(cls, value):
5656
class ExcludedPassword(pydantic.BaseModel):
5757
username: str = "Wagstaff"
5858
password: str = Field(default="swordfish", exclude=True)
59+
60+
61+
class ComputedPropertyField(pydantic.BaseModel):
62+
username: str = "Groucho"
63+
64+
@computed_field
65+
def email(self) -> str:
66+
return f"{self.username.lower()}@marx.bros"
67+
68+
69+
class ComputedPropertyWithAlias(pydantic.BaseModel):
70+
username: str = "Harpo"
71+
72+
@computed_field(alias="e")
73+
def email(self) -> str:
74+
return f"{self.username.lower()}@marx.bros"

tests/test_basemodel_csv_writer.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,14 @@
44

55
from pydantic_csv import BasemodelCSVWriter
66

7-
from .models import ExcludedPassword, NonBaseModelUser, SimpleUser, User
7+
from .models import (
8+
ComputedPropertyField,
9+
ComputedPropertyWithAlias,
10+
ExcludedPassword,
11+
NonBaseModelUser,
12+
SimpleUser,
13+
User,
14+
)
815

916

1017
def test_create_csv_file(users_as_csv_buffer, users_from_csv):
@@ -60,3 +67,22 @@ def test_excluded_field():
6067
w.write()
6168

6269
assert output.getvalue() == "username\r\nWagstaff\r\n"
70+
71+
72+
@pytest.mark.parametrize(
73+
("model", "use_alias", "expected_output"),
74+
[
75+
(ComputedPropertyField, True, "username,email\r\nGroucho,[email protected]\r\n"),
76+
(ComputedPropertyWithAlias, True, "username,e\r\nHarpo,[email protected]\r\n"),
77+
(ComputedPropertyField, False, "username,email\r\nGroucho,[email protected]\r\n"),
78+
(ComputedPropertyWithAlias, False, "username,email\r\nHarpo,[email protected]\r\n"),
79+
],
80+
)
81+
def test_computed_property_included(model, use_alias, expected_output):
82+
output = io.StringIO()
83+
user = model()
84+
85+
w = BasemodelCSVWriter(output, [user], model, use_alias=use_alias)
86+
w.write()
87+
88+
assert output.getvalue() == expected_output

0 commit comments

Comments
 (0)