mattermost-mobile-upstream/detox/e2e/support/server_api/post.ts
yasser khan f3af9dbe99
Fix/detox hittest cluster (#10023)
fix(e2e): stabilize Detox and Maestro test suite

Restore main features, and harden the E2E harness against flaky UI, network, retry, synchronization, and classification-lock failures.

Stabilize channel creation, saved messages, bookmarks, search, deep links, keyboard dismissal, and post verification.
Bound network, transport, health-check, synchronization, and lock retries by elapsed time.
Fix iOS and Android Maestro/Detox races and flaky interaction flows.
Restore Session Attributes and deep-link fixes lost during merge.
Improve test isolation, global-setting cleanup, and Jest/TSIO reporting.
Enforce Maestro flow-header validation in local and CI checks.
2026-08-27 08:58:03 +05:30

516 lines
19 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import path from 'path';
import {timeouts, wait} from '@support/utils';
import {withTransportRetry} from '@support/utils/transport_retry';
import client from './client';
import {apiUploadFile, getResponseFromError} from './common';
/**
* Create a new post in a channel. To create the post as a comment on another post, provide root_id.
* See https://api.mattermost.com/#operation/CreatePost
* @param {string} baseUrl - the base server URL
* @param {string} option.channelId - The channel ID to post in
* @param {string} option.message - The message contents, can be formatted with Markdown
* @param {string} option.rootId - The post ID to comment on
* @param {Object} option.props - A general object property bag to attach to the post
* @param {string[]} option.fileIds - Array of file IDs to attach to the post (top-level API field)
* @param {Date} option.createAt - The date the post is created at
* @return {Object} returns {post} on success. Throws on error (never returns {error}).
*/
export const apiCreatePost = async (baseUrl: string, {channelId, message, rootId, props = {}, fileIds, createAt = 0}: any): Promise<any> => {
try {
const payload: Record<string, any> = {
channel_id: channelId,
message,
root_id: rootId,
props,
create_at: createAt,
};
if (fileIds?.length) {
payload.file_ids = fileIds;
}
const response = await client.post(`${baseUrl}/api/v4/posts`, payload);
return {post: response.data};
} catch (err) {
// Throw rather than return {error}. Almost every call site destructures
// {post} without checking `error`, so a transport failure here used to
// surface as `TypeError: Cannot read properties of undefined` on whichever
// later line first touched the missing post, with nothing about the network
// in the report.
const error = getResponseFromError(err);
throw new Error(`apiCreatePost failed: ${JSON.stringify(error.error)}`);
}
};
/**
* Get posts for a channel.
* See https://api.mattermost.com/#operation/GetPostsForChannel
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to get the posts for
* @return {Object} returns {posts} on success or {error, status} on error
*/
export const apiGetPostsInChannel = async (baseUrl: string, channelId: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/channels/${channelId}/posts`);
const {order, posts} = response.data;
const orderedPosts = order.map((postId: string) => posts[postId]);
return {posts: orderedPosts};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get last post in a channel.
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to get the last post
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiGetLastPostInChannel = async (
baseUrl: string,
channelId: string,
{maxAttempts = 6, intervalMs = timeouts.TWO_SEC} = {},
): Promise<any> => {
/* eslint-disable no-await-in-loop -- poll until the post is indexed */
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (attempt > 0) {
await wait(intervalMs);
} else {
await wait(timeouts.TWO_SEC);
}
const response = await apiGetPostsInChannel(baseUrl, channelId);
if (response.error) {
if (attempt === maxAttempts - 1) {
return response;
}
continue;
}
const {posts} = response;
if (posts?.length) {
return {post: posts[0]};
}
}
/* eslint-enable no-await-in-loop */
return {error: {message: `No posts found in channel ${channelId} after ${maxAttempts} attempts`}};
};
/**
* Poll a channel until it contains a post for `message`.
*
* `exact` matters once callers use this to confirm their own send: substring matching can return an
* unrelated post whose text merely contains theirs (`Message abc` inside `Message abc reply`), and a
* caller that then treats it as "my post" acts on the wrong id. Verification callers pass
* `exact: true`; the default stays substring so existing content-search callers are unaffected.
*
* Relies on apiGetPostsInChannel returning newest-first (it maps the API's `order` array, which is
* why apiGetLastPostInChannel can take `posts[0]`). So when a suite legitimately posts the same text
* twice to one channel, this returns the newer one — the one the caller just sent.
*/
export const apiFindPostInChannelByMessage = async (
baseUrl: string,
channelId: string,
message: string,
{maxAttempts = 6, intervalMs = timeouts.TWO_SEC, exact = false} = {},
): Promise<any> => {
/* eslint-disable no-await-in-loop -- poll until the target post is indexed */
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (attempt > 0) {
await wait(intervalMs);
} else {
await wait(timeouts.TWO_SEC);
}
const response = await apiGetPostsInChannel(baseUrl, channelId);
if (response.error) {
if (attempt === maxAttempts - 1) {
return response;
}
continue;
}
const post = response.posts?.find((candidate: any) => (
exact ? candidate.message === message : candidate.message.includes(message)
));
if (post) {
return {post};
}
}
/* eslint-enable no-await-in-loop */
return {error: {message: `No post containing "${message}" found in channel ${channelId} after ${maxAttempts} attempts`}};
};
/**
* Patch a post.
* See https://api.mattermost.com/#operation/PatchPost
* @param {string} baseUrl - the base server URL
* @param {string} postId - the post ID
* @param {Object} postData - data to partially update a post
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiPatchPost = async (baseUrl: string, postId: string, postData: string): Promise<any> => {
try {
const response = await client.put(
`${baseUrl}/api/v4/posts/${postId}/patch`,
postData,
);
return {post: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Create an ephemeral post visible only to the given user.
* See https://api.mattermost.com/#operation/CreatePostEphemeral
* @param {string} baseUrl - base server URL
* @param {string} userId - user ID that can see the ephemeral post
* @param {{channel_id: string, message: string, root_id?: string, props?: Record<string, unknown>}} post - ephemeral post payload
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiCreatePostEphemeral = async (
baseUrl: string,
userId: string,
post: {channel_id: string; message: string; root_id?: string; props?: Record<string, unknown>},
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/ephemeral`, {
user_id: userId,
post,
});
return {post: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Create an incoming webhook.
* See https://api.mattermost.com/#operation/CreateIncomingWebhook
* @param {string} baseUrl - base server URL
* @param {{channel_id: string, display_name: string}} hook - incoming webhook payload
* @return {Object} returns {hook} on success or {error, status} on error
*/
export const apiCreateIncomingWebhook = async (
baseUrl: string,
hook: {channel_id: string; display_name: string},
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/hooks/incoming`, hook);
return {hook: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* POST a payload to an incoming webhook URL path (`/hooks/{id}`).
* @param {string} baseUrl - base server URL
* @param {string} hookId - incoming webhook id/path
* @param {Record<string, unknown>} payload - body sent to the webhook
* @return {Object} returns {data} on success or {error, status} on error
*/
export const apiPostIncomingWebhook = async (
baseUrl: string,
hookId: string,
payload: Record<string, unknown>,
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/hooks/${hookId}`, payload);
return {data: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Pin a post in its channel.
* See https://api.mattermost.com/#operation/PinPost
* @param {string} baseUrl - the base server URL
* @param {string} postId - the post ID
* @return {Object} returns {data} on success or {error, status} on error
*/
export const apiPinPost = async (baseUrl: string, postId: string): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/${postId}/pin`);
return {data: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Upload a file to a channel via the Mattermost REST API.
* See https://api.mattermost.com/#operation/UploadFile
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to upload the file to
* @param {string} absFilePath - The absolute path to the file to upload
* @param {Object} [options]
* @param {boolean} [options.forBookmark] - Upload with bookmark=true so CreatorId is
* "bookmark" (required before creating a type=file channel bookmark).
* @return {Object} returns {fileId} on success or {error, status} on error
*/
export const apiUploadFileToChannel = async (
baseUrl: string,
channelId: string,
absFilePath: string,
options?: {forBookmark?: boolean},
): Promise<any> => {
const query = new URLSearchParams({channel_id: channelId});
if (options?.forBookmark) {
// Server sets FileInfo.CreatorId to "bookmark" when bookmark=true
// (required by ChannelBookmark store for type=file bookmarks).
query.set('bookmark', 'true');
}
// A replayed upload can leave an extra FileInfo behind, but an unreferenced file is
// invisible to every assertion in the suite, and losing the upload fails the test
// outright — so a duplicate is the cheaper outcome here.
const result = await withTransportRetry(() => apiUploadFile('files', absFilePath, {
url: `${baseUrl}/api/v4/files?${query.toString()}`,
method: 'POST',
}), {idempotent: false, allowDuplicateWrites: true, label: 'apiUploadFileToChannel'});
if (result.error) {
return result;
}
const fileId = result.data?.file_infos?.[0]?.id;
if (!fileId) {
return {error: {message: 'Upload response missing file_infos[0].id'}};
}
return {fileId};
};
/**
* Upload a fixture image and create a post with that image attached.
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to post in
* @param {string} rootId - (optional) root post ID for thread replies
* @return {Object} returns {post, fileId} on success. Throws after transport retries if upload or create fails.
*/
export const apiCreatePostWithImageAttachment = async (baseUrl: string, channelId: string, rootId = ''): Promise<any> => {
const absFilePath = path.resolve(__dirname, '../../support/fixtures/image.png');
const {fileId, error: uploadError} = await apiUploadFileToChannel(baseUrl, channelId, absFilePath);
if (uploadError || !fileId) {
throw new Error(`apiCreatePostWithImageAttachment: upload failed: ${JSON.stringify(uploadError)}`);
}
// Creating a post is not idempotent and a duplicate IS observable — it shows up in
// the channel and breaks post-count assertions. A timed-out create may already have
// committed, so fail and let the caller surface it rather than posting twice.
const {post, error: postError} = await apiCreatePost(baseUrl, {
channelId,
message: '',
rootId: rootId || undefined,
fileIds: [fileId],
});
if (postError || !post?.id) {
throw new Error(`apiCreatePostWithImageAttachment: create post failed: ${JSON.stringify(postError)}`);
}
if (!post.file_ids || !post.file_ids.includes(fileId)) {
throw new Error(`apiCreatePostWithImageAttachment: server did not attach file. post.file_ids=${JSON.stringify(post.file_ids)}, fileId=${fileId}`);
}
return {post, fileId};
};
export const apiGetFlaggedPosts = async (baseUrl: string, userId: string): Promise<{order: string[]; posts: Record<string, any>; error?: any}> => {
try {
const response = await client.get(`${baseUrl}/api/v4/users/${userId}/posts/flagged`);
return {order: response.data?.order ?? [], posts: response.data?.posts ?? {}};
} catch (err) {
// Callers must not read the empty order as "no flagged posts" — see waitForPostUnflagged.
return {order: [], posts: {}, ...getResponseFromError(err)};
}
};
export const waitForPostFlagged = async (baseUrl: string, userId: string, postId: string, maxAttempts = 10): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until post appears in flagged index */
for (let i = 0; i < maxAttempts; i++) {
const {order} = await apiGetFlaggedPosts(baseUrl, userId);
if (order.includes(postId)) {
return;
}
if (i < maxAttempts - 1) {
await wait(2000);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} not flagged after ${maxAttempts} attempts`);
};
export const waitForPostUnflagged = async (baseUrl: string, userId: string, postId: string, maxAttempts = 10): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until post disappears from flagged index */
for (let i = 0; i < maxAttempts; i++) {
const {order, error} = await apiGetFlaggedPosts(baseUrl, userId);
if (!error && !order.includes(postId)) {
return;
}
if (i < maxAttempts - 1) {
await wait(2000);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} still flagged after ${maxAttempts} attempts`);
};
export const waitForPostPinned = async (
baseUrl: string,
channelId: string,
postId: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until server reports is_pinned */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post?.is_pinned) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} not pinned after ${maxAttempts} attempts`);
};
export const waitForPostUnpinned = async (
baseUrl: string,
channelId: string,
postId: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until server clears is_pinned */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post && !post.is_pinned) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} still pinned after ${maxAttempts} attempts`);
};
export const waitForPostMessage = async (
baseUrl: string,
channelId: string,
postId: string,
expectedMessage: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until the edited post is returned by the server */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post?.message === expectedMessage) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} did not update to "${expectedMessage}" after ${maxAttempts} attempts`);
};
/**
* Search posts (same endpoint recent mentions uses).
* See https://api.mattermost.com/#operation/SearchPosts
*/
export const apiSearchPosts = async (
baseUrl: string,
terms: string,
{isOrSearch = true, teamId = ''}: {isOrSearch?: boolean; teamId?: string} = {},
): Promise<{order?: string[]; posts?: Record<string, any>; error?: unknown}> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/search`, {
terms,
is_or_search: isOrSearch,
...(teamId ? {team_id: teamId} : {}),
});
return {
order: response.data?.order,
posts: response.data?.posts,
};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Poll search until it returns the expected post message. Recent Mentions is
* search-backed; channel GET can succeed while search still serves the old text.
*/
export const waitForPostMessageInSearch = async (
baseUrl: string,
terms: string,
postId: string,
expectedMessage: string,
maxAttempts = 15,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll search index until it catches up */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiSearchPosts(baseUrl, terms);
if (!error && posts?.[postId]?.message === expectedMessage) {
return;
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(
`Search did not return post ${postId} with message "${expectedMessage}" after ${maxAttempts} attempts`,
);
};
export const Post = {
apiCreatePost,
apiCreatePostEphemeral,
apiCreateIncomingWebhook,
apiCreatePostWithImageAttachment,
apiFindPostInChannelByMessage,
apiGetLastPostInChannel,
apiGetPostsInChannel,
apiPinPost,
apiPatchPost,
apiPostIncomingWebhook,
apiSearchPosts,
apiUploadFileToChannel,
apiGetFlaggedPosts,
waitForPostFlagged,
waitForPostMessage,
waitForPostMessageInSearch,
waitForPostPinned,
waitForPostUnflagged,
waitForPostUnpinned,
};
export default Post;