我想测试我的Django应用程序的视图。
def search(request):
query = request.GET.get('query')
query_lower = query.lower()
list_name = re.split("[- ’? ; , ' . : ' ' " " ]",query_lower)
stripped_query = [strip_accents(x) for x in list_name]
clean_query =[word for word in stripped_query if word not in stopwords]
match_list = []
for x in Product.objects.all():
match = 0
for y in clean_query:
if y in x.name or y in x.brand:
match += 1
if match == len(clean_query):
match_list.append(x.id)
else:
pass
if not query:
products_list= Product.objects.all()
else:
products_list = Product.objects.filter(id__in=match_list)
context = {
'products': products_list,
}
return render(request, 'finder/search.html', context)
I did create some products in my tests.py with setup
and I want to test if I have a 200 status code if on of those products is searched:
def test_Search(self):
self.response = self.client.post(reverse(('finder:search'), {'query':'gazpacho'}))
self.assertEqual(self.response.status_code, 200)
I got a TypeError: unhashable type: 'dict'
.
So, how I am supposed to pass my query into my test for it to be run?
像这样吗
Your view handles
GET
-parameters so the request itself is aGET
-request.In your test you are sending a post, which should be a
get
accordingly:Parameters are passed as the second argument for
get()
/post
.See more in the docs.
In your case most likely (without having the full trace of the error) your error is the way you are calling
reverse()
in your test.The second argument passed to that function is
urlconf
. From the docs: