Skip to content

Commit

Permalink
More on tests
Browse files Browse the repository at this point in the history
  • Loading branch information
barseghyanartur committed Dec 2, 2023
1 parent e826555 commit 9a81a2b
Show file tree
Hide file tree
Showing 8 changed files with 229 additions and 17 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,4 @@ local_settings.py
examples/pydantic/media/
examples/tortoise/media/
examples/django/media/
examples/dataclasses/media/
6 changes: 3 additions & 3 deletions .secrets.baseline
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,16 @@
"filename": "Makefile",
"hashed_secret": "ee783f2421477b5483c23f47eca1f69a1f2bf4fb",
"is_verified": true,
"line_number": 56
"line_number": 59
},
{
"type": "Secret Keyword",
"filename": "Makefile",
"hashed_secret": "1457a35245051927fac6fa556074300f4162ed66",
"is_verified": true,
"line_number": 59
"line_number": 62
}
]
},
"generated_at": "2023-12-01T23:12:14Z"
"generated_at": "2023-12-02T22:21:04Z"
}
13 changes: 8 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ django-shell:
pydantic-shell:
source $(VENV) && python examples/pydantic/shell.py

dataclasses-shell:
source $(VENV) && python examples/dataclasses/shell.py

tortoise-shell:
source $(VENV) && python examples/tortoise/shell.py

Expand All @@ -60,11 +63,11 @@ detect-secrets:

# Clean up generated files
clean:
find . -name "*.pyc" -exec rm -rf {} \;
find . -name "builddocs.zip" -exec rm -rf {} \;
find . -name "*.py,cover" -exec rm -rf {} \;
find . -name "*.orig" -exec rm -rf {} \;
find . -name "__pycache__" -exec rm -rf {} \;
find . -type f -name "*.pyc" -exec rm -f {} \;
find . -type f -name "builddocs.zip" -exec rm -f {} \;
find . -type f -name "*.py,cover" -exec rm -f {} \;
find . -type f -name "*.orig" -exec rm -f {} \;
find . -type d -name "__pycache__" -exec rm -rf {} \; -prune
rm -rf build/
rm -rf dist/
rm -rf .cache/
Expand Down
Empty file.
47 changes: 47 additions & 0 deletions examples/dataclasses/article/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from pathlib import Path

from fake import FACTORY, FileSystemStorage, ModelFactory, SubFactory

from article.models import Article, User

__all__ = (
"ArticleFactory",
"UserFactory",
)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = BASE_DIR / "media"

STORAGE = FileSystemStorage(root_path=MEDIA_ROOT, rel_path="tmp")


class UserFactory(ModelFactory):
id = FACTORY.pyint()
username = FACTORY.username()
first_name = FACTORY.first_name()
last_name = FACTORY.last_name()
email = FACTORY.email()
last_login = FACTORY.date_time()
is_superuser = False
is_staff = False
is_active = FACTORY.pybool()
date_joined = FACTORY.date_time()

class Meta:
model = User


class ArticleFactory(ModelFactory):
id = FACTORY.pyint()
title = FACTORY.sentence()
slug = FACTORY.slug()
content = FACTORY.text()
image = FACTORY.png_file(storage=STORAGE)
pub_date = FACTORY.date()
safe_for_work = FACTORY.pybool()
minutes_to_read = FACTORY.pyint(min_value=1, max_value=10)
author = SubFactory(UserFactory)

class Meta:
model = Article
42 changes: 42 additions & 0 deletions examples/dataclasses/article/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from dataclasses import dataclass
from datetime import datetime
from typing import Optional

__all__ = (
"Article",
"User",
)


@dataclass
class User:
id: int
username: str
first_name: str
last_name: str
email: str
last_login: Optional[datetime]
date_joined: Optional[datetime]
password: Optional[str] = None
is_superuser: bool = False
is_staff: bool = False
is_active: bool = True

def __str__(self):
return self.username


@dataclass
class Article:
id: int
title: str
slug: str
content: str
author: User
image: Optional[str] = None # Use str to represent the image path or URL
pub_date: datetime = datetime.now()
safe_for_work: bool = False
minutes_to_read: int = 5

def __str__(self):
return self.title
15 changes: 15 additions & 0 deletions examples/dataclasses/shell.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys

import IPython


def main():
"""Run administrative tasks."""
sys.path.insert(0, os.path.abspath("."))
IPython.embed()


if __name__ == "__main__":
main()
122 changes: 113 additions & 9 deletions fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import zipfile
import zlib
from abc import abstractmethod
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
from tempfile import NamedTemporaryFile, gettempdir
Expand Down Expand Up @@ -2021,7 +2022,7 @@ def test_ipv4(self) -> None:
self.assertTrue(part.isdigit())
self.assertTrue(0 <= int(part) <= 255)

def test_parse_date_string(self):
def test_parse_date_string(self) -> None:
# Test 'now' and 'today' special keywords
self.assertAlmostEqual(
self.faker._parse_date_string("now"),
Expand Down Expand Up @@ -2055,7 +2056,7 @@ def test_parse_date_string(self):
with self.assertRaises(ValueError):
self.faker._parse_date_string("1y")

def test_date(self):
def test_date(self) -> None:
# Test the same date for start and end
start_date = "now"
end_date = "+0d"
Expand All @@ -2074,7 +2075,7 @@ def test_date(self):
<= datetime.now().date() + timedelta(days=2)
)

def test_date_time(self):
def test_date_time(self) -> None:
# Test the same datetime for start and end
start_date = "now"
end_date = "+0d"
Expand All @@ -2095,7 +2096,7 @@ def test_date_time(self):
<= datetime.now() + timedelta(hours=2)
)

def test_text_pdf(self):
def test_text_pdf(self) -> None:
with self.subTest("All params None, should fail"):
with self.assertRaises(ValueError):
self.faker.pdf(
Expand All @@ -2115,27 +2116,27 @@ def test_text_pdf(self):
self.assertTrue(pdf)
self.assertIsInstance(pdf, bytes)

def test_graphic_pdf(self):
def test_graphic_pdf(self) -> None:
pdf = self.faker.pdf(generator=GraphicPdfGenerator)
self.assertTrue(pdf)
self.assertIsInstance(pdf, bytes)

def test_png(self):
def test_png(self) -> None:
png = self.faker.png()
self.assertTrue(png)
self.assertIsInstance(png, bytes)

def test_svg(self):
def test_svg(self) -> None:
svg = self.faker.svg()
self.assertTrue(svg)
self.assertIsInstance(svg, bytes)

def test_bmp(self):
def test_bmp(self) -> None:
bmp = self.faker.bmp()
self.assertTrue(bmp)
self.assertIsInstance(bmp, bytes)

def test_gif(self):
def test_gif(self) -> None:
gif = self.faker.gif()
self.assertTrue(gif)
self.assertIsInstance(gif, bytes)
Expand Down Expand Up @@ -2229,6 +2230,109 @@ def test_storage(self) -> None:
storage.unlink(str(file_3))
self.assertFalse(storage.exists(file_3.data["filename"]))

def test_factory_method(self) -> None:
"""Test FactoryMethod."""
with self.subTest("sentence"):
sentence_factory_method = FactoryMethod("sentence")
generated_sentence = sentence_factory_method()
self.assertIsInstance(generated_sentence, str)
with self.subTest("pyint"):
pyint_factory_method = FactoryMethod("pyint")
generated_int = pyint_factory_method()
self.assertIsInstance(generated_int, int)

def test_factory_meta(self) -> None:
class TestFactory(Factory):
pass

for method_name in FactoryMeta.enabled_methods:
self.assertTrue(hasattr(TestFactory, method_name))

def test_sub_factory(self) -> None:
"""Test FACTORY and SubFactory."""
# *************************
# ********* Models ********
# *************************

@dataclass
class User:
id: int
username: str
first_name: str
last_name: str
email: str
last_login: Optional[datetime]
date_joined: Optional[datetime]
password: Optional[str] = None
is_superuser: bool = False
is_staff: bool = False
is_active: bool = True

def __str__(self):
return self.username

@dataclass
class Article:
id: int
title: str
slug: str
content: str
author: User
image: Optional[
str
] = None # Use str to represent the image path or URL
pub_date: datetime = datetime.now()
safe_for_work: bool = False
minutes_to_read: int = 5

def __str__(self):
return self.title

# *************************
# ******* Factories *******
# *************************
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = BASE_DIR / "media"

STORAGE = FileSystemStorage(root_path=MEDIA_ROOT, rel_path="tmp")

class UserFactory(ModelFactory):
id = FACTORY.pyint()
username = FACTORY.username()
first_name = FACTORY.first_name()
last_name = FACTORY.last_name()
email = FACTORY.email()
last_login = FACTORY.date_time()
is_superuser = False
is_staff = False
is_active = FACTORY.pybool()
date_joined = FACTORY.date_time()

class Meta:
model = User

class ArticleFactory(ModelFactory):
id = FACTORY.pyint()
title = FACTORY.sentence()
slug = FACTORY.slug()
content = FACTORY.text()
image = FACTORY.png_file(storage=STORAGE)
pub_date = FACTORY.date()
safe_for_work = FACTORY.pybool()
minutes_to_read = FACTORY.pyint(min_value=1, max_value=10)
author = SubFactory(UserFactory)

class Meta:
model = Article

article = ArticleFactory()
self.assertIsInstance(article.author, User)
self.assertIsInstance(article.id, int)
self.assertIsInstance(article.slug, str)
self.assertIsInstance(article.author.id, int)
self.assertIsInstance(article.author.is_staff, bool)
self.assertIsInstance(article.author.date_joined, datetime)


if __name__ == "__main__":
unittest.main()

0 comments on commit 9a81a2b

Please sign in to comment.