|
| 1 | +import re |
1 | 2 | from enum import Enum |
2 | 3 | from typing import Dict, Optional |
3 | 4 |
|
| 5 | +import pytest |
4 | 6 | from sqlalchemy.orm.collections import attribute_keyed_dict |
5 | 7 | from sqlmodel import Field, Relationship, Session, SQLModel, create_engine |
6 | 8 |
|
@@ -43,3 +45,46 @@ class Parent(SQLModel, table=True): |
43 | 45 | assert parent.children_by_color[Color.Blue].parent_id == parent.id |
44 | 46 | assert parent.children_by_color[Color.Blue].color == Color.Blue |
45 | 47 | assert parent.children_by_color[Color.Blue].value == 2 |
| 48 | + |
| 49 | + |
| 50 | +def test_dict_relationship_throws_on_missing_annotation_arg(clear_sqlmodel): |
| 51 | + class Color(str, Enum): |
| 52 | + Orange = "Orange" |
| 53 | + Blue = "Blue" |
| 54 | + |
| 55 | + class Child(SQLModel, table=True): |
| 56 | + __tablename__ = "children" |
| 57 | + |
| 58 | + id: Optional[int] = Field(primary_key=True, default=None) |
| 59 | + parent_id: int = Field(foreign_key="parents.id") |
| 60 | + color: Color |
| 61 | + value: int |
| 62 | + |
| 63 | + error_msg_re = re.escape( |
| 64 | + "Dict/Mapping relationship field 'children_by_color' must have both key and value type arguments (e.g., dict[str, Model])" |
| 65 | + ) |
| 66 | + # No type args |
| 67 | + with pytest.raises(ValueError, match=error_msg_re): |
| 68 | + |
| 69 | + class Parent(SQLModel, table=True): |
| 70 | + __tablename__ = "parents" |
| 71 | + |
| 72 | + id: Optional[int] = Field(primary_key=True, default=None) |
| 73 | + children_by_color: dict[()] = Relationship( |
| 74 | + sa_relationship_kwargs={ |
| 75 | + "collection_class": attribute_keyed_dict("color") |
| 76 | + } |
| 77 | + ) |
| 78 | + |
| 79 | + # One type arg |
| 80 | + with pytest.raises(ValueError, match=error_msg_re): |
| 81 | + |
| 82 | + class Parent(SQLModel, table=True): |
| 83 | + __tablename__ = "parents" |
| 84 | + |
| 85 | + id: Optional[int] = Field(primary_key=True, default=None) |
| 86 | + children_by_color: dict[Color] = Relationship( |
| 87 | + sa_relationship_kwargs={ |
| 88 | + "collection_class": attribute_keyed_dict("color") |
| 89 | + } |
| 90 | + ) |
0 commit comments