Open History to see the last commit
1import { describe, expect } from 'vitest'
2import { fc, test as fcTest } from '@fast-check/vitest'
3import { hash } from '../src/hashing/hash'
4
5/**
6 * Property-based tests for hash function
7 *
8 * Key properties:
9 * 1. Determinism: hash(x) always returns the same value
10 * 2. Structural equality: equal structures should have the same hash
11 * 3. Property order independence: objects with same properties in different order have same hash
12 * 4. Number normalization: -0 and 0 have same hash, NaN has consistent hash
13 * 5. Type markers: different types should generally produce different hashes
14 */
15
16// Arbitraries for generating test values
17const arbitraryPrimitive = fc.oneof(
18 fc.string(),
19 fc.integer(),
20 fc.double({ noNaN: true }),
21 fc.boolean(),
22 fc.constant(null),
23 fc.constant(undefined),
24)
25
26const arbitraryDate = fc.date({ noInvalidDate: true })
27
28const arbitraryUint8Array = fc.uint8Array({ minLength: 0, maxLength: 128 })
29
30const arbitrarySimpleObject = fc.dictionary(fc.string(), fc.integer(), {
31 maxKeys: 5,
32})
33
34const arbitrarySimpleArray = fc.array(fc.integer(), { maxLength: 10 })
35
36describe(`hash property-based tests`, () => {
37 describe(`determinism`, () => {
38 fcTest.prop([arbitraryPrimitive])(
39 `hash is deterministic for primitives`,
40 (value) => {
41 const first = hash(value)
42 const second = hash(value)
43 expect(first).toBe(second)
44 },
45 )
46
47 fcTest.prop([arbitrarySimpleObject])(
48 `hash is deterministic for objects`,
49 (obj) => {
50 const first = hash(obj)
51 const second = hash(obj)
52 expect(first).toBe(second)
53 },
54 )
55
56 fcTest.prop([arbitrarySimpleArray])(
57 `hash is deterministic for arrays`,
58 (arr) => {
59 const first = hash(arr)
60 const second = hash(arr)
61 expect(first).toBe(second)
62 },
63 )
64
65 fcTest.prop([arbitraryDate])(`hash is deterministic for dates`, (date) => {
66 const first = hash(date)
67 const second = hash(date)
68 expect(first).toBe(second)
69 })
70
71 fcTest.prop([arbitraryUint8Array])(
72 `hash is deterministic for Uint8Arrays`,
73 (arr) => {
74 const first = hash(arr)
75 const second = hash(arr)
76 expect(first).toBe(second)
77 },
78 )
79 })
80
81 describe(`structural equality`, () => {
82 fcTest.prop([arbitrarySimpleObject])(
83 `cloned objects have same hash`,
84 (obj) => {
85 const clone = { ...obj }
86 expect(hash(clone)).toBe(hash(obj))
87 },
88 )
89
90 fcTest.prop([arbitrarySimpleArray])(
91 `cloned arrays have same hash`,
92 (arr) => {
93 const clone = [...arr]
94 expect(hash(clone)).toBe(hash(arr))
95 },
96 )
97
98 fcTest.prop([arbitraryDate])(
99 `dates with same time have same hash`,
100 (date) => {
101 const clone = new Date(date.getTime())
102 expect(hash(clone)).toBe(hash(date))
103 },
104 )
105
106 fcTest.prop([arbitraryUint8Array])(
107 `Uint8Arrays with same content have same hash`,
108 (arr) => {
109 const clone = new Uint8Array(arr)
110 expect(hash(clone)).toBe(hash(arr))
111 },
112 )
113
114 fcTest.prop([
115 fc.array(fc.tuple(fc.string(), fc.integer()), { maxLength: 5 }),
116 ])(`Maps with same entries have same hash`, (entries) => {
117 const map1 = new Map(entries)
118 const map2 = new Map(entries)
119 expect(hash(map1)).toBe(hash(map2))
120 })
121
122 fcTest.prop([fc.array(fc.integer(), { maxLength: 10 })])(
123 `Sets with same values have same hash`,
124 (arr) => {
125 const set1 = new Set(arr)
126 const set2 = new Set(arr)
127 expect(hash(set1)).toBe(hash(set2))
128 },
129 )
130 })
131
132 describe(`property order independence`, () => {
133 fcTest.prop([
134 fc.tuple(
135 fc.string().filter((s) => s !== `` && s !== `__proto__`),
136 fc.integer(),
137 fc.string().filter((s) => s !== `` && s !== `__proto__`),
138 fc.integer(),
139 ),
140 ])(
141 `objects with same properties in different order have same hash`,
142 ([key1, val1, key2, val2]) => {
143 // Skip if keys are the same
144 if (key1 === key2) return
145
146 const obj1 = { [key1]: val1, [key2]: val2 }
147 const obj2 = { [key2]: val2, [key1]: val1 }
148 expect(hash(obj1)).toBe(hash(obj2))
149 },
150 )
151
152 fcTest.prop([
153 fc.dictionary(
154 fc.string().filter((s) => s !== `__proto__`),
155 fc.integer(),
156 { minKeys: 2, maxKeys: 5 },
157 ),
158 ])(`object hash is independent of property insertion order`, (obj) => {
159 const keys = Object.keys(obj)
160 const reversedKeys = [...keys].reverse()
161
162 // Create new object with reversed key order
163 const reversed: Record<string, number> = {}
164 for (const key of reversedKeys) {
165 reversed[key] = obj[key]!
166 }
167
168 expect(hash(reversed)).toBe(hash(obj))
169 })
170 })
171
172 describe(`number normalization`, () => {
173 fcTest.prop([fc.constant(0)])(`0 and -0 have the same hash`, () => {
174 expect(hash(0)).toBe(hash(-0))
175 })
176
177 fcTest.prop([fc.constant(NaN)])(`NaN has consistent hash`, () => {
178 const first = hash(NaN)
179 const second = hash(NaN)
180 expect(first).toBe(second)
181 })
182
183 fcTest.prop([fc.integer()])(`integers hash consistently`, (n) => {
184 expect(hash(n)).toBe(hash(n))
185 })
186
187 fcTest.prop([fc.double({ noNaN: true, noDefaultInfinity: true })])(
188 `doubles hash consistently`,
189 (n) => {
190 expect(hash(n)).toBe(hash(n))
191 },
192 )
193 })
194
195 describe(`type distinction`, () => {
196 fcTest.prop([fc.array(fc.integer(), { minLength: 0, maxLength: 5 })])(
197 `array and object with same indices have different hashes`,
198 (arr) => {
199 // Create object with same numeric keys
200 const obj: Record<string, number> = {}
201 arr.forEach((val, idx) => {
202 obj[String(idx)] = val
203 })
204
205 // Arrays and objects should generally have different hashes due to markers
206 // but for empty ones, both might hash the same
207 if (arr.length > 0) {
208 expect(hash(arr)).not.toBe(hash(obj))
209 }
210 },
211 )
212
213 fcTest.prop([fc.integer()])(
214 `number and string representation have different hashes`,
215 (n) => {
216 expect(hash(n)).not.toBe(hash(String(n)))
217 },
218 )
219
220 fcTest.prop([fc.boolean()])(
221 `boolean and its string representation have different hashes`,
222 (b) => {
223 expect(hash(b)).not.toBe(hash(String(b)))
224 },
225 )
226
227 fcTest.prop([fc.date({ noInvalidDate: true })])(
228 `date and its timestamp have different hashes`,
229 (date) => {
230 expect(hash(date)).not.toBe(hash(date.getTime()))
231 },
232 )
233
234 fcTest.prop([fc.array(fc.integer(), { minLength: 1, maxLength: 5 })])(
235 `array and Set with same values have different hashes`,
236 (arr) => {
237 const set = new Set(arr)
238 expect(hash(arr)).not.toBe(hash(set))
239 },
240 )
241 })
242
243 describe(`nested structures`, () => {
244 fcTest.prop([
245 fc.array(fc.array(fc.integer(), { maxLength: 3 }), { maxLength: 3 }),
246 ])(`nested arrays hash consistently`, (nested) => {
247 const clone = nested.map((inner) => [...inner])
248 expect(hash(clone)).toBe(hash(nested))
249 })
250
251 fcTest.prop([
252 fc.dictionary(
253 fc.string(),
254 fc.dictionary(fc.string(), fc.integer(), { maxKeys: 3 }),
255 { maxKeys: 3 },
256 ),
257 ])(`nested objects hash consistently`, (nested) => {
258 const clone = Object.fromEntries(
259 Object.entries(nested).map(([k, v]) => [k, { ...v }]),
260 )
261 expect(hash(clone)).toBe(hash(nested))
262 })
263 })
264
265 describe(`hash produces numbers`, () => {
266 fcTest.prop([arbitraryPrimitive])(
267 `hash returns a number for primitives`,
268 (value) => {
269 expect(typeof hash(value)).toBe(`number`)
270 expect(Number.isFinite(hash(value))).toBe(true)
271 },
272 )
273
274 fcTest.prop([arbitrarySimpleObject])(
275 `hash returns a number for objects`,
276 (obj) => {
277 expect(typeof hash(obj)).toBe(`number`)
278 expect(Number.isFinite(hash(obj))).toBe(true)
279 },
280 )
281
282 fcTest.prop([arbitrarySimpleArray])(
283 `hash returns a number for arrays`,
284 (arr) => {
285 expect(typeof hash(arr)).toBe(`number`)
286 expect(Number.isFinite(hash(arr))).toBe(true)
287 },
288 )
289 })
290
291 describe(`inequality detection`, () => {
292 fcTest.prop([fc.integer(), fc.integer()])(
293 `different integers have different hashes (most of the time)`,
294 (a, b) => {
295 // Hash collisions are possible, so we only check that equal values have equal hashes
296 if (a === b) {
297 expect(hash(a)).toBe(hash(b))
298 }
299 // We don't assert different values have different hashes due to collisions
300 },
301 )
302
303 fcTest.prop([fc.string(), fc.string()])(
304 `equal strings have equal hashes`,
305 (a, b) => {
306 if (a === b) {
307 expect(hash(a)).toBe(hash(b))
308 }
309 },
310 )
311
312 fcTest.prop([
313 fc.array(fc.integer(), { minLength: 1, maxLength: 10 }),
314 fc.integer(),
315 ])(`arrays with extra element have different hashes`, (arr, extra) => {
316 const extended = [...arr, extra]
317 expect(hash(arr)).not.toBe(hash(extended))
318 })
319
320 fcTest.prop([
321 fc.dictionary(fc.string(), fc.integer(), { minKeys: 1, maxKeys: 5 }),
322 fc.string(),
323 fc.integer(),
324 ])(
325 `objects with extra property have different hashes`,
326 (obj, newKey, newValue) => {
327 if (!(newKey in obj)) {
328 const extended = { ...obj, [newKey]: newValue }
329 expect(hash(obj)).not.toBe(hash(extended))
330 }
331 },
332 )
333 })
334})