Testing#
openhab-scripting includes framework classes to allow you to write unit tests
for your openHAB rules written in JRuby. It loads up a limited actual openHAB runtime
environment. Because it is a limited environment, with no actual bindings or things,
you may need to stub out those actions in your tests. The autoupdate manager is
running, so any commands sent to items that aren't marked as autoupdate="false" will
update automatically.
Usage#
You must run tests on a system with an actual openHAB instance installed, with your configuration. JRuby >= 10.0.0.1 must also be installed, though it's recommended you use the same version of JRuby that openHAB is using internally.
- Install and activate JRuby (by your method of choice - chruby, rbenv, etc.).
- Either create an empty directory, or use
$OPENHAB_CONFitself (the former is untested) - Create a
Gemfile, with the following contents (you can configure your actual openHAB Gemfile to point here to ensure both environments stay in sync):
source "https://rubygems.org"
plugin "bundler-openhab-stub"
group :development do
gem "rake", "~> 13.0", require: false
end
group :test do
gem "rspec", "~> 3.11"
gem "timecop"
end
group :openhab do
gem "openhab-scripting", "~> 5.0"
# include any other gems you want to use in your rules
end
- Run
bundle install - Run
bundle exec rspec --init - Edit the generated
spec/spec_helper.rbto satisfy your preferences, and add:
require "rubygems"
require "bundler"
Bundler.require(:default, :openhab, :test)
require "openhab/rspec"
# if you have any automatic requires setup in jrubyscripting's config,
# (besides `openhab`), you need to manually require them here
- Create some specs! An example of
spec/switches_spec.rb:
RSpec.describe "switches.rb" do
describe "gFullOn" do
it "works" do
GuestDownlights_Dimmer.update(0)
GuestDownlights_Scene.update(1.3)
expect(GuestDownlights_Dimmer.state).to eq 100
end
it "sets some state" do
rules["my rule"].trigger
expect(GuestDownlights_Scene.state).to be_nil
end
it "triggers a rule expecting an event" do
rules["my rule 2"].trigger(Struct.new(:item).new(GuestDownlights_Scene))
expect(GuestDownlights_Scene.state).to be_nil
end
end
end
- Run your specs:
bundle exec rspec
Reusing a background runtime with Thermos#
Thermos is a preloader based on Spring, and might be familiar if you have used Rails before.
To keep openHAB running between spec runs, install a project launcher and enable your RSpec binstub:
bundle exec thermos binstub rspec
This creates bin/thermos and adds its loader to bin/rspec.
Then run bin/rspec with your usual RSpec arguments. The first invocation starts
an openHAB server in the background. Subsequent invocations reuse that runtime.
Each RSpec invocation creates a fresh engine inside the shared openHAB instance, installs the test helpers, and loads autorequires, transformations, rules, and specs in that engine. Spec runs execute sequentially against the shared openHAB instance; Ruby globals and loaded files belong to the individual engine, but changes to the openHAB environment may persist, so make sure to clean up after yourself in user written specs.
bin/thermos server --background
bin/thermos status
bin/thermos version
bin/thermos stop
DISABLE_THERMOS=1 bin/rspec
Clients can use CRuby for convenience and faster startup. When starting a server from CRuby,
Thermos locates the JRuby embedded in the jrubyscripting addon and launches it
using $JAVA_HOME/bin/java (or java on $PATH). If no addon
is found, start the server with an installed JRuby instead. The embedded launcher
clears CRuby gem paths and startup options. It reads gem_home from the addon’s persisted
settings in $OPENHAB_USERDATA/config/org/openhab/automation/jrubyscripting.config
and $OPENHAB_CONF/services/*.cfg expanding the addon’s Ruby version placeholders.
When unset, the addon default is $OPENHAB_CONF/automation/ruby/.gem/<JRuby version>.
An explicitly empty setting leaves JRuby’s default gem paths in use.
thermos server starts the server in the foreground; add --background
to start it without running a command.
Stop the server before rebuilding or refreshing the test instance, and restart
it after changing boot configuration, the Gemfile, or helper library code.
You can also run specs directly with bundle exec thermos rspec.
Use thermos binstub --remove --all to remove the generated loaders.
The normal spec runner remains available through bundle exec rspec or by setting
DISABLE_THERMOS=1.
Maintaining the test instance#
The test harness reuses a .karaf directory in your project directory. To update
its copy of your openHAB installation add a Rakefile:
require "openhab/karaf/tasks"
OpenHAB::Karaf::Tasks.new
This will add new Rake tasks:
bundle exec rake karaf:rebuild
bundle exec rake karaf:refresh
karaf:rebuild completely removes .karaf and creates a new clone from your
installed openHAB instance. Use it after upgrading openHAB or when you need a
fresh test environment. It builds the clone without starting the runtime.
karaf:refresh replaces only .karaf/jsondb and .karaf/persistence with fresh
copies from openHAB's userdata directory. This will update your test copy of
openHAB with changes to managed items, things, and the latest persisted data.
Spec Writing Tips#
- By default Ruby files are looked for in
$OPENHAB_CONF/automation/rubyand in$OPENHAB_CONF/automation/jsr223. You can replace or append to these paths with theopenhab_automation_search_pathsRSpec configuration setting in yourspec_helper.rb. When multiple files have the same path relative to their search directory, only the file from the last search path is loaded. For example,staging/sl10/lighting.rboverridesautomation/ruby/sl10/lighting.rb, whilestaging/lighting.rbdoes not. Start levels determine the load order after these overrides are applied.
RSpec.configure do |config|
config.openhab_automation_search_paths += ["/my/staging/directory"]
end
To develop and test rule changes before modifying a production install, copy the rules you want to change into a staging directory outside the production automation directories, preserving their relative paths (including subdirectories), and append that directory as shown above. Edit the staged copies and run your specs: they replace the matching production files in the test runtime, while the other production rules still load. Once the tests pass, copy the updated files to the production install.
-
Skip automatic loading of specific files or directories by setting
config.openhab_automation_exclude_paths = ["lighting.rb", "experimental"]. Paths are relative to the automation search paths; excluding a directory skips all files beneath it across all search paths. -
Use
load_rule("experimental/lighting.rb")in a spec or hook to explicitly load a rule, including an excluded rule. Include the.rbextension and use a path relative to an automation search path.load_ruleis idempotent, so you don't have to worry about if a file has already been loaded before calling it. -
See OpenHAB::RSpec::Helpers for all helper methods available in specs.
-
All items are reset to NULL before each spec.
-
on_loadtriggers are not honored. Items will be reset to NULL before the next spec anyway, so just don't waste the energy running them. You can still trigger rules manually. -
Other rule triggers, such as watchers, can be tested with trigger.
-
You can trigger channels directly with OpenHAB::RSpec::Helpers#trigger_channel.
-
Timers aren't triggered automatically. Use the OpenHAB::RSpec::Helpers#execute_timers helper to execute any timers that are ready to run. The
timecopgem is automatically included, so useTimecop.travel(5.seconds)(for example) to travel forward in time and have timers ready to execute. Note that this includes implicit timers created by rules that use thefor:feature, as well as time-based rule triggers. Recurring triggers fire once per call and then advance to their next future occurrence, skipping missed occurrences. Item updates reschedule item-based time triggers; disabling or removing a rule cancels its pending triggers. -
Logging levels can be changed in your code. Setting a log level for a logger further up the chain (separated by dots) applies to all loggers underneath it.
OpenHAB::Log.logger("org.openhab.core.automation.internal.RuleEngineImpl").level = :debug
OpenHAB::Log.gem_root.level = :debug
OpenHAB::Log.root.level = :debug
OpenHAB::Log.events.level = :info
- Differing from when openHAB loads rules, all rules are loaded into a single JRuby execution context, so changes to globals in one file will affect other files. In particular, this applies to ids for reentrant timers will now share a single namespace among all files.
- Some actions may not be available; you should stub them out if you use them. Core actions like OpenHAB::Core::Actions#notify, OpenHAB::Core::Actions::Voice.say, and OpenHAB::Core::Actions::Audio.play_sound are stubbed to only log a message (at debug level).
- You may want to avoid rules from firing while setting up the proper state for a test. In that case, use the OpenHAB::RSpec::Helpers#suspend_rules helper.
- Item persistence is enabled by default using an in-memory store that only tracks changes to items.
- The OpenHAB::RSpec::Helpers#install_addon helper can be used to install an
addon like
binding-astroif you need to be able to create things from your rules. Note that the addon isn't actually allowed to start, just be installed to make type metadata from XML available. - If you have any Things in your openHAB instance that take two minutes to come online due to missing type metadata, you can force them to initialize immediately by calling OpenHAB::RSpec::Helpers#initialize_missing_thing_types.
- You can add a
binding.irbcall in to a spec (or your rule file) to break execution at that point and allow you to explore the current state of things with a REPL.
Configuration#
There are a few environment variables you can set to help the gem find the necessary dependencies. The default should work for an OpenHABian install or installation on Ubuntu or Debian with .debs. You may need to customize them if your installation is laid out differently. Additional openHAB or Karaf specific system properties will be set the same as openHAB would.
| Variable | Default | Description |
|---|---|---|
$OPENHAB_HOME |
/usr/share/openhab |
Location for the openHAB installation |
$OPENHAB_RUNTIME |
$OPENHAB_HOME/runtime |
Location for openHAB's private Maven repository containing its JARs |
Transformations#
Ruby transformations must have a magic comment # -*- mode: ruby -*- in them to be loaded.
Then they can be accessed as a method on OpenHAB::Transform based on the filename:
OpenHAB::Transform.compass("59 °")
OpenHAB::Transform.compass("30", param: "7")
OpenHAB::Transform::Ruby.compass("59 °")
They're loaded into a sub-JRuby engine, just like they run in openHAB.
Standalone specs#
The library's client and transport specs can run under CRuby or JRuby without starting openHAB:
bin/rake spec:standalone
This task skips the repository's .rspec auto-requires. CI runs it under CRuby
in the Thermos matrix jobs.
IRB#
If you would like to use a REPL sandbox to play with your items, create bin/console with the following contents, and then run it:
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/setup"
Bundler.require(:default, :openhab)
require "irb"
begin
require "openhab/rspec"
autorequires
load_rules
load_transforms
rescue => e
puts e.backtrace
raise
end
IRB.start(__FILE__)
You can also use Thermos to speed up launching IRB by running
bin/thermos binstub --all once after creating bin/console.