File: test_runners.md

package info (click to toggle)
python-model-bakery 1.20.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 532 kB
  • sloc: python: 4,298; sh: 149; makefile: 21
file content (53 lines) | stat: -rw-r--r-- 1,526 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Test Runners

Most of the code examples shown so far have used the [Django TestCase](https://docs.djangoproject.com/en/dev/topics/testing/tools/#testcase) to explain how Model Bakery is used.

However, [pytest](https://docs.pytest.org/en/stable/) (with the [pytest-django](https://pytest-django.readthedocs.io/en/latest/) plugin) is often preferred for it\'s simplicity and other benefits. See [here](https://realpython.com/django-pytest-fixtures/).

The following examples show Model Bakery usage with different test runners.

## Django

```python
    # Core Django imports
    from django.test import TestCase

    # Third-party app imports
    from model_bakery import baker

    from shop.models import Customer

    class CustomerTestModel(TestCase):
        """
        Class to test the model Customer
        """

        def setUp(self):
            """Set up test class."""
            self.customer = baker.make(Customer)

        def test_using_customer(self):
            """Test function using baked model."""
            self.assertIsInstance(self.customer, Customer)
```

## pytest

```python
    # pytest import
    import pytest

    # Third-party app imports
    from model_bakery import baker

    from shop.models import Customer

    @pytest.fixture
    def customer():
        """Fixture for baked Customer model."""
        return baker.make(Customer)

    def test_using_customer(customer):
        """Test function using fixture of baked model."""
        assert isinstance(customer, Customer)
```