mattermost-mobile-upstream/app/actions/websocket/properties.test.ts
Pablo Vélez 4d842026f6
Some checks failed
ci / lint-typecheck (push) Has been cancelled
ci / detox-lint-typecheck (push) Has been cancelled
ci / test (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Mm 70564 channel labels use in channel creation (#10146)
* MM-70516 - Add ability to edit channel attribute values from Channel Info

* Add API methods for patching property fields and setting channel attribute requirements

* Update channel attribute clearing behavior for required and non-required fields

* MM-70564 - use channel attributes on channel creation

* Fix undefined propertyValues and ternary formatting in channel attributes

* Fix spelling of "colour" to "color" in attribute chip tests and related comments

* Add visibility checks for channel attribute labels in tests

* Fix data-integrity, permission, and accessibility issues in channel attributes: scoped pruning, atomic writes, race serialization, required clear/stale-option guards

* Fix handling of null values in apiGetChannelAttributeValue and update test assertions for channel attributes

* Improve channel attribute editor sizing for long labels, keep Save visible, and prevent keyboard overlap on Android

* Address CodeRabbit feedback for nullable values, bottom-sheet state, async validation, and reliable E2E cleanup

* lock-safe field fetch, create-time gate recheck, scoped value pruning, and tappable header chips

* Address CodeRabbit feedback: drop queued attribute saves on channel switch and use page object selectors in E2E

* Respect the ChannelAttributesRequired flag on channel creation and enable it for channel attribute E2E

* Skip required channel attribute E2E tests and stop enabling ChannelAttributesRequired on the shared server until  they move to SITE_3

* Fix clearing channel attributes on iOS by sending an empty value instead of null, and stop E2E suites from turning  off the ChannelAttributes flag mid-run

* Refactor getEmptyPropertyValue to accept string type for fieldType parameter

* E2E: give channel attribute test fields a suite-unique suffix

Pool shards may only create optional property fields named <name>_<6 hex>; fixed names were blocked by the pool guard.

* E2E: restore channel attribute cleanup checks; name network error codes

Brings back the PR's afterEach/afterAll error handling that the main merge replaced, and makes a no-response error show its codes (an AggregateError has an empty message).

* E2E: run channel attribute creation and editing specs on server B

Their 11 required-attribute tests could not run on the shared servers. Both specs now run on the mutation server with ChannelAttributesRequired on for their run, and the tests are re-enabled. setChannelAttributesRequired moves to the shared helper.

* Check header chips instead of their wrapper and use toExist for the create screen in channel attribute E2E

---------

Co-authored-by: yasserfaraazkhan <attitude3cena.yf@gmail.com>
2026-10-30 15:03:55 +01:00

456 lines
18 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Q, type Database} from '@nozbe/watermelondb';
import {setAccessControlGroupId} from '@actions/local/channel_attributes';
import {fetchAccessControlAttributeFields, fetchChannelAttributeValues} from '@actions/remote/classification';
import {MM_TABLES} from '@constants/database';
import DatabaseManager from '@database/manager';
import EphemeralStore from '@store/ephemeral_store';
import {handlePropertyFieldCreatedOrUpdated, handlePropertyFieldDeleted, handlePropertyValuesUpdated} from './properties';
jest.mock('@actions/remote/classification', () => ({
accessControlWriteLockKey: (serverUrl: string) => `access-control:${serverUrl}`,
fetchAccessControlAttributeFields: jest.fn(),
fetchChannelAttributeValues: jest.fn(),
}));
const mockedFetchChannelAttributeValues = jest.mocked(fetchChannelAttributeValues);
import type {PropertyFieldModel, PropertyValueModel} from '@database/models/server';
const {PROPERTY_FIELD, PROPERTY_VALUE} = MM_TABLES.SERVER;
const serverUrl = 'ws-properties.test.com';
const groupId = 'test_group';
const makeField = (id: string, overrides?: Partial<PropertyField>): PropertyField => ({
id,
group_id: groupId,
name: `field_${id}`,
type: 'select',
object_type: 'template',
target_type: 'system',
target_id: '',
delete_at: 0,
create_at: 1000,
update_at: 1000,
attrs: {},
...overrides,
});
const makeValue = (fieldId: string, value: string, overrides?: Partial<PropertyValue<string>>): PropertyValue<string> => ({
id: `val-${fieldId}`,
target_id: 'system',
target_type: 'system',
group_id: groupId,
field_id: fieldId,
value,
create_at: 1000,
update_at: 1000,
delete_at: 0,
...overrides,
});
const getStoredFields = async (database: Database) => {
const records = await database.get<PropertyFieldModel>(PROPERTY_FIELD).query(Q.where('group_id', groupId)).fetch();
return records;
};
const getStoredValues = async (database: Database, targetId: string) => {
const records = await database.get<PropertyValueModel>(PROPERTY_VALUE).query(Q.where('target_id', targetId)).fetch();
return records;
};
beforeEach(async () => {
await DatabaseManager.init([serverUrl]);
jest.clearAllMocks();
});
afterEach(async () => {
await DatabaseManager.destroyServerDatabase(serverUrl);
});
describe('handlePropertyFieldCreatedOrUpdated', () => {
it('should add a field to the DB', async () => {
const field = makeField('f1');
const msg = {
event: 'property_field_created',
data: {property_field: JSON.stringify(field), object_type: 'template'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const fields = await getStoredFields(database);
expect(fields).toHaveLength(1);
expect(fields[0].id).toBe('f1');
});
it('should update an existing field in the DB', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [makeField('f1')], prepareRecordsOnly: false});
const updated = makeField('f1', {name: 'updated'});
const msg = {
event: 'property_field_updated',
data: {property_field: JSON.stringify(updated), object_type: 'template'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
const fields = await getStoredFields(database);
expect(fields).toHaveLength(1);
expect(fields[0].name).toBe('updated');
});
it('should force a field fetch after releasing the lock when an owned field arrives before the group id is known', async () => {
// The real fetch takes the same lock; if the handler awaited it while still
// holding the lock, this would never resolve and the test would time out.
jest.mocked(fetchAccessControlAttributeFields).mockImplementationOnce(() => (
EphemeralStore.runExclusive(`access-control:${serverUrl}`, async () => ({}))
));
const field = makeField('f1', {object_type: 'channel', target_type: 'system'});
const msg = {
event: 'property_field_created',
data: {property_field: JSON.stringify(field), object_type: 'channel'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
expect(fetchAccessControlAttributeFields).toHaveBeenCalledTimes(1);
expect(fetchAccessControlAttributeFields).toHaveBeenCalledWith(serverUrl, true);
});
it('should not fetch fields when the group id is already known', async () => {
await setAccessControlGroupId(serverUrl, groupId);
const field = makeField('f1', {object_type: 'channel'});
const msg = {
event: 'property_field_created',
data: {property_field: JSON.stringify(field), object_type: 'channel'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
expect(fetchAccessControlAttributeFields).not.toHaveBeenCalled();
});
it('should ignore events with no property_field data', async () => {
const msg = {
event: 'property_field_created',
data: {},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should ignore events with invalid JSON', async () => {
const msg = {
event: 'property_field_created',
data: {property_field: 'not-json'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldCreatedOrUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
});
describe('handlePropertyFieldDeleted', () => {
it('should remove a field and its values from the DB by id', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [makeField('f1'), makeField('f2')], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [makeValue('f1', 'v1')], prepareRecordsOnly: false});
const msg = {
event: 'property_field_deleted',
data: {field_id: 'f1', object_type: 'template'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldDeleted(serverUrl, msg);
const fields = await getStoredFields(database);
expect(fields).toHaveLength(1);
expect(fields[0].id).toBe('f2');
expect(await getStoredValues(database, 'system')).toHaveLength(0);
});
it('should do nothing when field_id is missing', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [makeField('f1')], prepareRecordsOnly: false});
const msg = {
event: 'property_field_deleted',
data: {object_type: 'template'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldDeleted(serverUrl, msg);
expect(await getStoredFields(database)).toHaveLength(1);
});
it('should do nothing when field_id does not match any stored field', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [makeField('f1')], prepareRecordsOnly: false});
const msg = {
event: 'property_field_deleted',
data: {field_id: 'non-existent', object_type: 'template'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyFieldDeleted(serverUrl, msg);
expect(await getStoredFields(database)).toHaveLength(1);
});
});
describe('handlePropertyValuesUpdated', () => {
it('should add new values to the DB', async () => {
const values = [makeValue('f1', 'v1'), makeValue('f2', 'v2')];
const msg = {
event: 'property_values_updated',
data: {values: JSON.stringify(values)},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, 'system')).toHaveLength(2);
});
it('should update existing values in the DB', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [makeValue('f1', 'old')], prepareRecordsOnly: false});
const updated = [makeValue('f1', 'new')];
const msg = {
event: 'property_values_updated',
data: {values: JSON.stringify(updated)},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const stored = await getStoredValues(database, 'system');
expect(stored).toHaveLength(1);
expect(stored[0].value).toBe('new');
});
it('should ignore events with no values', async () => {
const msg = {
event: 'property_values_updated',
data: {},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, 'system')).toHaveLength(0);
});
it('should ignore events with invalid JSON', async () => {
const msg = {
event: 'property_values_updated',
data: {values: 'not-json'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, 'system')).toHaveLength(0);
});
it('should ignore events with empty values array', async () => {
const msg = {
event: 'property_values_updated',
data: {values: '[]'},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, 'system')).toHaveLength(0);
});
it('should store channel property values by their target_id', async () => {
const channelId = 'channel-abc';
const channelValue = makeValue('chan-field', 'level-1', {id: 'val-chan', target_id: channelId, target_type: 'channel'});
const msg = {
event: 'property_values_updated',
data: {values: JSON.stringify([channelValue])},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const stored = await getStoredValues(database, channelId);
expect(stored).toHaveLength(1);
expect(stored[0].value).toBe('level-1');
});
it('should isolate values across different target ids', async () => {
const channelId = 'channel-xyz';
const systemVal = makeValue('sys-field', 'sys-val');
const channelVal = makeValue('chan-field', 'chan-val', {id: 'val-chan', target_id: channelId, target_type: 'channel'});
const msg = {
event: 'property_values_updated',
data: {values: JSON.stringify([systemVal, channelVal])},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, 'system')).toHaveLength(1);
expect(await getStoredValues(database, channelId)).toHaveLength(1);
});
describe('pruning', () => {
const channelId = 'channel-prune';
// The group this feature owns, published the way the field fetch would.
const ownedGroupId = 'access_control_group';
const ownedValue = makeValue('owned-field', 'opt-1', {
id: 'val-owned',
target_id: channelId,
target_type: 'channel',
group_id: ownedGroupId,
});
// Another feature's per-channel value on the same channel. Managed channel
// categories stores these in the same table.
const foreignValue = makeValue('foreign-field', 'category', {
id: 'val-foreign',
target_id: channelId,
target_type: 'channel',
group_id: 'managed_channel_categories',
});
const clearedMessage = (data: Record<string, string>) => ({
event: 'property_values_updated',
data: {values: '[]', object_type: 'channel', ...data},
broadcast: {},
seq: 1,
} as WebSocketMessage);
beforeEach(async () => {
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [ownedValue, foreignValue], prepareRecordsOnly: false});
await setAccessControlGroupId(serverUrl, ownedGroupId);
});
// An empty-target event carries no group identity: the exact same shape is
// sent for "all access_control values cleared" and for "all managed
// channel categories values cleared" on this channel. Pruning locally here
// would apply someone else's clear to our data whenever the two happen to
// race, so the handler defers to a forced, group-scoped REST
// reconciliation instead of deleting anything itself.
it('should trigger a forced, group-scoped reconciliation instead of pruning locally when a target is cleared', async () => {
await handlePropertyValuesUpdated(serverUrl, clearedMessage({target_id: channelId}));
expect(mockedFetchChannelAttributeValues).toHaveBeenCalledWith(serverUrl, channelId, true);
// Nothing was deleted synchronously by the handler itself — the
// reconciliation (mocked here) owns that decision.
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, channelId)).toHaveLength(2);
});
it('should not trigger reconciliation when a non-channel target is cleared', async () => {
await handlePropertyValuesUpdated(serverUrl, clearedMessage({target_id: 'user-id', object_type: 'user'}));
expect(mockedFetchChannelAttributeValues).not.toHaveBeenCalled();
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, channelId)).toHaveLength(2);
});
it('should still trigger reconciliation when the group id is not known yet', async () => {
await setAccessControlGroupId(serverUrl, '');
await handlePropertyValuesUpdated(serverUrl, clearedMessage({target_id: channelId}));
expect(mockedFetchChannelAttributeValues).toHaveBeenCalledWith(serverUrl, channelId, true);
});
it('should prune every value of a field when that field is cleared', async () => {
await handlePropertyValuesUpdated(serverUrl, clearedMessage({field_id: 'owned-field'}));
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const remaining = await getStoredValues(database, channelId);
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('val-foreign');
});
it('should not prune when a non-empty list arrives, since it is only the changed values', async () => {
const msg = {
event: 'property_values_updated',
data: {target_id: channelId, values: JSON.stringify([{...ownedValue, value: 'opt-2'}])},
broadcast: {},
seq: 1,
} as WebSocketMessage;
await handlePropertyValuesUpdated(serverUrl, msg);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, channelId)).toHaveLength(2);
});
it('should prune nothing when an empty list carries no target or field', async () => {
await handlePropertyValuesUpdated(serverUrl, clearedMessage({}));
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, channelId)).toHaveLength(2);
});
it('should scope reconciliation to the event\'s own target and leave other channels alone', async () => {
const otherTarget = 'channel-no-attributes';
await handlePropertyValuesUpdated(serverUrl, clearedMessage({target_id: otherTarget}));
expect(mockedFetchChannelAttributeValues).toHaveBeenCalledWith(serverUrl, otherTarget, true);
// The original channel's values must be completely untouched.
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredValues(database, channelId)).toHaveLength(2);
});
});
});