You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by el...@apache.org on 2025/11/15 01:26:35 UTC
(superset) 01/05: fix(alerts): implement Slack channel pagination to resolve timeout issues
This is an automated email from the ASF dual-hosted git repository.
elizabeth pushed a commit to branch alerts-reports-unable-to-edit-slack-recipients
in repository https://gitbox.apache.org/repos/asf/superset.git
commit f9a2e26723bae902b7c227dbf3b22d0c95ce31b1
Author: Gabriel Torres Ruiz <ga...@gmail.com>
AuthorDate: Fri Oct 24 10:28:17 2025 -0400
fix(alerts): implement Slack channel pagination to resolve timeout issues
---
.../alerts/components/NotificationMethod.test.tsx | 1014 +++++++++++---------
.../alerts/components/NotificationMethod.tsx | 258 +++--
superset/reports/api.py | 11 +-
superset/reports/schemas.py | 3 +
superset/utils/slack.py | 166 +++-
tests/integration_tests/reports/api_tests.py | 177 ++++
tests/unit_tests/utils/slack_test.py | 516 +++++++++-
7 files changed, 1476 insertions(+), 669 deletions(-)
diff --git a/superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx b/superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx
index c4e69ed220..91b8d4d5f6 100644
--- a/superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx
+++ b/superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx
@@ -62,499 +62,621 @@ const mockSettingSlackV2: NotificationSetting = {
],
};
-// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
-describe('NotificationMethod', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- cleanup();
- });
+beforeEach(() => {
+ jest.clearAllMocks();
+ cleanup();
+});
- test('should render the component', () => {
- render(
- <NotificationMethod
- setting={mockSetting}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+test('NotificationMethod - should render the component', () => {
+ render(
+ <NotificationMethod
+ setting={mockSetting}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ expect(screen.getByText('Notification Method')).toBeInTheDocument();
+ expect(screen.getByText('Email subject name (optional)')).toBeInTheDocument();
+ expect(screen.getByText('Email recipients')).toBeInTheDocument();
+});
- expect(screen.getByText('Notification Method')).toBeInTheDocument();
- expect(
- screen.getByText('Email subject name (optional)'),
- ).toBeInTheDocument();
- expect(screen.getByText('Email recipients')).toBeInTheDocument();
- });
+test('NotificationMethod - should call onRemove when the delete button is clicked', () => {
+ render(
+ <NotificationMethod
+ setting={mockSetting}
+ index={1}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ const deleteButton = document.querySelector('.delete-button');
+ if (deleteButton) userEvent.click(deleteButton);
+
+ expect(mockOnRemove).toHaveBeenCalledWith(1);
+});
- test('should call onRemove when the delete button is clicked', () => {
- render(
- <NotificationMethod
- setting={mockSetting}
- index={1}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+test('NotificationMethod - should update recipient value when input changes', () => {
+ render(
+ <NotificationMethod
+ setting={mockSetting}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ const recipientsInput = screen.getByTestId('recipients');
+ fireEvent.change(recipientsInput, {
+ target: { value: 'test1@example.com' },
+ });
- const deleteButton = document.querySelector('.delete-button');
- if (deleteButton) userEvent.click(deleteButton);
+ expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+ ...mockSetting,
+ recipients: 'test1@example.com',
+ });
+});
- expect(mockOnRemove).toHaveBeenCalledWith(1);
+test('NotificationMethod - should call onRecipientsChange when the recipients value is changed', () => {
+ render(
+ <NotificationMethod
+ setting={mockSetting}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ const recipientsInput = screen.getByTestId('recipients');
+ fireEvent.change(recipientsInput, {
+ target: { value: 'test1@example.com' },
});
- test('should update recipient value when input changes', () => {
- render(
- <NotificationMethod
- setting={mockSetting}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+ expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+ ...mockSetting,
+ recipients: 'test1@example.com',
+ });
+});
- const recipientsInput = screen.getByTestId('recipients');
- fireEvent.change(recipientsInput, {
- target: { value: 'test1@example.com' },
- });
+test('NotificationMethod - should correctly map recipients when method is SlackV2', () => {
+ const method = 'SlackV2';
+ const recipientValue = 'user1,user2';
+ const slackOptions: { label: string; value: string }[] = [
+ { label: 'User One', value: 'user1' },
+ { label: 'User Two', value: 'user2' },
+ ];
- expect(mockOnUpdate).toHaveBeenCalledWith(0, {
- ...mockSetting,
- recipients: 'test1@example.com',
- });
- });
+ const result = mapSlackValues({ method, recipientValue, slackOptions });
- test('should call onRecipientsChange when the recipients value is changed', () => {
- render(
- <NotificationMethod
- setting={mockSetting}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+ expect(result).toEqual([
+ { label: 'User One', value: 'user1' },
+ { label: 'User Two', value: 'user2' },
+ ]);
+});
- const recipientsInput = screen.getByTestId('recipients');
- fireEvent.change(recipientsInput, {
- target: { value: 'test1@example.com' },
- });
+test('NotificationMethod - should return an empty array when recipientValue is an empty string', () => {
+ const method = 'SlackV2';
+ const recipientValue = '';
+ const slackOptions: { label: string; value: string }[] = [
+ { label: 'User One', value: 'user1' },
+ { label: 'User Two', value: 'user2' },
+ ];
- expect(mockOnUpdate).toHaveBeenCalledWith(0, {
- ...mockSetting,
- recipients: 'test1@example.com',
- });
- });
+ const result = mapSlackValues({ method, recipientValue, slackOptions });
- test('should correctly map recipients when method is SlackV2', () => {
- const method = 'SlackV2';
- const recipientValue = 'user1,user2';
- const slackOptions: { label: string; value: string }[] = [
- { label: 'User One', value: 'user1' },
- { label: 'User Two', value: 'user2' },
- ];
+ expect(result).toEqual([]);
+});
- const result = mapSlackValues({ method, recipientValue, slackOptions });
+test('NotificationMethod - should correctly map recipients when method is Slack with updated recipient values', () => {
+ const method = 'Slack';
+ const recipientValue = 'User One,User Two';
+ const slackOptions: { label: string; value: string }[] = [
+ { label: 'User One', value: 'user1' },
+ { label: 'User Two', value: 'user2' },
+ ];
- expect(result).toEqual([
- { label: 'User One', value: 'user1' },
- { label: 'User Two', value: 'user2' },
- ]);
- });
+ const result = mapSlackValues({ method, recipientValue, slackOptions });
- test('should return an empty array when recipientValue is an empty string', () => {
- const method = 'SlackV2';
- const recipientValue = '';
- const slackOptions: { label: string; value: string }[] = [
- { label: 'User One', value: 'user1' },
- { label: 'User Two', value: 'user2' },
- ];
+ expect(result).toEqual([
+ { label: 'User One', value: 'user1' },
+ { label: 'User Two', value: 'user2' },
+ ]);
+});
- const result = mapSlackValues({ method, recipientValue, slackOptions });
+test('NotificationMethod - should render CC and BCC fields when method is Email and visibility flags are true', () => {
+ const defaultProps = {
+ setting: {
+ method: NotificationMethodOption.Email,
+ recipients: 'recipient1@example.com, recipient2@example.com',
+ cc: 'cc1@example.com',
+ bcc: 'bcc1@example.com',
+ options: [NotificationMethodOption.Email, NotificationMethodOption.Slack],
+ },
+ index: 0,
+ onUpdate: jest.fn(),
+ onRemove: jest.fn(),
+ onInputChange: jest.fn(),
+ email_subject: 'Test Subject',
+ defaultSubject: 'Default Subject',
+ setErrorSubject: jest.fn(),
+ };
+
+ const { getByTestId } = render(<NotificationMethod {...defaultProps} />);
+
+ // Check if CC and BCC fields are rendered
+ expect(getByTestId('cc')).toBeInTheDocument();
+ expect(getByTestId('bcc')).toBeInTheDocument();
+});
- expect(result).toEqual([]);
- });
+test('NotificationMethod - should render CC and BCC fields with correct values when method is Email', () => {
+ const defaultProps = {
+ setting: {
+ method: NotificationMethodOption.Email,
+ recipients: 'recipient1@example.com, recipient2@example.com',
+ cc: 'cc1@example.com',
+ bcc: 'bcc1@example.com',
+ options: [NotificationMethodOption.Email, NotificationMethodOption.Slack],
+ },
+ index: 0,
+ onUpdate: jest.fn(),
+ onRemove: jest.fn(),
+ onInputChange: jest.fn(),
+ email_subject: 'Test Subject',
+ defaultSubject: 'Default Subject',
+ setErrorSubject: jest.fn(),
+ };
+
+ const { getByTestId } = render(<NotificationMethod {...defaultProps} />);
+
+ // Check if CC and BCC fields are rendered with correct values
+ expect(getByTestId('cc')).toHaveValue('cc1@example.com');
+ expect(getByTestId('bcc')).toHaveValue('bcc1@example.com');
+});
- test('should correctly map recipients when method is Slack with updated recipient values', () => {
- const method = 'Slack';
- const recipientValue = 'User One,User Two';
- const slackOptions: { label: string; value: string }[] = [
- { label: 'User One', value: 'user1' },
- { label: 'User Two', value: 'user2' },
- ];
+test('NotificationMethod - should not render CC and BCC fields when method is not Email', () => {
+ const defaultProps = {
+ setting: {
+ method: NotificationMethodOption.Slack,
+ recipients: 'recipient1@example.com, recipient2@example.com',
+ cc: 'cc1@example.com',
+ bcc: 'bcc1@example.com',
+ options: [NotificationMethodOption.Email, NotificationMethodOption.Slack],
+ },
+ index: 0,
+ onUpdate: jest.fn(),
+ onRemove: jest.fn(),
+ onInputChange: jest.fn(),
+ email_subject: 'Test Subject',
+ defaultSubject: 'Default Subject',
+ setErrorSubject: jest.fn(),
+ };
+
+ const { queryByTestId } = render(<NotificationMethod {...defaultProps} />);
+
+ // Check if CC and BCC fields are not rendered
+ expect(queryByTestId('cc')).not.toBeInTheDocument();
+ expect(queryByTestId('bcc')).not.toBeInTheDocument();
+});
+// Handle empty recipients list gracefully
+test('NotificationMethod - should handle empty recipients list gracefully', () => {
+ const defaultProps = {
+ setting: {
+ method: NotificationMethodOption.Email,
+ recipients: '',
+ cc: '',
+ bcc: '',
+ options: [NotificationMethodOption.Email, NotificationMethodOption.Slack],
+ },
+ index: 0,
+ onUpdate: jest.fn(),
+ onRemove: jest.fn(),
+ onInputChange: jest.fn(),
+ email_subject: 'Test Subject',
+ defaultSubject: 'Default Subject',
+ setErrorSubject: jest.fn(),
+ };
+
+ const { queryByTestId } = render(<NotificationMethod {...defaultProps} />);
+
+ // Check if CC and BCC fields are not rendered
+ expect(queryByTestId('cc')).not.toBeInTheDocument();
+ expect(queryByTestId('bcc')).not.toBeInTheDocument();
+});
- const result = mapSlackValues({ method, recipientValue, slackOptions });
+test('shows the right combo when ff is false', async () => {
+ /* should show the div with "Recipients are separated by"
+ when FeatureFlag.AlertReportSlackV2 is false and fetchSlackChannels errors
+ */
+ // Mock the feature flag to be false
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: false };
- expect(result).toEqual([
- { label: 'User One', value: 'user1' },
- { label: 'User Two', value: 'user2' },
- ]);
- });
- test('should render CC and BCC fields when method is Email and visibility flags are true', () => {
- const defaultProps = {
- setting: {
- method: NotificationMethodOption.Email,
- recipients: 'recipient1@example.com, recipient2@example.com',
- cc: 'cc1@example.com',
- bcc: 'bcc1@example.com',
- options: [
- NotificationMethodOption.Email,
- NotificationMethodOption.Slack,
- ],
- },
- index: 0,
- onUpdate: jest.fn(),
- onRemove: jest.fn(),
- onInputChange: jest.fn(),
- email_subject: 'Test Subject',
- defaultSubject: 'Default Subject',
- setErrorSubject: jest.fn(),
- };
-
- const { getByTestId } = render(<NotificationMethod {...defaultProps} />);
-
- // Check if CC and BCC fields are rendered
- expect(getByTestId('cc')).toBeInTheDocument();
- expect(getByTestId('bcc')).toBeInTheDocument();
- });
- test('should render CC and BCC fields with correct values when method is Email', () => {
- const defaultProps = {
- setting: {
- method: NotificationMethodOption.Email,
- recipients: 'recipient1@example.com, recipient2@example.com',
- cc: 'cc1@example.com',
- bcc: 'bcc1@example.com',
- options: [
- NotificationMethodOption.Email,
- NotificationMethodOption.Slack,
- ],
- },
- index: 0,
- onUpdate: jest.fn(),
- onRemove: jest.fn(),
- onInputChange: jest.fn(),
- email_subject: 'Test Subject',
- defaultSubject: 'Default Subject',
- setErrorSubject: jest.fn(),
- };
-
- const { getByTestId } = render(<NotificationMethod {...defaultProps} />);
-
- // Check if CC and BCC fields are rendered with correct values
- expect(getByTestId('cc')).toHaveValue('cc1@example.com');
- expect(getByTestId('bcc')).toHaveValue('bcc1@example.com');
+ // Mock the SupersetClient.get to simulate an error
+ jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
+ throw new Error('Error fetching Slack channels');
});
- test('should not render CC and BCC fields when method is not Email', () => {
- const defaultProps = {
- setting: {
+
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSetting,
method: NotificationMethodOption.Slack,
- recipients: 'recipient1@example.com, recipient2@example.com',
- cc: 'cc1@example.com',
- bcc: 'bcc1@example.com',
- options: [
- NotificationMethodOption.Email,
- NotificationMethodOption.Slack,
- ],
- },
- index: 0,
- onUpdate: jest.fn(),
- onRemove: jest.fn(),
- onInputChange: jest.fn(),
- email_subject: 'Test Subject',
- defaultSubject: 'Default Subject',
- setErrorSubject: jest.fn(),
- };
-
- const { queryByTestId } = render(<NotificationMethod {...defaultProps} />);
-
- // Check if CC and BCC fields are not rendered
- expect(queryByTestId('cc')).not.toBeInTheDocument();
- expect(queryByTestId('bcc')).not.toBeInTheDocument();
- });
- // Handle empty recipients list gracefully
- test('should handle empty recipients list gracefully', () => {
- const defaultProps = {
- setting: {
- method: NotificationMethodOption.Email,
- recipients: '',
- cc: '',
- bcc: '',
- options: [
- NotificationMethodOption.Email,
- NotificationMethodOption.Slack,
- ],
- },
- index: 0,
- onUpdate: jest.fn(),
- onRemove: jest.fn(),
- onInputChange: jest.fn(),
- email_subject: 'Test Subject',
- defaultSubject: 'Default Subject',
- setErrorSubject: jest.fn(),
- };
-
- const { queryByTestId } = render(<NotificationMethod {...defaultProps} />);
-
- // Check if CC and BCC fields are not rendered
- expect(queryByTestId('cc')).not.toBeInTheDocument();
- expect(queryByTestId('bcc')).not.toBeInTheDocument();
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for the component to handle the error and render the expected div
+ await waitFor(() => {
+ expect(
+ screen.getByText('Recipients are separated by "," or ";"'),
+ ).toBeInTheDocument();
});
- test('shows the right combo when ff is false', async () => {
- /* should show the div with "Recipients are separated by"
- when FeatureFlag.AlertReportSlackV2 is false and fetchSlackChannels errors
- */
- // Mock the feature flag to be false
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: false };
-
- // Mock the SupersetClient.get to simulate an error
- jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
- throw new Error('Error fetching Slack channels');
- });
-
- render(
- <NotificationMethod
- setting={{
- ...mockSetting,
- method: NotificationMethodOption.Slack,
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+});
- // Wait for the component to handle the error and render the expected div
- await waitFor(() => {
- expect(
- screen.getByText('Recipients are separated by "," or ";"'),
- ).toBeInTheDocument();
- });
- });
- test('shows the textbox when the fetch fails', async () => {
- /* should show the div with "Recipients are separated by"
+test('shows the textbox when the fetch fails', async () => {
+ /* should show the div with "Recipients are separated by"
when FeatureFlag.AlertReportSlackV2 is true and fetchSlackChannels errors
*/
- // Mock the feature flag to be false
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: false };
-
- // Mock the SupersetClient.get to simulate an error
- jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
- throw new Error('Error fetching Slack channels');
- });
-
- render(
- <NotificationMethod
- setting={{
- ...mockSetting,
- method: NotificationMethodOption.Slack,
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+ // Mock the feature flag to be false
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: false };
- // Wait for the component to handle the error and render the expected div
- await waitFor(() => {
- expect(
- screen.getByText('Recipients are separated by "," or ";"'),
- ).toBeInTheDocument();
- });
+ // Mock the SupersetClient.get to simulate an error
+ jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
+ throw new Error('Error fetching Slack channels');
});
- test('shows the dropdown when ff is true and slackChannels succeed', async () => {
- /* should show the Select channels dropdown
+
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSetting,
+ method: NotificationMethodOption.Slack,
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for the component to handle the error and render the expected div
+ await waitFor(() => {
+ expect(
+ screen.getByText('Recipients are separated by "," or ";"'),
+ ).toBeInTheDocument();
+ });
+});
+
+test('shows the dropdown when ff is true and slackChannels succeed', async () => {
+ /* should show the Select channels dropdown
when FeatureFlag.AlertReportSlackV2 is true and fetchSlackChannels succeeds
*/
- // Mock the feature flag to be false
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
-
- // Mock the SupersetClient.get to simulate an error
- jest
- .spyOn(SupersetClient, 'get')
- .mockImplementation(
- () =>
- Promise.resolve({ json: { result: [] } }) as unknown as Promise<
- Response | JsonResponse | TextResponse
- >,
- );
-
- render(
- <NotificationMethod
- setting={{
- ...mockSetting,
- method: NotificationMethodOption.SlackV2,
- recipients: 'slack-channel',
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
+ // Mock the feature flag to be false
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+
+ // Mock the SupersetClient.get to simulate an error
+ jest
+ .spyOn(SupersetClient, 'get')
+ .mockImplementation(
+ () =>
+ Promise.resolve({ json: { result: [] } }) as unknown as Promise<
+ Response | JsonResponse | TextResponse
+ >,
);
- // Wait for the component to handle the error and render the expected div
- await waitFor(() => {
- expect(screen.getByTitle('Slack')).toBeInTheDocument();
- });
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSetting,
+ method: NotificationMethodOption.SlackV2,
+ recipients: 'slack-channel',
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for the component to handle the error and render the expected div
+ await waitFor(() => {
+ expect(screen.getByTitle('Slack')).toBeInTheDocument();
});
- test('shows the textarea when ff is true and slackChannels fail', async () => {
- /* should show the Select channels dropdown
+});
+
+test('shows the textarea when ff is true and slackChannels fail', async () => {
+ /* should show the Select channels dropdown
when FeatureFlag.AlertReportSlackV2 is true and fetchSlackChannels succeeds
*/
- // Mock the feature flag to be false
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
-
- // Mock the SupersetClient.get to simulate an error
- jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
- throw new Error('Error fetching Slack channels');
- });
-
- render(
- <NotificationMethod
- setting={{
- ...mockSetting,
- method: NotificationMethodOption.Slack,
- recipients: 'slack-channel',
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+ // Mock the feature flag to be false
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
- // Wait for the component to handle the error and render the expected div
- expect(
- screen.getByText('Recipients are separated by "," or ";"'),
- ).toBeInTheDocument();
+ // Mock the SupersetClient.get to simulate an error
+ jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
+ throw new Error('Error fetching Slack channels');
});
- test('shows the textarea when ff is true and slackChannels fail and slack is selected', async () => {
- /* should show the Select channels dropdown
+
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSetting,
+ method: NotificationMethodOption.Slack,
+ recipients: 'slack-channel',
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for the component to handle the error and render the expected div
+ expect(
+ screen.getByText('Recipients are separated by "," or ";"'),
+ ).toBeInTheDocument();
+});
+
+test('shows the textarea when ff is true and slackChannels fail and slack is selected', async () => {
+ /* should show the Select channels dropdown
when FeatureFlag.AlertReportSlackV2 is true and fetchSlackChannels succeeds
*/
- // Mock the feature flag to be false
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
-
- // Mock the SupersetClient.get to simulate an error
- jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
- throw new Error('Error fetching Slack channels');
- });
-
- render(
- <NotificationMethod
- setting={{
- ...mockSetting,
- method: NotificationMethodOption.Slack,
- recipients: 'slack-channel',
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
+ // Mock the feature flag to be false
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
- // Wait for the component to handle the error and render the expected div
- expect(
- screen.getByText('Recipients are separated by "," or ";"'),
- ).toBeInTheDocument();
+ // Mock the SupersetClient.get to simulate an error
+ jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
+ throw new Error('Error fetching Slack channels');
});
- test('shows the textarea when ff is true, slackChannels fail and slack is selected', async () => {
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
- jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
- throw new Error('Error fetching Slack channels');
- });
-
- render(
- <NotificationMethod
- setting={{
- ...mockSettingSlackV2,
- method: NotificationMethodOption.Slack,
- }}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSetting,
+ method: NotificationMethodOption.Slack,
+ recipients: 'slack-channel',
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for the component to handle the error and render the expected div
+ expect(
+ screen.getByText('Recipients are separated by "," or ";"'),
+ ).toBeInTheDocument();
+});
+
+test('shows the textarea when ff is true, slackChannels fail and slack is selected', async () => {
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+ jest.spyOn(SupersetClient, 'get').mockImplementation(() => {
+ throw new Error('Error fetching Slack channels');
+ });
+
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSettingSlackV2,
+ method: NotificationMethodOption.Slack,
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ expect(
+ screen.getByText('Recipients are separated by "," or ";"'),
+ ).toBeInTheDocument();
+});
+
+test('NotificationMethod - AsyncSelect should render for SlackV2 method', async () => {
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+ const mockChannels = [
+ { name: 'general', id: 'C001', is_private: false, is_member: true },
+ { name: 'random', id: 'C002', is_private: false, is_member: true },
+ ];
+
+ jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ result: mockChannels,
+ next_cursor: null,
+ has_more: false,
+ },
+ } as unknown as Promise<Response | JsonResponse | TextResponse>);
+
+ render(
+ <NotificationMethod
+ setting={mockSettingSlackV2}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Verify AsyncSelect is rendered for SlackV2
+ await waitFor(() => {
+ expect(screen.getByTitle('Slack')).toBeInTheDocument();
+ });
+});
+
+test('NotificationMethod - AsyncSelect should handle SlackV2 with valid API response', async () => {
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+ const mockChannels = [
+ {
+ name: 'test-channel',
+ id: 'C123',
+ is_private: false,
+ is_member: true,
+ },
+ ];
+
+ jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ result: mockChannels,
+ next_cursor: null,
+ has_more: false,
+ },
+ } as unknown as Promise<Response | JsonResponse | TextResponse>);
+
+ const { container } = render(
+ <NotificationMethod
+ setting={mockSettingSlackV2}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Verify AsyncSelect container is present (not a textarea)
+ await waitFor(() => {
+ const textarea = container.querySelector(
+ 'textarea[data-test="recipients"]',
);
+ expect(textarea).toBeNull(); // Should NOT have textarea for SlackV2
+ });
+});
- expect(
- screen.getByText('Recipients are separated by "," or ";"'),
- ).toBeInTheDocument();
+test('NotificationMethod - AsyncSelect should render refresh button for SlackV2', async () => {
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+ const mockChannels = [
+ {
+ name: 'test-channel',
+ id: 'C123',
+ is_private: false,
+ is_member: true,
+ },
+ ];
+
+ jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ result: mockChannels,
+ next_cursor: null,
+ has_more: false,
+ },
+ } as unknown as Promise<Response | JsonResponse | TextResponse>);
+
+ render(
+ <NotificationMethod
+ setting={mockSettingSlackV2}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Verify refresh button is present (icon only button)
+ await waitFor(() => {
+ const refreshButton = screen.getByTestId('refresh-slack-channels');
+ expect(refreshButton).toBeInTheDocument();
+ expect(refreshButton).toHaveAttribute('title', 'Refresh channels');
+ });
+});
+
+test('NotificationMethod - AsyncSelect should clear recipients and reload channels when refresh button clicked', async () => {
+ window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
+ const mockChannels = [
+ {
+ name: 'test-channel',
+ id: 'C123',
+ is_private: false,
+ is_member: true,
+ },
+ ];
+
+ jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ result: mockChannels,
+ next_cursor: null,
+ has_more: false,
+ },
+ } as unknown as Promise<Response | JsonResponse | TextResponse>);
+
+ render(
+ <NotificationMethod
+ setting={{
+ ...mockSettingSlackV2,
+ recipients: 'C123', // Pre-existing recipient
+ }}
+ index={0}
+ onUpdate={mockOnUpdate}
+ onRemove={mockOnRemove}
+ onInputChange={mockOnInputChange}
+ email_subject={mockEmailSubject}
+ defaultSubject={mockDefaultSubject}
+ setErrorSubject={mockSetErrorSubject}
+ />,
+ );
+
+ // Wait for initial render
+ await waitFor(() => {
+ expect(screen.getByTestId('refresh-slack-channels')).toBeInTheDocument();
});
- // eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
- describe('RefreshLabel functionality', () => {
- test('should call updateSlackOptions with force true when RefreshLabel is clicked', async () => {
- // Set feature flag so that SlackV2 branch renders RefreshLabel
- window.featureFlags = { [FeatureFlag.AlertReportSlackV2]: true };
- // Spy on SupersetClient.get which is called by updateSlackOptions
- const supersetClientSpy = jest
- .spyOn(SupersetClient, 'get')
- .mockImplementation(
- () =>
- Promise.resolve({ json: { result: [] } }) as unknown as Promise<
- Response | JsonResponse | TextResponse
- >,
- );
-
- render(
- <NotificationMethod
- setting={mockSettingSlackV2}
- index={0}
- onUpdate={mockOnUpdate}
- onRemove={mockOnRemove}
- onInputChange={mockOnInputChange}
- email_subject={mockEmailSubject}
- defaultSubject={mockDefaultSubject}
- setErrorSubject={mockSetErrorSubject}
- />,
- );
-
- // Wait for RefreshLabel to be rendered (it may have a tooltip with the provided content)
- const refreshLabel = await waitFor(() => screen.getByLabelText('sync'));
- // Simulate a click on the RefreshLabel
- userEvent.click(refreshLabel);
- // Verify that the SupersetClient.get was called indicating that updateSlackOptions executed
- await waitFor(() => {
- expect(supersetClientSpy).toHaveBeenCalled();
- });
- });
+ // Click refresh button
+ const refreshButton = screen.getByTestId('refresh-slack-channels');
+ fireEvent.click(refreshButton);
+
+ // Verify onUpdate was called with empty recipients
+ await waitFor(() => {
+ expect(mockOnUpdate).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ recipients: '',
+ }),
+ );
});
});
diff --git a/superset-frontend/src/features/alerts/components/NotificationMethod.tsx b/superset-frontend/src/features/alerts/components/NotificationMethod.tsx
index 4c53cce544..b1d59d2583 100644
--- a/superset-frontend/src/features/alerts/components/NotificationMethod.tsx
+++ b/superset-frontend/src/features/alerts/components/NotificationMethod.tsx
@@ -20,14 +20,13 @@ import {
FunctionComponent,
useState,
ChangeEvent,
- useEffect,
useMemo,
+ useRef,
} from 'react';
import rison from 'rison';
import {
FeatureFlag,
- JsonResponse,
SupersetClient,
isFeatureEnabled,
styled,
@@ -35,8 +34,7 @@ import {
useTheme,
} from '@superset-ui/core';
import { Icons } from '@superset-ui/core/components/Icons';
-import { Input, Select } from '@superset-ui/core/components';
-import RefreshLabel from '@superset-ui/core/components/RefreshLabel';
+import { Input, Select, AsyncSelect } from '@superset-ui/core/components';
import {
NotificationMethodOption,
NotificationSetting,
@@ -77,6 +75,17 @@ const StyledNotificationMethod = styled.div`
margin-left: ${theme.sizeUnit * 2}px;
padding-top: ${theme.sizeUnit}px;
}
+
+ .refresh-button {
+ margin-left: ${theme.sizeUnit * 2}px;
+ cursor: pointer;
+ color: ${theme.colorTextSecondary};
+
+ &:hover {
+ color: ${theme.colorPrimary};
+ }
+ }
+
.anticon {
margin-left: ${theme.sizeUnit}px;
}
@@ -150,47 +159,6 @@ export const mapSlackValues = ({
.filter(val => !!val) as { label: string; value: string }[];
};
-export const mapChannelsToOptions = (result: SlackChannel[]) => {
- const publicChannels: SlackChannel[] = [];
- const privateChannels: SlackChannel[] = [];
-
- result.forEach(channel => {
- if (channel.is_private) {
- privateChannels.push(channel);
- } else {
- publicChannels.push(channel);
- }
- });
-
- return [
- {
- label: 'Public Channels',
- options: publicChannels.map((channel: SlackChannel) => ({
- label: `${channel.name} ${
- channel.is_member ? '' : t('(Bot not in channel)')
- }`,
- value: channel.id,
- key: channel.id,
- })),
- key: 'public',
- },
- {
- label: t('Private Channels (Bot in channel)'),
- options: privateChannels.map((channel: SlackChannel) => ({
- label: channel.name,
- value: channel.id,
- key: channel.id,
- })),
- key: 'private',
- },
- ];
-};
-
-type SlackOptionsType = {
- label: string;
- options: { label: string; value: string }[];
-}[];
-
export const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
setting = null,
index,
@@ -214,24 +182,16 @@ export const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
const [ccValue, setCcValue] = useState<string>(cc || '');
const [bccValue, setBccValue] = useState<string>(bcc || '');
const theme = useTheme();
- const [methodOptionsLoading, setMethodOptionsLoading] =
- useState<boolean>(true);
- const [slackOptions, setSlackOptions] = useState<SlackOptionsType>([
- {
- label: '',
- options: [],
- },
- ]);
-
const [useSlackV1, setUseSlackV1] = useState<boolean>(false);
- const [isSlackChannelsLoading, setIsSlackChannelsLoading] =
- useState<boolean>(true);
+ const cursorRef = useRef<Record<string, string | null>>({});
+ const [refreshKey, setRefreshKey] = useState(0);
+ const forceRefreshRef = useRef(false);
+ const [isRefreshing, setIsRefreshing] = useState(false);
const onMethodChange = (selected: {
label: string;
value: NotificationMethodOption;
}) => {
- // Since we're swapping the method, reset the recipients
setRecipientValue('');
setCcValue('');
setBccValue('');
@@ -249,84 +209,91 @@ export const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
}
};
- const fetchSlackChannels = async ({
- searchString = '',
- types = [],
- exactMatch = false,
- force = false,
- }: {
- searchString?: string | undefined;
- types?: string[];
- exactMatch?: boolean | undefined;
- force?: boolean | undefined;
- } = {}): Promise<JsonResponse> => {
- const queryString = rison.encode({
- searchString,
- types,
- exactMatch,
- force,
- });
- const endpoint = `/api/v1/report/slack_channels/?q=${queryString}`;
- return SupersetClient.get({ endpoint });
- };
+ const fetchSlackChannels = async (
+ search: string,
+ page: number,
+ pageSize: number,
+ ): Promise<{
+ data: { label: string; value: string }[];
+ totalCount: number;
+ }> => {
+ try {
+ const cacheKey = `${search}:${page}`;
+ const cursor = page > 0 ? cursorRef.current[cacheKey] : null;
+
+ const params: Record<string, any> = {
+ types: ['public_channel', 'private_channel'],
+ limit: pageSize,
+ };
- const updateSlackOptions = async ({
- force,
- }: {
- force?: boolean | undefined;
- } = {}) => {
- setIsSlackChannelsLoading(true);
- fetchSlackChannels({ types: ['public_channel', 'private_channel'], force })
- .then(({ json }) => {
- const { result } = json;
- const options: SlackOptionsType = mapChannelsToOptions(result);
-
- setSlackOptions(options);
-
- if (isFeatureEnabled(FeatureFlag.AlertReportSlackV2)) {
- // for edit mode, map existing ids to names for display if slack v2
- // or names to ids if slack v1
- const [publicOptions, privateOptions] = options;
- if (
- method &&
- [
- NotificationMethodOption.SlackV2,
- NotificationMethodOption.Slack,
- ].includes(method)
- ) {
- setSlackRecipients(
- mapSlackValues({
- method,
- recipientValue,
- slackOptions: [
- ...publicOptions.options,
- ...privateOptions.options,
- ],
- }),
- );
- }
- }
- })
- .catch(e => {
- // Fallback to slack v1 if slack v2 is not compatible
- setUseSlackV1(true);
- })
- .finally(() => {
- setMethodOptionsLoading(false);
- setIsSlackChannelsLoading(false);
- });
+ if (page === 0 && forceRefreshRef.current) {
+ params.force = true;
+ forceRefreshRef.current = false;
+ }
+
+ if (search) {
+ params.search_string = search;
+ }
+
+ if (cursor) {
+ params.cursor = cursor;
+ }
+
+ const queryString = rison.encode(params);
+ const endpoint = `/api/v1/report/slack_channels/?q=${queryString}`;
+ const response = await SupersetClient.get({ endpoint });
+
+ const { result, next_cursor, has_more } = response.json;
+
+ if (next_cursor) {
+ cursorRef.current[`${search}:${page + 1}`] = next_cursor;
+ }
+
+ const options = result.map((channel: SlackChannel) => ({
+ label: channel.name,
+ value: channel.id,
+ }));
+
+ const totalCount = has_more
+ ? (page + 1) * pageSize + 1 // Fake "has more"
+ : page * pageSize + options.length; // Last page
+
+ return {
+ data: options,
+ totalCount,
+ };
+ } catch (error) {
+ console.error('Failed to fetch Slack channels:', error);
+ setUseSlackV1(true);
+ throw error;
+ }
};
- useEffect(() => {
- const slackEnabled = options?.some(
- option =>
- option === NotificationMethodOption.Slack ||
- option === NotificationMethodOption.SlackV2,
- );
- if (slackEnabled && !slackOptions[0]?.options.length) {
- updateSlackOptions();
+ const handleRefreshSlackChannels = async () => {
+ setIsRefreshing(true);
+
+ try {
+ forceRefreshRef.current = true;
+ cursorRef.current = {};
+
+ setSlackRecipients([]);
+
+ if (onUpdate && setting) {
+ onUpdate(index, {
+ ...setting,
+ recipients: '',
+ } as NotificationSetting);
+ }
+
+ await fetchSlackChannels('', 0, 100);
+
+ setRefreshKey(prev => prev + 1);
+ } catch (error) {
+ console.error('Error refreshing channels:', error);
+ } finally {
+ setIsRefreshing(false);
}
- }, []);
+ };
const methodOptions = useMemo(
() =>
@@ -459,10 +426,8 @@ export const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
options={methodOptions}
showSearch
value={methodOptions.find(option => option.value === method)}
- loading={methodOptionsLoading}
/>
{index !== 0 && !!onRemove ? (
- // eslint-disable-next-line jsx-a11y/control-has-associated-label
<span
role="button"
tabIndex={0}
@@ -541,24 +506,31 @@ export const NotificationMethod: FunctionComponent<NotificationMethodProps> = ({
) : (
// for SlackV2
<div className="input-container">
- <Select
+ <AsyncSelect
+ key={refreshKey}
ariaLabel={t('Select channels')}
mode="multiple"
name="recipients"
value={slackRecipients}
- options={slackOptions}
+ options={fetchSlackChannels}
onChange={onSlackRecipientsChange}
allowClear
data-test="recipients"
- loading={isSlackChannelsLoading}
- allowSelectAll={false}
- labelInValue
- />
- <RefreshLabel
- onClick={() => updateSlackOptions({ force: true })}
- tooltipContent={t('Force refresh Slack channels list')}
- disabled={isSlackChannelsLoading}
+ fetchOnlyOnSearch={false}
+ pageSize={100}
+ placeholder={t('Select Slack channels')}
/>
+ <span
+ role="button"
+ tabIndex={0}
+ className="refresh-button"
+ onClick={handleRefreshSlackChannels}
+ data-test="refresh-slack-channels"
+ title={t('Refresh channels')}
+ style={{ opacity: isRefreshing ? 0.5 : 1 }}
+ >
+ <Icons.SyncOutlined iconSize="l" spin={isRefreshing} />
+ </span>
</div>
)}
</div>
diff --git a/superset/reports/api.py b/superset/reports/api.py
index a0ebabb202..8763d87ed9 100644
--- a/superset/reports/api.py
+++ b/superset/reports/api.py
@@ -577,14 +577,17 @@ class ReportScheduleRestApi(BaseSupersetModelRestApi):
search_string = params.get("search_string")
types = params.get("types", [])
exact_match = params.get("exact_match", False)
- force = params.get("force", False)
- channels = get_channels_with_search(
+ cursor = params.get("cursor")
+ limit = params.get("limit", 100)
+
+ channels_data = get_channels_with_search(
search_string=search_string,
types=types,
exact_match=exact_match,
- force=force,
+ cursor=cursor,
+ limit=limit,
)
- return self.response(200, result=channels)
+ return self.response(200, **channels_data)
except SupersetException as ex:
logger.error("Error fetching slack channels %s", str(ex))
return self.response_422(message=str(ex))
diff --git a/superset/reports/schemas.py b/superset/reports/schemas.py
index cfccc579bc..6b78fa55bb 100644
--- a/superset/reports/schemas.py
+++ b/superset/reports/schemas.py
@@ -58,6 +58,9 @@ get_slack_channels_schema = {
"items": {"type": "string", "enum": ["public_channel", "private_channel"]},
},
"exact_match": {"type": "boolean"},
+ "cursor": {"type": ["string", "null"]},
+ "limit": {"type": "integer", "default": 100},
+ "force": {"type": "boolean"},
},
}
diff --git a/superset/utils/slack.py b/superset/utils/slack.py
index ce3d214af5..2fc078d741 100644
--- a/superset/utils/slack.py
+++ b/superset/utils/slack.py
@@ -17,7 +17,7 @@
import logging
-from typing import Callable, Optional
+from typing import Any, Optional
from flask import current_app as app
from slack_sdk import WebClient
@@ -30,7 +30,6 @@ from superset.extensions import cache_manager
from superset.reports.schemas import SlackChannelSchema
from superset.utils import cache as cache_util
from superset.utils.backports import StrEnum
-from superset.utils.core import recipients_string_to_list
logger = logging.getLogger(__name__)
@@ -117,22 +116,137 @@ def get_channels() -> list[SlackChannelSchema]:
raise
+def _fetch_channels_without_search(
+ client: WebClient,
+ channel_schema: SlackChannelSchema,
+ types_param: str,
+ cursor: Optional[str],
+ limit: int,
+) -> dict[str, Any]:
+ """Fetch channels without search filtering, paginating as needed."""
+ response = client.conversations_list(
+ limit=limit,
+ cursor=cursor,
+ exclude_archived=True,
+ types=types_param,
+ )
+
+ channels = [channel_schema.load(channel) for channel in response.data["channels"]]
+
+ next_cursor = response.data.get("response_metadata", {}).get("next_cursor")
+
+ return {
+ "result": channels,
+ "next_cursor": next_cursor,
+ "has_more": bool(next_cursor),
+ }
+
+
+def _channel_matches_search(
+ channel: dict[str, Any], search_string: str, exact_match: bool
+) -> bool:
+ """Check if a channel matches the search criteria."""
+ search_lower = search_string.lower()
+ name_lower = channel["name"].lower()
+ id_lower = channel["id"].lower()
+
+ if exact_match:
+ return search_lower == name_lower or search_lower == id_lower
+ return search_lower in name_lower or search_lower in id_lower
+
+
+def _fetch_channels_with_search(
+ client: WebClient,
+ channel_schema: SlackChannelSchema,
+ types_param: str,
+ search_string: str,
+ exact_match: bool,
+ cursor: Optional[str],
+ limit: int,
+) -> dict[str, Any]:
+ """Fetch channels with search filtering, streaming through pages."""
+ matches: list[SlackChannelSchema] = []
+ slack_cursor = cursor
+ max_pages_to_fetch = 50
+ pages_fetched = 0
+
+ while len(matches) < limit and pages_fetched < max_pages_to_fetch:
+ response = client.conversations_list(
+ limit=200,
+ cursor=slack_cursor,
+ exclude_archived=True,
+ types=types_param,
+ )
+
+ for channel_data in response.data["channels"]:
+ channel = channel_schema.load(channel_data)
+
+ if _channel_matches_search(channel, search_string, exact_match):
+ matches.append(channel)
+
+ if len(matches) >= limit:
+ break
+
+ slack_cursor = response.data.get("response_metadata", {}).get("next_cursor")
+ if not slack_cursor:
+ break
+
+ pages_fetched += 1
+
+ has_more = bool(slack_cursor) and len(matches) >= limit
+
+ return {
+ "result": matches[:limit],
+ "next_cursor": slack_cursor if has_more else None,
+ "has_more": has_more,
+ }
+
+
def get_channels_with_search(
search_string: str = "",
types: Optional[list[SlackChannelTypes]] = None,
exact_match: bool = False,
- force: bool = False,
-) -> list[SlackChannelSchema]:
+ cursor: Optional[str] = None,
+ limit: int = 100,
+) -> dict[str, Any]:
"""
- The slack api is paginated but does not include search, so we need to fetch
- all channels and filter them ourselves
- This will search by slack name or id
+ Fetches Slack channels with pagination and search support.
+
+ Returns a dict with:
+ - result: list of channels
+ - next_cursor: cursor for next page (None if no more pages)
+ - has_more: boolean indicating if more pages exist
+
+ The Slack API is paginated but does not include search. We handle two cases:
+ 1. WITHOUT search: Fetch single page from Slack API (fast, no timeout)
+ 2. WITH search: Stream through Slack API pages until we find enough matches
+ (stops early to prevent timeouts on large workspaces)
"""
try:
- channels = get_channels(
- force=force,
- cache_timeout=app.config["SLACK_CACHE_TIMEOUT"],
+ client = get_slack_client()
+ channel_schema = SlackChannelSchema()
+
+ types_param = (
+ ",".join(types)
+ if types and len(types) < len(SlackChannelTypes)
+ else ",".join(SlackChannelTypes)
)
+
+ if not search_string:
+ return _fetch_channels_without_search(
+ client, channel_schema, types_param, cursor, limit
+ )
+
+ return _fetch_channels_with_search(
+ client,
+ channel_schema,
+ types_param,
+ search_string,
+ exact_match,
+ cursor,
+ limit,
+ )
+
except SlackApiError as ex:
# Check if it's a rate limit error
status_code = getattr(ex.response, "status_code", None)
@@ -146,38 +260,6 @@ def get_channels_with_search(
except SlackClientError as ex:
raise SupersetException(f"Failed to list channels: {ex}") from ex
- if types and not len(types) == len(SlackChannelTypes):
- conditions: list[Callable[[SlackChannelSchema], bool]] = []
- if SlackChannelTypes.PUBLIC in types:
- conditions.append(lambda channel: not channel["is_private"])
- if SlackChannelTypes.PRIVATE in types:
- conditions.append(lambda channel: channel["is_private"])
-
- channels = [
- channel for channel in channels if any(cond(channel) for cond in conditions)
- ]
-
- # The search string can be multiple channels separated by commas
- if search_string:
- search_array = recipients_string_to_list(search_string)
- channels = [
- channel
- for channel in channels
- if any(
- (
- search.lower() == channel["name"].lower()
- or search.lower() == channel["id"].lower()
- if exact_match
- else (
- search.lower() in channel["name"].lower()
- or search.lower() in channel["id"].lower()
- )
- )
- for search in search_array
- )
- ]
- return channels
-
def should_use_v2_api() -> bool:
if not feature_flag_manager.is_feature_enabled("ALERT_REPORT_SLACK_V2"):
diff --git a/tests/integration_tests/reports/api_tests.py b/tests/integration_tests/reports/api_tests.py
index 58bde34ac7..a09c8e118b 100644
--- a/tests/integration_tests/reports/api_tests.py
+++ b/tests/integration_tests/reports/api_tests.py
@@ -2049,3 +2049,180 @@ class TestReportSchedulesApi(SupersetTestCase):
)
assert json.loads(report_schedule.extra_json) == extra_json
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_without_pagination(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint without pagination
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock response without pagination
+ mock_get_channels.return_value = {
+ "result": [
+ {"id": "C001", "name": "general", "is_private": False, "is_member": True},
+ {"id": "C002", "name": "random", "is_private": False, "is_member": True},
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ uri = "api/v1/report/slack_channels/"
+ rv = self.client.get(uri)
+ assert rv.status_code == 200
+
+ data = json.loads(rv.data.decode("utf-8"))
+ assert len(data["result"]) == 2
+ assert data["result"][0]["name"] == "general"
+ assert data["next_cursor"] is None
+ assert data["has_more"] is False
+
+ # Verify get_channels_with_search was called with defaults
+ mock_get_channels.assert_called_once_with(
+ search_string=None,
+ types=[],
+ exact_match=False,
+ cursor=None,
+ limit=100,
+ )
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_with_pagination(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint with pagination
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock response with pagination
+ mock_get_channels.return_value = {
+ "result": [
+ {"id": f"C{i:03d}", "name": f"channel-{i}", "is_private": False, "is_member": True}
+ for i in range(100)
+ ],
+ "next_cursor": "page_1",
+ "has_more": True,
+ }
+
+ uri = "api/v1/report/slack_channels/?q=(limit:100)"
+ rv = self.client.get(uri)
+ assert rv.status_code == 200
+
+ data = json.loads(rv.data.decode("utf-8"))
+ assert len(data["result"]) == 100
+ assert data["next_cursor"] == "page_1"
+ assert data["has_more"] is True
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_with_cursor(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint with cursor for next page
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock response for second page
+ mock_get_channels.return_value = {
+ "result": [
+ {"id": "C100", "name": "channel-100", "is_private": False, "is_member": True},
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ uri = "api/v1/report/slack_channels/?q=(cursor:'page_1',limit:100)"
+ rv = self.client.get(uri)
+ assert rv.status_code == 200
+
+ data = json.loads(rv.data.decode("utf-8"))
+ assert len(data["result"]) == 1
+ assert data["next_cursor"] is None
+
+ # Verify cursor was passed
+ mock_get_channels.assert_called_once_with(
+ search_string=None,
+ types=[],
+ exact_match=False,
+ cursor="page_1",
+ limit=100,
+ )
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_with_search(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint with search parameter
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock response with search results
+ mock_get_channels.return_value = {
+ "result": [
+ {"id": "C001", "name": "engineering", "is_private": False, "is_member": True},
+ {"id": "C002", "name": "engineering-ops", "is_private": True, "is_member": True},
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ uri = "api/v1/report/slack_channels/?q=(search_string:'engineering')"
+ rv = self.client.get(uri)
+ assert rv.status_code == 200
+
+ data = json.loads(rv.data.decode("utf-8"))
+ assert len(data["result"]) == 2
+ assert all("engineering" in ch["name"] for ch in data["result"])
+
+ # Verify search_string was passed
+ mock_get_channels.assert_called_once_with(
+ search_string="engineering",
+ types=[],
+ exact_match=False,
+ cursor=None,
+ limit=100,
+ )
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_with_types(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint with channel types filter
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock response with filtered types
+ mock_get_channels.return_value = {
+ "result": [
+ {"id": "C001", "name": "general", "is_private": False, "is_member": True},
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ uri = "api/v1/report/slack_channels/?q=(types:!('public_channel'))"
+ rv = self.client.get(uri)
+ assert rv.status_code == 200
+
+ # Verify types were passed
+ mock_get_channels.assert_called_once_with(
+ search_string=None,
+ types=["public_channel"],
+ exact_match=False,
+ cursor=None,
+ limit=100,
+ )
+
+ @patch("superset.reports.api.get_channels_with_search")
+ def test_slack_channels_api_error_handling(self, mock_get_channels):
+ """
+ Test /api/v1/report/slack_channels/ endpoint error handling
+ """
+ self.login(ADMIN_USERNAME)
+
+ # Mock Slack API error
+ from superset.exceptions import SupersetException
+
+ mock_get_channels.side_effect = SupersetException("Slack API error")
+
+ uri = "api/v1/report/slack_channels/"
+ rv = self.client.get(uri)
+ assert rv.status_code == 422
+
+ data = json.loads(rv.data.decode("utf-8"))
+ assert "Slack API error" in data["message"]
diff --git a/tests/unit_tests/utils/slack_test.py b/tests/unit_tests/utils/slack_test.py
index 024d6cf96e..919c18461b 100644
--- a/tests/unit_tests/utils/slack_test.py
+++ b/tests/unit_tests/utils/slack_test.py
@@ -34,7 +34,14 @@ class TestGetChannelsWithSearch:
def test_fetch_all_channels_no_search_string(self, mocker):
# Mock data
mock_data = {
- "channels": [{"name": "general", "id": "C12345"}],
+ "channels": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
"response_metadata": {"next_cursor": None},
}
@@ -46,12 +53,30 @@ class TestGetChannelsWithSearch:
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
result = get_channels_with_search()
- assert result == [{"name": "general", "id": "C12345"}]
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
# Handle an empty search string gracefully
def test_handle_empty_search_string(self, mocker):
mock_data = {
- "channels": [{"name": "general", "id": "C12345"}],
+ "channels": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
"response_metadata": {"next_cursor": None},
}
@@ -61,15 +86,41 @@ class TestGetChannelsWithSearch:
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
result = get_channels_with_search(search_string="")
- assert result == [{"name": "general", "id": "C12345"}]
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
def test_handle_exact_match_search_string_single_channel(self, mocker):
# Mock data with multiple channels
mock_data = {
"channels": [
- {"name": "general", "id": "C12345"},
- {"name": "general2", "id": "C13454"},
- {"name": "random", "id": "C67890"},
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "general2",
+ "id": "C13454",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ },
],
"response_metadata": {"next_cursor": None},
}
@@ -81,17 +132,45 @@ class TestGetChannelsWithSearch:
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
# Call the function with a search string that matches a single channel
- result = get_channels_with_search(search_string="general", exact_match=True)
+ result = get_channels_with_search(
+ search_string="general", exact_match=True, limit=100
+ )
- # Assert that the result is a list with a single channel dictionary
- assert result == [{"name": "general", "id": "C12345"}]
+ # Assert that the result is a dict with proper structure
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
def test_handle_exact_match_search_string_multiple_channels(self, mocker):
mock_data = {
"channels": [
- {"name": "general", "id": "C12345"},
- {"name": "general2", "id": "C13454"},
- {"name": "random", "id": "C67890"},
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "general2",
+ "id": "C13454",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ },
],
"response_metadata": {"next_cursor": None},
}
@@ -102,19 +181,48 @@ class TestGetChannelsWithSearch:
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
result = get_channels_with_search(
- search_string="general,random", exact_match=True
+ search_string="general,random", exact_match=True, limit=100
)
- assert result == [
- {"name": "general", "id": "C12345"},
- {"name": "random", "id": "C67890"},
- ]
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ },
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
def test_handle_loose_match_search_string_multiple_channels(self, mocker):
mock_data = {
"channels": [
- {"name": "general", "id": "C12345"},
- {"name": "general2", "id": "C13454"},
- {"name": "random", "id": "C67890"},
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "general2",
+ "id": "C13454",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ },
],
"response_metadata": {"next_cursor": None},
}
@@ -124,12 +232,31 @@ class TestGetChannelsWithSearch:
mock_client.conversations_list.return_value = mock_response_instance
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
- result = get_channels_with_search(search_string="general,random")
- assert result == [
- {"name": "general", "id": "C12345"},
- {"name": "general2", "id": "C13454"},
- {"name": "random", "id": "C67890"},
- ]
+ result = get_channels_with_search(search_string="general,random", limit=100)
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "general2",
+ "id": "C13454",
+ "is_private": False,
+ "is_member": True,
+ },
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ },
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
def test_handle_slack_client_error_listing_channels(self, mocker):
from slack_sdk.errors import SlackApiError
@@ -189,15 +316,93 @@ The server responded with: missing scope: channels:read"""
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
result = get_channels_with_search(types=types)
- assert {channel["id"] for channel in result} == expected_channel_ids
+ assert {channel["id"] for channel in result["result"]} == expected_channel_ids
+
+ def test_handle_pagination_without_search(self, mocker):
+ """Test pagination returns single page with cursor"""
+ mock_data_page1 = {
+ "channels": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "response_metadata": {"next_cursor": "page2_cursor"},
+ }
+
+ mock_response_instance_page1 = MockResponse(mock_data_page1)
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response_instance_page1
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ result = get_channels_with_search(limit=100)
+ assert result == {
+ "result": [
+ {
+ "name": "general",
+ "id": "C12345",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "next_cursor": "page2_cursor",
+ "has_more": True,
+ }
+
+ def test_handle_pagination_with_cursor(self, mocker):
+ """Test pagination with cursor fetches next page"""
+ mock_data_page2 = {
+ "channels": [
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "response_metadata": {"next_cursor": None},
+ }
- def test_handle_pagination_multiple_pages(self, mocker):
+ mock_response_instance_page2 = MockResponse(mock_data_page2)
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response_instance_page2
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ result = get_channels_with_search(cursor="page2_cursor", limit=100)
+ assert result == {
+ "result": [
+ {
+ "name": "random",
+ "id": "C67890",
+ "is_private": False,
+ "is_member": True,
+ }
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ def test_streaming_search_pagination(self, mocker):
+ """Test search mode streams through pages until limit is reached"""
mock_data_page1 = {
- "channels": [{"name": "general", "id": "C12345"}],
+ "channels": [
+ {"name": "general", "id": "C1", "is_private": False, "is_member": True},
+ {"name": "random", "id": "C2", "is_private": False, "is_member": True},
+ ],
"response_metadata": {"next_cursor": "page2"},
}
mock_data_page2 = {
- "channels": [{"name": "random", "id": "C67890"}],
+ "channels": [
+ {
+ "name": "general-2",
+ "id": "C3",
+ "is_private": False,
+ "is_member": True,
+ },
+ {"name": "other", "id": "C4", "is_private": False, "is_member": True},
+ ],
"response_metadata": {"next_cursor": None},
}
@@ -211,8 +416,251 @@ The server responded with: missing scope: channels:read"""
]
mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+ # Search for "general" - should find 2 channels across 2 pages
+ result = get_channels_with_search(search_string="general", limit=100)
+ assert result == {
+ "result": [
+ {"name": "general", "id": "C1", "is_private": False, "is_member": True},
+ {
+ "name": "general-2",
+ "id": "C3",
+ "is_private": False,
+ "is_member": True,
+ },
+ ],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ def test_streaming_search_max_pages_safety_limit(self, mocker):
+ """Test that streaming search stops after 50 pages to prevent runaway requests"""
+
+ # Create a response that always has a next cursor (infinite pagination)
+ mock_data = {
+ "channels": [
+ {"name": "channel", "id": "C1", "is_private": False, "is_member": True},
+ ],
+ "response_metadata": {"next_cursor": "next_page"},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Search that matches the channel - should stop at 50 pages
+ result = get_channels_with_search(search_string="channel", limit=100)
+
+ # Should have called conversations_list exactly 50 times (max pages)
+ assert mock_client.conversations_list.call_count == 50
+ # Should return the matches found (50 channels, one per page)
+ assert len(result["result"]) == 50
+
+ def test_search_with_no_matches(self, mocker):
+ """Test search that finds no matching channels"""
+
+ mock_data = {
+ "channels": [
+ {"name": "general", "id": "C1", "is_private": False, "is_member": True},
+ {"name": "random", "id": "C2", "is_private": False, "is_member": True},
+ ],
+ "response_metadata": {"next_cursor": None},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Search for non-existent channel
+ result = get_channels_with_search(search_string="nonexistent", limit=100)
+
+ assert result == {
+ "result": [],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ def test_search_returns_exactly_limit(self, mocker):
+ """Test search that returns exactly the requested limit"""
+
+ # Create 100 matching channels
+ channels = [
+ {"name": f"test-{i}", "id": f"C{i}", "is_private": False, "is_member": True}
+ for i in range(100)
+ ]
+
+ mock_data = {
+ "channels": channels,
+ "response_metadata": {"next_cursor": "next_page"},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Search that matches all channels
+ result = get_channels_with_search(search_string="test", limit=100)
+
+ # Should return exactly 100 channels
+ assert len(result["result"]) == 100
+ # Should indicate more results available
+ assert result["has_more"] is True
+ assert result["next_cursor"] == "next_page"
+
+ def test_partial_page_results(self, mocker):
+ """Test pagination with partial page (less than limit)"""
+
+ # Only 50 channels returned (less than default 100 limit)
+ channels = [
+ {
+ "name": f"channel-{i}",
+ "id": f"C{i}",
+ "is_private": False,
+ "is_member": True,
+ }
+ for i in range(50)
+ ]
+
+ mock_data = {
+ "channels": channels,
+ "response_metadata": {"next_cursor": None},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ result = get_channels_with_search(limit=100)
+
+ # Should return all 50 channels
+ assert len(result["result"]) == 50
+ # Should indicate no more results
+ assert result["has_more"] is False
+ assert result["next_cursor"] is None
+
+ def test_streaming_search_stops_when_limit_reached(self, mocker):
+ """Test that streaming search stops immediately when limit is reached"""
+
+ # First page with 60 matching channels
+ page1_channels = [
+ {"name": f"test-{i}", "id": f"C{i}", "is_private": False, "is_member": True}
+ for i in range(60)
+ ]
+ # Second page with 60 more matching channels (should not be fully processed)
+ page2_channels = [
+ {
+ "name": f"test-{i}",
+ "id": f"C{i+60}",
+ "is_private": False,
+ "is_member": True,
+ }
+ for i in range(60)
+ ]
+
+ mock_data_page1 = {
+ "channels": page1_channels,
+ "response_metadata": {"next_cursor": "page2"},
+ }
+ mock_data_page2 = {
+ "channels": page2_channels,
+ "response_metadata": {"next_cursor": "page3"},
+ }
+
+ mock_response_page1 = MockResponse(mock_data_page1)
+ mock_response_page2 = MockResponse(mock_data_page2)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.side_effect = [
+ mock_response_page1,
+ mock_response_page2,
+ ]
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Request limit of 100
+ result = get_channels_with_search(search_string="test", limit=100)
+
+ # Should return exactly 100 channels (60 from page1 + 40 from page2)
+ assert len(result["result"]) == 100
+ # Should indicate more results available (stopped at page2 cursor)
+ assert result["has_more"] is True
+ assert result["next_cursor"] == "page2"
+
+ def test_cursor_format_with_special_characters(self, mocker):
+ """Test that cursor with special characters is handled correctly"""
+
+ # Slack cursors are base64 encoded strings that might contain special chars
+ special_cursor = "dGVhbTpDMDYxRkE1UEw="
+
+ mock_data = {
+ "channels": [
+ {"name": "test", "id": "C123", "is_private": False, "is_member": True},
+ ],
+ "response_metadata": {"next_cursor": None},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Call with special cursor
+ result = get_channels_with_search(cursor=special_cursor, limit=100)
+
+ # Verify cursor was passed to Slack API
+ mock_client.conversations_list.assert_called_once()
+ call_kwargs = mock_client.conversations_list.call_args[1]
+ assert call_kwargs["cursor"] == special_cursor
+
+ def test_empty_channel_list_response(self, mocker):
+ """Test handling of empty channels list from Slack API"""
+
+ mock_data = {
+ "channels": [],
+ "response_metadata": {"next_cursor": None},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
result = get_channels_with_search()
- assert result == [
- {"name": "general", "id": "C12345"},
- {"name": "random", "id": "C67890"},
+
+ assert result == {
+ "result": [],
+ "next_cursor": None,
+ "has_more": False,
+ }
+
+ def test_custom_limit_parameter(self, mocker):
+ """Test that custom limit parameter is respected"""
+
+ channels = [
+ {
+ "name": f"channel-{i}",
+ "id": f"C{i}",
+ "is_private": False,
+ "is_member": True,
+ }
+ for i in range(200)
]
+
+ mock_data = {
+ "channels": channels,
+ "response_metadata": {"next_cursor": "next_page"},
+ }
+ mock_response = MockResponse(mock_data)
+
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = mock_response
+ mocker.patch("superset.utils.slack.get_slack_client", return_value=mock_client)
+
+ # Request custom limit of 50
+ result = get_channels_with_search(limit=50)
+
+ # Should return exactly 50 channels
+ assert len(result["result"]) == 50
+ assert result["has_more"] is True