rebenitez1802 commented on code in PR #45591:
URL: https://github.com/apache/superset/pull/45591#discussion_r4352859436


##########
superset-frontend/src/features/groups/utils.test.ts:
##########
@@ -0,0 +1,217 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { SupersetClient } from '@superset-ui/core';
+import rison from 'rison';
+import { render, screen } from 'spec/helpers/testing-library';
+import {
+  fetchUserOptions,
+  toUserSelectOption,
+  USER_OPTION_FILTER_PROPS,
+  userOptionSortComparator,
+} from './utils';
+
+type GetResponse = Awaited<ReturnType<typeof SupersetClient.get>>;
+
+const getMock = jest.spyOn(SupersetClient, 'get');
+
+const mockUsersResponse = (
+  result: Record<string, unknown>[],
+  count = result.length,
+) =>
+  getMock.mockResolvedValue({
+    json: { count, result },
+  } as unknown as GetResponse);
+
+const decodeQuery = () => {
+  const { endpoint } = getMock.mock.calls[0][0] as { endpoint: string };
+  return rison.decode(endpoint.split('?q=')[1]);

Review Comment:
   With `rison.encode_uri`, spaces are sent as `+` (e.g. `Jane+Sm`), so 
`rison.decode` on the raw split string would fail. Decode `q` the way the 
server does:
   
   ```suggestion
     const q = new URLSearchParams(endpoint.split('?')[1]).get('q') ?? '';
     return rison.decode(q);
   ```
   



##########
superset-frontend/src/features/groups/utils.ts:
##########
@@ -47,8 +112,13 @@ export const fetchUserOptions = async (
   pageSize: number,
   addDangerToast: (msg: string) => void,
 ) => {
+  // The ListView filter path passes the raw input, so trim here to keep both
+  // callers from sending a whitespace-only search.
+  const searchTerm = filterValue.trim();
   const query = rison.encode({

Review Comment:
   🔴 **Search term isn't URL-encoded**
   
   `rison.encode` output is appended as `?q=${query}` without URL-encoding. 
Before this PR the server ignored the value, but now that it filters on it, `+` 
is decoded server-side as a space and `&` ends the `q` parameter:
   
   - `jane+ops` → rison `value:jane+ops` reaches the server as `value:jane ops` 
→ **400** "Not a valid rison/json argument" → "There was an error while 
fetching users" toast
   - `[email protected]` → searched as `jane [email protected]` → silently 
returns no users
   - `a&b` → `q` is truncated at `&` → **400**
   
   Plus-addressed emails are a common case for the new email search. 
`rison.encode_uri` is what the other list fetchers use (e.g. `useDatasetLists`, 
`AlertReportModal`):
   
   ```suggestion
     const query = rison.encode_uri({
   ```
   
   (`encode_uri` encodes spaces as `+`, so the test helper needs a matching 
tweak; see the next two comments.)
   



##########
superset-frontend/src/features/groups/utils.test.ts:
##########
@@ -0,0 +1,217 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { SupersetClient } from '@superset-ui/core';
+import rison from 'rison';
+import { render, screen } from 'spec/helpers/testing-library';
+import {
+  fetchUserOptions,
+  toUserSelectOption,
+  USER_OPTION_FILTER_PROPS,
+  userOptionSortComparator,
+} from './utils';
+
+type GetResponse = Awaited<ReturnType<typeof SupersetClient.get>>;
+
+const getMock = jest.spyOn(SupersetClient, 'get');
+
+const mockUsersResponse = (
+  result: Record<string, unknown>[],
+  count = result.length,
+) =>
+  getMock.mockResolvedValue({
+    json: { count, result },
+  } as unknown as GetResponse);
+
+const decodeQuery = () => {
+  const { endpoint } = getMock.mock.calls[0][0] as { endpoint: string };
+  return rison.decode(endpoint.split('?q=')[1]);
+};
+
+afterEach(() => {
+  getMock.mockReset();
+});
+
+test('fetchUserOptions sends the search term as a server-side filter', async 
() => {
+  mockUsersResponse([
+    {
+      id: 7,
+      username: 'jsmith',
+      first_name: 'Jane',
+      last_name: 'Smith',
+      email: '[email protected]',
+    },
+  ]);
+
+  const result = await fetchUserOptions('Jane Sm', 0, 100, jest.fn());
+
+  expect(decodeQuery()).toEqual({
+    filters: [{ col: 'username', opr: 'user_all_text', value: 'Jane Sm' }],
+    page: 0,
+    page_size: 100,
+    order_column: 'username',
+    order_direction: 'asc',
+  });
+  expect(result).toEqual({
+    data: [
+      {
+        value: 7,
+        label: expect.anything(),
+        title: 'Jane Smith',
+        textLabel: 'Jane Smith',
+        subjectDetail: '[email protected]',
+        username: 'jsmith',
+      },
+    ],
+    totalCount: 1,
+  });
+});
+
+test('fetchUserOptions trims the search term before sending it', async () => {
+  mockUsersResponse([]);
+
+  await fetchUserOptions('  jane ', 0, 100, jest.fn());
+
+  expect(decodeQuery()).toEqual({
+    filters: [{ col: 'username', opr: 'user_all_text', value: 'jane' }],
+    page: 0,
+    page_size: 100,
+    order_column: 'username',
+    order_direction: 'asc',
+  });
+});
+
+test.each([
+  ['an empty', ''],
+  ['a whitespace-only', '   '],
+])(
+  'fetchUserOptions sends no filters for %s search term',
+  async (_label, filterValue) => {
+    mockUsersResponse([{ id: 1, username: 'admin' }], 250);
+
+    const result = await fetchUserOptions(filterValue, 2, 100, jest.fn());
+
+    expect(decodeQuery()).toEqual({
+      filters: [],
+      page: 2,
+      page_size: 100,
+      order_column: 'username',
+      order_direction: 'asc',
+    });
+    expect(result).toEqual({
+      data: [
+        expect.objectContaining({
+          value: 1,
+          title: 'admin',
+          username: 'admin',
+        }),
+      ],
+      totalCount: 250,
+    });
+  },
+);
+
+test('fetchUserOptions shows a toast and returns no options on error', async 
() => {
+  getMock.mockRejectedValue(new Error('boom'));
+  const addDangerToast = jest.fn();
+
+  const result = await fetchUserOptions('jane', 0, 100, addDangerToast);
+
+  expect(addDangerToast).toHaveBeenCalledWith(
+    'There was an error while fetching users',
+  );
+  expect(result).toEqual({ data: [], totalCount: 0 });
+});
+
+test('toUserSelectOption shows the email under the display name', () => {
+  const option = toUserSelectOption({
+    id: 7,
+    username: 'jsmith',
+    first_name: 'Jane',
+    last_name: 'Smith',
+    email: '[email protected]',
+  });
+
+  render(option.label);
+
+  expect(screen.getByText('Jane Smith')).toBeInTheDocument();
+  expect(screen.getByText('[email protected]')).toBeInTheDocument();
+  expect(option).toMatchObject({
+    value: 7,
+    title: 'Jane Smith',
+    textLabel: 'Jane Smith',
+    subjectDetail: '[email protected]',
+    username: 'jsmith',
+  });
+});
+
+test('USER_OPTION_FILTER_PROPS covers every column the server search matches', 
() => {
+  // The server-side user_all_text filter matches name, email and username.
+  // Each must be a plain-text prop on the option, or AsyncSelect's client-side
+  // re-filter hides a user the server returned.
+  const option = toUserSelectOption({
+    id: 7,
+    username: 'jsmith',
+    first_name: 'Jane',
+    last_name: 'Smith',
+    email: '[email protected]',
+  });
+
+  expect(USER_OPTION_FILTER_PROPS).toEqual([
+    'textLabel',
+    'subjectDetail',
+    'username',
+  ]);
+  expect(
+    USER_OPTION_FILTER_PROPS.map(prop => option[prop as keyof typeof option]),
+  ).toEqual(['Jane Smith', '[email protected]', 'jsmith']);
+});
+
+test('toUserSelectOption falls back to the username and omits a missing 
email', () => {
+  const option = toUserSelectOption({ id: 3, username: 'svc_reporting' });
+
+  render(option.label);
+
+  expect(screen.getByText('svc_reporting')).toBeInTheDocument();
+  expect(option).toMatchObject({
+    value: 3,
+    title: 'svc_reporting',
+    textLabel: 'svc_reporting',
+    subjectDetail: undefined,
+  });
+});
+
+test('userOptionSortComparator orders users by display name, not id', () => {
+  const options = [
+    toUserSelectOption({ id: 1, first_name: 'Zoe', last_name: 'Adams' }),
+    toUserSelectOption({ id: 2, first_name: 'Amy', last_name: 'Young' }),
+    toUserSelectOption({ id: 3, first_name: 'Max', last_name: 'Ng' }),
+  ];
+
+  expect(
+    [...options]
+      .sort((a, b) => userOptionSortComparator(a, b))
+      .map(o => o.value),
+  ).toEqual([2, 3, 1]);
+  // With a search term, names containing it rank first
+  expect(
+    [...options]
+      .sort((a, b) => userOptionSortComparator(a, b, 'ad'))
+      .map(o => o.value),
+  ).toEqual([1, 2, 3]);
+});

Review Comment:
   Regression test for the encoding fix. It fails on the current code and 
passes with `rison.encode_uri`:
   
   ```suggestion
   });
   
   test('fetchUserOptions URL-encodes reserved characters in the search term', 
async () => {
     mockUsersResponse([]);
   
     await fetchUserOptions('jane+ops&co', 0, 100, jest.fn());
   
     expect(decodeQuery().filters).toEqual([
       { col: 'username', opr: 'user_all_text', value: 'jane+ops&co' },
     ]);
   });
   ```
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to