在测试Django Rest Framework时可以避免身份验证的需求

问题描述 投票:0回答:1

我第一次尝试使用DRF测试,所以我创建了以下TestCase:

class TestInventoryActionInputNoSeriable(TestCase):
    def setUp(self):
        self.repository = create_repository()
        self.not_seriable_product = create_not_seriable_product()

    def test_post_inventory_input_not_seriable(self):
        client = APIClient()

        response = client.post('/api/inventory/execute_action/', {
            'action': 'input',
            'repository': self.repository.id,
            'product': self.not_seriable_product.id,
            'amount': 1,
        })
        self.assertEqual(response.status_code, 200)

        inventory_actions = models.InventoryAction.objects.all()
        inventory_inputs = models.InventoryInput.objects.all()
        kardexs = models.Kardex.objects.all()

        self.assertEqual(len(inventory_actions), 1)
        self.assertEqual(len(inventory_inputs), 1)
        self.assertEqual(len(kardexs), 1)

        inventory_action = inventory_actions.first()
        inventory_input = inventory_inputs.first()
        kardex = kardexs.first()

        self.assertEqual(inventory_action.action_content_type.model, 'inventoryinput')
        self.assertEqual(inventory_action.action_object_id, inventory_input.id)
        self.assertEqual(kardex.type, models.KARDEX_INPUT)
        self.assertEqual(kardex.repository_id, self.repository_id)
        self.assertEqual(kardex.product_id, self.not_seriable_product.id)
        self.assertEqual(kardex.amount, 1)
        self.assertEqual(kardex.stock, 1)

但是我得到以下结果:

(TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_post_inventory_input_not_seriable (inventory.tests.TestInventoryActionInputNoSeriable)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigital/inventory/tests.py", line 31, in test_post_inventory_input_not_seriable
    self.assertEqual(response.status_code, 200)
AssertionError: 401 != 200

----------------------------------------------------------------------
Ran 1 test in 0.083s

FAILED (failures=1)
Destroying test database for alias 'default'...

这意味着请求由于身份验证失败而被拒绝。我关注了DRF authentication documentation

def test_post_inventory_input_not_seriable(self):
        token = Token.objects.get(user__username='admin')
        client = APIClient()
        client.credentials(HTTP_AUTHORIZATION='token '+token.key)

        response = client.post('/api/inventory/execute_action/', {
            'action': 'input',
            'repository': self.repository.id,
            'product': self.not_seriable_product.id,
            'amount': 1,
        })
        self.assertEqual(response.status_code, 200)
        ...

但我收到此错误:

(TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_post_inventory_input_not_seriable (inventory.tests.TestInventoryActionInputNoSeriable)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigital/inventory/tests.py", line 23, in test_post_inventory_input_not_seriable
    token = Token.objects.get(user__username='admin')
  File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigitalVenv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigitalVenv/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
    self.model._meta.object_name
rest_framework.authtoken.models.Token.DoesNotExist: Token matching query does not exist.

----------------------------------------------------------------------
Ran 1 test in 0.046s

FAILED (errors=1)
Destroying test database for alias 'default'...

我不知道每次运行测试是否都必须创建用户,还有一种方法可以避免对测试进行身份验证。

python django testing django-rest-framework django-testing
1个回答
0
投票

您应该为每个测试用例创建用户,以便能够登录某人。但是,您可以更轻松地登录他:

admin = User.objects.create_user(...)
self.client.force_login(admin)
response = client.post(...)

这将在您的测试期间强制login user,并且api将认为他已登录(无需发送标头和带有请求的内容)。

[self.client基本上是当前APIClient()TestCase

© www.soinside.com 2019 - 2024. All rights reserved.