forked from ontoportal/ontologies_api
-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_case.rb
244 lines (211 loc) · 7.59 KB
/
test_case.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
# 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
ENV['RACK_ENV'] = 'test'
require_relative 'test_log_file'
require_relative '../app'
require 'minitest/autorun'
require 'minitest/hooks/test'
require 'webmock/minitest'
WebMock.allow_net_connect!
require 'rack/test'
require 'multi_json'
require 'oj'
require 'json-schema'
MAX_TEST_REDIS_SIZE = 10_000
# 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,
Annotator.settings.annotator_redis_host,
LinkedData.settings.goo_redis_host].select { |x|
x.match(sh)
}.length == 3
end
unless LinkedData.settings.goo_host.match(safe_hosts) &&
safe_redis_hosts?(safe_hosts) &&
LinkedData.settings.search_server_url.match(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 annotator -- #{Annotator.settings.annotator_redis_host}:#{Annotator.settings.annotator_redis_port}\n"
print "redis http -- #{LinkedData.settings.http_redis_host}:#{LinkedData.settings.http_redis_port}\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
if !(confirm.to_s.strip == 'y')
abort("Canceling tests...\n\n")
end
print "Running tests..."
$stdout.flush
end
class AppUnit < Minitest::Test
include Minitest::Hooks
def 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 backend_4s_delete
if count_pattern("?s ?p ?o") < 400000
LinkedData::Models::Ontology.where.include(:acronym).each do |o|
query = "submissionAcronym:#{o.acronym}"
LinkedData::Models::Ontology.unindexByQuery(query)
end
LinkedData::Models::Ontology.indexCommit()
Goo.sparql_update_client.update("DELETE {?s ?p ?o } WHERE { ?s ?p ?o }")
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
else
raise Exception, "Too many triples in KB, does not seem right to run tests"
end
end
def before_suite
# code to run before the first test (gets inherited in sub-tests)
end
def after_suite
# code to run after the last test (gets inherited in sub-tests)
end
def before_all
super
backend_4s_delete
before_suite
end
def after_all
after_suite
super
end
def _run_suite(suite, type)
begin
backend_4s_delete
suite.before_suite if suite.respond_to?(:before_suite)
super(suite, type)
rescue Exception => e
puts e.message
puts e.backtrace.join("\n\t")
puts "Traced from:"
raise e
ensure
backend_4s_delete
suite.after_suite if suite.respond_to?(:after_suite)
end
end
end
# All tests should inherit from this class.
# Use 'rake test' from the command line to run tests.
# See http://www.sinatrarb.com/testing.html for testing information
class TestCase < AppUnit
include Rack::Test::Methods
def app
Sinatra::Application
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 = {})
if options[:process_submission] && options[:process_options].nil?
options[:process_options] = { process_rdf: true, extract_metadata: false, generate_missing_labels: false }
end
LinkedData::SampleData::Ontology.create_ontologies_and_submissions(options)
end
##
# Delete all ontologies and their submissions
def delete_ontologies_and_submissions
LinkedData::SampleData::Ontology.delete_ontologies_and_submissions
end
# Delete triple store models
# @param [Array] gooModelArray an array of GOO models
def delete_goo_models(gooModelArray)
gooModelArray.each do |m|
next if m.nil?
m.delete
end
end
# Validate JSON object against a JSON schema.
# @note schema is only validated after json data fails to validate.
# @param [String] jsonData a json string that will be parsed by MultiJson.load
# @param [String] jsonSchemaString a json schema string that will be parsed by MultiJson.load
# @param [boolean] list set it true for jsonObj array of items to validate against jsonSchemaString
def validate_json(jsonData, jsonSchemaString, list=false)
schemaVer = :draft3
jsonObj = MultiJson.load(jsonData)
jsonSchema = MultiJson.load(jsonSchemaString)
assert(
JSON::Validator.validate(jsonSchema, jsonObj, :list => list, :version => schemaVer),
JSON::Validator.fully_validate(jsonSchema, jsonObj, :list => list, :version => schemaVer, :validate_schema => true).to_s
)
end
# Abstract method to get error messages during a test.
def get_errors(response)
errors = ''
if response.respond_to?('errors')
errors += last_response.errors
end
errors += '; ' unless errors.empty?
begin
errors += MultiJson.load(last_response.body)['errors'].to_s
rescue
# pass
end
return errors.strip
end
def self.enable_security
@@old_security_setting = LinkedData.settings.enable_security
LinkedData.settings.enable_security = true
end
def self.reset_security(old_security = @@old_security_setting)
LinkedData.settings.enable_security = old_security
end
def self.make_admin(user)
user.bring_remaining
user.role = [LinkedData::Models::Users::Role.find(LinkedData::Models::Users::Role::ADMIN).first]
user.save
end
def self.reset_to_not_admin(user)
user.bring_remaining
user.role = [LinkedData::Models::Users::Role.find(LinkedData::Models::Users::Role::DEFAULT).first]
user.save
end
def unused_port
server = TCPServer.new('127.0.0.1', 0)
port = server.addr[1]
server.close
port
end
private
def port_in_use?(port)
server = TCPServer.new(port)
server.close
false
rescue Errno::EADDRINUSE
true
end
end