Skip to content

Commit 69d57bb

Browse files
committed
Add imprecise comparison variants to SnapshotTesting extension
This adds variants of the `Snapshotting` extensions that allow for imprecise comparisons, i.e. using the `precision` and `perceptualPrecision` parameters. ## Why is this necessary? Adding precision parameters has been a highly requested feature (see #63) to work around some simulator changes introduced in iOS 13. Historically the simulator has supported CPU-based rendering, giving us very stable image representations of views that we can compare pixel-by-pixel. Unfortunately, with iOS 13, Apple changed the simulator to use exclusively GPU-based rendering, which means that the resulting snapshots may differ slightly across machines (see pointfreeco/swift-snapshot-testing#313). The negative effects of this were mitigated in SnapshotTesting by adding two precision controls to snapshot comparisons: a **perceptual precision** that controls how close in color two pixels need to be to count as unchanged (using the Lab ΔE distance between colors) and an overall **precision** that controls what portion of pixels between two images need to be the same (based on the per-pixel calculation) for the images to be considered unchanged. Setting these precisions to non-one values enables engineers to record tests on one machine and run them on another (e.g. record new reference images on their laptop and then run tests on CI) without worrying about the tests failing due to differences in GPU rendering. This is great in theory, but from our testing we've found even the lowest tolerances (near-one precision values) to consistently handle GPU differences between machine types let through a significant number of visual regressions. In other words, there is no magic set of precision values that avoids false negatives based on GPU rendering and also avoids false positives based on minor visual regressions. This is especially true for accessibility snapshots. To start, tolerances seem to be more reliable when applied to relatively small snapshot images, but accessibility snapshots tend to be fairly large since they include both the view and the legend. Additionally, the text in the legend can change meaningfully and reflect only a small number of pixel changes. For example, I ran a test of full screen snapshot on an iPhone 12 Pro with two columns of legend. Even a precision of `0.9999` (99.99%) was enough to let through a regression where one of the elements lost its `.link` trait (represented by the text "Link." appended to the element's description in the snapshot). But this high a precision _wasn't_ enough to handle the GPU rendering differences between a MacBook Pro and a Mac Mini. This is a simplified example since it only uses `precision`, not `perceptualPrecision`, but we've found many similar situations arise even with the combination. Some teams have developed infrastructure to allow snapshots to run on the same hardware consistently and have built a developer process around that infrastructure, but many others have accepted lowering precision as a necessity today. ## Why create separate "imprecise" variants? The simplest approach to adding tolerances would be adding the `precision` and `perceptualPrecision` parameters to the existing snapshot methods, however I feel adding separate methods with an "imprecise" prefix is better in the long run. The naming is motivated by the idea that **it needs to be very obvious when what you're doing might result in unexpected/undesirable behavior**. In other words, when using one of the core snapshot variants, you should have extremely high confidence that a test passing means there's no regressions. When you use an "imprecise" variant, it's up to you to set your confidence levels according to your chosen precision values. This is similar to the "unsafe" terminology around memory in the Swift API. You should generally feel very confident in the memory safety of your code, but any time you see "unsafe" it's a sign to be extra careful and not gather unwarranted confidence from the compiler. Longer term, I'm hopeful we can find alternative comparison algorithms that allow for GPU rendering differences without opening the door to regressions. We can integrate these into the core snapshot variants as long as they do not introduce opportunities for regressions, or add additional comparison variants to iterate on different approaches.
1 parent f41a0d5 commit 69d57bb

File tree

2 files changed

+192
-81
lines changed

2 files changed

+192
-81
lines changed

Sources/AccessibilitySnapshot/SnapshotTesting/SnapshotTesting+Accessibility.swift

Lines changed: 11 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//
2-
// Copyright 2020 Square Inc.
2+
// Copyright 2023 Block Inc.
33
//
44
// Licensed under the Apache License, Version 2.0 (the "License");
55
// you may not use this file except in compliance with the License.
@@ -48,50 +48,15 @@ extension Snapshotting where Value == UIView, Format == UIImage {
4848
drawHierarchyInKeyWindow: Bool = false,
4949
markerColors: [UIColor] = []
5050
) -> Snapshotting {
51-
guard isRunningInHostApplication else {
52-
fatalError("Accessibility snapshot tests cannot be run in a test target without a host application")
53-
}
54-
55-
return Snapshotting<UIView, UIImage>
56-
.image(drawHierarchyInKeyWindow: drawHierarchyInKeyWindow)
57-
.pullback { view in
58-
let containerView = AccessibilitySnapshotView(
59-
containedView: view,
60-
viewRenderingMode: drawHierarchyInKeyWindow ? .drawHierarchyInRect : .renderLayerInContext,
61-
markerColors: markerColors,
62-
activationPointDisplayMode: activationPointDisplayMode
63-
)
64-
65-
let window = UIWindow(frame: UIScreen.main.bounds)
66-
window.makeKeyAndVisible()
67-
containerView.center = window.center
68-
window.addSubview(containerView)
69-
70-
do {
71-
try containerView.parseAccessibility(useMonochromeSnapshot: useMonochromeSnapshot)
72-
} catch AccessibilitySnapshotView.Error.containedViewExceedsMaximumSize {
73-
fatalError(
74-
"""
75-
View is too large to render monochrome snapshot. Try setting useMonochromeSnapshot to false or \
76-
use a different iOS version. In particular, this is known to fail on iOS 13, but was fixed in \
77-
iOS 14.
78-
"""
79-
)
80-
} catch AccessibilitySnapshotView.Error.containedViewHasUnsupportedTransform {
81-
fatalError(
82-
"""
83-
View has an unsupported transform for the specified snapshot parameters. Try using an identity \
84-
transform or changing the view rendering mode to render the layer in the graphics context.
85-
"""
86-
)
87-
} catch {
88-
fatalError("Failed to render snapshot image")
89-
}
90-
91-
containerView.sizeToFit()
92-
93-
return containerView
94-
}
51+
// For now this calls through to the imprecise variant, but should eventually use an alternate comparison
52+
// algorithm that... TODO
53+
return .impreciseAccessibilityImage(
54+
showActivationPoints: activationPointDisplayMode,
55+
useMonochromeSnapshot: useMonochromeSnapshot,
56+
drawHierarchyInKeyWindow: drawHierarchyInKeyWindow,
57+
markerColors: markerColors,
58+
precision: 1
59+
)
9560
}
9661

9762
/// Snapshots the current view using the specified content size category to test Dynamic Type.
@@ -110,42 +75,7 @@ extension Snapshotting where Value == UIView, Format == UIImage {
11075

11176
/// Snapshots the current view simulating the way it will appear with Smart Invert Colors enabled.
11277
public static var imageWithSmartInvert: Snapshotting {
113-
func postNotification() {
114-
NotificationCenter.default.post(
115-
name: UIAccessibility.invertColorsStatusDidChangeNotification,
116-
object: nil,
117-
userInfo: nil
118-
)
119-
}
120-
121-
return Snapshotting<UIImage, UIImage>.image.pullback { view in
122-
let requiresWindow = (view.window == nil && !(view is UIWindow))
123-
124-
if requiresWindow {
125-
let window = UIApplication.shared.firstKeyWindow ?? UIWindow(frame: UIScreen.main.bounds)
126-
window.addSubview(view)
127-
}
128-
129-
view.layoutIfNeeded()
130-
131-
let statusUtility = UIAccessibilityStatusUtility()
132-
statusUtility.mockInvertColorsStatus()
133-
postNotification()
134-
135-
let renderer = UIGraphicsImageRenderer(bounds: view.bounds)
136-
let image = renderer.image { context in
137-
view.drawHierarchyWithInvertedColors(in: view.bounds, using: context)
138-
}
139-
140-
statusUtility.unmockStatuses()
141-
postNotification()
142-
143-
if requiresWindow {
144-
view.removeFromSuperview()
145-
}
146-
147-
return image
148-
}
78+
return .impreciseImageWithSmartInvert(precision: 1)
14979
}
15080

15181
// MARK: - Internal Properties
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
//
2+
// Copyright 2023 Block Inc.
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
//
8+
// http://www.apache.org/licenses/LICENSE-2.0
9+
//
10+
// Unless required by applicable law or agreed to in writing, software
11+
// distributed under the License is distributed on an "AS IS" BASIS,
12+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
// See the License for the specific language governing permissions and
14+
// limitations under the License.
15+
//
16+
17+
import SnapshotTesting
18+
import UIKit
19+
20+
#if SWIFT_PACKAGE
21+
import AccessibilitySnapshotCore
22+
import AccessibilitySnapshotCore_ObjC
23+
#endif
24+
25+
extension Snapshotting where Value == UIView, Format == UIImage {
26+
27+
/// Snapshots the current view with colored overlays of each accessibility element it contains, as well as an
28+
/// approximation of the description that VoiceOver will read for each element.
29+
///
30+
/// - Important: Using a `precision` less than 1 may result in allowing regressions through.
31+
///
32+
/// - parameter showActivationPoints: When to show indicators for elements' accessibility activation points.
33+
/// Defaults to showing activation points only when they are different than the default activation point for that
34+
/// element.
35+
/// - parameter useMonochromeSnapshot: Whether or not the snapshot of the `view` should be monochrome. Using a
36+
/// monochrome snapshot makes it more clear where the highlighted elements are, but may make it difficult to
37+
/// read certain views. Defaults to `true`.
38+
/// - parameter drawHierarchyInKeyWindow: Whether or not to draw the view hierachy in the key window, rather than
39+
/// rendering the view's layer. This enables the rendering of `UIAppearance` and `UIVisualEffect`s.
40+
/// - parameter markerColors: The array of colors which will be chosen from when creating the overlays
41+
/// - parameter precision: The portion of pixels that must match for the image to be consider "unchanged". Value
42+
/// must be in the range `[0,1]`, where `0` means no pixels must match and `1` means all pixels must match.
43+
public static func impreciseAccessibilityImage(
44+
showActivationPoints activationPointDisplayMode: ActivationPointDisplayMode = .whenOverridden,
45+
useMonochromeSnapshot: Bool = true,
46+
drawHierarchyInKeyWindow: Bool = false,
47+
markerColors: [UIColor] = [],
48+
precision: Float
49+
) -> Snapshotting {
50+
guard isRunningInHostApplication else {
51+
fatalError("Accessibility snapshot tests cannot be run in a test target without a host application")
52+
}
53+
54+
return Snapshotting<UIView, UIImage>
55+
.image(drawHierarchyInKeyWindow: drawHierarchyInKeyWindow, precision: precision)
56+
.pullback { view in
57+
let containerView = AccessibilitySnapshotView(
58+
containedView: view,
59+
viewRenderingMode: drawHierarchyInKeyWindow ? .drawHierarchyInRect : .renderLayerInContext,
60+
markerColors: markerColors,
61+
activationPointDisplayMode: activationPointDisplayMode
62+
)
63+
64+
let window = UIWindow(frame: UIScreen.main.bounds)
65+
window.makeKeyAndVisible()
66+
containerView.center = window.center
67+
window.addSubview(containerView)
68+
69+
do {
70+
try containerView.parseAccessibility(useMonochromeSnapshot: useMonochromeSnapshot)
71+
} catch AccessibilitySnapshotView.Error.containedViewExceedsMaximumSize {
72+
fatalError(
73+
"""
74+
View is too large to render monochrome snapshot. Try setting useMonochromeSnapshot to false or \
75+
use a different iOS version. In particular, this is known to fail on iOS 13, but was fixed in \
76+
iOS 14.
77+
"""
78+
)
79+
} catch AccessibilitySnapshotView.Error.containedViewHasUnsupportedTransform {
80+
fatalError(
81+
"""
82+
View has an unsupported transform for the specified snapshot parameters. Try using an identity \
83+
transform or changing the view rendering mode to render the layer in the graphics context.
84+
"""
85+
)
86+
} catch {
87+
fatalError("Failed to render snapshot image")
88+
}
89+
90+
containerView.sizeToFit()
91+
92+
return containerView
93+
}
94+
}
95+
96+
/// Snapshots the current view simulating the way it will appear with Smart Invert Colors enabled.
97+
public static func impreciseImageWithSmartInvert(precision: Float) -> Snapshotting {
98+
func postNotification() {
99+
NotificationCenter.default.post(
100+
name: UIAccessibility.invertColorsStatusDidChangeNotification,
101+
object: nil,
102+
userInfo: nil
103+
)
104+
}
105+
106+
return Snapshotting<UIImage, UIImage>.image.pullback { view in
107+
let requiresWindow = (view.window == nil && !(view is UIWindow))
108+
109+
if requiresWindow {
110+
let window = UIApplication.shared.firstKeyWindow ?? UIWindow(frame: UIScreen.main.bounds)
111+
window.addSubview(view)
112+
}
113+
114+
view.layoutIfNeeded()
115+
116+
let statusUtility = UIAccessibilityStatusUtility()
117+
statusUtility.mockInvertColorsStatus()
118+
postNotification()
119+
120+
let renderer = UIGraphicsImageRenderer(bounds: view.bounds)
121+
let image = renderer.image { context in
122+
view.drawHierarchyWithInvertedColors(in: view.bounds, using: context)
123+
}
124+
125+
statusUtility.unmockStatuses()
126+
postNotification()
127+
128+
if requiresWindow {
129+
view.removeFromSuperview()
130+
}
131+
132+
return image
133+
}
134+
}
135+
136+
}
137+
138+
extension Snapshotting where Value == UIViewController, Format == UIImage {
139+
140+
/// Snapshots the current view with colored overlays of each accessibility element it contains, as well as an
141+
/// approximation of the description that VoiceOver will read for each element.
142+
///
143+
/// - parameter showActivationPoints: When to show indicators for elements' accessibility activation points.
144+
/// Defaults to showing activation points only when they are different than the default activation point for that
145+
/// element.
146+
/// - parameter useMonochromeSnapshot: Whether or not the snapshot of the `view` should be monochrome. Using a
147+
/// monochrome snapshot makes it more clear where the highlighted elements are, but may make it difficult to
148+
/// read certain views. Defaults to `true`.
149+
/// - parameter drawHierarchyInKeyWindow: Whether or not to draw the view hierachy in the key window, rather than
150+
/// rendering the view's layer. This enables the rendering of `UIAppearance` and `UIVisualEffect`s.
151+
/// - parameter markerColors: The array of colors which will be chosen from when creating the overlays
152+
public static func impreciseAccessibilityImage(
153+
showActivationPoints activationPointDisplayMode: ActivationPointDisplayMode = .whenOverridden,
154+
useMonochromeSnapshot: Bool = true,
155+
drawHierarchyInKeyWindow: Bool = false,
156+
markerColors: [UIColor] = [],
157+
precision: Float
158+
) -> Snapshotting {
159+
return Snapshotting<UIView, UIImage>
160+
.impreciseAccessibilityImage(
161+
showActivationPoints: activationPointDisplayMode,
162+
useMonochromeSnapshot: useMonochromeSnapshot,
163+
drawHierarchyInKeyWindow: drawHierarchyInKeyWindow,
164+
markerColors: markerColors,
165+
precision: precision
166+
)
167+
.pullback { viewController in
168+
viewController.view
169+
}
170+
}
171+
172+
/// Snapshots the current view simulating the way it will appear with Smart Invert Colors enabled.
173+
public static func impreciseImageWithSmartInvert(precision: Float) -> Snapshotting {
174+
return Snapshotting<UIView, UIImage>
175+
.impreciseImageWithSmartInvert(precision: precision)
176+
.pullback { viewController in
177+
viewController.view
178+
}
179+
}
180+
181+
}

0 commit comments

Comments
 (0)