Files

830 lines
26 KiB
JavaScript

import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { ref } from 'vue'
import { TestApp } from '@baserow/test/helpers/testApp'
import { permission } from '@baserow/test/helpers/permission'
import { heldBack } from '@baserow/test/helpers/heldBack'
import { providePosthog } from '@baserow/test/helpers/posthog'
import { toastsOfType, updateJob } from '@baserow/test/helpers/store'
import TemplateInstall from '@baserow/modules/core/components/template/TemplateInstall'
import { BaserowPlugin } from '@baserow/modules/core/plugins'
import CreateWorkspaceModal from '@baserow/modules/core/components/workspace/CreateWorkspaceModal'
import Toasts from '@baserow/modules/core/components/toasts/Toasts'
import { workspaceSidebarVisibleKey } from '@baserow/modules/core/composables/useWorkspaceSidebar'
vi.mock('#app', async (importOriginal) =>
(await import('@baserow/test/helpers/permission')).mockHasPermission(
importOriginal
)
)
const template = { id: 5, slug: 'project-tracker', name: 'Project Tracker' }
// What the `app` layout provides to the page and its toasts: whether its sidebar
// lists the selected workspace.
const withWorkspaceSidebar = (sidebar) => ({
provide: { [workspaceSidebarVisibleKey]: sidebar },
})
describe('TemplateInstall', () => {
let testApp = null
let push = null
beforeEach(async () => {
testApp = new TestApp()
testApp.store.commit('settings/SET_LOADED', true)
await testApp.nuxtApp.$router.replace('/template/project-tracker')
push = vi.spyOn(testApp.nuxtApp.$router, 'push').mockResolvedValue()
})
afterEach(async () => {
permission.check = () => true
push.mockRestore()
await testApp.afterEach()
})
const signIn = () => {
testApp.authenticate({ id: 1, preferences: {}, completed_onboarding: true })
testApp.store.dispatch('workspace/forceCreate', { id: 1, name: 'First' })
testApp.store.dispatch('workspace/forceCreate', { id: 2, name: 'Second' })
}
const mockInstall = (workspaceId) =>
testApp.mock
.onPost(`/templates/install/${workspaceId}/${template.id}/async/`)
.reply(202, { id: 10, type: 'install_template', state: 'finished' })
const clickUse = async (wrapper) => {
await wrapper.find('.template-install__use').trigger('click')
await flushPromises()
}
test.each([
'/template/project-tracker',
`/template/project-tracker/private-link/${'a'.repeat(64)}`,
])(
'sends an anonymous visitor from %s to the login page and back',
async (path) => {
const wrapper = await testApp.mount(TemplateInstall, {
props: { template },
})
await testApp.nuxtApp.$router.replace(path)
expect(wrapper.find('.template-install__workspace').exists()).toBe(false)
await clickUse(wrapper)
expect(push).toHaveBeenCalledWith({
name: 'login',
query: { original: path },
})
expect(testApp.mock.history.post).toHaveLength(0)
expect(wrapper.emitted('installed')).toBeUndefined()
}
)
test.each([
[
'installs into the provided workspace without redirecting',
{ workspace: { id: 2 } },
2,
// The public revision, or the owner's latest one while it isn't public.
{},
],
[
'installs the latest revision when asked to',
{ workspace: { id: 2 }, latest: true },
2,
{ latest: true },
],
['installs into the first workspace without leaving the page', {}, 1, {}],
])('%s', async (_title, props, workspaceId, params) => {
signIn()
mockInstall(workspaceId)
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, ...props },
})
await clickUse(wrapper)
expect(testApp.mock.history.post.map((r) => r.url)).toStrictEqual([
`/templates/install/${workspaceId}/5/async/`,
])
expect(testApp.mock.history.post.map((r) => r.params)).toStrictEqual([
params,
])
expect(wrapper.emitted('installed')).toHaveLength(1)
expect(push).not.toHaveBeenCalled()
expect(
wrapper.find('.template-install__use').attributes('disabled')
).toBeUndefined()
})
test('disables the workspaces the user cannot add applications to', async () => {
signIn()
permission.check = (operation, context, workspaceId) =>
operation !== 'workspace.create_application' || workspaceId !== 1
mockInstall(2)
const wrapper = await testApp.mount(TemplateInstall, {
props: { template },
})
await flushPromises()
const items = wrapper.findAllComponents({ name: 'DropdownItem' })
expect(items.map((item) => item.props('disabled'))).toStrictEqual([
true,
false,
])
expect(items[0].props('description')).toBe(
'templateInstall.workspaceNoPermission'
)
// The first workspace the template can be installed into is preselected.
await clickUse(wrapper)
expect(testApp.mock.history.post.map((r) => r.url)).toStrictEqual([
'/templates/install/2/5/async/',
])
})
test('cannot install without a workspace to add applications to', async () => {
signIn()
permission.check = (operation) =>
operation !== 'workspace.create_application'
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, workspace: { id: 1 } },
})
await flushPromises()
expect(
wrapper.find('.template-install__use').attributes('disabled')
).toBeDefined()
})
const installToasts = () => toastsOfType(testApp.store, 'installTemplate')
const selectWorkspace = (id) =>
testApp.store.commit(
'workspace/SET_SELECTED',
testApp.store.getters['workspace/get'](id)
)
describe('while the install runs', () => {
const mockRunningInstall = (workspaceId) =>
testApp.mock
.onPost(`/templates/install/${workspaceId}/${template.id}/async/`)
.reply(202, {
id: 10,
type: 'install_template',
state: 'started',
progress_percentage: 10,
workspace: { id: workspaceId },
installed_applications: [],
human_readable_error: '',
})
// The page and the toasts of the `app` layout, which share its sidebar.
const startInstall = async (workspaceId, sidebar) => {
const global = withWorkspaceSidebar(sidebar)
const toasts = await testApp.mount(Toasts, { global })
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, workspace: { id: workspaceId } },
global,
})
await clickUse(wrapper)
return toasts
}
const shownInstallToasts = (toasts) =>
toasts.findAll('.install-template-toast')
test('hides the progress while the sidebar shows the target workspace, then shows the result', async () => {
signIn()
selectWorkspace(1)
mockRunningInstall(1)
const toasts = await startInstall(1, ref(true))
expect(installToasts()).toHaveLength(1)
expect(shownInstallToasts(toasts)).toHaveLength(0)
await updateJob(testApp.store, 10, {
state: 'finished',
installed_applications: [],
})
expect(shownInstallToasts(toasts)).toHaveLength(1)
expect(toasts.find('.toast__title').text()).toBe(
'InstallTemplateJobType.installedMessage'
)
})
test.each([
[
'shows the progress when the sidebar is collapsed during the install',
(sidebar) => {
sidebar.value = false
},
],
[
'shows the progress when the user switches workspace during the install',
() => selectWorkspace(2),
],
])('%s', async (_title, leaveWorkspace) => {
signIn()
selectWorkspace(1)
mockRunningInstall(1)
const sidebar = ref(true)
const toasts = await startInstall(1, sidebar)
leaveWorkspace(sidebar)
await flushPromises()
expect(shownInstallToasts(toasts)).toHaveLength(1)
expect(toasts.find('.toast__message').text()).toBe('10 %')
})
})
test('loads the workspace permissions only once the template can be installed', async () => {
signIn()
testApp.mock.onGet(/\/workspaces\/\d+\/permissions\//).reply(200, [])
const own = { ...template, type: 'user', is_own: true }
const wrapper = await testApp.mount(TemplateInstall, {
props: { template: { ...own, state: 'blocked' } },
})
const loaded = () =>
testApp.mock.history.get.filter(({ url }) =>
url.includes('/permissions/')
)
expect(loaded()).toHaveLength(0)
await wrapper.setProps({ template: { ...own, state: 'private' } })
await flushPromises()
expect(loaded()).toHaveLength(2)
})
test('shows the copy link only when asked', async () => {
let wrapper = await testApp.mount(TemplateInstall, {
props: { template },
})
await wrapper
.find('.template-install__actions .button-icon')
.trigger('click')
expect(wrapper.findAll('.context__menu-item-link')).toHaveLength(1)
wrapper = await testApp.mount(TemplateInstall, {
props: { template, copyLinkKind: null },
})
expect(
wrapper.find('.template-install__actions .button-icon').exists()
).toBe(false)
})
test('does not report a failed install as installed', async () => {
signIn()
testApp.dontFailOnErrorResponses()
testApp.mock
.onPost(`/templates/install/1/${template.id}/async/`)
.reply(400, { error: 'ERROR_USER_NOT_IN_GROUP' })
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, workspace: { id: 1 } },
})
await clickUse(wrapper)
expect(wrapper.emitted('installed')).toBeUndefined()
expect(push).not.toHaveBeenCalled()
expect(installToasts()).toHaveLength(0)
expect(
wrapper.find('.template-install__use').attributes('disabled')
).toBeUndefined()
})
test('captures the install click and its refused request', async () => {
const posthog = providePosthog(testApp.nuxtApp)
signIn()
testApp.dontFailOnErrorResponses()
testApp.mock
.onPost(`/templates/install/1/${template.id}/async/`)
.reply(400, { error: 'ERROR_TEMPLATE_BLOCKED', detail: 'Blocked' })
const wrapper = await testApp.mount(TemplateInstall, {
props: {
template: { ...template, type: 'user' },
workspace: { id: 1 },
source: 'admin',
},
})
await clickUse(wrapper)
const shown = {
template_id: template.id,
template_slug: null,
template_type: 'user',
source: 'admin',
}
expect(posthog.capture.mock.calls).toEqual([
['template_install_clicked', { ...shown, signed_in: true }],
[
'template_install_failed',
{ ...shown, stage: 'request', error_code: 'ERROR_TEMPLATE_BLOCKED' },
],
])
})
test('shows nothing when the install answers after a logout', async () => {
signIn()
const { reply, send } = heldBack()
testApp.mock
.onPost(`/templates/install/1/${template.id}/async/`)
.reply(reply)
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, workspace: { id: 1 } },
})
await clickUse(wrapper)
await testApp.store.dispatch('auth/forceLogoff')
send([202, { id: 10, type: 'install_template', state: 'started' }])
await flushPromises()
expect(installToasts()).toHaveLength(0)
expect(testApp.store.getters['job/getAll']).toHaveLength(0)
expect(wrapper.emitted('installed')).toBeUndefined()
})
test('tells the user and asks to reload when the template was updated', async () => {
signIn()
testApp.dontFailOnErrorResponses()
testApp.mock
.onPost(`/templates/install/1/${template.id}/async/`)
.reply(400, {
error: 'ERROR_TEMPLATE_UPDATED',
detail: 'The template was updated after it was opened.',
})
const wrapper = await testApp.mount(TemplateInstall, {
props: {
template: { ...template, revision_id: 8 },
workspace: { id: 1 },
},
})
await clickUse(wrapper)
expect(
testApp.store.state.toast.items.map((toast) => [toast.type, toast.title])
).toStrictEqual([['error', 'clientHandler.templateUpdatedTitle']])
expect(wrapper.emitted('outdated')).toHaveLength(1)
expect(wrapper.emitted('installed')).toBeUndefined()
expect(installToasts()).toHaveLength(0)
})
describe('download', () => {
const userTemplate = {
id: 5,
type: 'user',
revision_id: 9,
slug: 'crm-a1b2c3',
name: 'CRM',
}
const runningJob = () => ({
id: 20,
type: 'download_user_template',
state: 'pending',
progress_percentage: 0,
human_readable_error: '',
slug: 'crm-a1b2c3',
revision_id: 9,
template_name: 'CRM',
})
const downloadUrl = '/templates/crm-a1b2c3/download/'
// The copied label is left out of the texts of the menu.
const mountWithMenu = async (props) => {
const wrapper = await testApp.mount(TemplateInstall, {
props,
global: { stubs: { Copied: true } },
})
await flushPromises()
await wrapper
.find('.template-install__actions .button-icon')
.trigger('click')
await flushPromises()
return wrapper
}
const menuTexts = (wrapper) =>
wrapper.findAll('.context__menu-item-link').map((link) => link.text())
const downloadLink = (wrapper) =>
wrapper
.findAll('.context__menu-item-link')
.find((link) => link.text() === 'templateInstall.download')
// The click doesn't bubble, so that only the item handles it. In the tests the
// menu is rendered again with a new element, which its check of the clicks
// outside of it would take as one.
const clickDownload = async (wrapper) => {
downloadLink(wrapper).element.dispatchEvent(
new MouseEvent('click', { bubbles: false, cancelable: true })
)
await flushPromises()
}
const menuIsOpen = (wrapper) =>
wrapper.findComponent({ name: 'Context' }).vm.isOpen()
const downloadRequests = () =>
testApp.mock.history.post
.filter((request) => request.url === downloadUrl)
.map((request) => JSON.parse(request.data))
const downloadToasts = () => toastsOfType(testApp.store, 'downloadTemplate')
const errorToasts = () => toastsOfType(testApp.store, 'error')
test.each([
['a user template', userTemplate, ['download']],
['an official template', template, []],
])('menu of %s', async (_, shown, extra) => {
signIn()
const wrapper = await mountWithMenu({ template: shown })
expect(menuTexts(wrapper)).toStrictEqual([
'templateInstall.copyLink',
...extra.map((item) => `templateInstall.${item}`),
])
})
test('starts the download job of the shown revision with its toast, then closes the menu', async () => {
const posthog = providePosthog(testApp.nuxtApp)
signIn()
const { reply, send } = heldBack()
testApp.mock.onPost(downloadUrl).reply(reply)
const wrapper = await mountWithMenu({
template: userTemplate,
source: 'browser',
})
await clickDownload(wrapper)
// While the job is requested the item shows it, and the menu stays open.
expect(downloadLink(wrapper).classes()).toContain(
'context__menu-item-link--loading'
)
expect(menuIsOpen(wrapper)).toBe(true)
// A second click doesn't request it again.
await clickDownload(wrapper)
expect(downloadRequests()).toStrictEqual([{ revision_id: 9 }])
send([202, runningJob()])
await flushPromises()
expect(downloadToasts().map((toast) => toast.data)).toStrictEqual([
{
jobId: 20,
template_name: 'CRM',
revision_id: 9,
autoDownload: true,
},
])
expect(menuIsOpen(wrapper)).toBe(false)
expect(posthog.capture.mock.calls).toEqual([
[
'template_download_requested',
{
template_id: 5,
template_slug: null,
template_type: 'user',
source: 'browser',
},
],
])
})
test('captures no click that only gets the download that runs already', async () => {
const posthog = providePosthog(testApp.nuxtApp)
signIn()
testApp.mock.onPost(downloadUrl).reply(202, runningJob())
const wrapper = await mountWithMenu({
template: userTemplate,
source: 'browser',
})
await clickDownload(wrapper)
await wrapper
.find('.template-install__actions .button-icon')
.trigger('click')
await flushPromises()
await clickDownload(wrapper)
expect(downloadRequests()).toHaveLength(2)
expect(downloadToasts()).toHaveLength(1)
expect(posthog.capture).toHaveBeenCalledTimes(1)
})
test('asks to reload when the shown revision is no longer public', async () => {
signIn()
testApp.dontFailOnErrorResponses()
testApp.mock.onPost(downloadUrl).reply(400, {
error: 'ERROR_TEMPLATE_UPDATED',
detail: 'The template was updated after it was opened.',
})
const wrapper = await mountWithMenu({ template: userTemplate })
await clickDownload(wrapper)
expect(errorToasts().map((toast) => toast.title)).toStrictEqual([
'clientHandler.templateUpdatedTitle',
])
expect(wrapper.emitted('outdated')).toHaveLength(1)
expect(downloadToasts()).toHaveLength(0)
})
test('shows why a template is not downloaded', async () => {
const posthog = providePosthog(testApp.nuxtApp)
signIn()
testApp.dontFailOnErrorResponses()
testApp.mock.onPost(downloadUrl).reply(400, {
error: 'ERROR_TEMPLATE_BLOCKED',
detail: 'The template is blocked.',
})
const wrapper = await mountWithMenu({ template: userTemplate })
await clickDownload(wrapper)
expect(errorToasts().map((toast) => toast.title)).toStrictEqual([
'clientHandler.templateBlockedTitle',
])
expect(downloadToasts()).toHaveLength(0)
expect(testApp.store.getters['job/getAll']).toHaveLength(0)
expect(downloadLink(wrapper).classes()).not.toContain(
'context__menu-item-link--loading'
)
expect(posthog.capture).not.toHaveBeenCalled()
})
test('shows nothing when the answer comes after a logout', async () => {
signIn()
const { reply, send } = heldBack()
testApp.mock.onPost(downloadUrl).reply(reply)
const wrapper = await mountWithMenu({ template: userTemplate })
await clickDownload(wrapper)
await testApp.store.dispatch('auth/forceLogoff')
send([202, runningJob()])
await flushPromises()
expect(downloadToasts()).toHaveLength(0)
expect(testApp.store.getters['job/getAll']).toHaveLength(0)
})
test('sends an anonymous visitor to the login page and back', async () => {
const wrapper = await mountWithMenu({ template: userTemplate })
await clickDownload(wrapper)
expect(push).toHaveBeenCalledWith({
name: 'login',
query: { original: '/template/crm-a1b2c3' },
})
expect(downloadRequests()).toHaveLength(0)
})
})
describe('without a workspace', () => {
const userTemplate = {
id: 5,
type: 'user',
slug: 'crm-a1b2c3',
name: 'CRM',
}
const signInWithoutWorkspace = () =>
testApp.authenticate({
id: 1,
preferences: {},
completed_onboarding: true,
})
const mountWithoutWorkspace = (props, canCreateWorkspace = true) =>
testApp.mount(TemplateInstall, {
props,
global: {
mocks: { $hasPermission: () => canCreateWorkspace },
},
})
describe.each([
['an official template', template],
['a user template', userTemplate],
])('of %s', (_name, shownTemplate) => {
test('creates a workspace and installs into it without leaving', async () => {
signInWithoutWorkspace()
const wrapper = await mountWithoutWorkspace({ template: shownTemplate })
expect(wrapper.find('.template-install__no-workspace').text()).toBe(
'templateInstall.noWorkspace'
)
expect(wrapper.find('.template-install__workspace').exists()).toBe(
false
)
expect(wrapper.find('.template-install__use').exists()).toBe(false)
await wrapper
.find('.template-install__create-workspace')
.trigger('click')
const modal = wrapper.findComponent(CreateWorkspaceModal)
expect(modal.vm.$refs.modal.isOpen()).toBe(true)
// Done by the modal before it reports the new workspace.
await testApp.store.dispatch('workspace/forceCreate', {
id: 3,
name: 'New',
})
modal.vm.$emit('created', testApp.store.getters['workspace/get'](3))
await flushPromises()
expect(wrapper.find('.template-install__no-workspace').exists()).toBe(
false
)
expect(
wrapper.find('.template-install__create-workspace').exists()
).toBe(false)
expect(
wrapper.findComponent({ name: 'Dropdown' }).props('modelValue')
).toBe(3)
expect(
wrapper.find('.template-install__use').attributes('disabled')
).toBeUndefined()
testApp.mock
.onPost(`/templates/install/3/${shownTemplate.id}/async/`)
.reply(202, { id: 10, type: 'install_template', state: 'finished' })
await clickUse(wrapper)
expect(testApp.mock.history.post.map((r) => r.url)).toStrictEqual([
`/templates/install/3/${shownTemplate.id}/async/`,
])
expect(wrapper.emitted('installed')).toHaveLength(1)
expect(push).not.toHaveBeenCalled()
})
test('asks to be invited when the user may not create a workspace', async () => {
signInWithoutWorkspace()
const wrapper = await mountWithoutWorkspace(
{ template: shownTemplate },
false
)
expect(wrapper.find('.template-install__no-workspace').text()).toBe(
'templateInstall.noWorkspaceAskInvite'
)
expect(
wrapper.find('.template-install__create-workspace').exists()
).toBe(false)
expect(wrapper.find('.template-install__workspace').exists()).toBe(
false
)
expect(
wrapper.find('.template-install__use').attributes('disabled')
).toBeDefined()
})
})
test('shows neither to an anonymous visitor', async () => {
const wrapper = await mountWithoutWorkspace({ template })
expect(wrapper.find('.template-install__no-workspace').exists()).toBe(
false
)
expect(wrapper.find('.template-install__create-workspace').exists()).toBe(
false
)
expect(wrapper.findComponent(CreateWorkspaceModal).exists()).toBe(false)
})
})
describe('identities for Agents', () => {
const agent = {
id: 3,
type: 'agent',
name: 'Helper',
waits_for_identity: true,
}
const database = { id: 4, type: 'database', name: 'CRM' }
const site = { id: 5, type: 'builder', name: 'Site' }
class ScopedIdentitiesPlugin extends BaserowPlugin {
static getType() {
return 'test_scoped_identities'
}
canCreateScopedIdentities(workspace) {
return workspace.id === 1
}
}
const registerPlugin = () =>
testApp
.getRegistry()
.register(
'plugin',
new ScopedIdentitiesPlugin({ app: testApp.getApp() })
)
afterEach(() => {
const registry = testApp.getRegistry()
if (registry.exists('plugin', ScopedIdentitiesPlugin.getType())) {
registry.unregister('plugin', ScopedIdentitiesPlugin.getType())
}
})
const option = (wrapper) => wrapper.find('.template-install__summary')
test('is hidden without a plugin that can scope identities', async () => {
signIn()
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, applications: [database, agent] },
})
expect(option(wrapper).exists()).toBe(false)
})
test('is hidden for a template without Agents', async () => {
signIn()
registerPlugin()
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, applications: [database] },
})
expect(option(wrapper).exists()).toBe(false)
})
test('is shown for a template with only Agents', async () => {
signIn()
registerPlugin()
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, applications: [agent] },
})
expect(option(wrapper).exists()).toBe(true)
})
test('is shown for a template with an Agent and any other application', async () => {
signIn()
registerPlugin()
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, applications: [site, agent] },
})
expect(option(wrapper).exists()).toBe(true)
})
test('is hidden when no Agent came with an identity', async () => {
signIn()
registerPlugin()
const wrapper = await testApp.mount(TemplateInstall, {
props: {
template,
applications: [database, { ...agent, waits_for_identity: false }],
},
})
expect(option(wrapper).exists()).toBe(false)
})
test('is hidden for a workspace the user cannot scope identities in', async () => {
signIn()
registerPlugin()
const wrapper = await testApp.mount(TemplateInstall, {
props: {
template,
workspace: { id: 2 },
applications: [database, agent],
},
})
expect(option(wrapper).exists()).toBe(false)
})
test('says what the install creates and sends no option for it', async () => {
signIn()
registerPlugin()
mockInstall(1)
const wrapper = await testApp.mount(TemplateInstall, {
props: { template, applications: [database, agent] },
})
expect(option(wrapper).text()).toBe('templateInstall.createsIdentities')
expect(option(wrapper).find('input').exists()).toBe(false)
await clickUse(wrapper)
expect(testApp.mock.history.post.map((r) => r.params)).toStrictEqual([{}])
})
})
})