-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsnapshot_utils.rb
More file actions
247 lines (186 loc) · 7.7 KB
/
snapshot_utils.rb
File metadata and controls
247 lines (186 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# frozen_string_literal: true
# This is a copy of the SnapshotUtils from Herb:
# https://github.com/marcoroth/herb/blob/638e09f894e4473b661ec6d345d84f5c4d17aa74/test/snapshot_utils.rb
require "fileutils"
require "readline"
require "digest"
require "json"
require "prism"
def ask?(prompt = "")
Readline.readline("===> #{prompt}? (y/N) ", true).squeeze(" ").strip == "y"
end
module SnapshotUtils # rubocop:disable Metrics/ModuleLength
def assert_compiled_snapshot(source, handler: ReActionView::Template::Handlers::ERB, virtual_path: "test", format: :html, locals: [], options: {}) # rubocop:disable Metrics/ParameterLists
template = ActionView::Template.new(
source,
"test_template",
handler,
virtual_path: virtual_path,
format: format,
locals: locals
)
compiled_source = template.handler.call(template, source)
prism_result = Prism.parse(compiled_source)
syntax_errors = prism_result.errors.reject { |e| e.type == :invalid_yield }
assert syntax_errors.empty?, <<~MESSAGE
Compiled output is not valid Ruby:
#{syntax_errors.map { |e| " - #{e.message} (line #{e.location.start_line})" }.join("\n")}
Compiled source:
#{compiled_source}
MESSAGE
snapshot_key = JSON.generate({
source: source,
handler: handler,
virtual_path: virtual_path,
options: options,
locals: locals,
format: format,
})
assert_snapshot_matches(compiled_source, snapshot_key, mode: "compiled")
compiled_source
end
def assert_evaluated_snapshot(source, ivars: {}, options: {}, handler: ReActionView::Template::Handlers::ERB, virtual_path: "test", format: :html, locals: []) # rubocop:disable Metrics/ParameterLists,Layout/LineLength,Metrics/MethodLength
template = ActionView::Template.new(
source,
"test_template",
handler,
virtual_path: virtual_path,
format: format,
locals: locals
)
compiled_source = template.handler.call(template, source)
prism_result = Prism.parse(compiled_source)
syntax_errors = prism_result.errors.reject { |e| e.type == :invalid_yield }
assert syntax_errors.empty?, <<~MESSAGE
Compiled output is not valid Ruby:
#{syntax_errors.map { |e| " - #{e.message} (line #{e.location.start_line})" }.join("\n")}
Compiled source:
#{compiled_source}
MESSAGE
lookup_context = ActionView::LookupContext.new([])
view_context = ActionView::Base.with_empty_template_cache.new(lookup_context, {}, nil)
ivars.each do |key, value|
view_context.instance_variable_set(:"@#{key}", value)
end
result = view_context.instance_eval(compiled_source).to_s
snapshot_key = JSON.generate({
source: source,
ivars: ivars,
locals: locals,
options: options,
handler: handler,
format: format,
})
assert_snapshot_matches(result, snapshot_key, mode: "evaluated")
{ compiled: compiled_source, result: result }
end
def snapshot_changed?(content, source, options = {})
if snapshot_file(source, options).exist?
previous_content = snapshot_file(source, options).read
if previous_content == content
puts "\n\nSnapshot for '#{self.class.name} #{name}' didn't change: \n#{snapshot_file(source, options)}\n"
false
else
puts "\n\nSnapshot for '#{self.class.name} #{name}' changed:\n"
puts Difftastic::Differ.new(color: :always).diff_strings(previous_content, content)
puts "==============="
true
end
else
puts "\n\nSnapshot for '#{self.class.name} #{name}' doesn't exist at: \n#{snapshot_file(source, options)}\n"
true
end
end
def save_failures_to_snapshot(content, source, options = {})
return unless snapshot_changed?(content, source, options)
puts "\n==== [ Input for '#{self.class.name} #{name}' ] ====="
puts source
puts "\n\n"
if !ENV["FORCE_UPDATE_SNAPSHOTS"].nil? ||
ask?("Do you want to update (or create) the snapshot for '#{self.class.name} #{name}'?")
puts "\nUpdating Snapshot for '#{self.class.name} #{name}' at: \n#{snapshot_file(source, options)}\n"
FileUtils.mkdir_p(snapshot_file(source, options).dirname)
snapshot_file(source, options).write(content)
puts "\nSnapshot for '#{self.class.name} #{name}' written: \n#{snapshot_file(source, options)}\n"
else
puts "\nNot updating snapshot for '#{self.class.name} #{name}' at: \n#{snapshot_file(source, options)}.\n"
end
end
def assert_snapshot_matches(actual, source, options = {}, mode: nil)
snapshot_opts = options.dup
snapshot_opts[:mode] = mode if mode
assert snapshot_file(source, snapshot_opts).exist?,
"Expected snapshot file to exist: \n#{snapshot_file(source, snapshot_opts).to_path}"
assert_equal snapshot_file(source, snapshot_opts).read, actual
rescue Minitest::Assertion => e
save_failures_to_snapshot(actual, source, snapshot_opts) if ENV["UPDATE_SNAPSHOTS"] || ENV["FORCE_UPDATE_SNAPSHOTS"]
raise unless snapshot_file(source, snapshot_opts).exist?
if snapshot_file(source, snapshot_opts)&.read != actual
puts
divider = "=" * `tput cols`.strip.to_i
flunk(<<~MESSAGE)
\e[0m
#{divider}
#{Difftastic::Differ.new(color: :always).diff_strings(snapshot_file(source, snapshot_opts).read, actual)}
\e[31m#{divider}
Snapshots for "#{self.class.name} #{name}" didn't match.
Run the test using UPDATE_SNAPSHOTS=true to update (or create) the snapshot file for "#{self.class.name} #{name}"
UPDATE_SNAPSHOTS=true minitest #{e.location}
#{divider}
\e[0m
MESSAGE
end
end
def snapshot_file(source, options = {}) # rubocop:disable Metrics/MethodLength
test_class_name = underscore(self.class.name)
content_hash = Digest::MD5.hexdigest(source || "#{source.class}-#{source.inspect}")
test_name = sanitize_name_for_filesystem(name)
mode = options[:mode]
mode_suffix = mode ? "_#{mode}" : ""
opts_for_hash = options.except(:mode)
if opts_for_hash && !opts_for_hash.empty?
options_hash = Digest::MD5.hexdigest(opts_for_hash.inspect)
expected_snapshot_filename = "#{test_name}#{mode_suffix}_#{content_hash}-#{options_hash}.txt"
else
expected_snapshot_filename = "#{test_name}#{mode_suffix}_#{content_hash}.txt"
end
base_path = Pathname.new("test/snapshots/") / test_class_name
expected_snapshot_path = base_path / expected_snapshot_filename
return expected_snapshot_path if expected_snapshot_path.exist?
matching_md5_files = if opts_for_hash && !opts_for_hash.empty?
Dir[base_path / "*#{mode_suffix}_#{content_hash}-#{options_hash}.txt"]
else
Dir[base_path / "*#{mode_suffix}_#{content_hash}.txt"]
end
if matching_md5_files.any? && matching_md5_files.length == 1
old_file = Pathname.new(matching_md5_files.first)
return expected_snapshot_path if old_file.rename(expected_snapshot_path).zero?
return old_file
end
expected_snapshot_path
end
private
def sanitize_name_for_filesystem(name)
[
# ntfs reserved characters
# https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
["<", "lt"],
[">", "gt"],
[":", ""],
["/", "_"],
["\\", ""],
["|", ""],
["?", ""],
["*", ""],
[" ", "_"]
].inject(name) { |name, substitution| name.gsub(substitution[0], substitution[1]) }
end
def underscore(string)
string.gsub("::", "/")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.tr(" ", "_")
.downcase
end
end