def test_from_query_value(self): attributes = [ "population_max", "population_min", "population_avg", ] query_string = ( "field=population|func=avg|to=population_avg|filters=rivers.length=<1500|early=0," "field=population|func=max|to=population_max|filters=rivers.length=<1500|early=0," "field=population|func=min|to=population_min|filters=rivers.length=<1500|early=0" ) annotations = utils.split_list_values([query_string], ",") annotations = [Annotation.from_query_value(a, Country, False, self.censor) for a in annotations] query = Country.objects.all() for a in annotations: query = a.apply(query) query = [ {a: getattr(c, a) for a in attributes} for c in query ] expected = Country.objects.all().annotate( population_max=models.Max("population", filter=Q(rivers__length__lt=1500)), population_min=models.Min("population", filter=Q(rivers__length__lt=1500)), population_avg=models.Avg("population", filter=Q(rivers__length__lt=1500)), ) expected = [ {a: getattr(c, a) for a in attributes} for c in expected ] self.assertEqual(expected, query)
def test_invalid_early(self): query_string = ( "field=population|func=max|to=population_max|filters=rivers.length=<1500|early=invalid" ) annotations = utils.split_list_values([query_string], ",") with self.assertRaises(InvalidCommandError): [Annotation.from_query_value(a, Country, False, self.censor) for a in annotations]
def test_from_query_value(self): query_string = ( "field=population|func=avg|to=population_avg," "field=population|func=max|to=population_max," "field=population|func=min|to=population_min" ) aggregations = utils.split_list_values([query_string], ",") aggregations = [Aggregation.from_query_value(a, Country, self.censor) for a in aggregations] aggregations = [a.get() for a in aggregations] kwargs = dict(aggregations) query = Country.objects.all().aggregate(**kwargs) expected = Country.objects.all().aggregate( population_max=models.Max("population"), population_min=models.Min("population"), population_avg=models.Avg("population"), ) self.assertEqual(expected, query)
def test_missing_field(self): query_string = "to=population_max|func=max" aggregations = utils.split_list_values([query_string], ",") with self.assertRaises(InvalidCommandError): [Aggregation.from_query_value(a, Country, self.censor) for a in aggregations]
def test_no_equal_subquery_string(self): query_string = "population" aggregations = utils.split_list_values([query_string], ",") with self.assertRaises(InvalidCommandError): [Aggregation.from_query_value(a, Country, self.censor) for a in aggregations]
def test_invalid_to(self): query_string = "field=population|func=max|to=1notvalid" aggregations = utils.split_list_values([query_string], ",") with self.assertRaises(InvalidCommandError): [Aggregation.from_query_value(a, Country, self.censor) for a in aggregations]