|
1 |
| -from typing import List, Optional |
| 1 | +from typing import List, Optional, Literal |
2 | 2 |
|
3 | 3 | import pytest
|
4 | 4 | from sqlalchemy.exc import IntegrityError
|
@@ -125,3 +125,26 @@ class Hero(SQLModel, table=True):
|
125 | 125 | # The next statement should not raise an AttributeError
|
126 | 126 | assert hero_rusty_man.team
|
127 | 127 | assert hero_rusty_man.team.name == "Preventers"
|
| 128 | + |
| 129 | + |
| 130 | +def test_literal_typehints_are_treated_as_strings(clear_sqlmodel): |
| 131 | + """Test https://github.com/fastapi/sqlmodel/issues/57""" |
| 132 | + |
| 133 | + class Hero(SQLModel, table=True): |
| 134 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 135 | + name: str = Field(unique=True) |
| 136 | + weakness: Literal["Kryptonite", "Dehydration", "Munchies"] |
| 137 | + |
| 138 | + |
| 139 | + superman = Hero(name="Superman", weakness="Kryptonite") |
| 140 | + |
| 141 | + engine = create_engine("sqlite://", echo=True) |
| 142 | + |
| 143 | + SQLModel.metadata.create_all(engine) |
| 144 | + |
| 145 | + with Session(engine) as session: |
| 146 | + session.add(superman) |
| 147 | + session.commit() |
| 148 | + session.refresh(superman) |
| 149 | + assert superman.weakness == "Kryptonite" |
| 150 | + assert isinstance(superman.weakness, str) |
0 commit comments