Type row tests

This commit is contained in:
Adria Navarro 2023-07-13 12:17:24 +02:00
parent ca0d8e2eb6
commit 85aa105972
2 changed files with 119 additions and 107 deletions

View File

@ -1,27 +1,27 @@
const tk = require( "timekeeper") import tk from "timekeeper"
const timestamp = new Date("2023-01-26T11:48:57.597Z").toISOString() const timestamp = new Date("2023-01-26T11:48:57.597Z").toISOString()
tk.freeze(timestamp) tk.freeze(timestamp)
import { outputProcessing } from "../../../utilities/rowProcessor"
const { outputProcessing } = require("../../../utilities/rowProcessor") import * as setup from "./utilities"
const setup = require("./utilities")
const { basicRow } = setup.structures const { basicRow } = setup.structures
const { context, tenancy } = require("@budibase/backend-core") import { context, tenancy } from "@budibase/backend-core"
const { import { quotas } from "@budibase/pro"
quotas, import {
} = require("@budibase/pro")
const {
QuotaUsageType, QuotaUsageType,
StaticQuotaName, StaticQuotaName,
MonthlyQuotaName, MonthlyQuotaName,
} = require("@budibase/types") Row,
const { structures } = require("@budibase/backend-core/tests"); Table,
FieldType,
} from "@budibase/types"
import { structures } from "@budibase/backend-core/tests"
describe("/rows", () => { describe("/rows", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
let table let table: Table
let row let row: Row
afterAll(setup.afterAll) afterAll(setup.afterAll)
@ -29,12 +29,12 @@ describe("/rows", () => {
await config.init() await config.init()
}) })
beforeEach(async()=>{ beforeEach(async () => {
table = await config.createTable() table = await config.createTable()
row = basicRow(table._id) row = basicRow(table._id!)
}) })
const loadRow = async (id, tbl_Id, status = 200) => const loadRow = async (id: string, tbl_Id: string, status = 200) =>
await request await request
.get(`/api/${tbl_Id}/rows/${id}`) .get(`/api/${tbl_Id}/rows/${id}`)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
@ -42,21 +42,28 @@ describe("/rows", () => {
.expect(status) .expect(status)
const getRowUsage = async () => { const getRowUsage = async () => {
const { total } = await config.doInContext(null, () => quotas.getCurrentUsageValues(QuotaUsageType.STATIC, StaticQuotaName.ROWS)) const { total } = await config.doInContext(null, () =>
quotas.getCurrentUsageValues(QuotaUsageType.STATIC, StaticQuotaName.ROWS)
)
return total return total
} }
const getQueryUsage = async () => { const getQueryUsage = async () => {
const { total } = await config.doInContext(null, () => quotas.getCurrentUsageValues(QuotaUsageType.MONTHLY, MonthlyQuotaName.QUERIES)) const { total } = await config.doInContext(null, () =>
quotas.getCurrentUsageValues(
QuotaUsageType.MONTHLY,
MonthlyQuotaName.QUERIES
)
)
return total return total
} }
const assertRowUsage = async expected => { const assertRowUsage = async (expected: number) => {
const usage = await getRowUsage() const usage = await getRowUsage()
expect(usage).toBe(expected) expect(usage).toBe(expected)
} }
const assertQueryUsage = async expected => { const assertQueryUsage = async (expected: number) => {
const usage = await getQueryUsage() const usage = await getQueryUsage()
expect(usage).toBe(expected) expect(usage).toBe(expected)
} }
@ -70,9 +77,11 @@ describe("/rows", () => {
.post(`/api/${row.tableId}/rows`) .post(`/api/${row.tableId}/rows`)
.send(row) .send(row)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.res.statusMessage).toEqual(`${table.name} saved successfully`) expect((res as any).res.statusMessage).toEqual(
`${table.name} saved successfully`
)
expect(res.body.name).toEqual("Test Contact") expect(res.body.name).toEqual("Test Contact")
expect(res.body._rev).toBeDefined() expect(res.body._rev).toBeDefined()
await assertRowUsage(rowUsage + 1) await assertRowUsage(rowUsage + 1)
@ -86,12 +95,11 @@ describe("/rows", () => {
const newTable = await config.createTable({ const newTable = await config.createTable({
name: "TestTableAuto", name: "TestTableAuto",
type: "table", type: "table",
key: "name",
schema: { schema: {
...table.schema, ...table.schema,
"Row ID": { "Row ID": {
name: "Row ID", name: "Row ID",
type: "number", type: FieldType.NUMBER,
subtype: "autoID", subtype: "autoID",
icon: "ri-magic-line", icon: "ri-magic-line",
autocolumn: true, autocolumn: true,
@ -104,28 +112,30 @@ describe("/rows", () => {
}, },
}, },
}, },
} },
}) })
const ids = [1,2,3] const ids = [1, 2, 3]
// Performing several create row requests should increment the autoID fields accordingly // Performing several create row requests should increment the autoID fields accordingly
const createRow = async (id) => { const createRow = async (id: number) => {
const res = await request const res = await request
.post(`/api/${newTable._id}/rows`) .post(`/api/${newTable._id}/rows`)
.send({ .send({
name: "row_" + id name: "row_" + id,
}) })
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.res.statusMessage).toEqual(`${newTable.name} saved successfully`) expect((res as any).res.statusMessage).toEqual(
`${newTable.name} saved successfully`
)
expect(res.body.name).toEqual("row_" + id) expect(res.body.name).toEqual("row_" + id)
expect(res.body._rev).toBeDefined() expect(res.body._rev).toBeDefined()
expect(res.body["Row ID"]).toEqual(id) expect(res.body["Row ID"]).toEqual(id)
} }
for (let i=0; i<ids.length; i++ ){ for (let i = 0; i < ids.length; i++) {
await createRow(ids[i]) await createRow(ids[i])
} }
@ -150,7 +160,7 @@ describe("/rows", () => {
.expect("Content-Type", /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.res.statusMessage).toEqual( expect((res as any).res.statusMessage).toEqual(
`${table.name} updated successfully.` `${table.name} updated successfully.`
) )
expect(res.body.name).toEqual("Updated Name") expect(res.body.name).toEqual("Updated Name")
@ -196,8 +206,8 @@ describe("/rows", () => {
.expect(200) .expect(200)
expect(res.body.length).toBe(2) expect(res.body.length).toBe(2)
expect(res.body.find(r => r.name === newRow.name)).toBeDefined() expect(res.body.find((r: Row) => r.name === newRow.name)).toBeDefined()
expect(res.body.find(r => r.name === row.name)).toBeDefined() expect(res.body.find((r: Row) => r.name === row.name)).toBeDefined()
await assertQueryUsage(queryUsage + 1) await assertQueryUsage(queryUsage + 1)
}) })
@ -215,92 +225,91 @@ describe("/rows", () => {
it("row values are coerced", async () => { it("row values are coerced", async () => {
const str = { const str = {
type: "string", type: FieldType.STRING,
name: "str",
constraints: { type: "string", presence: false }, constraints: { type: "string", presence: false },
} }
const attachment = { const attachment = {
type: "attachment", type: FieldType.ATTACHMENT,
name: "attachment",
constraints: { type: "array", presence: false }, constraints: { type: "array", presence: false },
} }
const bool = { const bool = {
type: "boolean", type: FieldType.BOOLEAN,
name: "boolean",
constraints: { type: "boolean", presence: false }, constraints: { type: "boolean", presence: false },
} }
const number = { const number = {
type: "number", type: FieldType.NUMBER,
name: "str",
constraints: { type: "number", presence: false }, constraints: { type: "number", presence: false },
} }
const datetime = { const datetime = {
type: "datetime", type: FieldType.DATETIME,
name: "datetime",
constraints: { constraints: {
type: "string", type: "string",
presence: false, presence: false,
datetime: { earliest: "", latest: "" }, datetime: { earliest: "", latest: "" },
} },
} }
const arrayField = { const arrayField = {
type: "array", type: FieldType.ARRAY,
constraints: { constraints: {
type: "array", type: "array",
presence: false, presence: false,
inclusion: [ inclusion: ["One", "Two", "Three"],
"One",
"Two",
"Three",
]
}, },
name: "Sample Tags", name: "Sample Tags",
sortable: false sortable: false,
} }
const optsField = { const optsField = {
fieldName: "Sample Opts", fieldName: "Sample Opts",
name: "Sample Opts", name: "Sample Opts",
type: "options", type: FieldType.OPTIONS,
constraints: { constraints: {
type: "string", type: "string",
presence: false, presence: false,
inclusion: [ "Alpha", "Beta", "Gamma" ] inclusion: ["Alpha", "Beta", "Gamma"],
},
}, },
}, table = await config.createTable({
name: "TestTable2",
table = await config.createTable({ type: "table",
name: "TestTable2", schema: {
type: "table", name: str,
key: "name", stringUndefined: str,
schema: { stringNull: str,
name: str, stringString: str,
stringUndefined: str, numberEmptyString: number,
stringNull: str, numberNull: number,
stringString: str, numberUndefined: number,
numberEmptyString: number, numberString: number,
numberNull: number, numberNumber: number,
numberUndefined: number, datetimeEmptyString: datetime,
numberString: number, datetimeNull: datetime,
numberNumber: number, datetimeUndefined: datetime,
datetimeEmptyString: datetime, datetimeString: datetime,
datetimeNull: datetime, datetimeDate: datetime,
datetimeUndefined: datetime, boolNull: bool,
datetimeString: datetime, boolEmpty: bool,
datetimeDate: datetime, boolUndefined: bool,
boolNull: bool, boolString: bool,
boolEmpty: bool, boolBool: bool,
boolUndefined: bool, attachmentNull: attachment,
boolString: bool, attachmentUndefined: attachment,
boolBool: bool, attachmentEmpty: attachment,
attachmentNull: attachment, attachmentEmptyArrayStr: attachment,
attachmentUndefined: attachment, arrayFieldEmptyArrayStr: arrayField,
attachmentEmpty: attachment, arrayFieldArrayStrKnown: arrayField,
attachmentEmptyArrayStr: attachment, arrayFieldNull: arrayField,
arrayFieldEmptyArrayStr: arrayField, arrayFieldUndefined: arrayField,
arrayFieldArrayStrKnown: arrayField, optsFieldEmptyStr: optsField,
arrayFieldNull: arrayField, optsFieldUndefined: optsField,
arrayFieldUndefined: arrayField, optsFieldNull: optsField,
optsFieldEmptyStr: optsField, optsFieldStrKnown: optsField,
optsFieldUndefined: optsField, },
optsFieldNull: optsField, })
optsFieldStrKnown: optsField
},
})
row = { row = {
name: "Test Row", name: "Test Row",
@ -334,13 +343,13 @@ describe("/rows", () => {
optsFieldEmptyStr: "", optsFieldEmptyStr: "",
optsFieldUndefined: undefined, optsFieldUndefined: undefined,
optsFieldNull: null, optsFieldNull: null,
optsFieldStrKnown: 'Alpha' optsFieldStrKnown: "Alpha",
} }
const createdRow = await config.createRow(row); const createdRow = await config.createRow(row)
const id = createdRow._id const id = createdRow._id!
const saved = (await loadRow(id, table._id)).body const saved = (await loadRow(id, table._id!)).body
expect(saved.stringUndefined).toBe(undefined) expect(saved.stringUndefined).toBe(undefined)
expect(saved.stringNull).toBe("") expect(saved.stringNull).toBe("")
@ -365,15 +374,15 @@ describe("/rows", () => {
expect(saved.attachmentNull).toEqual([]) expect(saved.attachmentNull).toEqual([])
expect(saved.attachmentUndefined).toBe(undefined) expect(saved.attachmentUndefined).toBe(undefined)
expect(saved.attachmentEmpty).toEqual([]) expect(saved.attachmentEmpty).toEqual([])
expect(saved.attachmentEmptyArrayStr).toEqual([]) expect(saved.attachmentEmptyArrayStr).toEqual([])
expect(saved.arrayFieldEmptyArrayStr).toEqual([]) expect(saved.arrayFieldEmptyArrayStr).toEqual([])
expect(saved.arrayFieldNull).toEqual([]) expect(saved.arrayFieldNull).toEqual([])
expect(saved.arrayFieldUndefined).toEqual(undefined) expect(saved.arrayFieldUndefined).toEqual(undefined)
expect(saved.optsFieldEmptyStr).toEqual(null) expect(saved.optsFieldEmptyStr).toEqual(null)
expect(saved.optsFieldUndefined).toEqual(undefined) expect(saved.optsFieldUndefined).toEqual(undefined)
expect(saved.optsFieldNull).toEqual(null) expect(saved.optsFieldNull).toEqual(null)
expect(saved.arrayFieldArrayStrKnown).toEqual(['One']) expect(saved.arrayFieldArrayStrKnown).toEqual(["One"])
expect(saved.optsFieldStrKnown).toEqual('Alpha') expect(saved.optsFieldStrKnown).toEqual("Alpha")
}) })
}) })
@ -396,13 +405,13 @@ describe("/rows", () => {
.expect("Content-Type", /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.res.statusMessage).toEqual( expect((res as any).res.statusMessage).toEqual(
`${table.name} updated successfully.` `${table.name} updated successfully.`
) )
expect(res.body.name).toEqual("Updated Name") expect(res.body.name).toEqual("Updated Name")
expect(res.body.description).toEqual(existing.description) expect(res.body.description).toEqual(existing.description)
const savedRow = await loadRow(res.body._id, table._id) const savedRow = await loadRow(res.body._id, table._id!)
expect(savedRow.body.description).toEqual(existing.description) expect(savedRow.body.description).toEqual(existing.description)
expect(savedRow.body.name).toEqual("Updated Name") expect(savedRow.body.name).toEqual("Updated Name")
@ -504,7 +513,7 @@ describe("/rows", () => {
.expect(200) .expect(200)
expect(res.body.length).toEqual(2) expect(res.body.length).toEqual(2)
await loadRow(row1._id, table._id, 404) await loadRow(row1._id!, table._id!, 404)
await assertRowUsage(rowUsage - 2) await assertRowUsage(rowUsage - 2)
await assertQueryUsage(queryUsage + 1) await assertQueryUsage(queryUsage + 1)
}) })
@ -562,7 +571,7 @@ describe("/rows", () => {
describe("fetchEnrichedRows", () => { describe("fetchEnrichedRows", () => {
it("should allow enriching some linked rows", async () => { it("should allow enriching some linked rows", async () => {
const { table, firstRow, secondRow } = await tenancy.doInTenant( const { table, firstRow, secondRow } = await tenancy.doInTenant(
setup.structures.TENANT_ID, config.getTenantId(),
async () => { async () => {
const table = await config.createLinkedTable() const table = await config.createLinkedTable()
const firstRow = await config.createRow({ const firstRow = await config.createRow({
@ -624,7 +633,7 @@ describe("/rows", () => {
await setup.switchToSelfHosted(async () => { await setup.switchToSelfHosted(async () => {
context.doInAppContext(config.getAppId(), async () => { context.doInAppContext(config.getAppId(), async () => {
const enriched = await outputProcessing(table, [row]) const enriched = await outputProcessing(table, [row])
expect(enriched[0].attachment[0].url).toBe( expect((enriched as Row[])[0].attachment[0].url).toBe(
`/files/signed/prod-budi-app-assets/${config.getProdAppId()}/attachments/${attachmentId}` `/files/signed/prod-budi-app-assets/${config.getProdAppId()}/attachments/${attachmentId}`
) )
}) })

View File

@ -135,7 +135,10 @@ class TestConfiguration {
} }
} }
async doInContext(appId: string | null, task: any) { async doInContext<T>(
appId: string | null,
task: () => Promise<T>
): Promise<T> {
if (!appId) { if (!appId) {
appId = this.appId appId = this.appId
} }