Implement logic for automatic setup of api tests

This commit is contained in:
Pedro Silva 2023-01-09 15:31:07 +00:00
parent 664d660f99
commit e8ff068dae
13 changed files with 224 additions and 65 deletions

View File

@ -4,4 +4,7 @@ ENCRYPTED_TEST_PUBLIC_API_KEY=a65722f06bee5caeadc5d7ca2f543a43-d610e627344210c64
COUCH_DB_URL=http://budibase:budibase@localhost:4567
COUCH_DB_USER=budibase
COUCH_DB_PASSWORD=budibase
JWT_SECRET=test
JWT_SECRET=test
BUDIBASE_SERVER_URL=http://localhost:4100
BUDIBASE_HOST= budirelease.live
BUDIBASE_ACCOUNTS_URL=https://account.budirelease.live

View File

@ -11,40 +11,53 @@ interface ApiOptions {
class InternalAPIClient {
host: string
tenantName?: string
appId?: string
cookie?: string
constructor(appId?: string) {
if (!env.BUDIBASE_SERVER_URL) {
if (!env.BUDIBASE_HOST) {
throw new Error("Must set BUDIBASE_SERVER_URL env var")
}
this.host = `${env.BUDIBASE_SERVER_URL}/api`
this.host = `${env.BUDIBASE_HOST}/api`
this.appId = appId
}
setTenantName(tenantName: string) {
this.tenantName = tenantName
}
apiCall =
(method: APIMethod) =>
async (url = "", options: ApiOptions = {}) => {
const requestOptions = {
method,
body: JSON.stringify(options.body),
headers: {
"x-budibase-app-id": this.appId,
"Content-Type": "application/json",
Accept: "application/json",
cookie: this.cookie,
...options.headers,
},
credentials: "include",
}
async (url = "", options: ApiOptions = {}) => {
const requestOptions = {
method,
body: JSON.stringify(options.body),
headers: {
"x-budibase-app-id": this.appId,
"Content-Type": "application/json",
Accept: "application/json",
cookie: this.cookie,
redirect: "follow",
follow: 20,
...options.headers,
},
credentials: "include",
}
// @ts-ignore
const response = await fetch(`${this.host}${url}`, requestOptions)
if (response.status !== 200) {
console.error(response)
// @ts-ignore
const response = await fetch(`https://${process.env.TENANT_ID}.${this.host}${url}`, requestOptions)
if (response.status == 404 || response.status == 500) {
console.error("Error in apiCall")
console.error("Response:")
console.error(response)
console.error("Response body:")
console.error(response.body)
console.error("Request body:")
console.error(requestOptions.body)
}
return response
}
return response
}
post = this.apiCall("POST")
get = this.apiCall("GET")

View File

@ -1,32 +1,34 @@
import { Response } from "node-fetch"
import { Account } from "@budibase/types"
import InternalAPIClient from "./InternalAPIClient"
import AccountsAPIClient from "./accountsAPIClient"
import { NewAccount } from "../fixtures/types/newAccount"
export default class AccountsApi {
api: InternalAPIClient
api: AccountsAPIClient
constructor(apiClient: InternalAPIClient) {
this.api = apiClient
constructor(AccountsAPIClient: AccountsAPIClient) {
this.api = AccountsAPIClient
}
async validateEmail(email: string): Promise<[Response, any]> {
async validateEmail(email: string): Promise<Response> {
const response = await this.api.post(`/accounts/validate/email`, { body: { email } })
const json = await response.json()
expect(response).toHaveStatusCode(200)
return [response, json]
return response
}
async validateTenantId(tenantId: string): Promise<[Response, any]> {
async validateTenantId(tenantId: string): Promise<Response> {
const response = await this.api.post(`/accounts/validate/tenantId`, { body: { tenantId } })
const json = await response.json()
expect(response).toHaveStatusCode(200)
return [response, json]
return response
}
async create(body: Account): Promise<[Response, Account]> {
const response = await this.api.post(`/accounts`, { body })
async create(body: Partial<NewAccount>): Promise<[Response, Account]> {
const headers = {
'no-verify': '1'
}
const response = await this.api.post(`/accounts`, { body, headers })
const json = await response.json()
expect(response).toHaveStatusCode(200)
expect(response).toHaveStatusCode(201)
return [response, json]
}
}

View File

@ -0,0 +1,64 @@
import env from "../../../environment"
import fetch, { HeadersInit } from "node-fetch"
type APIMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
interface ApiOptions {
method?: APIMethod
body?: object
headers?: HeadersInit | undefined
}
class AccountsAPIClient {
host: string
appId?: string
cookie?: string
constructor(appId?: string) {
if (!env.BUDIBASE_ACCOUNTS_URL) {
throw new Error("Must set BUDIBASE_SERVER_URL env var")
}
this.host = `${env.BUDIBASE_ACCOUNTS_URL}/api`
this.appId = appId
}
apiCall =
(method: APIMethod) =>
async (url = "", options: ApiOptions = {}) => {
const requestOptions = {
method,
body: JSON.stringify(options.body),
headers: {
"x-budibase-app-id": this.appId,
"Content-Type": "application/json",
Accept: "application/json",
cookie: this.cookie,
redirect: "follow",
follow: 20,
...options.headers,
},
credentials: "include",
}
// @ts-ignore
const response = await fetch(`${this.host}${url}`, requestOptions)
if (response.status == 404 || response.status == 500) {
console.error("Error in apiCall")
console.error("Response:")
console.error(response)
console.error("Response body:")
console.error(response.body)
console.error("Request body:")
console.error(requestOptions.body)
}
return response
}
post = this.apiCall("POST")
get = this.apiCall("GET")
patch = this.apiCall("PATCH")
del = this.apiCall("DELETE")
put = this.apiCall("PUT")
}
export default AccountsAPIClient

View File

@ -1,6 +1,7 @@
import ApplicationApi from "./applications"
import AuthApi from "./auth"
import InternalAPIClient from "./InternalAPIClient"
import AccountsApiClient from "./accountsAPIClient"
import TablesApi from "./tables"
import RowApi from "./rows"
import ScreenApi from "./screens"
@ -17,15 +18,20 @@ export default class TestConfiguration<T> {
rows: RowApi
users: UserManagementApi
accounts: AccountsApi
apiClient: InternalAPIClient
accountsApiClient: AccountsApiClient
constructor(apiClient: InternalAPIClient) {
this.applications = new ApplicationApi(apiClient)
this.tables = new TablesApi(apiClient)
this.rows = new RowApi(apiClient)
this.auth = new AuthApi(apiClient)
this.screen = new ScreenApi(apiClient)
this.users = new UserManagementApi(apiClient)
this.accounts = new AccountsApi(apiClient)
constructor(apiClient: InternalAPIClient, accountsApiClient: AccountsApiClient) {
this.apiClient = apiClient
this.accountsApiClient = accountsApiClient
this.applications = new ApplicationApi(this.apiClient)
this.tables = new TablesApi(this.apiClient)
this.rows = new RowApi(this.apiClient)
this.auth = new AuthApi(this.apiClient)
this.screen = new ScreenApi(this.apiClient)
this.users = new UserManagementApi(this.apiClient)
this.accounts = new AccountsApi(this.accountsApiClient)
this.context = <T>{}
}
@ -35,10 +41,23 @@ export default class TestConfiguration<T> {
async setupAccountAndTenant() {
const account = generateAccount()
await this.accounts.validateEmail(account.email)
await this.accounts.validateTenantId(account.tenantId)
//await this.accounts.validateEmail(<string>account.email)
//await this.accounts.validateTenantId(<string>account.tenantId)
process.env.TENANT_ID = <string>account.tenantId
await this.accounts.create(account)
await this.auth.login(account.email, account.password)
await this.updateApiClients(<string>account.tenantName)
await this.auth.login(<string>account.email, <string>account.password)
}
async updateApiClients(tenantName: string) {
this.apiClient.setTenantName(tenantName)
this.applications = new ApplicationApi(this.apiClient)
this.tables = new TablesApi(this.apiClient)
this.rows = new RowApi(this.apiClient)
this.auth = new AuthApi(this.apiClient)
this.screen = new ScreenApi(this.apiClient)
this.users = new UserManagementApi(this.apiClient)
this.context = <T>{}
}
async login(email: string, password: string) {

View File

@ -1,17 +1,22 @@
import { Account } from "@budibase/types";
import generator from "../../generator";
import { NewAccount } from "./types/newAccount";
export const generateAccount = (): Account => {
import generator from "../../generator";
import { Hosting } from "@budibase/types";
export const generateAccount = (): Partial<NewAccount> => {
const randomGuid = generator.guid();
let tenant: string = 'a' + randomGuid;
tenant = tenant.replace(/-/g, '');
return {
email: `qa+${randomGuid}@budibase.com`,
hosting: "cloud",
hosting: Hosting.CLOUD,
name: `qa+${randomGuid}@budibase.com`,
password: `${randomGuid}`,
profession: "software_engineer",
size: "10+",
tenantId: `${randomGuid}`,
tenantName: `${randomGuid}`,
tenantId: `${tenant}`,
tenantName: `${tenant}`,
}
}

View File

@ -0,0 +1,5 @@
import { Account } from "@budibase/types";
export interface NewAccount extends Account {
password: string;
}

View File

@ -1,6 +1,9 @@
const env = {
BUDIBASE_SERVER_URL: process.env.BUDIBASE_SERVER_URL,
BUDIBASE_ACCOUNT_URL: process.env.BUDIBASE_ACCOUNT_URL,
BUDIBASE_PUBLIC_API_KEY: process.env.BUDIBASE_PUBLIC_API_KEY,
BUDIBASE_ACCOUNTS_URL: process.env.BUDIBASE_ACCOUNTS_URL,
BUDIBASE_HOST: process.env.BUDIBASE_HOST,
_set(key: any, value: any) {
process.env[key] = value
module.exports[key] = value

View File

@ -2,16 +2,18 @@ import TestConfiguration from "../../../config/internal-api/TestConfiguration"
import { Application } from "@budibase/server/api/controllers/public/mapping/types"
import { db } from "@budibase/backend-core"
import InternalAPIClient from "../../../config/internal-api/TestConfiguration/InternalAPIClient"
import AccountsAPIClient from "../../../config/internal-api/TestConfiguration/accountsAPIClient"
import { generateApp, appFromTemplate } from "../../../config/internal-api/fixtures/applications"
import generator from "../../../config/generator"
import generateScreen from "../../../config/internal-api/fixtures/screens"
describe("Internal API - Application creation, update, publish and delete", () => {
const api = new InternalAPIClient()
const config = new TestConfiguration<Application>(api)
const accountsAPI = new AccountsAPIClient()
const config = new TestConfiguration<Application>(api, accountsAPI)
beforeAll(async () => {
await config.loginAsAdmin()
await config.setupAccountAndTenant()
})
afterAll(async () => {

View File

@ -1,17 +1,19 @@
import TestConfiguration from "../../../config/internal-api/TestConfiguration"
import { App } from "@budibase/types"
import InternalAPIClient from "../../../config/internal-api/TestConfiguration/InternalAPIClient"
import AccountsAPIClient from "../../../config/internal-api/TestConfiguration/accountsAPIClient"
import { generateApp, appFromTemplate } from "../../../config/internal-api/fixtures/applications"
import { Screen } from "@budibase/types"
import generateScreen from "../../../config/internal-api/fixtures/screens"
describe("Internal API - /screens endpoints", () => {
const api = new InternalAPIClient()
const config = new TestConfiguration<Screen>(api)
const appConfig = new TestConfiguration<App>(api)
const accountsAPI = new AccountsAPIClient()
const config = new TestConfiguration<Screen>(api, accountsAPI)
const appConfig = new TestConfiguration<App>(api, accountsAPI)
beforeAll(async () => {
await config.loginAsAdmin()
await config.setupAccountAndTenant()
})
afterAll(async () => {

View File

@ -1,6 +1,7 @@
import TestConfiguration from "../../../config/internal-api/TestConfiguration"
import { Application } from "@budibase/server/api/controllers/public/mapping/types"
import InternalAPIClient from "../../../config/internal-api/TestConfiguration/InternalAPIClient"
import AccountsAPIClient from "../../../config/internal-api/TestConfiguration/accountsAPIClient"
import generator from "../../../config/generator"
import {
generateTable,
@ -10,10 +11,11 @@ import { generateNewRowForTable } from "../../../config/internal-api/fixtures/ro
describe("Internal API - Application creation, update, publish and delete", () => {
const api = new InternalAPIClient()
const config = new TestConfiguration<Application>(api)
const accountsAPI = new AccountsAPIClient()
const config = new TestConfiguration<Application>(api, accountsAPI)
beforeAll(async () => {
await config.loginAsAdmin()
await config.setupAccountAndTenant()
})
afterAll(async () => {

View File

@ -1,6 +1,7 @@
import TestConfiguration from "../../../config/internal-api/TestConfiguration"
import { Application } from "@budibase/server/api/controllers/public/mapping/types"
import InternalAPIClient from "../../../config/internal-api/TestConfiguration/InternalAPIClient"
import AccountsAPIClient from "../../../config/internal-api/TestConfiguration/accountsAPIClient"
import { generateApp, appFromTemplate } from "../../../config/internal-api/fixtures/applications"
import { generateUser } from "../../../config/internal-api/fixtures/userManagement"
import { User } from "@budibase/types"
@ -9,12 +10,16 @@ import generateScreen from "../../../config/internal-api/fixtures/screens"
import { db } from "@budibase/backend-core"
describe("Internal API - App Specific Roles & Permissions", () => {
const api = new InternalAPIClient()
const config = new TestConfiguration<Application>(api)
let api: InternalAPIClient
let accountsAPI: AccountsAPIClient
let config: TestConfiguration<Application>
// Before each test, login as admin. Some tests will require login as a different user
beforeEach(async () => {
await config.loginAsAdmin()
api = new InternalAPIClient()
accountsAPI = new AccountsAPIClient()
config = new TestConfiguration<Application>(api, accountsAPI)
await config.setupAccountAndTenant()
})
afterAll(async () => {
@ -103,6 +108,22 @@ describe("Internal API - App Specific Roles & Permissions", () => {
})
describe("Check Access for default roles", () => {
let api: InternalAPIClient
let accountsAPI: AccountsAPIClient
let config: TestConfiguration<Application>
// Before each test, login as admin. Some tests will require login as a different user
beforeEach(async () => {
api = new InternalAPIClient()
accountsAPI = new AccountsAPIClient()
config = new TestConfiguration<Application>(api, accountsAPI)
await config.setupAccountAndTenant()
})
afterAll(async () => {
await config.afterAll()
})
it("Check Table access for app user", async () => {
const appUser = generateUser()
expect(appUser[0].builder?.global).toEqual(false)
@ -203,6 +224,22 @@ describe("Internal API - App Specific Roles & Permissions", () => {
})
describe("Screen Access for App specific roles", () => {
let api: InternalAPIClient
let accountsAPI: AccountsAPIClient
let config: TestConfiguration<Application>
// Before each test, login as admin. Some tests will require login as a different user
beforeEach(async () => {
api = new InternalAPIClient()
accountsAPI = new AccountsAPIClient()
config = new TestConfiguration<Application>(api, accountsAPI)
await config.setupAccountAndTenant()
})
afterAll(async () => {
await config.afterAll()
})
it("Check Screen access for BASIC Role", async () => {
// Set up user
const appUser = generateUser()

View File

@ -1,16 +1,18 @@
import TestConfiguration from "../../../config/internal-api/TestConfiguration"
import { Application } from "@budibase/server/api/controllers/public/mapping/types"
import InternalAPIClient from "../../../config/internal-api/TestConfiguration/InternalAPIClient"
import AccountsAPIClient from "../../../config/internal-api/TestConfiguration/accountsAPIClient"
import { generateUser } from "../../../config/internal-api/fixtures/userManagement"
import { User } from "@budibase/types"
describe("Internal API - User Management & Permissions", () => {
const api = new InternalAPIClient()
const config = new TestConfiguration<Application>(api)
const accountsAPI = new AccountsAPIClient()
const config = new TestConfiguration<Application>(api, accountsAPI)
// Before each test, login as admin. Some tests will require login as a different user
beforeEach(async () => {
await config.loginAsAdmin()
beforeAll(async () => {
await config.setupAccountAndTenant()
})
afterAll(async () => {