SystemCtl { public boolean serviceExists(TaskContext context, String unit) { return newCommandLine(context) .add("systemctl", "list-unit-files", unit + ".service").executeSilently() .mapOutput(output -> { Matcher matcher = UNIT_FILES_LISTED_PATTERN.matcher(output); if (!matcher.find()) { throw new IllegalArgumentException(); } return !matcher.group(1).equals("0"); }); } SystemCtl(Terminal terminal); SystemCtl withSudo(); boolean useSudo(); void daemonReload(TaskContext taskContext); SystemCtlEnable enable(String unit); SystemCtlDisable disable(String unit); SystemCtlStart start(String unit); SystemCtlStop stop(String unit); SystemCtlRestart restart(String unit); boolean serviceExists(TaskContext context, String unit); boolean isActive(TaskContext context, String unit);  }
@Test public void testUnitExists() { SystemCtl systemCtl = new SystemCtl(terminal); terminal.expectCommand("systemctl list-unit-files foo.service 2>&1", 0, "UNIT FILE STATE\n" + "\n" + "0 unit files listed.\n"); assertFalse(systemCtl.serviceExists(taskContext, "foo")); terminal.expectCommand("systemctl list-unit-files foo.service 2>&1", 0, "UNIT FILE STATE \n" + "foo.service enabled\n" + "\n" + "1 unit files listed.\n"); assertTrue(systemCtl.serviceExists(taskContext, "foo")); terminal.expectCommand("systemctl list-unit-files foo.service 2>&1", 0, "garbage"); try { systemCtl.serviceExists(taskContext, "foo"); fail(); } catch (Exception e) { assertThat(e.getMessage(), containsString("garbage")); } }