Skip to content

Commit

Permalink
Test examples
Browse files Browse the repository at this point in the history
  • Loading branch information
barseghyanartur committed Dec 3, 2023
1 parent c058735 commit 87d141d
Show file tree
Hide file tree
Showing 19 changed files with 496 additions and 79 deletions.
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": 59
"line_number": 71
},
{
"type": "Secret Keyword",
"filename": "Makefile",
"hashed_secret": "1457a35245051927fac6fa556074300f4162ed66",
"is_verified": true,
"line_number": 62
"line_number": 74
}
]
},
"generated_at": "2023-12-02T22:21:04Z"
"generated_at": "2023-12-03T22:23:51Z"
}
11 changes: 8 additions & 3 deletions CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,21 @@ For example:

**Good to know:**

- Test suite makes extensive use of parametrization. Make sure you have added
your changes in the right place.
- This library consists of a single ``fake.py`` module. That module is
dependency free, self-contained (includes all tests) and portable.
Do not submit pull requests splitting the ``fake.py`` module into small
parts.
- Some tests contain simplified implementation of existing libraries (Django
ORM). If you need to add integration tests for existing functionality,
you can add the relevant code and requirements to the examples.

**General list to go through:**

- Does your change require documentation update?
- Does your change require update to tests?
- Does your change rely on third-party package or a cloud based service?
If so, please consider turning it into a dedicated standalone package,
since this library is dependency free.
since this library is dependency free (and will always stay so).

**When fixing bugs (in addition to the general list):**

Expand Down
18 changes: 15 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,32 @@ install:
test:
source $(VENV) && pytest -vrx -s

django-test:
source $(VENV) && cd examples/django/ && ./manage.py test

pydantic-test:
source $(VENV) && cd examples/pydantic/ && python manage.py test

dataclasses-test:
source $(VENV) && cd examples/dataclasses/ && python manage.py test

tortoise-test:
source $(VENV) && cd examples/tortoise/ && python manage.py test

shell:
source $(VENV) && ipython

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

pydantic-shell:
source $(VENV) && python examples/pydantic/shell.py
source $(VENV) && cd examples/pydantic/ && python manage.py shell

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

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

create-secrets:
source $(VENV) && detect-secrets scan > .secrets.baseline
Expand Down
34 changes: 28 additions & 6 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ fake.py
.. External references
.. _Faker: https://faker.readthedocs.io/
.. _factory_boy: https://factoryboy.readthedocs.io/
.. _faker-file: https://faker-file.readthedocs.io/
.. _Pillow: https://python-pillow.org/
.. _dateutil: https://dateutil.readthedocs.io/
.. _Django: https://www.djangoproject.com/
.. _TortoiseORM: https://tortoise.github.io/
.. _Pydantic: https://docs.pydantic.dev/

.. Internal references
.. _fake.py: https://github.com/barseghyanartur/fake.py/
.. _Read the Docs: http://fakepy.readthedocs.io/
.. _Quick start: https://fakepy.readthedocs.io/en/latest/quick_start.html
.. _Recipes: https://fakepy.readthedocs.io/en/latest/recipes.html
Expand Down Expand Up @@ -44,7 +49,7 @@ Minimalistic, standalone alternative fake data generator with no dependencies.
:target: https://coveralls.io/github/barseghyanartur/fake.py?branch=main
:alt: Coverage

``fake.py`` is a standalone, portable library designed for generating various
`fake.py`_ is a standalone, portable library designed for generating various
random data types for testing.

It offers a simplified, dependency-free alternative for creating random
Expand Down Expand Up @@ -241,24 +246,41 @@ Tests

Run the tests with unittest:

.. code-block:: bash
.. code-block:: sh
python -m unittest fake.py
Or pytest:

.. code-block:: bash
.. code-block:: sh
pytest
Differences with `Faker`_
=========================
``fake.py`` is modeled after the famous `Faker`_ package. Its' API is highly
Differences with alternatives
=============================
`fake.py`_ is `Faker`_ + `factory_boy`_ + `faker-file`_ in one package,
radically simplified and reduced in features, but without any external
dependencies (not even `Pillow`_ or `dateutil`_).

`fake.py`_ is modeled after the famous `Faker`_ package. Its' API is highly
compatible, although drastically reduced. It's not multilingual and does not
support postal codes or that many RAW file formats. However, you could easily
include it in your production setup without worrying about yet another
dependency.

On the other hand, `fake.py`_ factories look quite similar to `factory_boy`_
factories, although again - drastically simplified and reduced in
features.

The file generation part of `fake.py`_ are modelled after the `faker-file`_.
You don't get a large variety of file types supported and you don't have that
much control over the content of the files generated, but you get
dependency-free valid files and if that's all you need, you don't need to look
further.

However, at any point, if you discover that you "need more", go for `Faker`_,
`factory_boy`_ and `faker-file`_ combination.

License
=======

Expand Down
29 changes: 28 additions & 1 deletion examples/dataclasses/article/factories.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from pathlib import Path

from fake import FACTORY, FileSystemStorage, ModelFactory, SubFactory
from fake import (
FACTORY,
FileSystemStorage,
ModelFactory,
SubFactory,
post_save,
pre_save,
)

from article.models import Article, User

Expand Down Expand Up @@ -31,6 +38,16 @@ class UserFactory(ModelFactory):
class Meta:
model = User

@staticmethod
@pre_save
def __pre_save_method(instance):
instance.pre_save_called = True

@staticmethod
@post_save
def __post_save_method(instance):
instance.post_save_called = True


class ArticleFactory(ModelFactory):
id = FACTORY.pyint()
Expand All @@ -45,3 +62,13 @@ class ArticleFactory(ModelFactory):

class Meta:
model = Article

@staticmethod
@pre_save
def __pre_save_method(instance):
instance.pre_save_called = True

@staticmethod
@post_save
def __post_save_method(instance):
instance.post_save_called = True
48 changes: 48 additions & 0 deletions examples/dataclasses/article/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import unittest
from datetime import datetime

from fake import FILE_REGISTRY

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

__all__ = ("FactoriesTestCase",)


class FactoriesTestCase(unittest.TestCase):
def tearDown(self):
FILE_REGISTRY.clean_up()

def test_sub_factory(self) -> None:
article = ArticleFactory()

# Testing SubFactory
self.assertIsInstance(article.author, User)
self.assertIsInstance(article.author.id, int)
self.assertIsInstance(article.author.is_staff, bool)
self.assertIsInstance(article.author.date_joined, datetime)

# Testing Factory
self.assertIsInstance(article.id, int)
self.assertIsInstance(article.slug, str)

# Testing hooks
self.assertTrue(
hasattr(article, "pre_save_called") and article.pre_save_called
)
self.assertTrue(
hasattr(article, "post_save_called") and article.post_save_called
)
self.assertTrue(
hasattr(article.author, "pre_save_called")
and article.author.pre_save_called
)
self.assertTrue(
hasattr(article.author, "post_save_called")
and article.author.post_save_called
)

# Testing batch creation
articles = ArticleFactory.create_batch(5)
self.assertEqual(len(articles), 5)
self.assertIsInstance(articles[0], Article)
37 changes: 37 additions & 0 deletions examples/dataclasses/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env python
import argparse
import os
import sys
import unittest

import IPython


def run_tests():
"""Function to run tests in the article directory."""
loader = unittest.TestLoader()
suite = loader.discover(start_dir="./article", pattern="tests.py")
runner = unittest.TextTestRunner()
runner.run(suite)


def main():
"""Run administrative tasks based on command line arguments."""
sys.path.insert(0, os.path.abspath("."))
parser = argparse.ArgumentParser(
description="Management script for the project."
)
parser.add_argument("command", help="The command to run (test or shell)")

args = parser.parse_args()

if args.command == "test":
run_tests()
elif args.command == "shell":
IPython.embed()
else:
print("Unknown command. Use 'test' or 'shell'.")


if __name__ == "__main__":
main()
15 changes: 0 additions & 15 deletions examples/dataclasses/shell.py

This file was deleted.

21 changes: 21 additions & 0 deletions examples/django/article/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
DjangoModelFactory,
FileSystemStorage,
SubFactory,
post_save,
pre_save,
)

Expand Down Expand Up @@ -48,6 +49,16 @@ class Meta:
def __set_password(instance):
instance.set_password("test")

@staticmethod
@pre_save
def __pre_save_method(instance):
instance.pre_save_called = True

@staticmethod
@post_save
def __post_save_method(instance):
instance.post_save_called = True


class ArticleFactory(DjangoModelFactory):
"""Article factory.
Expand All @@ -69,3 +80,13 @@ class ArticleFactory(DjangoModelFactory):

class Meta:
model = Article

@staticmethod
@pre_save
def __pre_save_method(instance):
instance.pre_save_called = True

@staticmethod
@post_save
def __post_save_method(instance):
instance.post_save_called = True
50 changes: 50 additions & 0 deletions examples/django/article/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from datetime import datetime

from django.contrib.auth.models import User
from django.test import TestCase
from fake import FILE_REGISTRY

from article.factories import ArticleFactory
from article.models import Article

__all__ = ("FactoriesTestCase",)


class FactoriesTestCase(TestCase):
def tearDown(self):
super().tearDown()
FILE_REGISTRY.clean_up()

def test_sub_factory(self) -> None:
article = ArticleFactory()

# Testing SubFactory
self.assertIsInstance(article.author, User)
self.assertIsInstance(article.author.id, int)
self.assertIsInstance(article.author.is_staff, bool)
self.assertIsInstance(article.author.date_joined, datetime)

# Testing Factory
self.assertIsInstance(article.id, int)
self.assertIsInstance(article.slug, str)

# Testing hooks
self.assertTrue(
hasattr(article, "pre_save_called") and article.pre_save_called
)
self.assertTrue(
hasattr(article, "post_save_called") and article.post_save_called
)
self.assertTrue(
hasattr(article.author, "pre_save_called")
and article.author.pre_save_called
)
self.assertTrue(
hasattr(article.author, "post_save_called")
and article.author.post_save_called
)

# Testing batch creation
articles = ArticleFactory.create_batch(5)
self.assertEqual(len(articles), 5)
self.assertIsInstance(articles[0], Article)
Loading

0 comments on commit 87d141d

Please sign in to comment.