Coverage for src/pytest_samples/database/_defs.py: 100%
44 statements
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-20 19:47 +0000
« prev ^ index » next coverage.py v7.4.2, created at 2024-02-20 19:47 +0000
1import sqlalchemy as _sqlalchemy
2import sqlalchemy.orm as _orm
4from arrow import Arrow as _Arrow
5from dataclasses import dataclass as _dataclass
6from sqlalchemy import Engine as _Engine
7from sqlalchemy.orm import DeclarativeBase as _DeclarativeBase, \
8 Mapped as _Mapped
9from sqlalchemy_utils import ArrowType as _ArrowType
10from typing import List as _List, Optional as _Optional
12from ..types import Location as _Location
15def create_tables(engine: _Engine) -> None:
16 """Create the relevant tables in the database.
18 Raises:
19 DatabaseError: If the database is corrupted.
21 Args:
22 engine (Engine): The engine to use for the creation of the
23 tables.
24 """
25 _Base.metadata.create_all(engine)
28class _Base(_DeclarativeBase):
29 """Base class for objects stored in the database, defining the ORM
30 root.
31 """
32 pass
35@_dataclass
36class TestFile(_Base):
37 """Defines how the test file information is stored in the
38 database.
39 """
41 __test__ = False # This is not a pytest test class.
43 __tablename__ = "test_file"
45 id: _Mapped[int] = _orm.mapped_column(primary_key=True)
46 """The id."""
48 path: _Mapped[str] = _orm.mapped_column(unique=True, index=True)
49 """The path of the file as defined in the item locations."""
51 last_hash: _Mapped[_Optional[bytes]] = _orm.mapped_column()
52 """The last known hash of the file, if it was recorded."""
54 items: _Mapped[_List["TestItem"]] = _orm.relationship(
55 back_populates="file"
56 )
57 """The test items contained in this file."""
60@_dataclass
61class TestItem(_Base):
62 """Defines how the test item information is stored in the
63 database.
64 """
66 __test__ = False # This is not a pytest test class.
68 __tablename__ = "test_item"
70 __table_args__ = (
71 _sqlalchemy.UniqueConstraint("file_id", "lineno", "testname"),
72 )
74 id: _Mapped[int] = _orm.mapped_column(primary_key=True)
75 """The id."""
77 file_id: _Mapped[int] = _orm.mapped_column(
78 _sqlalchemy.ForeignKey("test_file.id")
79 )
81 file: _Mapped[TestFile] = _orm.relationship(back_populates="items")
82 """The file in which the item was found."""
84 lineno: _Mapped[_Optional[int]] = _orm.mapped_column(nullable=True)
85 """The line where the test is found."""
87 testname: _Mapped[str] = _orm.mapped_column(nullable=False)
88 """The name of the test."""
90 last_run: _Mapped[_Arrow] = _orm.mapped_column(
91 nullable=False, type_=_ArrowType
92 )
93 """The date and time the test was last run."""
95 @property
96 def location(self) -> _Location:
97 """The location of the test.
99 Returns:
100 Location: The location of the test.
101 """
102 return (self.file.path, self.lineno, self.testname)