Module: OpenHAB::RSpec::Helpers
- Defined in:
- lib/openhab/rspec/helpers.rb
Overview
Provides helper methods for use in specs, to easily work with and adjust the openHAB environment.
These methods are automatically available in RSpec spec blocks, as well
as other per-spec hooks like before and after. You can also call them
explicitly.
Class Method Summary collapse
-
.autorequires ⇒ void
Require all files configured to be autorequired with the jrubyscripting addon in openHAB.
- .autoupdate_all_items ⇒ void deprecated Deprecated.
-
.execute_timers ⇒ void
Execute all due time-based rule triggers and pending timers.
-
.initialize_missing_thing_types ⇒ void
Force things to come online that are missing their thing type.
-
.install_addon(addon_id, wait: true, ready_markers: nil) ⇒ void
Install an openHAB addon.
-
.launch_karaf(include_bindings: true, include_jsondb: true, private_confdir: false, use_root_instance: false) ⇒ void
Launch the karaf instance.
-
.load_rule(path) ⇒ true, false
Load a rule once, using a path relative to an automation search path.
-
.load_rules ⇒ void
Load all Ruby rules in the config/automation directory.
-
.load_transforms ⇒ void
Load all Ruby transformations in the config/transform directory.
-
.log_file ⇒ String
The filename of the openHAB log.
-
.spec_log_lines ⇒ Array<String>
The log lines since this spec started.
-
.suspend_rules ⇒ Object
Suspend rules for the duration of the block.
-
.time_travel_and_execute_timers(duration) ⇒ void
Wait
durationseconds, then execute any pending timers. -
.trigger_channel(channel, event = "") ⇒ void
Manually send an event to a trigger channel.
-
.trigger_event(event) ⇒ void
Send an openHAB event through the event bus, triggering matching rules.
-
.wait(how_long = 2.seconds) { ... } ⇒ void
Calls the block repeatedly until the expectations inside pass.
Class Method Details
.autorequires ⇒ void
This method returns an undefined value.
Require all files configured to be autorequired with the jrubyscripting addon in openHAB.
This method is normally called by RSpec hooks.
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/openhab/rspec/helpers.rb', line 213 def autorequires ENV["RUBYLIB"] ||= "" ENV["RUBYLIB"] += ":" unless ENV["RUBYLIB"].empty? ENV["RUBYLIB"] += rubylib_dirs.join(":") $LOAD_PATH.unshift(*ENV["RUBYLIB"] .split(File::PATH_SEPARATOR) .reject(&:empty?) .reject do |path| $LOAD_PATH.include?(path) end) requires = jrubyscripting_config&.get("require") || "" requires.split(",").each do |f| require f.strip end end |
.autoupdate_all_items ⇒ void
This method returns an undefined value.
Reconfigure all items to autoupdate
To bypass any items configured to not autoupdate, waiting for the binding to update them.
83 84 85 |
# File 'lib/openhab/rspec/helpers.rb', line 83 def autoupdate_all_items # no-op end |
.execute_timers ⇒ void
This method returns an undefined value.
Execute all due time-based rule triggers and pending timers. Recurring rule triggers fire once per call, skipping missed occurrences.
122 123 124 125 126 127 128 129 130 |
# File 'lib/openhab/rspec/helpers.rb', line 122 def execute_timers raise "Cannot execute timers when timers aren't mocked" unless self.class.mock_timers? now = ZonedDateTime.now Mocks::CronScheduler.execute_timers(now) DSL::TimerManager.instance.instance_variable_get(:@timers).each_key do |t| t.execute if t.active? && t.execution_time <= now end end |
.initialize_missing_thing_types ⇒ void
This method returns an undefined value.
Force things to come online that are missing their thing type
As of openHAB 4.0, things that are missing their thing type will not come online immediately. This especially impacts bindings that dynamically generate their thing types, but don't persist those thing types. You can use this method to force them to come online immediately.
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/openhab/rspec/helpers.rb', line 98 def initialize_missing_thing_types thing_manager = OpenHAB::OSGi.service("org.openhab.core.thing.ThingManager") thing_manager.class.field_reader :missingPrerequisites first = true thing_manager.missingPrerequisites.each_value do |prereq| if first prereq.class.field_accessor :timesChecked first = false end prereq.timesChecked = 60 end m = thing_manager.class.java_class.get_declared_method(:checkMissingPrerequisites) m.accessible = true suspend_rules do m.invoke(thing_manager) end end |
.install_addon(addon_id, wait: true, ready_markers: nil) ⇒ void
This method returns an undefined value.
Install an openHAB addon
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 |
# File 'lib/openhab/rspec/helpers.rb', line 492 def install_addon(addon_id, wait: true, ready_markers: nil) service_filter = "(component.name=org.openhab.core.karafaddons)" addon_service = OSGi.service("org.openhab.core.addon.AddonService", filter: service_filter) addon_service.install(addon_id) return unless wait addon = nil loop do addon = addon_service.get_addon(addon_id, nil) break if addon.installed? sleep 0.25 end return unless ready_markers package_id = addon.logger_packages.first ready_markers = Array(ready_markers).map do |marker| case marker when String org.openhab.core.service.ReadyMarker.new(marker, package_id) else marker end end rs = OSGi.service("org.openhab.core.service.ReadyService") loop do break if ready_markers.all? { |rm| rs.ready?(rm) } sleep 0.25 end end |
.launch_karaf(include_bindings: true, include_jsondb: true, private_confdir: false, use_root_instance: false) ⇒ void
This method returns an undefined value.
Launch the karaf instance
This method is normally called by RSpec hooks.
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 |
# File 'lib/openhab/rspec/helpers.rb', line 239 def launch_karaf(include_bindings: true, include_jsondb: true, private_confdir: false, use_root_instance: false) return attach_runtime if defined?(OpenHAB::Thermos.context) && OpenHAB::Thermos.context karaf = Karaf.new("#{Dir.pwd}/.karaf") karaf.include_bindings = include_bindings karaf.include_jsondb = include_jsondb karaf.private_confdir = private_confdir karaf.use_root_instance = use_root_instance main = karaf.launch # Ensure DefaultScriptScopeProvider has registered before loading the DSL. karaf.send(:wait) do |continue| karaf.send( :wait_for_service, "org.openhab.core.automation.module.script.ScriptExtensionProvider", filter: "(component.name=org.openhab.core.automation.module.script" \ ".internal.defaultscope.DefaultScriptScopeProvider)" ) { continue.call } end deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 30 until (ir = $se.get("ir")) break if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline java.lang.Thread.sleep(100) unless ir end raise "$ir was not populated by the default script scope before loading openhab/dsl" unless ir prepare_runtime rs = OSGi.service("org.openhab.core.service.ReadyService") # Wait for model loading (20), state restoration (30), and the rule engine (50). [org.openhab.core.service.StartLevelService::STARTLEVEL_MODEL, org.openhab.core.service.StartLevelService::STARTLEVEL_STATES, org.openhab.core.service.StartLevelService::STARTLEVEL_RULEENGINE].each do |level| filter = org.openhab.core.service.ReadyMarkerFilter.new .with_type(org.openhab.core.service.StartLevelService::STARTLEVEL_MARKER_TYPE) .with_identifier(level.to_s) karaf.send(:wait) do |continue| rs.register_tracker(org.openhab.core.service.ReadyService::ReadyTracker.impl { continue.call }, filter) end end # openHAB 5.2.0.M5+ can leave RuleEngineImpl.started false in the rspec # harness even after the rule-engine startlevel marker is reached. # Force it on so RuleEngineImpl.runRule won't drop triggered events. rule_manager = OSGi.service("org.openhab.core.automation.RuleManager") rule_manager.class.field_accessor :started rule_manager.started = true unless rule_manager.started load_storage_based_type_providers # RSpec additions require_relative "suspend_rules" if defined?(::RSpec) ::RSpec.configure do |config| config.include OpenHAB::DSL end end main rescue Exception => e puts e.inspect puts e.backtrace raise end |
.load_rule(path) ⇒ true, false
Load a rule once, using a path relative to an automation search path.
Later search paths take precedence, just as with #load_rules.
Explicit loading ignores openhab_automation_exclude_paths.
442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/openhab/rspec/helpers.rb', line 442 def load_rule(path) path = path.to_s if path.empty? || path.start_with?("/") || path.split("/").include?("..") raise ArgumentError, "Expected a path relative to an automation search path" end paths = Array(::RSpec.configuration.openhab_automation_search_paths) files = paths.reverse.map { |base| File.join(base, path) } file = files.find { |candidate| File.file?(candidate) } raise LoadError, "Cannot find rule #{path.inspect} in automation search paths" unless file SuspendRules.suspend_rules { load_rule_file(file) } end |
.load_rules ⇒ void
This method returns an undefined value.
Load all Ruby rules in the config/automation directory
This method is normally called by RSpec hooks.
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 |
# File 'lib/openhab/rspec/helpers.rb', line 399 def load_rules automation_paths = Array(::RSpec.configuration.openhab_automation_search_paths) lib_dirs = rubylib_dirs.map { |d| File.join(d, "") } lib_dirs << File.join(gem_home, "") SuspendRules.suspend_rules do files = {} automation_paths.each do |path| prefix = File.join(path, "") Dir["#{prefix}**/*.rb"].each do |file| next if lib_dirs.any? { |lib| file.start_with?(lib) } # Later search paths override matching paths relative to the base directory. files[file.delete_prefix(prefix)] = file end end excluded = Array(::RSpec.configuration.openhab_automation_exclude_paths) files.reject! do |relative, _file| excluded.any? do |path| path = path.to_s.delete_suffix("/") relative == path || relative.start_with?("#{path}/") end end files.values.sort_by { |f| [get_start_level(f), f] }.each do |f| load_rule_file(f) rescue Exception => e warn "Failed loading #{f}: #{e.inspect}" warn e.backtrace end end end |
.load_transforms ⇒ void
This method returns an undefined value.
Load all Ruby transformations in the config/transform directory
Since Ruby transformations must end with the .script extension, you must include
an Emacs modeline comment (# -*- mode: ruby -*-) in your script for it to be
recognized.
This method is normally called by RSpec hooks.
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
# File 'lib/openhab/rspec/helpers.rb', line 467 def load_transforms transform_path = "#{org.openhab.core.OpenHAB.config_folder}/transform" Dir["#{transform_path}/**/*.script"].each do |filename| script = File.read(filename) next unless ruby_file?(script) filename.slice!(0..transform_path.length) dir = File.dirname(filename) modules = (dir == ".") ? [] : moduleize(dir) basename = File.basename(filename) method = basename[0...-7] modules << method Transform.add_script(modules, script) end end |
.log_file ⇒ String
Returns The filename of the openHAB log.
528 529 530 |
# File 'lib/openhab/rspec/helpers.rb', line 528 def log_file "#{java.lang.System.get_property("openhab.logdir", nil)}/openhab.log" end |
.spec_log_lines ⇒ Array<String>
Returns The log lines since this spec started.
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
# File 'lib/openhab/rspec/helpers.rb', line 541 def spec_log_lines lines = [] # Give the underlying Log4j file channel up to ~50ms to flush its buffer to disk 5.times do lines = File.open(log_file, "rb") do |f| f.seek(@log_index) if @log_index f.read.split("\n") end # If we read lines, break early. If it's still empty, yield execution to the # JVM thread scheduler so the file appender thread can finish flushing. break unless lines.empty? sleep 0.01 end lines end |
.suspend_rules ⇒ Object
Suspend rules for the duration of the block
154 155 156 |
# File 'lib/openhab/rspec/helpers.rb', line 154 def suspend_rules(&) SuspendRules.suspend_rules(&) end |
.time_travel_and_execute_timers(duration) ⇒ void
This method returns an undefined value.
Wait duration seconds, then execute any pending timers
If timers are mocked, it will use Timecop. If they're not mocked, it
will just sleep for duration
140 141 142 143 144 145 146 147 |
# File 'lib/openhab/rspec/helpers.rb', line 140 def time_travel_and_execute_timers(duration) if self.class.mock_timers? Timecop.frozen? ? Timecop.freeze(duration) : Timecop.travel(duration) execute_timers else sleep duration end end |
.trigger_channel(channel, event = "") ⇒ void
This method returns an undefined value.
Manually send an event to a trigger channel
185 186 187 188 189 190 |
# File 'lib/openhab/rspec/helpers.rb', line 185 def trigger_channel(channel, event = "") channel = org.openhab.core.thing.ChannelUID.new(channel) if channel.is_a?(String) channel = channel.uid if channel.is_a?(org.openhab.core.thing.Channel) thing = channel.thing thing.handler.callback.channel_triggered(nil, channel, event) end |
.trigger_event(event) ⇒ void
This method returns an undefined value.
Send an openHAB event through the event bus, triggering matching rules. The event supplies its own type, topic, payload, and source.
202 203 204 |
# File 'lib/openhab/rspec/helpers.rb', line 202 def trigger_event(event) Core::Events.publisher.post(event) end |
.wait(how_long = 2.seconds) { ... } ⇒ void
This method returns an undefined value.
Calls the block repeatedly until the expectations inside pass.
164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/openhab/rspec/helpers.rb', line 164 def wait(how_long = 2.seconds) start = Process.clock_gettime(Process::CLOCK_MONOTONIC) begin yield rescue ::RSpec::Expectations::ExpectationNotMetError, ::RSpec::Mocks::MockExpectationError raise if Process.clock_gettime(Process::CLOCK_MONOTONIC) > start + how_long.to_f sleep 0.1 retry end end |