Skip to content

Commit

Permalink
Fix/update examples (#50)
Browse files Browse the repository at this point in the history
* Update examples

* More on examples
  • Loading branch information
barseghyanartur authored Dec 17, 2023
1 parent 84450b2 commit ef39268
Show file tree
Hide file tree
Showing 14 changed files with 232 additions and 36 deletions.
3 changes: 2 additions & 1 deletion examples/dataclasses/article/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
__license__ = "MIT"
__all__ = (
"ArticleFactory",
"GroupFactory",
"UserFactory",
)

Expand Down Expand Up @@ -53,11 +54,11 @@ class UserFactory(ModelFactory):
first_name = FACTORY.first_name() # type: ignore
last_name = FACTORY.last_name() # type: ignore
email = FACTORY.email() # type: ignore
date_joined = FACTORY.date_time() # type: ignore
last_login = FACTORY.date_time() # type: ignore
is_superuser = False
is_staff = False
is_active = FACTORY.pybool() # type: ignore
date_joined = FACTORY.date_time() # type: ignore
password = PreSave(set_password, password="test1234") # type: ignore
group = PostSave(add_to_group, name="TestGroup1234") # type: ignore

Expand Down
17 changes: 3 additions & 14 deletions examples/dataclasses/article/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,18 @@
from datetime import date, datetime
from typing import Optional, Set

from fake import xor_transform

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
__copyright__ = "2023 Artur Barseghyan"
__license__ = "MIT"
__all__ = (
"Article",
"Group",
"User",
)


def xor_transform(val: str, key: int = 10) -> str:
"""Simple, deterministic string encoder/decoder.
Usage example:
.. code-block:: python
val = "abcd"
encoded_val = xor_transform(val)
decoded_val = xor_transform(encoded_val)
"""
return "".join(chr(ord(__c) ^ key) for __c in val)


@dataclass(frozen=True)
class Group:
id: int
Expand Down
4 changes: 2 additions & 2 deletions examples/dataclasses/article/tests.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import unittest
from datetime import datetime

from fake import FILE_REGISTRY
from fake import FILE_REGISTRY, xor_transform

from article.factories import ArticleFactory, UserFactory
from article.models import Article, User, xor_transform
from article.models import Article, User

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
__copyright__ = "2023 Artur Barseghyan"
Expand Down
8 changes: 4 additions & 4 deletions examples/django/article/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def set_password(user: User, password: str) -> None:
user.set_password(password)


def add_to_group(user: User, group_name: str) -> None:
group = GroupFactory(name=group_name)
def add_to_group(user: User, name: str) -> None:
group = GroupFactory(name=name)
user.groups.add(group)


Expand All @@ -60,13 +60,13 @@ class UserFactory(DjangoModelFactory):
first_name = FACTORY.first_name()
last_name = FACTORY.last_name()
email = FACTORY.email()
date_joined = FACTORY.date_time(tzinfo=timezone.get_current_timezone())
last_login = FACTORY.date_time(tzinfo=timezone.get_current_timezone())
is_superuser = False
is_staff = False
is_active = FACTORY.pybool()
date_joined = FACTORY.date_time(tzinfo=timezone.get_current_timezone())
password = PreSave(set_password, password="test1234")
group = PostSave(add_to_group, group_name="TestGroup1234")
group = PostSave(add_to_group, name="TestGroup1234")

class Meta:
model = User
Expand Down
27 changes: 25 additions & 2 deletions examples/pydantic/article/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@
FACTORY,
FileSystemStorage,
ModelFactory,
PostSave,
PreSave,
SubFactory,
post_save,
pre_save,
trait,
)

from article.models import Article, User
from article.models import Article, Group, User

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
__copyright__ = "2023 Artur Barseghyan"
__license__ = "MIT"
__all__ = (
"ArticleFactory",
"GroupFactory",
"UserFactory",
)

Expand All @@ -27,17 +30,37 @@
STORAGE = FileSystemStorage(root_path=MEDIA_ROOT, rel_path="tmp")


class GroupFactory(ModelFactory):
id = FACTORY.pyint()
name = FACTORY.word()

class Meta:
model = Group
get_or_create = ("name",)


def set_password(user: User, password: str) -> None:
user.set_password(password)


def add_to_group(user: User, name: str) -> None:
group = GroupFactory(name=name)
user.groups.add(group)


class UserFactory(ModelFactory):
id = FACTORY.pyint()
username = FACTORY.username()
first_name = FACTORY.first_name()
last_name = FACTORY.last_name()
email = FACTORY.email()
date_joined = FACTORY.date_time()
last_login = FACTORY.date_time()
is_superuser = False
is_staff = False
is_active = FACTORY.pybool()
date_joined = FACTORY.date_time()
password = PreSave(set_password, password="test1234") # type: ignore
group = PostSave(add_to_group, name="TestGroup1234") # type: ignore

class Meta:
model = User
Expand Down
28 changes: 25 additions & 3 deletions examples/pydantic/article/models.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,58 @@
from datetime import date, datetime
from typing import Optional
from typing import Optional, Set

from fake import xor_transform
from pydantic import BaseModel, Field

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
__copyright__ = "2023 Artur Barseghyan"
__license__ = "MIT"
__all__ = (
"Article",
"Group",
"User",
)


class Group(BaseModel):
id: int
name: str

class Config:
allow_mutation = False

def __hash__(self):
return hash((self.id, self.name))

def __eq__(self, other):
if isinstance(other, Group):
return self.id == other.id and self.name == other.name
return False


class User(BaseModel):
id: int
username: str = Field(..., max_length=255)
first_name: str = Field(..., max_length=255)
last_name: str = Field(..., max_length=255)
email: str = Field(..., max_length=255)
password: Optional[str] = Field("", max_length=255)
date_joined: datetime = Field(default_factory=datetime.utcnow)
last_login: Optional[datetime] = None
password: Optional[str] = Field("", max_length=255)
is_superuser: bool = Field(default=False)
is_staff: bool = Field(default=False)
is_active: bool = Field(default=True)
date_joined: Optional[datetime] = None
groups: Set[Group] = Field(default_factory=set)

class Config:
extra = "allow" # For testing purposes only

def __str__(self):
return self.username

def set_password(self, password: str) -> None:
self.password = xor_transform(password)


class Article(BaseModel):
id: int
Expand Down
13 changes: 11 additions & 2 deletions examples/pydantic/article/tests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import unittest
from datetime import datetime

from fake import FILE_REGISTRY
from fake import FILE_REGISTRY, xor_transform

from article.factories import ArticleFactory
from article.factories import ArticleFactory, UserFactory
from article.models import Article, User

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
Expand Down Expand Up @@ -49,3 +49,12 @@ def test_sub_factory(self) -> None:
articles = ArticleFactory.create_batch(5)
self.assertEqual(len(articles), 5)
self.assertIsInstance(articles[0], Article)

def test_pre_save_and_post_save(self) -> None:
"""Test PreSave and PostSave."""
user = UserFactory(is_staff=True)
self.assertEqual(
xor_transform(user.password),
"test1234",
)
self.assertEqual(list(user.groups)[0].name, "TestGroup1234")
42 changes: 40 additions & 2 deletions examples/sqlalchemy/article/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
from fake import (
FACTORY,
FileSystemStorage,
PostSave,
PreSave,
SQLAlchemyModelFactory,
SubFactory,
post_save,
pre_save,
trait,
)

from article.models import Article, User
from article.models import Article, Group, User
from config import SESSION

__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
Expand All @@ -31,18 +33,54 @@ def get_session():
return SESSION()


class GroupFactory(SQLAlchemyModelFactory):
"""User factory."""

name = FACTORY.word()

class Meta:
model = Group
get_or_create = ("name",)

class MetaSQLAlchemy:
get_session = get_session


def set_password(user: User, password: str) -> None:
user.set_password(password)


def add_to_group(user: User, name: str) -> None:
session = get_session()
# Check if the group already exists
group = session.query(Group).filter_by(name=name).first()

# If the group doesn't exist, create a new one
if not group:
group = Group(name=name)
session.add(group)
session.commit() # Commit to assign an ID to the new group

# Add the group to the user's groups using append
if group not in user.groups:
user.groups.append(group)
session.commit() # Commit the changes


class UserFactory(SQLAlchemyModelFactory):
"""User factory."""

username = FACTORY.username() # mypy: ignore
first_name = FACTORY.first_name() # mypy: ignore
last_name = FACTORY.last_name() # mypy: ignore
email = FACTORY.email() # mypy: ignore
date_joined = FACTORY.date_time() # mypy: ignore
last_login = FACTORY.date_time() # mypy: ignore
is_superuser = False
is_staff = False
is_active = FACTORY.pybool() # mypy: ignore
date_joined = FACTORY.date_time() # mypy: ignore
password = PreSave(set_password, password="test1234") # type: ignore
group = PostSave(add_to_group, name="TestGroup1234") # type: ignore

class Meta:
model = User
Expand Down
36 changes: 34 additions & 2 deletions examples/sqlalchemy/article/models.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from datetime import datetime

from fake import xor_transform
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
String,
Table,
Text,
)
from sqlalchemy.ext.declarative import declarative_base
Expand All @@ -25,6 +27,27 @@
Base = declarative_base()


# Association table for the many-to-many relationship
user_group_association = Table(
"user_group",
Base.metadata,
Column("user_id", Integer, ForeignKey("users.id")),
Column("group_id", Integer, ForeignKey("groups.id")),
)


class Group(Base):
"""Group model."""

__tablename__ = "groups"

id = Column(Integer, primary_key=True)
name = Column(String(255), unique=True)

def __repr__(self):
return f"<Group(group='{self.name}')>"


class User(Base):
"""User model."""

Expand All @@ -35,18 +58,27 @@ class User(Base):
first_name = Column(String(255))
last_name = Column(String(255))
email = Column(String(255))
password = Column(String(255), nullable=True)
date_joined = Column(DateTime, default=datetime.utcnow)
last_login = Column(DateTime, nullable=True)
password = Column(String(255), nullable=True)
is_superuser = Column(Boolean, default=False)
is_staff = Column(Boolean, default=False)
is_active = Column(Boolean, default=True)
date_joined = Column(DateTime, nullable=True)

# Many-to-many relationship
groups = relationship(
"Group", secondary=user_group_association, backref="users"
)

# One-to-many relationship
articles = relationship("Article", back_populates="author")

def __repr__(self):
return f"<User(username='{self.username}', email='{self.email}')>"

def set_password(self, password: str) -> None:
self.password = xor_transform(password)


class Article(Base):
"""Article model."""
Expand Down
Loading

0 comments on commit ef39268

Please sign in to comment.