Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add __repr__ to Index class #1822

Merged
merged 1 commit into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions tests/contrib/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
Employee,
EnumFields,
Event,
ModelTestPydanticMetaBackwardRelations1,
ModelTestPydanticMetaBackwardRelations2,
IntFields,
JSONFields,
ModelTestPydanticMetaBackwardRelations1,
ModelTestPydanticMetaBackwardRelations2,
Reporter,
Team,
Tournament,
Expand Down Expand Up @@ -70,11 +70,17 @@ async def test_backward_relations_with_meta_override(self):
self.assertTrue("address" in event_schema["properties"])
self.assertFalse("address" in event_non_backward_schema_by_override["properties"])
del event_schema["properties"]["address"]
self.assertEqual(event_schema["properties"], event_non_backward_schema_by_override["properties"])
self.assertEqual(
event_schema["properties"], event_non_backward_schema_by_override["properties"]
)

async def test_backward_relations_with_pydantic_meta(self):
test_model1_schema = self.ModelTestPydanticMetaBackwardRelations1_Pydantic.model_json_schema()
test_model2_schema = self.ModelTestPydanticMetaBackwardRelations2_Pydantic.model_json_schema()
test_model1_schema = (
self.ModelTestPydanticMetaBackwardRelations1_Pydantic.model_json_schema()
)
test_model2_schema = (
self.ModelTestPydanticMetaBackwardRelations2_Pydantic.model_json_schema()
)
self.assertTrue("threes" in test_model2_schema["properties"])
self.assertFalse("threes" in test_model1_schema["properties"])
del test_model2_schema["properties"]["threes"]
Expand Down
13 changes: 12 additions & 1 deletion tests/fields/test_db_index.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import Any

from pypika.terms import Field

from tortoise import fields
from tortoise.contrib import test
from tortoise.exceptions import ConfigurationError
Expand All @@ -12,7 +14,7 @@ def __init__(self, *args, **kw):
self._foo = ""


class TestIndexHashEqual(test.TestCase):
class TestIndexHashEqualRepr(test.TestCase):
def test_index_eq(self):
assert Index(fields=("id",)) == Index(fields=("id",))
assert CustomIndex(fields=("id",)) == CustomIndex(fields=("id",))
Expand All @@ -38,6 +40,15 @@ def test_index_hash(self):
indexes.add(Index(fields=("name",)))
assert len(indexes) == 3

def test_index_repr(self):
assert repr(Index(fields=("id",))) == "Index(fields=['id'])"
assert repr(Index(fields=("id", "name"))) == "Index(fields=['id', 'name'])"
assert repr(Index(fields=("id",), name="MyIndex")) == "Index(fields=['id'], name='MyIndex')"
assert repr(Index(Field("id"))) == f'Index({str(Field("id"))})'
assert repr(Index(Field("a"), name="Id")) == f"Index({str(Field('a'))}, name='Id')"
with self.assertRaises(ValueError):
Index(Field("id"), fields=("name",))


class TestIndexAlias(test.TestCase):
Field: Any = fields.IntField
Expand Down
15 changes: 9 additions & 6 deletions tests/testmodels.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,19 @@ class PydanticMeta:
backward_relations = False


class ModelTestPydanticMetaBackwardRelations2(Model):
...
class ModelTestPydanticMetaBackwardRelations2(Model): ...


class ModelTestPydanticMetaBackwardRelations3(Model):
one: fields.ForeignKeyRelation[ModelTestPydanticMetaBackwardRelations1] = fields.ForeignKeyField(
"models.ModelTestPydanticMetaBackwardRelations1", related_name="threes"
one: fields.ForeignKeyRelation[ModelTestPydanticMetaBackwardRelations1] = (
fields.ForeignKeyField(
"models.ModelTestPydanticMetaBackwardRelations1", related_name="threes"
)
)
two: fields.ForeignKeyRelation[ModelTestPydanticMetaBackwardRelations2] = fields.ForeignKeyField(
"models.ModelTestPydanticMetaBackwardRelations2", related_name="threes"
two: fields.ForeignKeyRelation[ModelTestPydanticMetaBackwardRelations2] = (
fields.ForeignKeyField(
"models.ModelTestPydanticMetaBackwardRelations2", related_name="threes"
)
)


Expand Down
24 changes: 18 additions & 6 deletions tortoise/indexes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import TYPE_CHECKING, Any, Optional, Tuple, Type
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Type

from pypika.terms import Term, ValueWrapper

Expand All @@ -16,8 +18,8 @@ class Index:
def __init__(
self,
*expressions: Term,
fields: Optional[Tuple[str, ...]] = None,
name: Optional[str] = None,
fields: tuple[str, ...] | list[str] | None = None,
name: str | None = None,
) -> None:
"""
All kinds of index parent class, default is BTreeIndex.
Expand All @@ -38,6 +40,16 @@ def __init__(
self.expressions = expressions
self.extra = ""

def __repr__(self) -> str:
argument = ""
if self.expressions:
argument += ", ".join(map(str, self.expressions))
if fields := self.fields:
argument += f"{fields=}"
if name := self.name:
argument += f", {name=}"
return self.__class__.__name__ + "(" + argument + ")"

def get_sql(
self, schema_generator: "BaseSchemaGenerator", model: "Type[Model]", safe: bool
) -> str:
Expand Down Expand Up @@ -70,9 +82,9 @@ class PartialIndex(Index):
def __init__(
self,
*expressions: Term,
fields: Optional[Tuple[str, ...]] = None,
name: Optional[str] = None,
condition: Optional[dict] = None,
fields: tuple[str, ...] | list[str] | None = None,
name: str | None = None,
condition: dict | None = None,
) -> None:
super().__init__(*expressions, fields=fields, name=name)
if condition:
Expand Down