When running tests, I'd like to create and then delete some resources. Access to the target server requires authenticating with a token.
from django.test import TestCase
from rest_framework.test import APIClient
(...)
class MyTest(TestCase):
def setUp(self):
self.client = APIClient()
def test_creation_and_deletion(self):
payload = {"key": "value"}
# This works, but it's handled by a custom create() method from views.py:
res = self.client.post(<url>, payload)
(...)
# This doesn't work, no custom delete() method is defined anywhere:
tar_headers = {"private-token": "<token>"}
res2 = self.client.delete(res.data["target_resource_url"], headers=tar_headers)
# Either this doesn't work:
self.client.headers.update(tar_headers)
res3 = self.client.delete(res.data["target_resource_url"])
Printing res2
gives the following output:
<HttpResponseNotFound status_code=404, "text/html">
Calling res3
gives an error:
AttributeError: 'APIClient' object has no attribute 'headers'
Deletion requests sent towards target_resource_url
from e.g. Postman work fine as long as token is given in headers.
How to approach this issue?
Apparently, it's not possible to authenticate with a Private-Token
while requesting deletion via APIClient()
. But instead, the good old requests
library can be used:
import requests
HEADERS = {'PRIVATE-TOKEN': <TOKEN>}
res = ...
if "api_link" in res.data:
requests.delete(res.data["api_link"], headers=HEADERS)