samedi 15 décembre 2018

Matching QuerySets in Django Testing

I have a Django application and in my testing I run this code:

def test_search_keywords_logic(self):
    response = self.client.get(reverse('search-results'), { 'q': 'test11' })
    nt.assert_equal(response.status_code, 200)
    nt.assert_equal(response.context['query_string'], 'test11')
    nt.assert_equal(response.context['total_results'], 1)
    nt.assert_equal(response.context['found_results'], True)
    qs = QuerySet(CaseStudy.objects.filter(title='test1'))
    nt.assert_queryset_equal(response.context['study_results'], qs)

The last line: nt.assert_queryset_equal(response.context['study_results'], qs) gives me the error: AttributeError: 'QuerySet' object has no attribute '_meta'

I'm not sure what it means. All I want to do is assert that the queryset returned in the context variable 'study_results' is a match to what I know it should be CaseStudy.objects.get(title='test1') should return the correct CaseStudy object as it's the only one in the test db. However, it doesn't seem to work. I also tried just comparing the response context 'study_results' to <CaseStudy: test1>and even tried wrapping it in a QuerySet(). It still didn't work, seemed to see my QuerySet() for test1 as the test1 string divided into a list of the single characters.

I've tried using both nt.assert_equal() and nt.assert_queryset_equal() Neither work.

What would be the proper/working way to have these assertions pass? I know the study_results context returns the CaseStudy: test1 in this case. I just can't seem to get it to match in the assertion. Since I'm getting it from objects.filter it's already a queryset, but even with .get() I couldn't get it to work.

My problem seems to be on the right side of the comparison, even when I just put in 'test1 or <CaseStudy: test1> or QuerySet('test1') it doesn't work.

Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire