-
Is there some way of making an Arbitrary out of a callback that randomly generates a single example, sort of like using fc.gen()? The reason I ask is that working with individual examples seems easier when there are constraints within an example. For context, here's a bit more about what I'm doing. I'd like to generate data that contains unique ids and foreign key constraints. For example, for a SQL database with Department and Employee tables, I might generate multiple Departments and multiple Employees within each department, where an Employee record has a department id. It seems like generating ids first with fc.uniqueArray and then generating records would make sense, to make sure that foreign keys use an existing id. I suppose fc.chain() would make sense here. But thinking in terms of sets (Arbitraries) seems awkward compared to writing code that creates one example at a time. When combining Arbitraries, it results in taking the cross-product by default, which isn't what I want for fields that have constraints. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
There are probably many ways to approach this. Let's say your database records have the following structure: type DepartmentRow = {
id: number
department_name: string
}
type EmployeeRow = {
department_id: number
employee_name: string
} For many-to-one relations like this it's probably easiest to generate everything together in a nested structure first: const departmentArb = fc.record({
id: fc.nat(),
department_name: fc.string(),
employees: fc.array(fc.string())
}) From that we can easily derive the flat database records: fc.assert(
fc.property(
fc.array(departmentArb),
departments => {
const departmentRows: DepartmentRow[] = departments.map(
({ id, department_name }) => ({ id, department_name })
)
const employeeRows: EmployeeRow[] = departments.flatMap(
({ id, employees }) => employees.map(
employee_name => ({ department_id: id, employee_name })
)
)
console.log(departmentRows)
}
)
) That doesn't guarantee yet, that department IDs are unique. As you suggested, we can use fc.uniqueArray(departmentArb, { selector: dep => dep.id }) With that, uniqueness is determined based on the Alternatively, if you can sacrifice from generality, it might be easier in some cases to just use the array indices as IDs. |
Beta Was this translation helpful? Give feedback.
The answer provided by @gruhn has the advantage to uncouple the generation of the entities from the one of the relationships without sacrificing shrinking capabilities (no
chain
norgen
: both helpers have been added to offer a simpler adoption but suffer from unsolvable limitations).I think no. More precisely so far, I believe I have no built-in provided such level of complexity. That's said the few manyToXxx suggested by @gruhn could possibly be a great starting point to have a
fc.schema/database
(not planned).