2017-02-27 72 views
0

嗨,我现在正在使用Django REST3.5.3。我可以使用可浏览的API完美地完成CRUD。
Django客户端不会在测试中删除

我的问题是我的测试没有通过。

tests.py

import os 

from django.test import Client 

from apps.price_list_excel_files.models import PriceListExcelFile 


def upload_excel(user: str, passwd: str) -> tuple: 
    client = Client() 
    client.login(username=user, password=passwd) 

    dir_path = os.path.dirname(os.path.realpath(__file__)) 
    with open(dir_path + '/mixed_case.xlsx', 'rb') as fp: 
     response = client.post(
      '/api/price-list-excel-files/', 
      {'file': fp}, 
      format='multipart' 
     ) 
    return client, response 


def test_mgmt_user_upload_excel(prepare_mgmt_users): 
    client, response = upload_excel("John", "johnpassword") 
    assert 201 == response.status_code 
    assert 1 == PriceListExcelFile.objects.count() 


# TODO: Fix this testcase 
def test_mgmt_user_remove_excel(prepare_mgmt_users): 
    client, response = upload_excel("John", "johnpassword") 
    excel_id = response.data.get('id') 
    url = '/api/price-list-excel-files/' + str(excel_id) + '/' 
    res2 = client.delete(url, data={'format': 'json'}) 
    import pdb; 
    pdb.set_trace() 

    assert 0 == PriceListExcelFile.objects.count() 

这里是我的pdb控制台:

apps/price_list_excel_files/tests.py . 
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
> /Users/el/Code/siam-sbrand/portal/apps/price_list_excel_files/tests.py(37)test_mgmt_user_remove_excel() 
-> assert 0 == PriceListExcelFile.objects.count() 
(Pdb) list 
32   url = '/api/price-list-excel-files/' + str(excel_id) + '/' 
33   res2 = client.delete(url, data={'format': 'json'}) 
34   import pdb; 
35   pdb.set_trace() 
36 
37 ->  assert 0 == PriceListExcelFile.objects.count() 
[EOF] 
(Pdb) res2 
*** KeyError: 'content-type' 
(Pdb) url 
'/api/price-list-excel-files/2/' 
(Pdb) res3 = client.delete(url) 
(Pdb) res3 
<Response status_code=404, "application/json"> 

难道我错过了什么?

回答

0

我使用错误的客户端。我必须使用Djano REST客户端

from rest_framework.test import APIClient 
def test_mgmt_user_remove_excel(prepare_mgmt_users): 
    client, response = upload_excel("John", "johnpassword") 
    excel_id = response.data.get('id') 
    url = '/api/price-list-excel-files/' + str(excel_id) + '/' 

    client2 = APIClient() 
    client2.login(username="John", password="johnpassword") 

    res2 = client2.delete(url) 
    assert 0 == PriceListExcelFile.objects.count()