我正在使用Django和Python 3.7,并尝试通过web / views / tax_calculator.py上的视图测试AJAX请求
# Basic function that serves the default page
def get(request):
return render(request, "web/template/tax_calculator.html", {})
# This is an Ajax call that will calculate the overall taxes you pay for
# an S-Corp vs a sole proprietorship
def post(request):
state = request.GET.get('state', None)
gross_income = request.GET.get('gross', None)
owner_salary = request.GET.get('salary', None)
data = {
'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income),
's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary),
}
return JsonResponse(data)
这是我的测试文件,位于web / tests / test_views.py
from django.test.client import Client
import json
from web.models import *
c = Client()
class ViewTests(TestCase):
# Basic test to verify we can get valid return data
def test_calculate_tax(self):
state = 'MN'
gross = 100000
salary = 75000
json_data = json.dumps({'state': state,
'gross': gross,
'salary': salary})
response = c.post('/content/vote/', json_data,
content_type='application/json',
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 302) # this is OK.
print(response.content)
self.assertEqual(response.content, 2)
这将导致以下错误。我还需要做些什么来使测试理解我的Ajax请求?
======================================================================
ERROR: test_calculate_tax (web.tests.test_views.ViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/davea/Documents/workspace/myproject/web/tests/test_views.py", line 20, in test_calculate_tax
response = c.post('/content/vote/', json_data,
AttributeError: 'Client' object has no attribute 'post'
----------------------------------------------------------------------
Ran 2 tests in 0.010s