forked from ontoportal/ontologies_linked_data
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_case.rb
More file actions
267 lines (232 loc) · 10.4 KB
/
Copy pathtest_case.rb
File metadata and controls
267 lines (232 loc) · 10.4 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# Start simplecov if this is a coverage task or if it is run in the CI pipeline
if ENV['COVERAGE'] == 'true' || ENV['CI'] == 'true'
require 'simplecov'
require 'simplecov-cobertura'
# https://github.com/codecov/ruby-standard-2
# Generate HTML and Cobertura reports which can be consumed by codecov uploader
SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::CoberturaFormatter
])
SimpleCov.start do
add_filter '/test/'
add_filter 'app.rb'
add_filter 'init.rb'
add_filter '/config/'
end
end
require_relative 'test_log_file'
require_relative '../lib/ontologies_linked_data'
require_relative '../config/config.test'
require 'minitest/autorun'
require 'tmpdir'
require 'webmock/minitest'
WebMock.allow_net_connect!
# Minitest 5+ no longer supports `MiniTest::Unit.runner=`. We emulate the old
# custom runner behavior using Minitest hooks and a small patch around suite runs.
module LinkedData
module MinitestSuiteHooks
def run_suite(reporter, options = {})
return if filter_runnable_methods(options).empty?
before_suite if respond_to?(:before_suite)
super
rescue Exception => e
puts e.message
puts e.backtrace.join("\n\t")
puts 'Traced from:'
raise
ensure
after_suite if respond_to?(:after_suite)
end
end
end
# Apply per-suite before/after hooks around every runnable (test class).
Minitest::Runnable.singleton_class.prepend(LinkedData::MinitestSuiteHooks)
# Emulate the old Unit runner's before/after suites behavior.
# (Not all Minitest versions expose `before_run` / `after_run`.)
module LinkedData
module MinitestRunHooks
def run(*args)
LinkedData::TestCase.setup_test_repository_folder
LinkedData::TestCase.backend_4s_delete
super
ensure
LinkedData::TestCase.backend_4s_delete
LinkedData::TestCase.teardown_test_repository_folder
end
end
end
Minitest.singleton_class.prepend(LinkedData::MinitestRunHooks)
# Check to make sure you want to run if not pointed at localhost
safe_hosts = Regexp.new(/localhost|-ut|ncbo-dev*|ncbo-unittest*/)
def safe_redis_hosts?(sh)
return [LinkedData.settings.http_redis_host,
LinkedData.settings.goo_redis_host].select { |x|
x.match(sh)
}.length == 2
end
unless LinkedData.settings.goo_host.match(safe_hosts) &&
LinkedData.settings.search_server_url.match(safe_hosts) &&
safe_redis_hosts?(safe_hosts)
print '\n\n================================== WARNING ==================================\n'
print '** TESTS CAN BE DESTRUCTIVE -- YOU ARE POINTING TO A POTENTIAL PRODUCTION/STAGE SERVER **\n'
print 'Servers:\n'
print "triplestore -- #{LinkedData.settings.goo_host}\n"
print "search -- #{LinkedData.settings.search_server_url}\n"
print "redis http -- #{LinkedData.settings.http_redis_host}:#{LinkedData.settings.http_redis_port}\n"
print "redis goo -- #{LinkedData.settings.goo_redis_host}:#{LinkedData.settings.goo_redis_port}\n"
print "Type 'y' to continue: "
$stdout.flush
confirm = $stdin.gets
abort('Canceling tests...\n\n') unless confirm.strip == 'y'
print 'Running tests...'
$stdout.flush
end
module LinkedData
class TestCase < Minitest::Test
# Ensure all threads exit on any exception
Thread.abort_on_exception = true
def self.setup_test_repository_folder
return if defined?(@tmp_repository_folder) && @tmp_repository_folder
@old_repository_folder = LinkedData.settings.repository_folder
@tmp_repository_folder = Dir.mktmpdir("ontology-repo-")
puts "(LD) >> Using temp repository folder #{@tmp_repository_folder}"
LinkedData.settings.repository_folder = @tmp_repository_folder
end
def self.teardown_test_repository_folder
return unless defined?(@tmp_repository_folder) && @tmp_repository_folder
LinkedData.settings.repository_folder = @old_repository_folder if defined?(@old_repository_folder)
if ENV["KEEP_TEST_REPOSITORY_FOLDER"] == "true"
puts "(LD) >> Preserving temp repository folder #{@tmp_repository_folder}"
elsif File.exist?(@tmp_repository_folder)
FileUtils.remove_entry(@tmp_repository_folder)
end
@tmp_repository_folder = nil
end
def submission_dependent_objects(format, acronym, user_name)
# ontology format
owl = LinkedData::Models::OntologyFormat.where(acronym: format).first
assert_instance_of LinkedData::Models::OntologyFormat, owl
# ontology
users = LinkedData::Models::User.where(username: user_name).all
user = users.first
if user.nil?
user = LinkedData::Models::User.new({username: user_name})
user.email = 'a@example.org'
user.passwordHash = 'XXXXX'
user.save
end
ont = LinkedData::Models::Ontology.where(acronym: acronym).all
ont = ont.first
if ont.nil?
ont = LinkedData::Models::Ontology.new({acronym: acronym})
ont.name = "some name for #{acronym}"
ont.administeredBy = [user]
ont.save
end
contact = LinkedData::Models::Contact.new
contact.email = 'xxx@example.org'
contact.name = 'some name'
contact.save
return owl, ont, user, contact
end
##
# Creates a set of Ontology and OntologySubmission objects and stores them in the triplestore
# @param [Hash] options the options to create ontologies with
# @option options [Fixnum] :ont_count Number of ontologies to create
# @option options [Fixnum] :submission_count How many submissions each ontology should have (acts as max number when random submission count is used)
# @option options [TrueClass, FalseClass] :random_submission_count Use a random number of submissions between 1 and :submission_count
# @option options [TrueClass, FalseClass] :process_submission Parse the test ontology file
def create_ontologies_and_submissions(options = {})
LinkedData::SampleData::Ontology.create_ontologies_and_submissions(options)
end
##
# Retrieve ontology dependent objects
def ontology_objects
LinkedData::SampleData::Ontology.ontology_objects
end
##
# Delete all ontologies and their submissions
def delete_ontologies_and_submissions
LinkedData::SampleData::Ontology.delete_ontologies_and_submissions
end
def delete_goo_models(gooModelArray)
gooModelArray.each do |m|
m.delete
assert_equal(false, m.exist?(reload=true), 'Failed to delete a goo model.')
end
end
# Test the 'creator' attribute of a GOO model class
# @note This method name cannot begin with 'test_' or it will be called as a test
# @param [LinkedData::Models] model_class a GOO model class, e.g. LinkedData::Models::Project
# @param [LinkedData::Models::User] user a valid instance of LinkedData::Models::User
def model_creator_test(model, user)
# TODO: if the input argument is an instance, use the .class.new methods?
m = model.is_a?(Class) ? model.new : model
assert_equal(false, m.valid?, "#{m} .valid? returned true, it was expected to be invalid.")
m.creator = 'test name' # string is not valid
assert_equal(false, m.valid?, "#{m} .valid? returned true, it was expected to be invalid.")
assert_equal(false, m.errors[:creator].nil?) # We expect there to be errors on creator
assert_instance_of(LinkedData::Models::User, user, "#{user} is not an instance of LinkedData::Models::User")
assert_equal(true, user.valid?, "#{user} is not a valid instance of LinkedData::Models::User")
m.instance_of?(LinkedData::Models::Project) ? m.creator = [user] : m.creator = user
assert_equal(false, m.valid?, "#{m} .valid? returned true, it was expected to be invalid.")
assert_equal(true, m.errors[:creator].nil?, "Invalid model: #{m.errors}")
end
# Test the 'created' attribute of a GOO model
# @note This method name cannot begin with 'test_' or it will be called as a test
# @param [LinkedData::Models::Base] m a valid model instance with a 'created' attribute (without a value).
def model_created_test(m)
assert_equal(true, m.is_a?(LinkedData::Models::Base), 'Expected is_a?(LinkedData::Models::Base).')
assert_equal(true, m.valid?, "Expected valid model: #{m.errors}")
m.save if m.valid?
# The default value is auto-generated (during save), it should be OK.
assert_instance_of(DateTime, m.created, "The 'created' attribute is not a DateTime instance.")
assert_equal(true, m.errors[:created].nil?, m.errors.to_s)
begin
m.created = 'this string shuld fail'
rescue Exception => e
# in ruby 2.3+, this generates a runtime exception, so we need to handle it
assert_equal Date::Error, e.class
assert_equal 'invalid date', e.message
end
# The value should be an XSD date time.
m.created = DateTime.now
assert m.valid?
assert_instance_of(DateTime, m.created)
assert_equal(true, m.errors[:created].nil?, m.errors.to_s)
end
# Test the save and delete methods on a GOO model
# @param [LinkedData::Models::Base] m a valid model instance that can be saved and deleted
def model_lifecycle_test(m)
assert_equal(true, m.is_a?(LinkedData::Models::Base), 'Expected is_a?(LinkedData::Models::Base).')
assert_equal(true, m.valid?, "Expected valid model: #{m.errors}")
assert_equal(false, m.exist?, 'Given model is already saved, expected one that is not.')
m.save
assert_equal(true, m.exist?, 'Failed to save model.')
m.delete
assert_equal(false, m.exist?, 'Failed to delete model.')
end
def self.count_pattern(pattern)
q = "SELECT (count(DISTINCT ?s) as ?c) WHERE { #{pattern} }"
rs = Goo.sparql_query_client.query(q)
rs.each_solution do |sol|
return sol[:c].object
end
return 0
end
def self.backend_4s_delete
raise StandardError, 'Too many triples in KB, does not seem right to run tests' unless
count_pattern('?s ?p ?o') < 400000
graphs = Goo.sparql_query_client.query("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o . } }")
graphs.each_solution do |sol|
Goo.sparql_data_client.delete_graph(sol[:g])
end
LinkedData::Models::SubmissionStatus.init_enum
LinkedData::Models::OntologyType.init_enum
LinkedData::Models::OntologyFormat.init_enum
LinkedData::Models::Users::Role.init_enum
LinkedData::Models::Users::NotificationType.init_enum
end
end
end