From 1df3e8f5e700955d8f6d71d1fb93a1403dac6f4a Mon Sep 17 00:00:00 2001 From: saxenabhishek Date: Mon, 16 May 2022 07:14:53 +0530 Subject: [PATCH] test: test agg funtions --- frappe/query_builder/functions.py | 7 +++++-- frappe/tests/test_query_builder.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/frappe/query_builder/functions.py b/frappe/query_builder/functions.py index 0ae8dc138d..f03c139f57 100644 --- a/frappe/query_builder/functions.py +++ b/frappe/query_builder/functions.py @@ -6,7 +6,7 @@ from frappe.database.query import Query from frappe.query_builder.custom import GROUP_CONCAT, MATCH, STRING_AGG, TO_TSVECTOR from frappe.query_builder.utils import ImportMapper, db_type_is -from .utils import Column +from .utils import PseudoColumn class Concat_ws(Function): @@ -73,7 +73,10 @@ class Cast_(Function): def _aggregate(function, dt, fieldname, filters, **kwargs): return ( - Query().build_conditions(dt, filters).select(function(Column(fieldname))).run(**kwargs)[0][0] + Query() + .build_conditions(dt, filters) + .select(function(PseudoColumn(fieldname))) + .run(**kwargs)[0][0] or 0 ) diff --git a/frappe/tests/test_query_builder.py b/frappe/tests/test_query_builder.py index a73da1f11f..e15245422c 100644 --- a/frappe/tests/test_query_builder.py +++ b/frappe/tests/test_query_builder.py @@ -1,4 +1,5 @@ import unittest +from random import sample from typing import Callable import frappe @@ -163,6 +164,25 @@ class TestBuilderBase(object): self.assertIsInstance(query.run, Callable) self.assertIsInstance(data, list) + def test_agg_funcs(self): + frappe.db.truncate("Communication") + sample_data = { + "doctype": "Communication", + "communication_type": "Communication", + "content": "testing", + "rating": 1, + } + frappe.get_doc(sample_data).insert() + sample_data["rating"] = 3 + frappe.get_doc(sample_data).insert() + sample_data["rating"] = 4 + frappe.get_doc(sample_data).insert() + self.assertEqual(frappe.qb.max("Communication", "rating"), 4) + self.assertEqual(frappe.qb.min("Communication", "rating"), 1) + self.assertAlmostEqual(frappe.qb.avg("Communication", "rating"), 2.666, places=2) + self.assertEqual(frappe.qb.sum("Communication", "rating"), 8.0) + frappe.db.rollback() + class TestParameterization(unittest.TestCase): def test_where_conditions(self):