-
Notifications
You must be signed in to change notification settings - Fork 2
/
create_specs.rb
executable file
·396 lines (350 loc) · 11 KB
/
create_specs.rb
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env ruby
require 'json'
require 'yaml'
require 'fileutils'
require 'awesome_print'
require 'optparse'
require 'digest'
# Support Ruby < 2.4.0. In Ruby 2.4.0, the Fixnum and Bignum types were unified
# as Integer.
#
if not defined?(Fixnum)
class Fixnum < Integer
end
end
$default_config = [File.dirname($0), 'config.yml'].join('/')
def parse_arguments
options = YAML.load_file($default_config)
OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename($0)} [options]"
opts.on('-f', '--config_file CONFIG', 'Path to config file') do |opt|
options = YAML.load_file(opt)
end
opts.on('-c', '--catalog CATALOG', 'Path to the catalog JSON file') do |opt|
options[:catalog_file] = opt
end
opts.on('-C', '--class CLASS', 'Class (or node) name under test') do |opt|
options[:class_name] = opt
end
opts.on('-o', '--output OUTPUTFILE', 'Path to the output Rspec file') do |opt|
options[:output_file] = opt
end
opts.on('-x', '--exclude RESOURCE', [
'Resources to exclude. String or Regexp. ',
'Repeat this option to exclude multiple resources'].join) do |opt|
options[:excludes] << opt
end
opts.on('-i', '--include RESOURCE',
'Resources to include despite the exclude list.') do |opt|
options[:excludes].delete_if { |x| x == opt }
end
opts.on('-I', '--only-include RESOURCE',
'Only include these resources and exclude everything else. Regexp supported') do |opt|
options[:only_include] << opt
end
opts.on('-m', '--md5sums',
'Use md5sums instead of full file content to validate file content') do |opt|
options[:md5sums] = opt
end
opts.on('-t', '--[no-]compile-test', 'Include or exclude the catalog compilation test') do |opt|
options[:compile_test] = opt
end
opts.on('-h', '--help', 'Print this help') do
puts opts
exit 0
end
end.parse!
catalog_file = options[:catalog_file]
if catalog_file.empty?
puts 'You must specify a catalog file via -c'
exit 1
end
if ! File.exists?(catalog_file)
puts "#{catalog_file}: not found"
exit 1
end
return options
end
# Class for rewriting a catalog as a spec file.
#
# @param [Hash] options
#
# The options hash returned by parse_arguments above.
#
class SpecWriter
def initialize(options)
@options = options
@output_file = options[:output_file]
@catalog = JSON.parse(File.read(options[:catalog_file]))
convert_to_v4
@content = String.new
@class_name = class_name
@params = params
end
def write
clean_catalog
generate_content
write_to_file
end
private
# Set the class name based on the catalog content.
#
# The assumption here is that the class name that was used to compile the
# input catalog is the first resource of type Class found after the
# Class[main] in the resources array. This is true of all catalogs I have
# seen so far.
#
def class_name
return @options[:class_name] if not @options[:class_name].nil?
class_main_found = false
@catalog['resources'].each_with_index do |r,i|
if r['type'] == 'Class' and r['title'] == 'main'
class_main_found = true
next
end
if class_main_found and r['type'] == 'Class'
return r['title'].downcase
end
end
end
# Convert foo::bar to Foo::Bar.
#
def capitalize(string)
string.split(/::/).map{|x| x.capitalize}.join('::')
end
def params
begin
resources = @catalog['resources'].select do |r|
r['type'] == 'Class' and r['title'] == capitalize(@class_name)
end
return resources[0]['parameters']
rescue
end
return nil
end
# Convert a v3 catalog to v4 format. We are of course not really
# "converting" in that Puppet (I assume) could not actually use it. For our
# purposes, however, we care only about the contents of the resources array.
#
# If we find a key at @catalog['data'], then we move
# @catalog['data']['resources'] to @catalog['resources'].
#
def convert_to_v4
if @catalog.has_key?('data')
@catalog['resources'] = @catalog['data']['resources']
@catalog.delete('data')
end
end
# Any default or command-line specified exclusions are removed from the
# catalog here. Or, if only_include is specified, clean out everything other
# than what is specified there.
#
def clean_catalog
if @options[:only_include].empty?
clean_by_includes
else
clean_by_only_includes
end
end
def clean_by_only_includes
@catalog['resources'].delete_if do |resource|
typ = resource['type']
tit = resource['title']
delete_me = true
# TODO: handle invalid regexps gracefully.
#
@options[:only_include].each do |i|
type, title = i.tr('[]',' ').split(' ') if i =~ /\[/
if i =~ /^\/.*\/$/ # e.g. /File/
regexp("arg =~ #{i}", typ) and delete_me = false
elsif i =~ /.*\[\/.*\/\]/ # e.g. File[/.*/]
typ == type and regexp("arg =~ #{title}", tit) and delete_me = false
else
typ == type and tit == title and delete_me = false
end
end
delete_me
end
end
def regexp(regexp, arg)
begin
eval regexp
rescue SyntaxError
raise "Regexp in #{regexp} invalid (see your only_includes list)"
end
end
def clean_by_includes
delete_me = true
@catalog['resources'].delete_if do |resource|
delete_me = false
@options[:excludes].each do |x|
delete_me = true if resource['type'] == x
delete_me = true if
x =~ /^\/.*\/$/ and eval "resource['type'] =~ #{x}"
end
delete_me
end
end
# Generate the actual file content, using the @content instance variable.
#
def generate_content
generate_head_section
generate_setup_section
generate_params_section
generate_examples_section
generate_tail_section
end
def generate_head_section
@content = "require 'spec_helper'\n"
@content += "require 'json'\n" if not @params.nil?
@content += "require 'digest'\n" if @options[:md5sums]
@content += "\ndescribe '#{@class_name}' do\n"
end
def generate_setup_section
return if @options[:setup].empty?
setup = @options[:setup]
if setup.has_key?(:pre_condition)
@content +=
" let(:pre_condition) do\n" +
' """'"\n"
setup[:pre_condition].each do |l|
@content += " #{l}\n"
end
@content +=
' """'"\n" +
" end\n\n"
end
if setup.has_key?(:hiera_config)
@content += " let(:hiera_config){ '#{setup[:hiera_config]}' }\n\n"
end
if setup.has_key?(:facts)
@content +=
" let(:facts) do\n " +
setup[:facts].awesome_inspect(
:index => false,
:indent => -2,
:plain => true,
)
.
gsub(/\n/m, "\n ") + "\n end\n\n"
end
end
def generate_params_section
unless @params.nil?
@content += " let(:params) do\n " +
@params.awesome_inspect(
:index => false,
:indent => -2,
:plain => true,
)
.
gsub(/\n/m, "\n ") + "\n end\n\n"
end
end
def matcher(type)
"contain_#{type.downcase.gsub '::', '__'}"
end
# FIXME. This has grown too long.
#
def generate_examples_section
@catalog['resources'].each do |r|
type = r['type']
title = r['title'].gsub /'/, "\\\\'"
parameters = r['parameters']
if parameters.nil?
@content +=
" it 'is expected to contain #{type.downcase} #{title}' do\n" +
" is_expected.to #{matcher(type)}('#{title}')\n" +
" end\n\n"
next
end
@content +=
" it 'is expected to contain #{type.downcase} #{title}' do\n" +
" is_expected.to #{matcher(type)}('#{title}').with({\n"
parameters.each do |k, v|
unless type == 'File' and k == 'content'
if v.class == String
v.gsub! /'/, "\\\\'"
@content += " '#{k}' => '#{v}',\n"
elsif [Integer, TrueClass, FalseClass].include?(v.class)
@content += " '#{k}' => '#{v}',\n"
elsif [Array, Hash].include?(v.class)
@content += " '#{k}' => #{v},\n"
else
raise "Unhandled input at #{type}[#{title}] of class #{v.class}"
end
end
end
@content += " })\n end\n\n"
ensr = parameters['ensure']
cont = parameters['content']
if type == 'File' and
not cont.nil? and
(ensr == 'file' or ensr == 'present' or
not parameters.has_key?('ensure'))
mod = cont.clone
if parameters.has_key?('content')
begin
mod.gsub!('\\') { '\\\\' }
mod.gsub! /"/, '\"'
mod.gsub! /\@/, '\@'
mod.gsub! /\$;/, '\\$;'
rescue
end
end
if not cont.nil?
if @options[:md5sums]
generate_md5sum_check(title, cont)
else
generate_content_check(title, mod)
end
end
end
end
end
def generate_md5sum_check(title, content)
md5 = Digest::MD5.hexdigest(content)
@content +=
" it 'is expected to contain expected content for file " +
"#{title}' do\n" +
" content = catalogue.resource('file', '#{title}').send(:parameters)[:content]\n" +
" md5 = Digest::MD5.hexdigest(content)\n" +
" expect(md5).to eq '#{md5}'\n" +
" end\n\n"
end
def generate_content_check(title, content)
@content +=
" it 'is expected to contain expected content for file " +
"#{title}' do\n" +
" [\n\n" +
"\"#{content}\",\n\n" +
" ].map{|text| text.split(\"\\n\")}.each do |line|\n\n" +
" verify_contents(catalogue, '#{title}', line)\n" +
" end\n" +
" end\n\n"
end
def generate_tail_section
file_name = @class_name.gsub /::/, '__'
unless not @options[:compile_test]
@content +=
" it 'should write a compiled catalog' do\n" +
" is_expected.to compile.with_all_deps\n" +
" File.write(\n" +
" 'catalogs/#{file_name}.json',\n" +
" PSON.pretty_generate(catalogue)\n" +
" )\n" +
" end\n"
end
@content += "end\n"
end
def write_to_file
puts("Writing out as #{@output_file}")
FileUtils.mkdir_p 'spec/classes'
File.open(@output_file, 'w') {|f| f.write(@content)}
end
end
# Main.
if $0 == __FILE__
options = parse_arguments
SpecWriter.new(options).write
end