Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.1 KB
Raw Blame
import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch

from parameterized import parameterized

from posthog import settings
from posthog.models.integration import Integration
from posthog.models.sharing_configuration import SharingConfiguration

from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.facade.models import Insight
from products.subscriptions.backend.facade.contracts import SharedInsightImage

from ee.tasks.slack import handle_slack_event


def create_mock_unfurl_event(team_id: str, links: list[str]):
    return {
        "token": "XXYYZZ",
        "team_id": team_id,
        "api_app_id": "AXXXXXXXXX",
        "event": {
            "type": "link_shared",
            "channel": "Cxxxxxx",
            "is_bot_user_member": True,
            "user": "Uxxxxxxx",
            "message_ts": "123456789.9875",
            "unfurl_id": "C123456.123456789.987501.1b90fa1278528ce6e2f6c5c2bfa1abc9a41d57d02b29d173f40399c9ffdecf4b",
            "event_ts": "123456621.1855",
            "source": "conversations_history",
            "links": [{"domain": "app.posthog.com", "url": link} for link in links],
        },
        "type": "event_callback",
        "authed_users": ["UXXXXXXX1", "UXXXXXXX2"],
        "event_id": "Ev08MFMKH6",
        "event_time": 123456789,
    }


@patch("ee.tasks.slack.render_shared_insight_image")
@patch("ee.tasks.slack.SlackIntegration")
@time_machine.travel("2022-01-01T12:00:00.000Z", tick=False)
class TestSlackSubscriptionsTasks(APIBaseTest):
    dashboard: Dashboard
    insight: Insight
    integration: Integration

    def setUp(self) -> None:
        self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")
        self.sharingconfig = SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
        self.integration = Integration.objects.create(team=self.team, kind="slack", config={"team": {"id": "T12345"}})

    def test_unfurl_event(self, MockSlackIntegration: MagicMock, mock_render_shared_insight_image: MagicMock) -> None:
        mock_slack_integration = MagicMock()
        MockSlackIntegration.return_value = mock_slack_integration
        mock_render_shared_insight_image.return_value = SharedInsightImage(
            title="My Test subscription", image_url="https://example.com/insight.png", alt_text="My Test subscription"
        )
        mock_slack_integration.client.chat_unfurl.return_value = {"ok": "true"}

        handle_slack_event(
            create_mock_unfurl_event(
                "T12345",
                [
                    f"{settings.SITE_URL}/shared/{self.sharingconfig.access_token}",
                    f"{settings.SITE_URL}/shared/not-found",
                ],
            )
        )

        assert mock_slack_integration.client.chat_unfurl.call_count == 1
        post_message_calls = mock_slack_integration.client.chat_unfurl.call_args_list
        first_call = post_message_calls[0].kwargs

        valid_url = f"{settings.SITE_URL}/shared/{self.sharingconfig.access_token}"

        assert first_call == {
            "unfurls": {
                valid_url: {
                    "blocks": [
                        {
                            "type": "section",
                            "text": {"type": "mrkdwn", "text": "My Test subscription"},
                            "accessory": {
                                "type": "image",
                                "image_url": "https://example.com/insight.png",
                                "alt_text": "My Test subscription",
                            },
                        }
                    ]
                }
            },
            "unfurl_id": "C123456.123456789.987501.1b90fa1278528ce6e2f6c5c2bfa1abc9a41d57d02b29d173f40399c9ffdecf4b",
            "source": "conversations_history",
            "channel": "",
            "ts": "",
        }

    @parameterized.expand([("second_workspace_of_the_team", "T99999", True), ("unknown_workspace", "T00000", False)])
    def test_unfurl_uses_the_integration_of_the_event_workspace(
        self,
        MockSlackIntegration: MagicMock,
        mock_render_shared_insight_image: MagicMock,
        _name: str,
        slack_team_id: str,
        expect_unfurl: bool,
    ) -> None:
        second_workspace = Integration.objects.create(
            team=self.team, kind="slack", integration_id="T99999", config={"team": {"id": "T99999"}}
        )
        mock_render_shared_insight_image.return_value = SharedInsightImage(
            title="My Test subscription", image_url="https://example.com/insight.png", alt_text="My Test subscription"
        )

        handle_slack_event(
            create_mock_unfurl_event(slack_team_id, [f"{settings.SITE_URL}/shared/{self.sharingconfig.access_token}"])
        )

        if expect_unfurl:
            MockSlackIntegration.assert_called_once()
            assert MockSlackIntegration.call_args.args[0].pk == second_workspace.pk
            MockSlackIntegration.return_value.client.chat_unfurl.assert_called_once()
        else:
            MockSlackIntegration.assert_not_called()