将查询传递给Django测试

我想测试我的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?

评论
  • 择一城终老
    择一城终老 回复

    像这样吗

    class TestKlass(...):
        def test_Search(self):
            url = reverse('finder:search')
            url_with_param = "{}?{}".format(url, 'query=gazpacho')
            self.response = self.client.post(url_with_param)
            self.assertEqual(self.response.status_code, 200)
  • Bobi
    Bobi 回复

    Your view handles GET-parameters so the request itself is a GET-request.

    In your test you are sending a post, which should be a get accordingly:

    self.client.get(url, {'query': '...'})
    

    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:

    urlconf参数是URLconf模块,其中包含用于反转的URL模式。默认情况下,使用当前线程的根URLconf。