-
Notifications
You must be signed in to change notification settings - Fork 433
/
test_helper.rb
561 lines (465 loc) · 16.3 KB
/
test_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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
ENV['origin_RAILS_ENV'] = ENV['RAILS_ENV']
ENV['RAILS_ENV'] = 'test'
require 'simplecov'
require 'coveralls'
require "minitest/reporters"
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
if ENV['DO_COVERAGE']
Coveralls.wear_merged!('rails')
SimpleCov.start 'rails' do
add_filter '/app/indices/'
add_filter '/app/models/user_ldap_strategy.rb'
merge_timeout 3600
formatter Coveralls::SimpleCov::Formatter
end
SimpleCov.at_exit do
puts "Coverage done"
SimpleCov.result.format!
end
end
require File.expand_path('../../config/environment', __FILE__)
require_relative 'test_consistency_helper'
require 'rails/test_help'
require 'minitest/unit'
require 'webmock/minitest'
require 'opensuse/backend'
require_relative 'activexml_matcher'
require_relative '../lib/obsapi/test_sphinx'
require 'test/unit/assertions'
require 'mocha/setup'
require 'capybara/poltergeist'
require 'capybara/rails'
Capybara.default_wait_time = 6
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, debug: false, timeout: 30)
end
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app, headers: {'HTTP_ACCEPT' => 'text/html'})
end
Capybara.javascript_driver = :poltergeist
WebMock.disable_net_connect!(allow_localhost: true)
unless File.exist? '/proc'
print 'ERROR: proc file system not mounted, aborting'
exit 1
end
unless File.exist? '/dev/fd'
print 'ERROR: /dev/fd does not exist, aborting'
exit 1
end
# uncomment to enable tests which currently are known to fail, but where either the test
# or the code has to be fixed
#$ENABLE_BROKEN_TEST=true
def backend_config
backend_dir_suffix = ""
if ENV['origin_RAILS_ENV'] == 'development'
backend_dir_suffix = "_development"
end
"#{Rails.root}/tmp/backend_config#{backend_dir_suffix}"
end
def backend_data
backend_dir_suffix = ""
if ENV['origin_RAILS_ENV'] == 'development'
backend_dir_suffix = "_development"
end
"#{Rails.root}/tmp/backend_data#{backend_dir_suffix}"
end
def inject_build_job(project, package, repo, arch, extrabinary = nil)
job=IO.popen("find #{backend_data}/jobs/#{arch}/ -name #{project}::#{repo}::#{package}-*")
jobfile=job.readlines.first
return unless jobfile
jobfile.chomp!
jobid=''
IO.popen("md5sum #{jobfile}|cut -d' ' -f 1") do |io|
jobid = io.readlines.first.chomp
end
data = REXML::Document.new(File.new(jobfile))
verifymd5 = data.elements['/buildinfo/verifymd5'].text
f = File.open("#{jobfile}:status", 'w')
output = '<jobstatus code="building">' \
"<jobid>#{jobid}</jobid>" \
'<starttime>0</starttime>' \
'<workerid>simulated</workerid>' \
"<hostarch>#{arch}</hostarch>" \
'</jobstatus>'
f.write(output)
f.close
extrabinary=" -o -name #{extrabinary}" if extrabinary
# rubocop:disable Metrics/LineLength
system("cd #{Rails.root}/test/fixtures/backend/binary/; exec find . -name '*#{arch}.rpm' -o -name '*src.rpm' -o -name logfile -o -name _statistics #{extrabinary} | cpio -H newc -o 2>/dev/null | curl -s -X POST -T - 'http://localhost:3201/putjob?arch=#{arch}&code=success&job=#{jobfile.gsub(/.*\//, '')}&jobid=#{jobid}' > /dev/null")
# rubocop:enable Metrics/LineLength
system("echo \"#{verifymd5} #{package}\" > #{jobfile}:dir/meta")
end
module Minitest
def self.__run reporter, options
# there is no way to avoid the randomization of used suites, so we overload this method.
suites = Runnable.runnables #.shuffle <- disabled here
parallel, serial = suites.partition { |s| s.test_order == :parallel }
serial.map { |suite| suite.run reporter, options } +
parallel.map { |suite| suite.run reporter, options }
end
# we should fix this first ... unfortunatly there seems to be no way to repeat the last order
# to find out what went wrong and to validate it :(
def self.sort_order
:sorted
end
end
class ActionDispatch::IntegrationTest
# usually we do only test at the end of all tests to not slow down too much.
# but for debugging or for deep testing the check can be run after each test case
def after_teardown
super
if false
begin
# something else is going wrong in some random test and you do not know where?
# add the specific test for it here:
#login_king
#get "/source/home:Iggy/TestPack/_link"
#assert_response 404
# simple test that the objects itself or the same in backend and api.
# it does not check the content (eg. repository list in project meta)
compare_project_and_package_lists
rescue MiniTest::Assertion => e
puts "Backend became out of sync in #{self.name}"
puts e.inspect
exit
end
end
end
end
module ActionDispatch
module Integration
class Session
def add_auth(headers)
headers = Hash.new if headers.nil?
if !headers.has_key? 'HTTP_AUTHORIZATION' and IntegrationTest.basic_auth
headers['HTTP_AUTHORIZATION'] = IntegrationTest.basic_auth
end
return headers
end
alias_method :real_process, :process
def process(method, path, parameters, rack_env)
CONFIG['global_write_through'] = true
self.accept = 'text/xml,application/xml'
real_process(method, path, parameters, add_auth(rack_env))
end
def raw_post(path, data, parameters = nil, rack_env = nil)
rack_env ||= Hash.new
rack_env['CONTENT_TYPE'] ||= 'application/octet-stream'
rack_env['CONTENT_LENGTH'] = data.length
rack_env['RAW_POST_DATA'] = data
process(:post, path, parameters, add_auth(rack_env))
end
def raw_put(path, data, parameters = nil, rack_env = nil)
rack_env ||= Hash.new
rack_env['CONTENT_TYPE'] ||= 'application/octet-stream'
rack_env['CONTENT_LENGTH'] = data.length
rack_env['RAW_POST_DATA'] = data
process(:put, path, parameters, add_auth(rack_env))
end
end
end
end
module Webui
class IntegrationTest < ActionDispatch::IntegrationTest
# Make the Capybara DSL available
include Capybara::DSL
@@frontend = nil
def self.start_test_api
return if @@frontend
if ENV['API_STARTED']
@@frontend = :dont
return
end
# avoid a race
Suse::Backend.start_test_backend
@@frontend = IO.popen(Rails.root.join('script', 'start_test_api').to_s)
puts "Starting test API with pid: #{@@frontend.pid}"
lines = []
while true
line = @@frontend.gets
unless line
puts lines.join()
raise RuntimeError.new('Frontend died')
end
break if line =~ /Test API ready/
lines << line
end
puts "Test API up and running with pid: #{@@frontend.pid}"
at_exit do
puts "Killing test API with pid: #{@@frontend.pid}"
Process.kill 'INT', @@frontend.pid
begin
Process.wait @@frontend.pid
rescue Errno::ECHILD
# already gone
end
@@frontend = nil
end
end
def login_user(user, password, opts = {})
# no idea why calling it twice would help
WebMock.disable_net_connect!(allow_localhost: true)
visit user_login_path
fill_in 'Username', with: user
fill_in 'Password', with: password
click_button 'Log In'
visit opts[:to] if opts[:to]
@current_user = user
if opts[:do_assert] != false
assert_match %r{^#{user}( |$)}, find('#link-to-user-home').text
end
# login into API to ease test cases
prepare_request_with_user(user, password)
end
# will provide a user without special permissions
def login_tom(opts = {})
login_user('tom', 'thunder', opts)
end
def login_Iggy(opts = {})
login_user('Iggy', 'asdfasdf', opts)
end
def login_adrian(opts = {})
login_user('adrian', 'so_alone', opts)
end
def login_king(opts = {})
login_user('king', 'sunflower', opts.merge(do_assert: false))
end
def login_fred(opts = {})
login_user('fred', 'geröllheimer', opts)
end
def login_dmayr(opts = {})
login_user 'dmayr', '123456', opts
end
def logout
@current_user = nil
ll = page.first('#logout-link')
ll.click if ll
end
def current_user
@current_user
end
self.use_transactional_fixtures = true
fixtures :all
setup do
Capybara.current_driver = :rack_test
# crude work around - one day I will dig into why this is necessary
Minitest::Spec.new('MINE') unless Minitest::Spec.current
self.class.start_test_api
#Capybara.current_driver = Capybara.javascript_driver
@starttime = Time.now
WebMock.disable_net_connect!(allow_localhost: true)
CONFIG['global_write_through'] = true
end
def use_js
Capybara.current_driver = Capybara.javascript_driver
end
teardown do
dirpath = Rails.root.join('tmp', 'capybara')
htmlpath = dirpath.join(self.name + '.html')
if !passed?
Dir.mkdir(dirpath) unless Dir.exist? dirpath
save_page(htmlpath)
elsif File.exist?(htmlpath)
File.unlink(htmlpath)
end
Capybara.reset!
Rails.cache.clear
WebMock.reset!
ActiveRecord::Base.clear_active_connections!
unless run_in_transaction?
DatabaseCleaner.clean_with :deletion
end
#puts "#{self.__name__} took #{Time.now - @starttime}"
end
def fill_autocomplete(field, options = {})
fill_in field, with: options[:with]
page.execute_script "$('##{field}').trigger('focus')"
page.execute_script "$('##{field}').trigger('keydown')"
page.must_have_selector('ul.ui-autocomplete li.ui-menu-item a')
ret = []
all('ul.ui-autocomplete li.ui-menu-item a').each do |l|
ret << l.text
end
ret.must_include options[:select]
page.execute_script "select_from_autocomplete('#{options[:select]}')"
ret
end
# ============================================================================
# Checks if a flash message is displayed on screen
#
def flash_message_appeared?
flash_message_type != nil
end
# ============================================================================
# Returns the text of the flash message currenlty on screen
# @note Doesn't fail if no message is on screen. Returns empty string instead.
# @return [String]
#
def flash_message
results = all(:css, 'div#flash-messages p')
if results.empty?
return 'none'
end
if results.count > 1
texts = results.map { |r| r.text }
raise "One flash expected, but we had #{texts.inspect}"
end
results.first.text
end
# ============================================================================
# Returns the text of the flash messages currenlty on screen
# @note Doesn't fail if no message is on screen. Returns empty list instead.
# @return [array]
#
def flash_messages
results = all(:css, 'div#flash-messages p')
ret = []
results.each { |r| ret << r.text }
return ret
end
# ============================================================================
# Returns the type of the flash message currenlty on screen
# @note Does not fail if no message is on screen! Returns nil instead!
# @return [:info, :alert]
#
def flash_message_type
result = first(:css, 'div#flash-messages span')
return nil unless result
return :info if result['class'].include? 'info'
return :alert if result['class'].include? 'alert'
end
# helper function for teardown
def delete_package project, package
visit package_show_path(package: package, project: project)
find(:id, 'delete-package').click
find(:id, 'del_dialog').must_have_text 'Delete Confirmation'
find_button('Ok').click
find('#flash-messages').must_have_text "Package was successfully removed."
end
end
end
module ActionDispatch
class IntegrationTest
def teardown
Rails.cache.clear
reset_auth
WebMock.reset!
end
@@auth = nil
def reset_auth
User.current = nil
@@auth = nil
end
def self.basic_auth
return @@auth
end
def basic_auth
return @@auth
end
def prepare_request_with_user(user, passwd)
re = 'Basic ' + Base64.encode64(user + ':' + passwd)
@@auth = re
end
# will provide a user without special permissions
def prepare_request_valid_user
prepare_request_with_user 'tom', 'thunder'
end
def prepare_request_invalid_user
prepare_request_with_user 'tom123', 'thunder123'
end
def load_fixture(path)
File.open(File.join(ActionController::TestCase.fixture_path, path)).read()
end
def load_backend_file(path)
load_fixture("backend/#{path}")
end
def assert_xml_tag(conds)
node = ActiveXML::Node.new(@response.body)
ret = node.find_matching(NodeMatcher::Conditions.new(conds))
raise MiniTest::Assertion.new("expected tag, but no tag found matching #{conds.inspect} in:\n#{node.dump_xml}") unless ret
end
def assert_no_xml_tag(conds)
node = ActiveXML::Node.new(@response.body)
ret = node.find_matching(NodeMatcher::Conditions.new(conds))
raise MiniTest::Assertion.new("expected no tag, but found tag matching #{conds.inspect} in:\n#{node.dump_xml}") if ret
end
# useful to fix our test cases
def url_for(hash)
raise ArgumentError.new('we need a hash here') unless hash.kind_of? Hash
raise ArgumentError.new('we need a :controller') unless hash.has_key?(:controller)
raise ArgumentError.new('we need a :action') unless hash.has_key?(:action)
super(hash)
end
def run_dispatcher
Rails.logger.debug 'run dispatcher'
perlopts="-I#{Rails.root}/../backend -I#{Rails.root}/../backend/build"
IO.popen("cd #{backend_config}; exec perl #{perlopts} ./bs_dispatch --test-mode") do |io|
# just for waiting until dispatcher finishes
io.each { |line| Rails.logger.debug("dispatcher: #{line.strip.chomp}") unless line.blank? }
end
end
def run_publisher
Rails.logger.debug 'run publisher'
perlopts="-I#{Rails.root}/../backend -I#{Rails.root}/../backend/build"
IO.popen("cd #{backend_config}; exec perl #{perlopts} ./bs_publish --testmode") do |io|
# just for waiting until publisher finishes
io.each { |line| Rails.logger.debug("publisher: #{line.strip.chomp}") unless line.blank? }
end
end
def wait_for_scheduler_start
Suse::Backend.wait_for_scheduler_start
end
def run_scheduler(arch)
Rails.logger.debug "RUN_SCHEDULER #{arch}"
perlopts="-I#{Rails.root}/../backend -I#{Rails.root}/../backend/build"
IO.popen("cd #{backend_config}; exec perl #{perlopts} ./bs_sched --testmode #{arch}") do |io|
# just for waiting until scheduler finishes
io.each { |line| Rails.logger.debug("scheduler(#{arch}): #{line.strip.chomp}") unless line.blank? }
end
end
def login_king
prepare_request_with_user 'king', 'sunflower'
end
def login_Iggy
prepare_request_with_user 'Iggy', 'asdfasdf'
end
def login_adrian
prepare_request_with_user 'adrian', 'so_alone'
end
def login_adrian_downloader
prepare_request_with_user 'adrian_downloader', 'so_alone'
end
def login_fred
prepare_request_with_user 'fred', 'geröllheimer'
end
def login_tom
prepare_request_with_user 'tom', 'thunder'
end
def login_dmayr
prepare_request_with_user 'dmayr', '123456'
end
end
end
class ActiveSupport::TestCase
set_fixture_class events: Event::Base
set_fixture_class history_elements: HistoryElement::Base
def assert_xml_tag(data, conds)
node = ActiveXML::Node.new(data)
ret = node.find_matching(NodeMatcher::Conditions.new(conds))
assert ret, "expected tag, but no tag found matching #{conds.inspect} in:\n#{node.dump_xml}" unless ret
end
def assert_no_xml_tag(data, conds)
node = ActiveXML::Node.new(data)
ret = node.find_matching(NodeMatcher::Conditions.new(conds))
assert !ret, "expected no tag, but found tag matching #{conds.inspect} in:\n#{node.dump_xml}" if ret
end
def load_fixture(path)
File.open(File.join(ActionController::TestCase.fixture_path, path)).read()
end
def load_backend_file(path)
load_fixture("backend/#{path}")
end
def teardown
Rails.cache.clear
end
end