【问题标题】:Can I avoid the need for authentication when testing Django Rest Framework我可以在测试 Django Rest Framework 时避免身份验证的需要吗
【发布时间】:2020-06-30 01:55:25
【问题描述】:

我是第一次尝试使用 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】:

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

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

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

    self.client 基本上是APIClient() 用于当前的TestCase

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2015-06-01
      • 2018-07-04
      • 2013-12-29
      • 2015-06-04
      • 2017-08-15
      • 2019-01-01
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多