users store unit tests

This commit is contained in:
Henry Jameson 2026-08-18 03:20:09 +03:00
commit 975b338586
16 changed files with 1804 additions and 727 deletions

View file

@ -63,7 +63,7 @@ export const paramsString = (params = {}) => {
}
export const promisedRequest = async ({
method,
method = 'GET',
url,
payload,
formData,

View file

@ -13,12 +13,12 @@ const MASTODON_REGISTRATION_URL = '/api/v1/accounts'
const MASTODON_PASSWORD_RESET_URL = ({ email }) =>
`/auth/password${paramsString({ email })}`
const MASTODON_FOLLOWING_URL = (
export const MASTODON_FOLLOWING_URL = (
id,
{ minId, maxId, sinceId, limit, withRelationships },
) =>
`/api/v1/accounts/${id}/following${paramsString({ minId, maxId, sinceId, limit, withRelationships })}`
const MASTODON_FOLLOWERS_URL = (
export const MASTODON_FOLLOWERS_URL = (
id,
{ minId, maxId, sinceId, limit, withRelationships },
) =>

View file

@ -34,8 +34,8 @@ const MASTODON_UNFAVORITE_URL = (id) => `/api/v1/statuses/${id}/unfavourite`
const MASTODON_RETWEET_URL = (id) => `/api/v1/statuses/${id}/reblog`
const MASTODON_UNRETWEET_URL = (id) => `/api/v1/statuses/${id}/unreblog`
const MASTODON_DELETE_URL = (id) => `/api/v1/statuses/${id}`
const MASTODON_FOLLOW_URL = (id) => `/api/v1/accounts/${id}/follow`
const MASTODON_UNFOLLOW_URL = (id) => `/api/v1/accounts/${id}/unfollow`
export const MASTODON_FOLLOW_URL = (id) => `/api/v1/accounts/${id}/follow`
export const MASTODON_UNFOLLOW_URL = (id) => `/api/v1/accounts/${id}/unfollow`
const MASTODON_FOLLOW_REQUESTS_URL = '/api/v1/follow_requests'
const MASTODON_APPROVE_USER_URL = (id) =>
@ -43,30 +43,31 @@ const MASTODON_APPROVE_USER_URL = (id) =>
const MASTODON_DENY_USER_URL = (id) => `/api/v1/follow_requests/${id}/reject`
const MASTODON_USER_RELATIONSHIPS_URL = ({ id, withSuspended }) =>
`/api/v1/accounts/relationships/${paramsString({ id, withSuspended })}`
const MASTODON_USER_IN_LISTS = (id) => `/api/v1/accounts/${id}/lists`
export const MASTODON_USER_IN_LISTS = (id) => `/api/v1/accounts/${id}/lists`
export const MASTODON_LIST_URL = (id = '') => `/api/v1/lists/${id}`
export const MASTODON_LIST_ACCOUNTS_URL = (id) => `/api/v1/lists/${id}/accounts`
const MASTODON_USER_BLOCKS_URL = ({
export const MASTODON_USER_BLOCKS_URL = ({
maxId,
sinceId,
limit,
withRelationships,
}) =>
`/api/v1/blocks/${paramsString({ maxId, sinceId, limit, withRelationships })}`
const MASTODON_USER_MUTES_URL = ({
export const MASTODON_USER_MUTES_URL = ({
maxId,
sinceId,
limit,
withRelationships,
}) =>
`/api/v1/mutes/${paramsString({ maxId, sinceId, limit, withRelationships })}`
const MASTODON_BLOCK_USER_URL = (id) => `/api/v1/accounts/${id}/block`
const MASTODON_UNBLOCK_USER_URL = (id) => `/api/v1/accounts/${id}/unblock`
const MASTODON_MUTE_USER_URL = (id) => `/api/v1/accounts/${id}/mute`
const MASTODON_UNMUTE_USER_URL = (id) => `/api/v1/accounts/${id}/unmute`
const MASTODON_REMOVE_USER_FROM_FOLLOWERS = (id) =>
export const MASTODON_BLOCK_USER_URL = (id) => `/api/v1/accounts/${id}/block`
export const MASTODON_UNBLOCK_USER_URL = (id) =>
`/api/v1/accounts/${id}/unblock`
export const MASTODON_MUTE_USER_URL = (id) => `/api/v1/accounts/${id}/mute`
export const MASTODON_UNMUTE_USER_URL = (id) => `/api/v1/accounts/${id}/unmute`
export const MASTODON_REMOVE_USER_FROM_FOLLOWERS_URL = (id) =>
`/api/v1/accounts/${id}/remove_from_followers`
const MASTODON_USER_NOTE_URL = (id) => `/api/v1/accounts/${id}/note`
export const MASTODON_USER_NOTE_URL = (id) => `/api/v1/accounts/${id}/note`
const MASTODON_BOOKMARK_STATUS_URL = (id) => `/api/v1/statuses/${id}/bookmark`
const MASTODON_UNBOOKMARK_STATUS_URL = (id) =>
`/api/v1/statuses/${id}/unbookmark`
@ -79,7 +80,7 @@ const MASTODON_PIN_OWN_STATUS = (id) => `/api/v1/statuses/${id}/pin`
const MASTODON_UNPIN_OWN_STATUS = (id) => `/api/v1/statuses/${id}/unpin`
const MASTODON_MUTE_CONVERSATION = (id) => `/api/v1/statuses/${id}/mute`
const MASTODON_UNMUTE_CONVERSATION = (id) => `/api/v1/statuses/${id}/unmute`
const MASTODON_DOMAIN_BLOCKS_URL = '/api/v1/domain_blocks'
export const MASTODON_DOMAIN_BLOCKS_URL = '/api/v1/domain_blocks'
const MASTODON_ANNOUNCEMENTS_URL = '/api/v1/announcements'
const MASTODON_ANNOUNCEMENTS_DISMISS_URL = (id) =>
`/api/v1/announcements/${id}/dismiss`
@ -656,7 +657,7 @@ export const fetchUserInLists = ({ id, credentials }) =>
export const removeUserFromFollowers = ({ id, credentials }) =>
promisedRequest({
url: MASTODON_REMOVE_USER_FROM_FOLLOWERS(id),
url: MASTODON_REMOVE_USER_FROM_FOLLOWERS_URL(id),
credentials,
method: 'POST',
})

View file

@ -1,11 +1,8 @@
import { defineAsyncComponent } from 'vue'
import {
requestFollow,
requestUnfollow,
} from '../../services/follow_manipulate/follow_manipulate'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useUsersStore } from 'src/stores/users.js'
export default {
props: ['relationship', 'user', 'labelFollowing', 'buttonClass'],
components: {
@ -64,9 +61,11 @@ export default {
},
follow() {
this.inProgress = true
requestFollow(this.relationship.id, this.$store).then(() => {
this.inProgress = false
})
useUsersStore()
.followUser(this.relationship.id)
.then(() => {
this.inProgress = false
})
},
unfollow() {
if (this.shouldConfirmUnfollow) {
@ -78,13 +77,15 @@ export default {
doUnfollow() {
const store = this.$store
this.inProgress = true
requestUnfollow(this.relationship.id, store).then(() => {
this.inProgress = false
store.commit('removeStatus', {
timeline: 'friends',
userId: this.relationship.id,
useUsersStore()
.unfollowUser(this.relationship.id)
.then(() => {
this.inProgress = false
store.commit('removeStatus', {
timeline: 'friends',
userId: this.relationship.id,
})
})
})
this.hideConfirmUnfollow()
},

View file

@ -39,8 +39,7 @@ const UserProfile = {
},
unmounted() {
useInterfaceStore().setForeignProfileBackground(null)
this.$store.dispatch('clearFollowers', this.userId)
this.$store.dispatch('clearFriends', this.userId)
useUsersStore().clearFollowLists(this.userId)
},
computed: {
favorites() {

View file

@ -7,7 +7,6 @@ export const piniaPushNotificationsPlugin = ({ store }) => {
const validActions = {
sync_config: new Set(['setPreference']),
interface: new Set(['setNotificationPermission', 'setLoginStatus']),
user: new Set(['setCurrentUser', 'clearCurrentUser']),
}
if (!validActions[store.$id]) return // Not applicable to the store
@ -56,9 +55,9 @@ export const piniaPushNotificationsPlugin = ({ store }) => {
}
if (permissionGranted && enabled && user) {
return useUsersStore().registerPushNotifications()
return useInterfaceStore().registerPushNotifications()
} else {
return useUsersStore().unregisterPushNotifications()
return useInterfaceStore().unregisterPushNotifications()
}
})
}

View file

@ -1,67 +0,0 @@
import { useOAuthStore } from 'src/stores/oauth.js'
import {
fetchUserRelationship,
followUser,
unfollowUser,
} from 'src/api/user.js'
const fetchRelationship = (attempt, userId, store) =>
new Promise((resolve, reject) => {
setTimeout(() => {
fetchUserRelationship({
id: userId,
credentials: useOAuthStore().token,
})
.then(({ data: relationship }) => {
store.commit('updateUserRelationship', [relationship])
return relationship
})
.then((relationship) =>
resolve([
relationship.following,
relationship.requested,
relationship.locked,
attempt,
]),
)
.catch((e) => reject(e))
}, 500)
}).then(([following, sent, locked, attempt]) => {
if (!following && !(locked && sent) && attempt <= 3) {
// If we BE reports that we still not following that user - retry,
// increment attempts by one
fetchRelationship(++attempt, userId, store)
}
})
export const requestFollow = async (userId, store) => {
const { data: updated } = await followUser({
id: userId,
credentials: useOAuthStore().token,
})
store.commit('updateUserRelationship', [updated])
if (updated.following || (updated.locked && updated.requested)) {
// If we get result immediately or the account is locked, just stop.
return
}
// But usually we don't get result immediately, so we ask server
// for updated user profile to confirm if we are following them
// Sometimes it takes several tries. Sometimes we end up not following
// user anyway, probably because they locked themselves and we
// don't know that yet.
// Recursive Promise, it will call itself up to 3 times.
return await fetchRelationship(1, updated, store)
}
export const requestUnfollow = async (userId, store) => {
const { data: updated } = await unfollowUser({
id: userId,
credentials: useOAuthStore().token,
})
return await store.commit('updateUserRelationship', [updated])
}

View file

@ -3,6 +3,7 @@ import { defineStore } from 'pinia'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useStatusesStore } from 'src/stores/statuses.js'
import { useUsersStore } from 'src/stores/users.js'
import {
addNewEmojiFile,
@ -399,12 +400,10 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
return {
items: await Promise.all(
users.map(
async (userAdminData) =>
await window.vuex.dispatch('updateUserAdminData', {
userAdminData,
}),
),
users.map((user) => {
useUsersStore().updateUserAdminData(user.id, user)
return useUsersStore().findUser(user.id)
}),
),
count,
}
@ -418,7 +417,8 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
screen_name,
})
window.vuex.commit('updateUserAdminData', { user: result.data })
const { data } = result
useUsersStore().updateUserAdminData(data.id, data)
},
async deleteUsers({ users }) {
const screen_names = users.map((u) => u.screen_name)
@ -491,7 +491,7 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
})
users.forEach((user) => {
window.vuex.commit('updateRight', { user, right, value })
useUsersStore().updateRight(user.id, right, value)
})
},
async setUsersActivationStatus({ users, value }) {
@ -505,7 +505,7 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
})
resultUsers.data.forEach((user) => {
window.vuex.commit('updateUserAdminData', { user })
useUsersStore().updateUserAdminData(user.id, user)
})
},
async setUsersSuggestionStatus({ users, value }) {
@ -519,7 +519,7 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
})
resultUsers.data.forEach((user) => {
window.vuex.commit('updateUserAdminData', { user })
useUsersStore().updateUserAdminData(user.id, user)
})
},
async setUsersConfirmationStatus({ users }) {
@ -545,7 +545,7 @@ export const useAdminSettingsStore = defineStore('adminSettings', {
})
resultUsers.data.forEach((user) => {
window.vuex.commit('updateUserAdminData', { user })
useUsersStore().updateUserAdminData(user.id, user)
})
},
reloadEmoji() {

View file

@ -96,7 +96,7 @@ export const useAnnouncementsStore = defineStore('announcements', {
this.announcements[index].read = true
})
},
startFetchingAnnouncements() {
startFetching() {
if (this.fetchAnnouncementsTimer) {
return
}
@ -109,7 +109,7 @@ export const useAnnouncementsStore = defineStore('announcements', {
return this.fetchAnnouncements()
},
stopFetchingAnnouncements() {
stopFetching() {
const interval = this.fetchAnnouncementsTimer
this.fetchAnnouncementsTimer = undefined
clearInterval(interval)

View file

@ -43,11 +43,11 @@ export const useChatsStore = defineStore('chats', {
useStreamingStore().addSubscriber(socket)
},
startFetchingChats() {
startFetching() {
const fetcher = () => this.fetchChats()
this.setChatListFetcher(() => promiseInterval(fetcher, 5000))
},
stopFetchingChats() {
stopFetching() {
this.setChatListFetcher(null)
},
async fetchChats() {

View file

@ -6,20 +6,38 @@ import {
tryLoadCache,
} from '../services/style_setter/style_setter.js'
import { deserialize } from '../services/theme_data/iss_deserializer.js'
import {
windowHeight,
windowWidth,
} from '../services/window_utils/window_utils'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useStreamingStore } from 'src/stores/streaming.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import { useUsersStore } from 'src/stores/users.js'
import { WSConnectionStatus } from 'src/api/websocket.js'
import {
registerPushNotifications,
unregisterPushNotifications,
} from 'src/services/sw/sw.js'
import {
CURRENT_VERSION,
generatePreset,
} from 'src/services/theme_data/theme_data.service.js'
import { convertTheme2To3 } from 'src/services/theme_data/theme2_to_theme3.js'
const getNotificationPermission = async () => {
const Notification = window.Notification
if (!Notification) return null
if (Notification.permission === 'default')
return Notification.requestPermission()
return Notification.permission
}
const GENERIC_FONT_NAMES = new Set([
'serif',
'sans-serif',
@ -85,6 +103,19 @@ export const useInterfaceStore = defineStore('interface', {
useStreamingStore().addSubscriber(socket)
},
onLogin() {
getNotificationPermission().then((permission) =>
useInterfaceStore().setNotificationPermission(permission),
)
this.setLayoutWidth(windowWidth())
this.setLayoutHeight(windowHeight())
},
onLogout() {
this.setLastTimeline('public-timeline')
this.setLayoutWidth(windowWidth())
this.setLayoutHeight(windowHeight())
},
onStreamConnect() {
if (useStreamingStore().state !== WSConnectionStatus.STARTING_INITIAL) {
this.pushGlobalNotice({
@ -805,6 +836,28 @@ export const useInterfaceStore = defineStore('interface', {
window.splashError(e)
}
},
// Push notifications
registerPushNotifications() {
const token = useOAuthStore().token
const vapidPublicKey = useInstanceStore().vapidPublicKey
const isEnabled = useMergedConfigStore().mergedConfig.webPushNotifications
const notificationVisibility =
useMergedConfigStore().mergedConfig.notificationVisibility
registerPushNotifications(
isEnabled,
vapidPublicKey,
token,
notificationVisibility,
)
},
unregisterPushNotifications() {
const token = this.currentUser.credentials
unregisterPushNotifications(token)
},
},
})

View file

@ -592,6 +592,15 @@ export const useStatusesStore = defineStore('statuses', {
})
},
// For when blocking a user
wipeUserStatuses(userId) {
this.allStatuses.values().forEach((status) => {
if (status.user.id === userId) {
this.allStatuses.delete(status.id)
}
})
},
// Search
search({ q, resolve, limit, offset, following, type }) {
return search2({

View file

@ -317,22 +317,24 @@ export const useTimelinesStore = defineStore('timelines', {
},
// Misc
removeUserStatuses({ timelineName, userId }) {
const timeline = this.timelines[timelineName]
wipeUserStatuses(userId) {
TIMELINES.forEach((timelineName) => {
const timeline = this.timelines[timelineName]
timeline.statuses
.values()
.filter(({ user }) => user.id === userId)
.forEach(({ id }) => {
timeline.statuses.delete(id)
timeline.visibleStatusesIds.delete(id)
})
timeline.minVisibleId =
timeline.visibleStatusesIds.size > 0
? last(timeline.visibleStatusesIds).id
: 0
timeline.maxId =
timeline.statuses.length > 0 ? first(timeline.statuses).id : 0
timeline.statuses
.values()
.filter(({ user }) => user.id === userId)
.forEach(({ id }) => {
timeline.statuses.delete(id)
timeline.visibleStatusesIds.delete(id)
})
timeline.minVisibleId =
timeline.visibleStatusesIds.size > 0
? last(timeline.visibleStatusesIds).id
: 0
timeline.maxId =
timeline.statuses.length > 0 ? first(timeline.statuses).id : 0
})
},
},
})

File diff suppressed because it is too large Load diff

View file

@ -1,120 +0,0 @@
import { cloneDeep } from 'lodash'
import {
defaultState,
getters,
mutations,
} from '../../../../src/modules/users.js'
describe('The users module', () => {
describe('mutations', () => {
it('adds new users to the set, merging in new information for old users', () => {
const state = cloneDeep(defaultState)
const user = { id: '1', name: 'Guy' }
const modUser = { id: '1', name: 'Dude' }
mutations.addNewUsers(state, [user])
expect(state.users).to.have.length(1)
expect(state.users).to.eql([user])
mutations.addNewUsers(state, [modUser])
expect(state.users).to.have.length(1)
expect(state.users).to.eql([user])
expect(state.users[0].name).to.eql('Dude')
})
it('merging array field in new information for old users', () => {
const state = cloneDeep(defaultState)
const user = {
id: '1',
fields: [{ name: 'Label 1', value: 'Content 1' }],
}
const firstModUser = {
id: '1',
fields: [
{ name: 'Label 2', value: 'Content 2' },
{ name: 'Label 3', value: 'Content 3' },
],
}
const secondModUser = {
id: '1',
fields: [{ name: 'Label 4', value: 'Content 4' }],
}
mutations.addNewUsers(state, [user])
expect(state.users[0].fields).to.have.length(1)
expect(state.users[0].fields[0].name).to.eql('Label 1')
mutations.addNewUsers(state, [firstModUser])
expect(state.users[0].fields).to.have.length(2)
expect(state.users[0].fields[0].name).to.eql('Label 2')
expect(state.users[0].fields[1].name).to.eql('Label 3')
mutations.addNewUsers(state, [secondModUser])
expect(state.users[0].fields).to.have.length(1)
expect(state.users[0].fields[0].name).to.eql('Label 4')
})
})
describe('findUser', () => {
it('does not return user with matching screen_name', () => {
const user = { screen_name: 'Guy', id: '1' }
const state = {
usersObject: {
1: user,
},
usersByNameObject: {
guy: user,
},
}
const name = 'Guy'
expect(getters.findUser(state)(name)).to.be.undefined
})
it('returns user with matching id', () => {
const user = { screen_name: 'Guy', id: '1' }
const state = {
usersObject: {
1: user,
},
usersByNameObject: {
guy: user,
},
}
const id = '1'
const expected = { screen_name: 'Guy', id: '1' }
expect(getters.findUser(state)(id)).to.eql(expected)
})
})
describe('findUserByName', () => {
it('returns user with matching screen_name', () => {
const user = { screen_name: 'Guy', id: '1' }
const state = {
usersObject: {
1: user,
},
usersByNameObject: {
guy: user,
},
}
const name = 'Guy'
const expected = { screen_name: 'Guy', id: '1' }
expect(getters.findUserByName(state)(name)).to.eql(expected)
})
it('does not return user with matching id', () => {
const user = { screen_name: 'Guy', id: '1' }
const state = {
usersObject: {
1: user,
},
usersByNameObject: {
guy: user,
},
}
const id = '1'
expect(getters.findUserByName(state)(id)).to.be.undefined
})
})
})

File diff suppressed because it is too large Load diff