/
spec_helper.rb
502 lines (401 loc) · 15 KB
/
spec_helper.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'spec/autorun'
require 'spec/rails'
# Stolen shamelessly from DataBaseCleaner gem - modified to not kill the main Webiva tables
# but only the domain model tables
class WebivaCleaner
def start
if DomainModel.connection.respond_to?(:increment_open_transactions)
DomainModel.connection.increment_open_transactions
else
DomainModel.__send__(:increment_open_transactions)
end
DomainModel.connection.begin_db_transaction
end
def clean
DomainModel.connection.rollback_db_transaction
if DomainModel.connection.respond_to?(:decrement_open_transactions)
DomainModel.connection.decrement_open_transactions
else
DomainModel.__send__(:decrement_open_transactions)
end
end
def connection
DomainModel.connection
end
def tables_to_truncate
connection.tables - %w[component_schemas, schema_migrations]
end
def truncate_table(table_name)
connection.execute("TRUNCATE TABLE #{connection.quote_table_name(table_name)};")
end
def reset
connection.disable_referential_integrity do
tables_to_truncate.each do |table_name|
truncate_table table_name
end
end
end
def self.cleaner
@@cleaner ||= WebivaCleaner.new
end
end
Spec::Runner.configure do |config|
# If you're not using ActiveRecord you should remove these
# lines, delete config/database.yml and disable :active_record
# in your config/boot.rb
config.use_transactional_fixtures = false # Modified for 2.3.2
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
config.before(:suite) do
WebivaCleaner.cleaner.reset
end
config.before(:each) do
UserClass.create_built_in_classes
SiteVersion.default
end
end
# http://gensym.org/2007/10/18/rspec-on-rails-tip-weaning-myself-off-of-fixtures
# Wean ourselves off of fixtures
# Call this within the description (e.g., after the describe block) to remove everything from the associated class or table
# Changed so that we're modifying DomainModel tables
def reset_domain_tables(*tables)
callback = lambda do
DomainModel.connection.reconnect! if !DomainModel.connection.active?
tables.each do |table|
DomainModel.connection.execute("TRUNCATE #{table.is_a?(Symbol) ? table.to_s.tableize : table}") unless %w(component_schemas).include?(table)
end
end
before(:each,&callback)
after(:each,&callback)
end
def transaction_reset
before(:each) {
DomainFile.root_folder
UserClass.create_built_in_classes
SiteVersion.default
WebivaCleaner.cleaner.start }
after(:each) { WebivaCleaner.cleaner.clean }
end
# Activate a module in a test (force the activation) so you can use handlers etc.
def test_activate_module(name,options = nil)
mod = SiteModule.activate_module(Domain.find(DomainModel.active_domain_id),name.to_s,:force => true)
mod.update_attributes(:status => 'active')
if options
mod_options = "#{name.to_s.classify}::AdminController".constantize.module_options(options)
Configuration.set_config_model(mod_options)
end
end
def renderer_builder(name,&block)
parts = name.split("/")
define_method("#{parts[-1]}_renderer_helper") do |opts,conns|
if block
opt_opts = yield
opts = opt_opts.merge(opts)
end
build_renderer("/#{parts[1]}",name,opts,conns)
end
class_eval <<-METHOD
def #{parts[-1]}_renderer(opts={},conns={})
#{parts[-1]}_renderer_helper(opts,conns)
end
METHOD
end
def add_factory_girl_path(dir)
if !Factory.definition_file_paths.include?(dir)
Factory.definition_file_paths << dir
Factory.definition_file_paths.uniq!
Factory.find_definitions
end
end
ActiveSupport::TestCase.fixture_path = RAILS_ROOT + '/spec/fixtures/'
# Custom Matchers
class HandleActiveTableMatcher
def initialize(table_name,&block)
@table_name = table_name
@block = block
@error_msgs = []
end
def matches?(controller,&block)
@block ||= block # Could be passed in via the match func instead of initialization
@controller = controller
@cols = controller.send("#{@table_name}_columns",{})
# Go through each column
@cols.each do |header|
# Try a search
if header.is_searchable?
args = HashWithIndifferentAccess.new({ @table_name => { header.field_hash => header.dummy_search, :display => { header.field_hash => 1 } } })
begin
@block.call(args)
rescue Mysql::Error, ActiveRecord::StatementInvalid => e
@error_msgs << "Error searching on '#{header.field}' (#{e.to_s})"
end
end
if header.is_orderable?
begin
@block.call(args)
rescue Mysql::Error, ActiveRecord::StatementInvalid => e
@error_msgs << "Error ordering on '#{header.field}' (#{e.to_s})"
end
end
end
@error_msgs.length == 0
end
def description
"handle active table #{@table_name}"
end
def failure_message
" active table #{@table_name} did not operate properly: " + @error_msgs.join(",")
end
end
def handle_active_table(table_name,&block)
HandleActiveTableMatcher.new(table_name,&block)
end
def activate_module(name,options={})
mod = SiteModule.activate_module(Domain.find(DomainModel.active_domain_id),'mailing', :force => true)
mod.update_attributes(:status => 'active', :options => options.to_hash)
end
module RspecRendererExtensions
def renderer_feature_data=(val); @renderer_feature_data = val; end
def renderer_feature_data; @renderer_feature_data; end
def should_render_feature(feature_name)
renderer = self
expt = renderer.should_receive("#{feature_name}_feature") do |*feature_data|
if feature_data.length == 0
renderer.renderer_feature_data = renderer.instance_variable_hash
else
renderer.renderer_feature_data = feature_data[0]
end
"WEBIVA FEATURE OUTPUT"
end
expt
end
end
module Spec
module Rails
module Example
class ModelExampleGroup
def mock_editor(email = 'test@webiva.com',permissions = nil)
# get me a client user to ignore any permission issues
@myself = EndUser.push_target('test@webiva.com')
if permissions.nil?
@myself.user_class = UserClass.client_user_class
@myself.client_user_id = 1
@myself.save
else
@myself.user_class = UserClass.domain_user_class
@myself.save
permissions = [ permissions ] unless permissions.is_a?(Array)
permissions.map! { |perm| perm.to_sym }
permissions.each do |perm|
@myself.user_class.has_role(perm)
end
end
@myself
end
def mock_user(email = 'test@webiva.com')
# get me a client user to ignore any permission issues
@myself = EndUser.push_target(email)
end
end
class ControllerExampleGroup < FunctionalExampleGroup
def mock_editor(email = 'test@webiva.com',permissions = nil)
# get me a client user to ignore any permission issues
@myself = EndUser.push_target('test@webiva.com')
if permissions.nil?
@myself.user_class = UserClass.client_user_class
@myself.client_user_id = 1
@myself.save
else
@myself.user_class = UserClass.domain_user_class
@myself.save
permissions = [ permissions ] unless permissions.is_a?(Array)
permissions.map! { |perm| perm.to_sym }
permissions.each do |perm|
@myself.user_class.has_role(perm)
end
end
controller.should_receive('myself').at_least(:once).and_return(@myself)
end
def mock_user(email = 'test@webiva.com')
# get me a client user to ignore any permission issues
@myself = EndUser.push_target(email)
controller.should_receive('myself').at_least(:once).and_return(@myself)
@myself
end
def paragraph_controller_helper(site_node_path,display_module_type,data={},extra_attributes = {})
display_parts = display_module_type.split("/")
@site_version ||= SiteVersion.new :name => 'Test', :default_version => true
@root_node ||= SiteNode.create :site_version => @site_version, :node_type => 'R', :node_path => '/'
@site_node = @root_node.add_subpage(site_node_path.sub('/', ''))
@revision = PageRevision.create :revision_container => @site_node, :language => 'en', :active => true, :created_by => @myself, :updated_by => @myself
@paragraph = PageParagraph.create :display_module => display_parts[0..-2].join("/"), :display_type => display_parts[-1], :page_revision_id => @revision.id, :data => data, :attributes => extra_attributes
end
def paragraph_controller_path
['page', @site_node.id, @revision.id, @paragraph.id, 0]
end
def paragraph_controller_get(page, args = {})
args[:path] = paragraph_controller_path
get page, args
end
def paragraph_controller_post(page, args = {})
args[:path] = paragraph_controller_path
post page, args
end
def display_all_editors_for(&block)
controller.class.get_editor_for.each do |editor|
paragraph_controller_helper("/#{editor[0]}", "/#{controller.class.to_s.underscore}/#{editor[0]}")
output = paragraph_controller_get editor[0]
yield editor[0], output
end
end
def build_renderer_helper(user_class,site_node_path,display_module_type,data={},page_connections={},extra_attributes = {})
display_parts = display_module_type.split("/")
para = PageParagraph.create(:display_type => display_parts[-1], :display_module => display_parts[0..-2].join("/"),:data=>data)
para.attributes = extra_attributes
para.direct_set_page_connections(page_connections)
rnd = para.renderer.new(user_class,controller,para,SiteNode.new(:node_path => site_node_path,:site_version_id => SiteVersion.default.id),PageRevision.new,{})
rnd.extend(RspecRendererExtensions)
rnd
end
def build_renderer(site_node_path,display_module_type,data={},page_connections={},extra_attributes={})
build_renderer_helper(UserClass.default_user_class,site_node_path,display_module_type,data,page_connections,extra_attributes)
end
def build_anonymous_renderer(site_node_path,display_module_type,data={},page_connections={},extra_attributes={})
build_renderer_helper(UserClass.anonymous_user_class,site_node_path,display_module_type,data,page_connections,extra_attributes)
end
def renderer_get(rnd,args = {})
controller.set_test_renderer(rnd)
get :renderer_test, args
end
def renderer_post(rnd,args = {})
controller.set_test_renderer(rnd)
post :renderer_test, args
end
end
class ViewExampleGroup < FunctionalExampleGroup
def build_feature(feature_class,code=nil)
if code
site_feature = mock_model(SiteFeature,:body => code,:body_html => code,:feature_type => :any,:options => {} )
paragraph = mock_model(PageParagraph,:site_feature => site_feature, :content_publication => nil)
else
paragraph = mock_model(PageParagraph,:site_feature => nil, :content_publication => nil)
end
renderer = mock_model(ParagraphRenderer,:get_handler_info => [],:protect_against_forgery? => false)
feature_class.classify.constantize.new(paragraph,renderer)
end
end
end
end
end
class ParagraphOutputMatcher
def initialize(output_type,args)
@output_type = output_type
@args = args
@output_args = nil
end
def matches?(renderer)
output = renderer.output
if @output_type == 'render_feature'
renderer.renderer_feature_data == @args
elsif @output_type == 'assign_feature_data' # break this out into a separate matcher
if renderer.renderer_feature_data && renderer.renderer_feature_data[@args[0].to_sym] == @args[1]
true
else
@output_type_error = "mis-assigned :#{@args[0]}"
@output_args = renderer.renderer_feature_data ? renderer.renderer_feature_data[@args[0].to_sym] : nil
@args = @args[1]
false
end
else
if output.is_a?(ParagraphRenderer::ParagraphOutput)
@output_args = output.render_args.clone
@output_args.delete(:locals) if !@args[:locals]
if @output_type == 'render'
@output_args == @args
else
@output_type_error = "Renderered"
false
end
elsif output.is_a?(ParagraphRenderer::ParagraphRedirect)
@output_args = output.args
if @output_type == 'redirect'
@output_args == @args
else
@output_type_error = "Redirected"
false
end
else
@output_type_error = "Failed to output anything"
false
end
end
end
def description
"Should #{@type.humanize}"
end
def failure_message
msg = "Does not match expected renderer output:\n"
if @output_type_error
msg << "Expected paragraph to #{@output_type.humanize} instead it #{@output_type_error}\n"
end
msg << "Expected:"
PP.singleline_pp(@args,msg)
msg << "\nReceived:"
PP.singleline_pp(@output_args,msg)
msg
end
end
def render_feature_data(args)
ParagraphOutputMatcher.new('render_feature',args)
end
def render_paragraph(args)
ParagraphOutputMatcher.new('render',args)
end
def redirect_paragraph(args)
ParagraphOutputMatcher.new('redirect',args)
end
def assign_to_feature(elem,data)
ParagraphOutputMatcher.new('assign_feature_data',[elem,data])
end
# Custom Matchers
class ModelInjectionAttackMatcher
def initialize(model,test_string="<script>test();</script>",&block)
@model = model
@test_string = test_string
@block = block
@error_msgs = []
end
def matches?(feature,&block)
@block ||= block # Could be passed in via the match func instead of initialization
@feature = feature
@columns = @model.class.columns
# Go through each column
@columns.each do |col|
if [:string,:text].include?(col.type)
@model.send("#{col.name}=",@test_string)
end
end
@output = @block.call(@feature,@model)
!@output.include?(@test_string)
end
def description
"check for escaping of '#{@test_string}' in argument attributes"
end
def failure_message
msg = " '#{@test_string}' was successfully injected into the output: "
PP.pp(@output.to_s,msg)
msg
end
end
def prevent_feature_injection(model,&block)
ModelInjectionAttackMatcher.new(model,&block)
end
# No Longer available in ModelTests
def fixture_file_upload(path, mime_type = nil, binary = false)
fixture_path = ActionController::TestCase.send(:fixture_path) if ActionController::TestCase.respond_to?(:fixture_path)
ActionController::TestUploadedFile.new("#{fixture_path}#{path}", mime_type, binary)
end