Skip to content

Commit

Permalink
svg snapshot testing
Browse files Browse the repository at this point in the history
  • Loading branch information
seveibar committed Aug 27, 2024
1 parent 8110568 commit b01db7f
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 46 deletions.
60 changes: 47 additions & 13 deletions lib/utils/schematic/getAllDimensionsForSchematicBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type PortArrangement = SideSizes | ExplicitPinMappingArrangement
interface Params {
schWidth?: number
schHeight?: number
portDistanceFromEdge?: number
schPinSpacing: number
schPinStyle?: Record<
`pin${number}` | number | `${number}`,
Expand Down Expand Up @@ -78,7 +79,7 @@ interface SchematicBoxDimensions {
export const getAllDimensionsForSchematicBox = (
params: Params,
): SchematicBoxDimensions => {
const parsedParams: ParsedParams = { ...params } as any
const portDistanceFromEdge = params.portDistanceFromEdge ?? 0.2

let sideSizes = params.schPortArrangement
? getSizeOfSidesFromPortArrangement(params.schPortArrangement)
Expand Down Expand Up @@ -247,13 +248,6 @@ export const getAllDimensionsForSchematicBox = (
truePinIndex++
}

console.log(orderedTruePorts, {
leftTotalLength,
rightTotalLength,
topTotalLength,
bottomTotalLength,
})

// Use lengths to determine schWidth and schHeight
let schWidth = params.schWidth
if (!schWidth) {
Expand All @@ -264,22 +258,62 @@ export const getAllDimensionsForSchematicBox = (
schHeight = Math.max(leftTotalLength + 0.2, rightTotalLength + 0.2, 1)
}

const trueEdgePositions = {
// Top left corner
left: {
x: -schWidth / 2 - portDistanceFromEdge,
y: leftTotalLength / 2,
},
// bottom left corner
bottom: {
x: -leftTotalLength / 2,
y: -schHeight / 2 - portDistanceFromEdge,
},
// bottom right corner
right: {
x: schWidth / 2 + portDistanceFromEdge,
y: -leftTotalLength / 2,
},
// top right corner
top: {
x: leftTotalLength / 2,
y: schHeight / 2 + portDistanceFromEdge,
},
}

const trueEdgeTraversalDirections = {
left: { x: 0, y: -1 },
right: { x: 0, y: 1 },
top: { x: -1, y: 0 },
bottom: { x: 1, y: 0 },
}

const truePortsWithPositions = orderedTruePorts.map((p) => {
const { distanceFromEdge, trueIndex, pinNumber, side } = p
let x: number
let y: number
const { distanceFromEdge, side } = p
const edgePos = trueEdgePositions[side]
const edgeDir = trueEdgeTraversalDirections[side]

return {
x: edgePos.x + distanceFromEdge * edgeDir.x,
y: edgePos.y + distanceFromEdge * edgeDir.y,
...p,
}
})

return {
getPortPositionByPinNumber(pinNumber: number): { x: number; y: number } {
return { x: 0, y: 0 }
const port = truePortsWithPositions.find(
(p) => p.pinNumber.toString() === pinNumber.toString(),
)
if (!port) {
throw new Error(
`Could not find port for pin number ${pinNumber}, available pins: ${truePortsWithPositions.map((tp) => tp.pinNumber).join(", ")}`,
)
}
return port
},
getSize(): { width: number; height: number } {
return { width: 10, height: 10 }
return { width: schWidth, height: schHeight }
},
}
}
79 changes: 79 additions & 0 deletions tests/fixtures/extend-expect-any-svg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { expect, type MatcherResult } from "bun:test"
import * as fs from "node:fs"
import * as path from "node:path"
import looksSame from "looks-same"

async function toMatchSvgSnapshot(
this: any,
received: string,
testPathOriginal: string,
svgName?: string,
): Promise<MatcherResult> {
const testPath = testPathOriginal.replace(/\.test\.tsx?$/, "")
const snapshotDir = path.join(path.dirname(testPath), "__snapshots__")
const snapshotName = svgName
? `${svgName}.snap.svg`
: `${path.basename(testPath)}.snap.svg`
const filePath = path.join(snapshotDir, snapshotName)

if (!fs.existsSync(snapshotDir)) {
fs.mkdirSync(snapshotDir, { recursive: true })
}

const updateSnapshot =
process.argv.includes("--update-snapshots") ||
process.argv.includes("-u") ||
Boolean(process.env.BUN_UPDATE_SNAPSHOTS)

if (!fs.existsSync(filePath) || updateSnapshot) {
fs.writeFileSync(filePath, received)
return {
message: () => `Snapshot created at ${filePath}`,
pass: true,
}
}

const existingSnapshot = fs.readFileSync(filePath, "utf-8")

const result = await looksSame(
Buffer.from(received),
Buffer.from(existingSnapshot),
{
strict: false,
tolerance: 2,
},
)

if (result.equal) {
return {
message: () => "Snapshot matches",
pass: true,
}
}

const diffPath = filePath.replace(".snap.svg", ".diff.png")
await looksSame.createDiff({
reference: Buffer.from(existingSnapshot),
current: Buffer.from(received),
diff: diffPath,
highlightColor: "#ff00ff",
})

return {
message: () => `Snapshot does not match. Diff saved at ${diffPath}`,
pass: false,
}
}

expect.extend({
toMatchSvgSnapshot: toMatchSvgSnapshot as any,
})

declare module "bun:test" {
interface Matchers<T = unknown> {
toMatchSvgSnapshot(
testPath: string,
svgName?: string,
): Promise<MatcherResult>
}
}

This file was deleted.

1 change: 1 addition & 0 deletions tests/utils/schematic/__snapshots__/schematicbox1.snap.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
46 changes: 14 additions & 32 deletions tests/utils/schematic/getAllDimensionsForSchematicBox.test.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,20 @@
import { expect, test, describe } from "bun:test"
import { getAllDimensionsForSchematicBox } from "lib/utils/schematic/getAllDimensionsForSchematicBox"
import fs from "node:fs"
import { getSchematicBoxSvg } from "./getSchematicBoxSvg"
import "tests/fixtures/extend-expect-any-svg"

describe("getAllDimensionsForSchematicBox", () => {
test("should correctly calculate dimensions and generate SVG", () => {
const params: Parameters<typeof getAllDimensionsForSchematicBox>[0] = {
schWidth: 1,
schPinSpacing: 0.2,
schPinStyle: {},
pinCount: 8,
}
test("getAllDimensionsForSchematicBox 1", () => {
const params: Parameters<typeof getAllDimensionsForSchematicBox>[0] = {
schWidth: 1,
schPinSpacing: 0.2,
schPinStyle: {},
pinCount: 8,
}

const dimensions = getAllDimensionsForSchematicBox(params)
const size = dimensions.getSize()
const dimensions = getAllDimensionsForSchematicBox(params)

// Generate SVG
let svg = `<svg width="500" height="500" viewBox="${-size.width / 2 - 10} ${-size.height / 2 - 10} ${size.width + 20} ${size.height + 20}" xmlns="http://www.w3.org/2000/svg"><g transform="scale(1,-1)">`

// Draw the box
svg += `<rect x="${-size.width / 2}" y="${-size.height / 2}" width="${size.width}" height="${size.height}" fill="none" stroke-width="0.1px" stroke="black" />`

// Draw the pins
for (let i = 1; i <= 8; i++) {
const pos = dimensions.getPortPositionByPinNumber(i)
svg += `<circle cx="${pos.x}" cy="${pos.y}" r="0.5" fill="red" />`
svg += `<text x="${pos.x}" y="${pos.y + 0.2}" font-size="0.8" text-anchor="middle">${i}</text>`
}

svg += "</g></svg>"

// Save SVG to file
fs.writeFileSync(
`${import.meta.dir}/__snapshots__/schematic_box_test.snapshot.svg`,
svg,
)
})
expect(getSchematicBoxSvg(dimensions)).toMatchSvgSnapshot(
import.meta.path,
"schematicbox1",
)
})
23 changes: 23 additions & 0 deletions tests/utils/schematic/getSchematicBoxSvg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { getAllDimensionsForSchematicBox } from "lib/utils/schematic/getAllDimensionsForSchematicBox"

const MARGIN = 1

export const getSchematicBoxSvg = (
dimensions: ReturnType<typeof getAllDimensionsForSchematicBox>,
) => {
const size = dimensions.getSize()
let svg = `<svg width="500" height="500" viewBox="${-size.width / 2 - MARGIN} ${-size.height / 2 - MARGIN} ${size.width + MARGIN * 2} ${size.height + MARGIN * 2}" xmlns="http://www.w3.org/2000/svg"><g transform="scale(1,-1)">`

// Draw the box
svg += `<rect x="${-size.width / 2}" y="${-size.height / 2}" width="${size.width}" height="${size.height}" fill="none" stroke-width="0.1px" stroke="black" />`

// Draw the pins
for (let i = 1; i <= 8; i++) {
const pos = dimensions.getPortPositionByPinNumber(i)
svg += `<circle cx="${pos.x}" cy="${pos.y}" r="0.02" fill="red" />`
svg += `<text x="${pos.x + 0.1}" y="${pos.y + 0.01}" transform="translate(0,${(pos.y + 0.01) * 2}) scale(1,-1)" fill="green" font-size="0.1" text-anchor="middle">${i}</text>`
}

svg += "</g></svg>"
return svg
}

0 comments on commit b01db7f

Please sign in to comment.