Skip to content

Commit cb53632

Browse files
committed
tests/common: Add helper functions for mocking D-Bus API
The init_dbus_mock() and clean_dbus_mock() functions along with a template for 'python-dbusmock' could be utilized to set up a D-Bus service mock.
1 parent 175e035 commit cb53632

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

tests/test_common.sh.in

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,31 @@ function require {
124124
return 0
125125
}
126126

127+
# Check if Python module is available. For example:
128+
# require_python_module 'dbusmock' || return 255
129+
function require_python_module {
130+
eval "python -c \"import $1\" >/dev/null 2>&1"
131+
if [ $? -gt 0 ]; then
132+
echo -e "No '$1' Python module found!\n"
133+
return 255 # Test is not applicable.
134+
fi
135+
}
136+
137+
# Check if D-Bus service is present. Arguments are:
138+
# Args:
139+
# $1: 'system' or 'session' keyword
140+
# $2: Bus name (e.g. 'org.domain.foo')
141+
# $3: Object (e.g. '/')
142+
# require_dbus 'system' 'org.freedesktop.fwupd' '/' || return 255
143+
function require_dbus {
144+
require "gdbus" || return 255
145+
eval "gdbus introspect --$1 -d $2 -o $3 >/dev/null 2>&1"
146+
if [ $? -gt 0 ]; then
147+
echo -e "No '$2' ($1) D-Bus bus found!\n"
148+
return 255 # Test is not applicable.
149+
fi
150+
}
151+
127152
# Check if probe exists, use it as follows:
128153
# probecheck 'probe' || return 255
129154
function probecheck {
@@ -336,6 +361,27 @@ die() {
336361
exit $?
337362
}
338363

364+
# See https://github.com/martinpitt/python-dbusmock
365+
# Args:
366+
# $1: The name of the mock template file without extension.
367+
init_dbus_mock() {
368+
require_python_module "dbusmock" || return 255
369+
require "gdbus" || return 255
370+
printf "%s\n" "Initializing D-Bus mock from template: $1.py"
371+
python -m dbusmock --template "${srcdir}/$1.py" & disown
372+
# We have to replace system bus address because mock D-Bus
373+
# endpoint is created inside the user session
374+
export DBUS_SYSTEM_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS
375+
}
376+
377+
# Args:
378+
# $1: The name of the mock service bus
379+
clean_dbus_mock() {
380+
require "gdbus" || return 255
381+
printf "%s\n" "Shutting down D-Bus mock: $1"
382+
gdbus call --session -d "$1" -o / -m "$1.Exit" || true
383+
}
384+
339385
export -f assert_exists
340386

341387
export OPENSCAP_ENABLE_MD5="@OPENSCAP_ENABLE_MD5@"

0 commit comments

Comments
 (0)