diff --git a/api/features/tasks.py b/api/features/tasks.py index c935fabf44f4..125409d7a1ae 100644 --- a/api/features/tasks.py +++ b/api/features/tasks.py @@ -34,7 +34,7 @@ def trigger_feature_state_change_webhooks( else _get_feature_state_webhook_data(instance) ) data = {"new_state": new_state, "changed_by": changed_by, "timestamp": timestamp} - previous_state = _get_previous_state(history_instance, event_type) + previous_state = _get_previous_state(instance, history_instance, event_type) if previous_state: data.update(previous_state=previous_state) @@ -52,10 +52,12 @@ def trigger_feature_state_change_webhooks( def _get_previous_state( - history_instance: HistoricalFeatureState, event_type: WebhookEventType + instance: FeatureState, + history_instance: HistoricalFeatureState, + event_type: WebhookEventType, ) -> dict: if event_type == WebhookEventType.FLAG_DELETED: - return _get_feature_state_webhook_data(history_instance.instance) + return _get_feature_state_webhook_data(instance) if history_instance and history_instance.prev_record: return _get_feature_state_webhook_data( history_instance.prev_record.instance, previous=True diff --git a/api/tests/unit/features/test_unit_features_tasks.py b/api/tests/unit/features/test_unit_features_tasks.py index 769e7e95e95a..6cb222fe39a1 100644 --- a/api/tests/unit/features/test_unit_features_tasks.py +++ b/api/tests/unit/features/test_unit_features_tasks.py @@ -97,3 +97,43 @@ def test_trigger_feature_state_change_webhooks_for_deleted_flag( assert data["new_state"] is None assert data["previous_state"]["feature_state_value"] == new_value assert event_type == WebhookEventType.FLAG_DELETED.value + + +@pytest.mark.django_db +def test_trigger_feature_state_change_webhooks_for_deleted_flag_uses_fs_instance( + mocker: MockerFixture, + environment: Environment, + feature: Feature, +): + # Given + feature_state = FeatureState.objects.get(feature=feature, environment=environment) + + # Remove history instance to make sure it's not used + feature_state.history.all().delete() + + mock_call_environment_webhooks = mocker.patch( + "features.tasks.call_environment_webhooks" + ) + mock_call_organisation_webhooks = mocker.patch( + "features.tasks.call_organisation_webhooks" + ) + + trigger_feature_state_change_webhooks(feature_state, WebhookEventType.FLAG_DELETED) + + # Then + environment_webhook_call_args = ( + mock_call_environment_webhooks.delay.call_args.kwargs["args"] + ) + organisation_webhook_call_args = ( + mock_call_organisation_webhooks.delay.call_args.kwargs["args"] + ) + + # verify that the data for both calls is the same + assert environment_webhook_call_args[1] == organisation_webhook_call_args[1] + + data = environment_webhook_call_args[1] + event_type = environment_webhook_call_args[2] + assert data["new_state"] is None + + assert data["previous_state"]["feature"]["id"] == feature_state.feature.id + assert event_type == WebhookEventType.FLAG_DELETED.value