mercredi 4 décembre 2019

can't catch/get the created instance, during the test for create_view in Django

I can't get the just created instance during the create_view() test(in Django). The View class works properly. It seems that the instance is being deleted before I can make an assertion(if it's possible to happen like that).

this is my view:

    class CreateItemView(CreateView):
        form_class = ItemForm
        template_name = 'item/item_create.html'
        success_url = '/list_item'      # <---- redirecting

my test:

class ItemViewsTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.factory = RequestFactory()
        self.category = create_category()
        self.item = create_item(self.category)

    def test_item_create(self):
        data = {
                'number': 2,
                'name': 'item_2',
                'description': 'item 2 description',
                'created_by': 'admin',
                'quantity': 100,
                'category': self.category.pk,
        }
        request = self.factory.post('/item_create', data)
        response = CreateItemView.as_view()(request)

        """following has the same result(doesn't work):
        response = self.client.post(
                            '/create_item/',
                             data,
                             )""""

        print(Item.objects.all())    # <----- only getting instance created in SetUp function
        self.assertEqual(Item.objects.last().name,
                         data['name'])

getting no errors for request or response, except the following error for the assertion:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
FAIL: test_item_create (core.tests.test_views.ItemViewsTest)
Traceback (most recent call last):
  File "D:\PYTHON\Projects\My web\warehouse\warehouse\core\tests\test_views.py", line 155, in test_item_create
data['name'])
AssertionError: 'item_1' != 'item_2'
Ran 1 test in 0.497s
FAILED (failures=1)
Destroying test database for alias 'default'...

and I have the same for another model and it works:

class CreateCatView(CreateView):
    form_class = CategoryForm
    template_name = 'category/category_create.html'
    success_url = '/list_category'

class CatViewsTest(TestCase):

def setUp(self):
    self.client = Client()
    self.factory = RequestFactory()
    self.category = create_category()

def test_cat_create(self):
    data = {'name': 'category_2_s',
            'number': 2,
            'description': 'test category number 2',
            'created_by': 'admin'}
    request = self.factory.post('/category_create', data)
    response = CreateCatView.as_view()(request)
    self.assertEqual(response.status_code, 302)
    self.assertEqual(Category.objects.last().name,
                     data['name'])

Aucun commentaire:

Enregistrer un commentaire