rcpch / national-paediatric-diabetes-audit

A django application to audit the care of children and young people with diabetes in England and Wales.
0 stars 1 forks source link

[KPIS] Fix test for KPI45 sporadically failing #352

Closed anchit-chandran closed 2 weeks ago

anchit-chandran commented 2 weeks ago

Signed-off-by: anchit-chandran anchit97123@gmail.com

Overview

A few things were going on here, and was a fun rabbit hole!

TL/DR : main things contributing to the random failing were:

  1. Floating point precision
  2. SQL median is weird
  3. Accidentally using random values for Patient.diagnosis_date

All have been fixed. Run the test many times as it should now be fine (importantly, no random values are being used now, so one pass = deterministic!).

Fun details on above:

1. Floating point precision

We have our Visit.hba1c field defined as a DecimalField. The actual kpi calculation method querying this outputs a python Decimal( ) object. My test was just using float( ) objects. Good article on difference: https://www.laac.dev/blog/float-vs-decimal-python/ but generally:

This was partly leading to errors as tests are comparing different types of values. Fixed by converting expected values into Decimal. The output of the calculate_kpi_45_median_hba1c still returns a float though for convenience

2. SQL median is weird

There is no standard implementation of median in Django's ORM because it's more complicated to calculate. I created a custom SQL class for it but that ended up being harder to reason with. Instead, did a simpler approach of just using ORM to retrieve a list of hba1c values, and then calculate the median in Python. Much more straightforward.

3. Accidentally using random values for Patient.diagnosis_date

Rookie error! In the tests, just forgot to set PatientFactory.diagnosis_date. Expected behavior of the PatientFactory is to generate random valid values for any not given (to make it easier to create Patient objects).

Fixed by just defining.

Code changes

Related Issues

https://github.com/orgs/rcpch/projects/13?pane=issue&itemId=85211949&issue=rcpch%7Cnational-paediatric-diabetes-audit%7C338

Mentions

@mentions of the person or team responsible for reviewing proposed changes.

mbarton commented 2 weeks ago

Seen on STAGING (merged by @anchit-chandran 5 minutes and 24 seconds ago) Please check your changes!