Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Give typed measurement categories a stable identity

Roland Geider973dd5ecbfad
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.py
index f480f57e8..7d28bd7b0 100644
--- a/wger/measurements/api/serializers.py
+++ b/wger/measurements/api/serializers.py
@@ -76,6 +76,108 @@ class CategorySerializer(serializers.ModelSerializer):
return parent
+ def validate(self, data):
+ """
+ Structural rules of the typed categories.
+
+ Each metric type has one role: components live under the group they
+ belong to, every other typed category is top-level, and there is exactly
+ one category per type and user (see Category.deterministic_id).
+ """
+ instance = self.instance
+ metric_type = data.get(
+ 'metric_type',
+ instance.metric_type if instance else MetricType.CUSTOM,
+ )
+ parent = data.get('parent', instance.parent if instance else None)
+
+ if MetricType.is_component(metric_type):
+ group = MetricType.group_of(metric_type)
+ if parent is None or parent.metric_type != group:
+ raise serializers.ValidationError(
+ {'parent': f'A {metric_type} category must be part of a {group} group'}
+ )
+ elif metric_type != MetricType.CUSTOM and parent is not None:
+ raise serializers.ValidationError(
+ {'parent': f'A {metric_type} category cannot be nested'}
+ )
+
+ if parent is not None and MetricType.is_group(parent.metric_type):
+ allowed = [c for c, _ in MetricType.components_of(parent.metric_type)]
+ if metric_type not in allowed:
+ raise serializers.ValidationError(
+ {'metric_type': f'A {parent.metric_type} group only holds its own components'}
+ )
+
+ # A group is a container. It never carries measurements, so a category
+ # that has some cannot become one
+ if MetricType.is_group(metric_type) and instance and instance.measurement_set.exists():
+ raise serializers.ValidationError(
+ {'metric_type': 'A category with measurements cannot become a group'}
+ )
+
+ self._validate_unique_metric_type(metric_type)
+ return data
+
+ def _validate_unique_metric_type(self, metric_type):
+ """
+ Only one category per metric type and user.
+
+ The constraint carries a condition, for which DRF generates no validator
+ of its own, so a duplicate would otherwise only surface as an
+ IntegrityError when saving.
+ """
+ user_id = self._get_user_id()
+ if metric_type == MetricType.CUSTOM or user_id is None:
+ return
+
+ categories = Category.objects.filter(user_id=user_id, metric_type=metric_type)
+ if self.instance is not None:
+ categories = categories.exclude(pk=self.instance.pk)
+ if categories.exists():
+ raise serializers.ValidationError(
+ {'metric_type': f'You already have a {metric_type} category'}
+ )
+
+ def _get_user_id(self):
+ """
+ Returns the id of the user the category belongs to.
+
+ The owner is not part of the payload, it is passed to save() by the
+ viewset (as a request) or by the PowerSync handler (as a context value).
+ """
+ user_id = self.context.get('user_id')
+ if user_id is not None:
+ return user_id
+
+ request = self.context.get('request')
+ user = getattr(request, 'user', None) if request else None
+ return user.pk if user is not None and user.is_authenticated else None
+
+ def create(self, validated_data):
+ """
+ Derives the key of a typed category and fills a group with components
+ """
+ metric_type = validated_data.get('metric_type', MetricType.CUSTOM)
+ user_id = validated_data.get('user_id') or getattr(validated_data.get('user'), 'pk', None)
+
+ # A client that creates the category offline derives the same key, so
+ # only fill it in when the payload brought none of its own
+ if 'id' not in validated_data and Category.has_deterministic_id(metric_type) and user_id:
+ validated_data['id'] = Category.deterministic_id(user_id, metric_type)
+
+ category = super().create(validated_data)
+ category.create_components()
+ return category
+
+ def update(self, instance, validated_data):
+ """
+ A category that becomes a group gets its components
+ """
+ category = super().update(instance, validated_data)
+ category.create_components()
+ return category
+
class MeasurementSerializer(serializers.ModelSerializer):
"""
@@ -112,6 +214,13 @@ class MeasurementSerializer(serializers.ModelSerializer):
raise serializers.ValidationError(
'Measurements cannot be added to a category with subcategories'
)
+ # A group type is a container by definition, also while it still has no
+ # children: its readings belong in the component categories
+ if MetricType.is_group(category.metric_type):
+ raise serializers.ValidationError(
+ f'Measurements cannot be added to a {category.metric_type} category, '
+ f'they belong in its components'
+ )
return category
def validate_extra_data(self, extra_data):
diff --git a/wger/measurements/management/commands/dummy-generator-health-measurements.py b/wger/measurements/management/commands/dummy-generator-health-measurements.py
index 12073292b..e30eac278 100644
--- a/wger/measurements/management/commands/dummy-generator-health-measurements.py
+++ b/wger/measurements/management/commands/dummy-generator-health-measurements.py
@@ -79,9 +79,6 @@ CATEGORIES = {
'sleep': (MetricType.SLEEP, 'Sleep', 'min'),
}
-# Components of the blood pressure group, in the order the importer pairs them
-BLOOD_PRESSURE_COMPONENTS = ('Systolic', 'Diastolic')
-
class Command(BaseCommand):
"""
@@ -258,14 +255,16 @@ class Command(BaseCommand):
unit=user.userprofile.weight_unit,
)
- category = Category.objects.filter(user=user, metric_type=metric_type).first()
- if category is None:
- category = Category.objects.create(
- user=user,
- metric_type=metric_type,
- name=name,
- unit=unit,
- )
+ category, _ = Category.objects.get_or_create(
+ id=Category.deterministic_id(user.pk, metric_type),
+ defaults={
+ 'user': user,
+ 'metric_type': metric_type,
+ 'name': name,
+ 'unit': unit,
+ },
+ )
+ category.create_components()
return category
def get_components(self, group: Category) -> list[Category]:
@@ -274,19 +273,7 @@ class Command(BaseCommand):
Only the leaves carry measurements, the group itself stays empty.
"""
- components = []
- for order, name in enumerate(BLOOD_PRESSURE_COMPONENTS):
- component = group.children.filter(name=name).first()
- if component is None:
- component = Category.objects.create(
- user=group.user,
- name=name,
- unit=group.unit,
- parent=group,
- order=order,
- )
- components.append(component)
- return components
+ return list(group.children.order_by('order'))
#
# Entries
diff --git a/wger/measurements/migrations/0006_category_externally_synced_category_metric_type_and_more.py b/wger/measurements/migrations/0006_category_externally_synced_category_metric_type_and_more.py
index eb14089e0..7a4f3c78b 100644
--- a/wger/measurements/migrations/0006_category_externally_synced_category_metric_type_and_more.py
+++ b/wger/measurements/migrations/0006_category_externally_synced_category_metric_type_and_more.py
@@ -41,6 +41,8 @@ class Migration(migrations.Migration):
('body_fat', 'Body Fat'),
('height', 'Height'),
('blood_pressure', 'Blood Pressure'),
+ ('blood_pressure_systolic', 'Blood Pressure Systolic'),
+ ('blood_pressure_diastolic', 'Blood Pressure Diastolic'),
('heart_rate', 'Heart Rate'),
('resting_heart_rate', 'Resting Heart Rate'),
('steps', 'Steps'),
@@ -49,10 +51,18 @@ class Migration(migrations.Migration):
('sleep', 'Sleep'),
],
default='custom',
- max_length=20,
+ max_length=30,
verbose_name='Metric type',
),
),
+ migrations.AddConstraint(
+ model_name='category',
+ constraint=models.UniqueConstraint(
+ condition=models.Q(('metric_type', 'custom'), _negated=True),
+ fields=('user', 'metric_type'),
+ name='unique_typed_category_per_user',
+ ),
+ ),
migrations.AddField(
model_name='measurement',
name='external_id',
diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.py
index 8176821a5..612596d81 100644
--- a/wger/measurements/models/category.py
+++ b/wger/measurements/models/category.py
@@ -13,6 +13,9 @@
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
+# Standard Library
+import uuid
+
# Django
from django.contrib.auth.models import User
from django.db import models
@@ -31,6 +34,8 @@ class MetricType(models.TextChoices):
BODY_FAT = 'body_fat'
HEIGHT = 'height'
BLOOD_PRESSURE = 'blood_pressure'
+ BLOOD_PRESSURE_SYSTOLIC = 'blood_pressure_systolic'
+ BLOOD_PRESSURE_DIASTOLIC = 'blood_pressure_diastolic'
HEART_RATE = 'heart_rate'
RESTING_HEART_RATE = 'resting_heart_rate'
STEPS = 'steps'
@@ -38,6 +43,68 @@ class MetricType(models.TextChoices):
ENERGY = 'energy'
SLEEP = 'sleep'
+ #
+ # Roles. Each type is exactly one of leaf (top-level, carries the
+ # measurements), group (top-level container) or component (child of its
+ # group, carries the measurements). Asked of a value rather than of a
+ # category, because the rules are checked on incoming payloads, before
+ # there is a category to ask
+ #
+
+ @classmethod
+ def is_group(cls, metric_type: str) -> bool:
+ """
+ Whether the type is a container for components, e.g. blood pressure
+ """
+ return metric_type in GROUP_COMPONENTS
+
+ @classmethod
+ def is_component(cls, metric_type: str) -> bool:
+ """
+ Whether the type is one component of a group, e.g. systolic
+ """
+ return metric_type in COMPONENT_GROUPS
+
+ @classmethod
+ def group_of(cls, metric_type: str) -> str | None:
+ """
+ Returns the group a component belongs to, None for every other type
+ """
+ return COMPONENT_GROUPS.get(metric_type)
+
+ @classmethod
+ def components_of(cls, metric_type: str) -> list[tuple[str, str]]:
+ """
+ Returns the (type, name) of a group's components, in group order
+ """
+ return GROUP_COMPONENTS.get(metric_type, [])
+
+
+GROUP_COMPONENTS: dict[str, list[tuple[str, str]]] = {
+ MetricType.BLOOD_PRESSURE: [
+ (MetricType.BLOOD_PRESSURE_SYSTOLIC, 'Systolic'),
+ (MetricType.BLOOD_PRESSURE_DIASTOLIC, 'Diastolic'),
+ ],
+}
+"""
+The components of the multi-value metric types, in group order.
+
+This is the single definition of the structure: a group type is a container
+that carries no measurements itself, its components are the child categories
+that do. The names match the ones the health importer uses so that both sides
+create the same categories.
+"""
+
+COMPONENT_GROUPS: dict[str, str] = {
+ component: group
+ for group, components in GROUP_COMPONENTS.items()
+ for component, _ in components
+}
+
+
+CATEGORY_NAMESPACE = uuid.UUID('4c5ef6dd-97c9-5b18-9f8b-2a5c1ed70a2f')
+"""Namespace for the derived primary keys, see Category.deterministic_id()"""
+
class Category(models.Model):
class Meta:
@@ -52,7 +119,16 @@ class Category(models.Model):
fields=['user', 'metric_type'],
condition=models.Q(is_official=True),
name='unique_official_category_per_metric_type',
- )
+ ),
+ # A typed category is the one place its metric lives: the health
+ # importer looks it up by type, and both manual and synced entries
+ # have to end up in the same one. Free-form categories keep the
+ # default type and are unaffected.
+ models.UniqueConstraint(
+ fields=['user', 'metric_type'],
+ condition=~models.Q(metric_type=MetricType.CUSTOM),
+ name='unique_typed_category_per_user',
+ ),
]
id = models.UUIDField(
@@ -78,7 +154,7 @@ class Category(models.Model):
metric_type = models.CharField(
verbose_name='Metric type',
- max_length=20,
+ max_length=30,
choices=MetricType.choices,
default=MetricType.CUSTOM,
)
@@ -112,6 +188,52 @@ class Category(models.Model):
"""
return self
+ @staticmethod
+ def has_deterministic_id(metric_type: str) -> bool:
+ """
+ Whether the primary key of such a category is derived instead of random.
+
+ Body weight is excluded: the server creates that category on its own
+ (registration signal, weight backfill), so no client can race it, and
+ the existing rows carry uuid7 keys that every synced device holds
+ locally.
+ """
+ return metric_type not in (MetricType.CUSTOM, MetricType.BODY_WEIGHT)
+
+ @staticmethod
+ def deterministic_id(user_id: int, metric_type: str) -> uuid.UUID:
+ """
+ Returns the primary key a typed category gets for this user.
+
+ Clients create categories while offline, so two devices would otherwise
+ end up with two rows for the same metric. Deriving the key from user and
+ metric type makes both arrive at the same one: the second push is then an
+ idempotent no-op instead of a conflict with the uniqueness constraint.
+ """
+ return uuid.uuid5(CATEGORY_NAMESPACE, f'{user_id}:{metric_type}')
+
+ def create_components(self) -> None:
+ """
+ Creates the missing component categories of a multi-value group.
+
+ A group is a container, its readings live in one child category per
+ component, so creating e.g. a blood pressure category gives it its
+ systolic and diastolic children right away. Does nothing for every other
+ metric type.
+ """
+ for order, (metric_type, name) in enumerate(MetricType.components_of(self.metric_type)):
+ Category.objects.get_or_create(
+ id=Category.deterministic_id(self.user_id, metric_type),
+ defaults={
+ 'user_id': self.user_id,
+ 'name': name,
+ 'unit': self.unit,
+ 'metric_type': metric_type,
+ 'parent': self,
+ 'order': order,
+ },
+ )
+
@classmethod
def get_or_create_official(cls, user, metric_type, *, name, unit):
"""
diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.py
index e4f20e540..c379bf945 100644
--- a/wger/measurements/powersync.py
+++ b/wger/measurements/powersync.py
@@ -47,6 +47,10 @@ class CategoryHandler(PowerSyncHandler):
serializer_class = CategorySerializer
viewset_class = CategoryViewSet
+ # The serializer checks the "one category per metric type" rule, for which
+ # it needs to know whose categories to look at
+ pass_user_id_in_context = True
+
def handle_delete(self, payload, user_id):
entry = self._get_or_none(payload, user_id)
if entry is not None and entry.is_official:
diff --git a/wger/measurements/tests/test_categories.py b/wger/measurements/tests/test_categories.py
index 82082bb57..990385bc7 100644
--- a/wger/measurements/tests/test_categories.py
+++ b/wger/measurements/tests/test_categories.py
@@ -120,6 +120,192 @@ class CategoryGroupApiTestCase(WgerTestCase):
self.assertFalse(Category.objects.filter(pk=child.data['id']).exists())
+class TypedCategoryTestCase(WgerTestCase):
+ """
+ Identity and structural rules of the categories with a metric type
+ """
+
+ # Pinned in test-measurement-categories.json / test-measurements.json
+ category_empty = 'cccccccc-cccc-cccc-cccc-000000000003' # user 'test', no measurements
+ category_with_measurements = 'cccccccc-cccc-cccc-cccc-000000000001' # user 'test'
+
+ def setUp(self):
+ super().setUp()
+ self.url = reverse('measurement-category-list')
+ self.user_login('test')
+ self.user = User.objects.get(username='test')
+
+ def create_category(self, **data):
+ payload = {'name': 'Steps', 'unit': 'count', **data}
+ return self.client.post(self.url, payload)
+
+ def detail_url(self, pk):
+ return reverse('measurement-category-detail', kwargs={'pk': pk})
+
+ def test_typed_category_gets_derived_id(self):
+ """
+ Test that the key of a typed category is derived from user and type
+ """
+ response = self.create_category(metric_type=MetricType.STEPS)
+
+ self.assertEqual(response.status_code, 201)
+ self.assertEqual(
+ response.data['id'],
+ str(Category.deterministic_id(self.user.pk, MetricType.STEPS)),
+ )
+
+ def test_official_category_keeps_random_id(self):
+ """
+ Test that the server-managed body weight category is not derived
+ """
+ category = Category.objects.get(user=self.user, is_official=True)
+
+ self.assertNotEqual(
+ category.pk,
+ Category.deterministic_id(self.user.pk, MetricType.BODY_WEIGHT),
+ )
+
+ def test_second_typed_category_rejected(self):
+ """
+ Test that a metric type can only be used once per user
+ """
+ self.create_category(metric_type=MetricType.STEPS)
+
+ response = self.create_category(name='Steps again', metric_type=MetricType.STEPS)
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('metric_type', response.data)
+
+ def test_same_type_of_other_user_allowed(self):
+ """
+ Test that the uniqueness is per user
+ """
+ Category.objects.create(
+ user=User.objects.get(username='admin'),
+ name='Steps',
+ unit='count',
+ metric_type=MetricType.STEPS,
+ )
+
+ response = self.create_category(metric_type=MetricType.STEPS)
+
+ self.assertEqual(response.status_code, 201)
+
+ def test_custom_categories_can_repeat(self):
+ """
+ Test that free-form categories are unaffected by the uniqueness
+ """
+ self.create_category(name='Biceps left', unit='cm')
+
+ response = self.create_category(name='Biceps right', unit='cm')
+
+ self.assertEqual(response.status_code, 201)
+
+ def test_group_creates_components(self):
+ """
+ Test that a group category is created with its component children
+ """
+ response = self.create_category(
+ name='Blood pressure',
+ unit='mmHg',
+ metric_type=MetricType.BLOOD_PRESSURE,
+ )
+
+ self.assertEqual(response.status_code, 201)
+ children = Category.objects.filter(parent_id=response.data['id']).order_by('order')
+ self.assertEqual(
+ [(c.name, c.metric_type, c.unit) for c in children],
+ [
+ ('Systolic', MetricType.BLOOD_PRESSURE_SYSTOLIC, 'mmHg'),
+ ('Diastolic', MetricType.BLOOD_PRESSURE_DIASTOLIC, 'mmHg'),
+ ],
+ )
+
+ def test_adopting_a_category_as_group_creates_components(self):
+ """
+ Test that a category changed into a group also gets its components
+ """
+ response = self.client.patch(
+ self.detail_url(self.category_empty),
+ {'metric_type': MetricType.BLOOD_PRESSURE},
+ content_type='application/json',
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(Category.objects.filter(parent_id=self.category_empty).count(), 2)
+
+ def test_category_with_measurements_cannot_become_group(self):
+ """
+ Test that a category holding measurements cannot be turned into a group
+ """
+ response = self.client.patch(
+ self.detail_url(self.category_with_measurements),
+ {'metric_type': MetricType.BLOOD_PRESSURE},
+ content_type='application/json',
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('metric_type', response.data)
+
+ def test_component_without_group_rejected(self):
+ """
+ Test that a component category cannot be created on its own
+ """
+ response = self.create_category(
+ name='Systolic',
+ unit='mmHg',
+ metric_type=MetricType.BLOOD_PRESSURE_SYSTOLIC,
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('parent', response.data)
+
+ def test_component_under_wrong_group_rejected(self):
+ """
+ Test that a component category only fits under its own group type
+ """
+ response = self.create_category(
+ name='Systolic',
+ unit='mmHg',
+ metric_type=MetricType.BLOOD_PRESSURE_SYSTOLIC,
+ parent=self.category_empty,
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('parent', response.data)
+
+ def test_typed_category_cannot_be_nested(self):
+ """
+ Test that a non-component metric type stays top-level
+ """
+ response = self.create_category(
+ metric_type=MetricType.STEPS,
+ parent=self.category_empty,
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('parent', response.data)
+
+ def test_group_only_holds_its_own_components(self):
+ """
+ Test that a group does not take children other than its components
+ """
+ group = self.create_category(
+ name='Blood pressure',
+ unit='mmHg',
+ metric_type=MetricType.BLOOD_PRESSURE,
+ )
+
+ response = self.create_category(
+ name='Something else',
+ unit='mmHg',
+ parent=group.data['id'],
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('metric_type', response.data)
+
+
class OfficialCategoryTestCase(WgerTestCase):
"""
Automatic creation and protection of official categories
diff --git a/wger/measurements/tests/test_generator.py b/wger/measurements/tests/test_generator.py
index 4ef40ec0e..0deb116ae 100644
--- a/wger/measurements/tests/test_generator.py
+++ b/wger/measurements/tests/test_generator.py
@@ -21,6 +21,7 @@ from wger.measurements.models import (
Category,
Measurement,
)
+from wger.measurements.models.category import MetricType
class MeasurementGeneratorTestCase(WgerTestCase):
@@ -56,3 +57,26 @@ class MeasurementGeneratorTestCase(WgerTestCase):
# Assert
self.assertEqual(Measurement.objects.filter(category__user_id=1).count(), 10)
+
+ def test_generator_health_blood_pressure(self):
+ """
+ The health generator writes into the components of the group
+ """
+ # Act
+ call_command(
+ 'dummy-generator-health-measurements',
+ '--days',
+ 5,
+ '--metrics',
+ 'blood_pressure',
+ )
+
+ # Assert
+ group = Category.objects.get(user_id=1, metric_type=MetricType.BLOOD_PRESSURE)
+ components = group.children.order_by('order')
+ self.assertEqual(
+ [c.metric_type for c in components],
+ [MetricType.BLOOD_PRESSURE_SYSTOLIC, MetricType.BLOOD_PRESSURE_DIASTOLIC],
+ )
+ self.assertFalse(group.measurement_set.exists())
+ self.assertTrue(all(c.measurement_set.exists() for c in components))
diff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.py
index a824e4c58..122d8fe96 100644
--- a/wger/measurements/tests/test_measurements.py
+++ b/wger/measurements/tests/test_measurements.py
@@ -32,6 +32,7 @@ from wger.measurements.models import (
Category,
Measurement,
)
+from wger.measurements.models.category import MetricType
class MeasurementsApiTestCase(api_base_test.ApiBaseResourceTestCase):
@@ -108,6 +109,27 @@ class MeasurementLeafOnlyTestCase(WgerTestCase):
self.assertEqual(response.status_code, 400)
self.assertIn('category', response.data)
+ def test_measurement_on_group_type_rejected(self):
+ """
+ A group type is a container even while it has no children yet
+ """
+ self.user_login('test')
+ Category.objects.filter(pk=self.parent_id).update(
+ metric_type=MetricType.BLOOD_PRESSURE,
+ )
+
+ response = self.client.post(
+ reverse('measurement-list'),
+ {
+ 'category': self.parent_id,
+ 'date': '2021-08-12',
+ 'value': 120,
+ },
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('category', response.data)
+
class MeasurementUnitTestCase(WgerTestCase):
"""
diff --git a/wger/measurements/tests/test_powersync.py b/wger/measurements/tests/test_powersync.py
index 2640b4c5d..a63919173 100644
--- a/wger/measurements/tests/test_powersync.py
+++ b/wger/measurements/tests/test_powersync.py
@@ -12,6 +12,9 @@
#
# You should have received a copy of the GNU Affero General Public License
+# Django
+from django.contrib.auth.models import User
+
# Third Party
from rest_framework import status
@@ -21,6 +24,7 @@ from wger.measurements.models import (
Category,
Measurement,
)
+from wger.measurements.models.category import MetricType
# Pinned in test-measurement-categories.json (uuid field on the matching pk)
@@ -55,6 +59,85 @@ class CategoryPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):
fk_ownership = (('parent', CATEGORY_OTHER_UUID),)
+class TypedCategoryPowerSyncTestCase(powersync_base_test.PowerSyncBaseTestCase):
+ """
+ Typed categories created by an offline client.
+
+ The client derives the same keys the server would, so its pushes converge on
+ the rows that are already there instead of duplicating them.
+ """
+
+ table = 'measurements_category'
+ resource = Category
+
+ def setUp(self):
+ super().setUp()
+ self.authenticate()
+ self.user = User.objects.get(username=self.user_access)
+
+ def push_category(self, metric_type, **data):
+ payload = {
+ 'id': str(Category.deterministic_id(self.user.pk, metric_type)),
+ 'name': 'Blood pressure',
+ 'unit': 'mmHg',
+ 'metric_type': metric_type,
+ **data,
+ }
+ return self.push('PUT', payload)
+
+ def test_group_push_creates_components(self):
+ """
+ A group pushed by the client arrives with its components
+ """
+ response = self.push_category(MetricType.BLOOD_PRESSURE)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(
+ Category.objects.filter(
+ user=self.user,
+ parent__metric_type=MetricType.BLOOD_PRESSURE,
+ ).count(),
+ 2,
+ )
+
+ def test_component_push_matches_the_created_component(self):
+ """
+ A component the client created offline lands on the existing row
+ """
+ self.push_category(MetricType.BLOOD_PRESSURE)
+ count_before = Category.objects.count()
+
+ response = self.push_category(
+ MetricType.BLOOD_PRESSURE_SYSTOLIC,
+ name='Systolic',
+ parent=str(Category.deterministic_id(self.user.pk, MetricType.BLOOD_PRESSURE)),
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(Category.objects.count(), count_before)
+
+ def test_duplicate_typed_category_refused(self):
+ """
+ A second category of the same type is refused permanently
+ """
+ self.push_category(MetricType.STEPS, name='Steps', unit='count')
+ count_before = Category.objects.count()
+
+ response = self.push(
+ 'PUT',
+ {
+ 'id': 'cccccccc-cccc-cccc-cccc-000000000098',
+ 'name': 'Steps again',
+ 'unit': 'count',
+ 'metric_type': MetricType.STEPS,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertTrue(response.json().get('error'), response.content)
+ self.assertEqual(Category.objects.count(), count_before)
+
+
class MeasurementPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestCase):
"""
PowerSync handlers for measurements.Measurement. ``check_fk_ownership``