MCPcopy Create free account
hub / github.com/imgproxy/imgproxy / ImageMatches

Method ImageMatches

testutil/image_hash_cache_matcher.go:51–106  ·  view source on GitHub ↗

ImageMatches is a testing helper, which accepts image as reader, calculates hash and compares it with a hash saved to testdata/test-hashes folder.

(t *testing.T, img io.Reader, key string, maxDistance float32)

Source from the content-addressed store, hash-verified

49// ImageMatches is a testing helper, which accepts image as reader, calculates
50// hash and compares it with a hash saved to testdata/test-hashes folder.
51func (m *ImageHashCacheMatcher) ImageMatches(t *testing.T, img io.Reader, key string, maxDistance float32) {
52 t.Helper()
53
54 // Read image in memory
55 buf, err := io.ReadAll(img)
56 require.NoError(t, err)
57
58 // Save tmp image if requested
59 m.saveTmpImage(t, key, buf)
60
61 // Calculate hash using shared helper
62 sourceHash := m.calculateHash(t, buf)
63
64 // Calculate image hash path (create folder if missing)
65 hashPath := m.makeTargetPath(t, m.hashesPath, t.Name(), key, "hash")
66
67 // Try to read or create the hash file
68 f, err := os.Open(hashPath)
69 if os.IsNotExist(err) {
70 // If the hash file does not exist, and we are not allowed to create it, fail
71 if !m.createMissingHashes {
72 require.NoError(
73 t, err,
74 "failed to read target hash from %s, use %s=true to create it, %s=/some/path to check resulting images",
75 hashPath,
76 createMissingHashesEnv,
77 saveTmpImagesPathEnv,
78 )
79 }
80
81 // Create missing hash file
82 h, hashErr := os.Create(hashPath)
83 require.NoError(t, hashErr, "failed to create target hash file %s", hashPath)
84 defer h.Close()
85
86 // Dump calculated source hash to this hash file
87 hashErr = sourceHash.Dump(h)
88 require.NoError(t, hashErr, "failed to write target hash to %s", hashPath)
89
90 t.Logf("Created missing hash in %s", hashPath)
91 return
92 }
93
94 // Otherwise, if there is no error or error is something else
95 require.NoError(t, err)
96
97 // Load image hash from hash file
98 targetHash, err := LoadImageHash(f)
99 require.NoError(t, err, "failed to load target hash from %s", hashPath)
100
101 // Ensure distance is OK
102 distance, err := sourceHash.Distance(targetHash)
103 require.NoError(t, err, "failed to calculate hash distance for %s", key)
104
105 require.LessOrEqual(t, distance, maxDistance, "image hashes are too different for %s: distance %f", key, distance)
106}
107
108// calculateHash converts image data to RGBA using VIPS and calculates hash

Callers 3

testFormatMethod · 0.80
processImageAndCheckMethod · 0.80
processImgMethod · 0.80

Calls 7

saveTmpImageMethod · 0.95
calculateHashMethod · 0.95
makeTargetPathMethod · 0.95
LoadImageHashFunction · 0.85
DistanceMethod · 0.80
CloseMethod · 0.65
DumpMethod · 0.45

Tested by 3

testFormatMethod · 0.64
processImageAndCheckMethod · 0.64
processImgMethod · 0.64