io.bootique.BQRuntime Java Examples

The following examples show how to use io.bootique.BQRuntime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BQModuleProviderChecker.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected void testMetadata() {

        testWithFactory(testFactory -> {
            // must auto-load modules to ensure all tested module dependencies are present...
            BQRuntime runtime = testFactory.app().autoLoadModules().createRuntime();

            BQModuleProvider provider = matchingProvider();
            String providerName = provider.name();

            // loading metadata ensures that all annotations are properly applied...
            Optional<ModuleMetadata> moduleMetadata = runtime
                    .getInstance(ModulesMetadata.class)
                    .getModules()
                    .stream()
                    .filter(mmd -> providerName.equals(mmd.getProviderName()))
                    .findFirst();

            assertTrue("No module metadata available for provider: '" + providerName + "'", moduleMetadata.isPresent());
            moduleMetadata.get().getConfigs();
        });
    }
 
Example #2
Source File: BQModuleProviderChecker.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected void testMetadata() {

        try {
            testWithFactory(testFactory -> {
                // must auto-load modules to ensure all tested module dependencies are present...
                BQRuntime runtime = testFactory.app().autoLoadModules().createRuntime();

                BQModuleProvider provider = matchingProvider();
                String providerName = provider.name();

                // loading metadata ensures that all annotations are properly applied...
                Optional<ModuleMetadata> moduleMetadata = runtime
                        .getInstance(ModulesMetadata.class)
                        .getModules()
                        .stream()
                        .filter(mmd -> providerName.equals(mmd.getProviderName()))
                        .findFirst();

                assertTrue(moduleMetadata.isPresent(), "No module metadata available for provider: '" + providerName + "'");
                moduleMetadata.get().getConfigs();
            });
        } catch (Exception e) {
            Assertions.fail("Fail to test metadata.");
            throw new RuntimeException(e);
        }
    }
 
Example #3
Source File: BQTestExtension.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected Predicate<Field> isRunnable() {
    return f -> {

        // provide diagnostics for misapplied or missing annotations
        // TODO: will it be actually more useful to throw instead of print a warning?
        if (AnnotationSupport.isAnnotated(f, BQApp.class)) {

            if (!BQRuntime.class.isAssignableFrom(f.getType())) {
                logger.warn(() -> "Field '" + f.getName() + "' is annotated with @BQRun but is not a BQRuntime. Ignoring...");
                return false;
            }

            if (!ReflectionUtils.isStatic(f)) {
                logger.warn(() -> "BQRuntime field '" + f.getName() + "' is annotated with @BQRun but is not static. Ignoring...");
                return false;
            }

            return true;
        }

        return false;
    };
}
 
Example #4
Source File: CommandManagerIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultAndHelpAndModuleCommands() {

    Command defaultCommand = cli -> CommandOutcome.succeeded();
    BQModule defaultCommandModule = binder -> BQCoreModule.extend(binder).setDefaultCommand(defaultCommand);

    BQRuntime runtime = runtimeFactory.app().modules(M0.class, M1.class).module(defaultCommandModule).createRuntime();

    CommandManager commandManager = runtime.getInstance(CommandManager.class);

    assertEquals(5, commandManager.getAllCommands().size());
    assertSame(M0.mockCommand, commandManager.lookupByName("m0command").getCommand());
    assertSame(M1.mockCommand, commandManager.lookupByName("m1command").getCommand());
    assertSame(defaultCommand, commandManager.getPublicDefaultCommand().get());
    assertSame(runtime.getInstance(HelpCommand.class), commandManager.getPublicHelpCommand().get());
}
 
Example #5
Source File: BQTestFactoryIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigEnvExcludes_System() {
    System.setProperty("bq.a", "bq_a");
    System.setProperty("bq.c.m.k", "bq_c_m_k");
    System.setProperty("bq.c.m.l", "bq_c_m_l");

    BQRuntime runtime = testFactory.app("--config=src/test/resources/configEnvironment.yml").createRuntime();

    Bean1 b1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");

    assertEquals("e", b1.a);
    assertEquals("q", b1.c.m.k);
    assertEquals("n", b1.c.m.l);

    System.clearProperty("bq.a");
    System.clearProperty("bq.c.m.k");
    System.clearProperty("bq.c.m.l");
}
 
Example #6
Source File: CommandsIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testModuleCommands() {
    BQModuleProvider provider = Commands.builder().build();
    BQRuntime runtime = testFactory.app(args).moduleProvider(provider).createRuntime();
    CommandManager commandManager = runtime.getInstance(CommandManager.class);

    Map<String, ManagedCommand> commands = commandManager.getAllCommands();
    assertCommandKeys(commands, "help", "help-config");

    assertFalse(commands.get("help").isHidden());
    assertFalse(commands.get("help").isDefault());
    assertTrue(commands.get("help").isHelp());

    assertFalse(commands.get("help-config").isHidden());
    assertFalse(commands.get("help-config").isDefault());
}
 
Example #7
Source File: CommandsIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoModuleCommands() {
    BQModuleProvider provider = Commands.builder().noModuleCommands().build();
    BQRuntime runtime = testFactory.app(args).moduleProvider(provider).createRuntime();
    CommandManager commandManager = runtime.getInstance(CommandManager.class);

    Map<String, ManagedCommand> commands = commandManager.getAllCommands();
    assertCommandKeys(commands, "help", "help-config");

    assertTrue(commands.get("help").isHidden());
    assertFalse(commands.get("help").isDefault());
    assertTrue(commands.get("help").isHelp());

    assertTrue(commands.get("help-config").isHidden());
    assertFalse(commands.get("help-config").isDefault());
}
 
Example #8
Source File: CommandsIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testModule_ExtraCommandAsType() {
    BQModuleProvider provider = Commands.builder(C1.class).build();
    BQRuntime runtime = testFactory.app(args).moduleProvider(provider).createRuntime();
    CommandManager commandManager = runtime.getInstance(CommandManager.class);

    Map<String, ManagedCommand> commands = commandManager.getAllCommands();
    assertCommandKeys(commands, "c1", "help", "help-config");

    assertFalse(commands.get("help").isHidden());
    assertFalse(commands.get("help").isDefault());
    assertTrue(commands.get("help").isHelp());

    assertFalse(commands.get("help-config").isHidden());
    assertFalse(commands.get("help-config").isDefault());

    assertTrue(commands.containsKey("c1"));
    assertFalse(commands.get("c1").isDefault());
}
 
Example #9
Source File: BQTestClassFactoryIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("System props don't leak to test")
public void testConfigEnvExcludes_System() {
    System.setProperty("bq.a", "bq_a");
    System.setProperty("bq.c.m.k", "bq_c_m_k");
    System.setProperty("bq.c.m.l", "bq_c_m_l");

    BQRuntime runtime = testFactory.app("--config=src/test/resources/configEnvironment.yml").createRuntime();

    Bean1 b1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");

    assertEquals("e", b1.a);
    assertEquals("q", b1.c.m.k);
    assertEquals("n", b1.c.m.l);

    System.clearProperty("bq.a");
    System.clearProperty("bq.c.m.k");
    System.clearProperty("bq.c.m.l");
}
 
Example #10
Source File: BQTestFactoryIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("System props don't leak to test")
public void testConfigEnvExcludes_System() {
    System.setProperty("bq.a", "bq_a");
    System.setProperty("bq.c.m.k", "bq_c_m_k");
    System.setProperty("bq.c.m.l", "bq_c_m_l");

    BQRuntime runtime = testFactory.app("--config=src/test/resources/configEnvironment.yml").createRuntime();

    Bean1 b1 = runtime.getInstance(ConfigurationFactory.class).config(Bean1.class, "");

    assertEquals("e", b1.a);
    assertEquals("q", b1.c.m.k);
    assertEquals("n", b1.c.m.l);

    System.clearProperty("bq.a");
    System.clearProperty("bq.c.m.k");
    System.clearProperty("bq.c.m.l");
}
 
Example #11
Source File: ModuleMetadataIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomNamedModule() {
    BQRuntime runtime = runtimeFactory.app().moduleProvider(new BQModuleProvider() {
        @Override
        public BQModule module() {
            return b -> {
            };
        }

        @Override
        public BQModuleMetadata.Builder moduleBuilder() {
            return BQModuleProvider.super
                    .moduleBuilder()
                    .name("mymodule");
        }
    }).createRuntime();

    ModulesMetadata md = runtime.getInstance(ModulesMetadata.class);
    assertEquals(4, md.getModules().size(), "Expected BQCoreModule + 2 test modules + custom module");

    Optional<ModuleMetadata> myMd = md.getModules()
            .stream()
            .filter(m -> "mymodule".equals(m.getName()))
            .findFirst();
    assertTrue(myMd.isPresent());
}
 
Example #12
Source File: BQInternalTestFactory.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Override
public void afterEach(ExtensionContext extensionContext) {

    LOGGER.info("Stopping runtime...");
    Collection<BQRuntime> localRuntimes = this.runtimes;

    if (localRuntimes != null) {
        localRuntimes.forEach(runtime -> {
            try {
                runtime.shutdown();
            } catch (Exception e) {
                // ignore...
            }
        });
    }
}
 
Example #13
Source File: CommandDecorator_CommandsIT.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Test
public void testAlsoRun_DecorateWithPrivate() {

    // use private "-s" command in decorator
    BQModuleProvider commandsOverride = Commands.builder().add(MainCommand.class).noModuleCommands().build();
    CommandDecorator decorator = CommandDecorator.alsoRun("s");

    BQRuntime runtime = createRuntime(commandsOverride, decorator);
    CommandOutcome outcome = runtime.run();

    waitForAllToFinish();

    assertTrue(outcome.isSuccess());
    assertTrue(getCommand(runtime, MainCommand.class).isExecuted());
    assertTrue(getCommand(runtime, SuccessfulCommand.class).isExecuted());
}
 
Example #14
Source File: BQRuntimeChecker.java    From bootique with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that runtime contains expected modules.
 *
 * @param runtime         a Bootique runtime whose contents we are testing.
 * @param expectedModules a vararg array of expected module types.
 */
@SafeVarargs
public static void testModulesLoaded(BQRuntime runtime, Class<? extends BQModule>... expectedModules) {

    final ModulesMetadata modulesMetadata = runtime.getInstance(ModulesMetadata.class);

    final List<String> actualModules = modulesMetadata
            .getModules()
            .stream()
            .map(ModuleMetadata::getName)
            .collect(toList());

    final String[] expectedModuleNames = Stream.of(expectedModules)
            .map(Class::getSimpleName)
            .toArray(String[]::new);

    // Using class names for checking module existing - weak.
    assertThat(actualModules, hasItems(expectedModuleNames));
}
 
Example #15
Source File: TestRuntimesManager.java    From bootique with Apache License 2.0 5 votes vote down vote up
public void shutdown() {
    Collection<BQRuntime> localRuntimes = this.runtimes;

    if (localRuntimes != null) {
        localRuntimes.forEach(runtime -> {
            try {
                runtime.shutdown();
            } catch (Exception e) {
                // ignore...
            }
        });
    }
}
 
Example #16
Source File: BootiqueMain.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the options of the program.
 *
 * @return the options of the program.
 */
public List<HelpOption> getOptions() {
	final BQRuntime runtime = createRuntime();
	final ApplicationMetadata application = runtime.getInstance(ApplicationMetadata.class);
	final HelpOptions helpOptions = new HelpOptions();

	/*application.getCommands().forEach(c -> {
		helpOptions.add(c.asOption());
		c.getOptions().forEach(o -> helpOptions.add(o));
	});*/

	application.getOptions().forEach(o -> helpOptions.add(o));

	return helpOptions.getOptions();
}
 
Example #17
Source File: BQDaemonTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
/**
 * Creates runtime without starting it. Can be started via {@link BQDaemonTestFactory#start(BQRuntime)}.
 *
 * @return newly created managed runtime.
 * @since 0.23
 */
public BQRuntime createRuntime() {
    BQRuntime runtime = bootique.createRuntime();

    // wrap in BQRuntimeDaemon to handle thread pool shutdown and startup checks.
    BQRuntimeDaemon testRuntime =
            new BQRuntimeDaemon(runtime, startupCheck, startupTimeout, startupTimeoutTimeUnit);
    runtimes.put(runtime, testRuntime);

    return runtime;
}
 
Example #18
Source File: BQDaemonTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
protected Builder(Map<BQRuntime, BQRuntimeDaemon> runtimes, String[] args) {
    super(args);
    this.startupTimeout = 5;
    this.startupTimeoutTimeUnit = TimeUnit.SECONDS;
    this.runtimes = runtimes;
    this.startupCheck = AFFIRMATIVE_STARTUP_CHECK;
}
 
Example #19
Source File: BootiqueMain.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create the compiler runtime.
 *
 * @param sarlLanguageSetup indicates if the SARL language setup should be realized.
 * @param args the command line arguments.
 * @return the runtime.
 */
protected BQRuntime createRuntime(String... args) {
	Bootique bootique = Bootique.app(args).autoLoadModules();
	if (this.providers != null) {
		for (final BQModuleProvider provider : this.providers) {
			bootique = bootique.module(provider);
		}
	}
	final BQRuntime runtime = bootique.createRuntime();
	return runtime;
}
 
Example #20
Source File: BQInternalDaemonTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
protected Builder(Collection<BQRuntime> runtimes, ExecutorService executor, String[] args) {

            super(runtimes, args);

            this.executor = executor;
            this.startupTimeout = 5;
            this.startupTimeoutTimeUnit = TimeUnit.SECONDS;
            this.startupCheck = AFFIRMATIVE_STARTUP_CHECK;
        }
 
Example #21
Source File: BQInternalDaemonTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Override
public BQRuntime createRuntime() {
    BQRuntime runtime = super.createRuntime();
    LOGGER.info("Starting runtime...");
    executor.submit(() -> Optional.of(runtime.run()));
    checkStartupSucceeded(runtime, startupTimeout, startupTimeoutTimeUnit);
    return runtime;
}
 
Example #22
Source File: CommandManagerIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testHiddenCommands() {

    Command hiddenCommand = new Command() {
        @Override
        public CommandOutcome run(Cli cli) {
            return CommandOutcome.succeeded();
        }

        @Override
        public CommandMetadata getMetadata() {
            return CommandMetadata.builder("xyz").hidden().build();
        }
    };

    BQRuntime runtime = runtimeFactory.app()
            .module(binder -> BQCoreModule.extend(binder).addCommand(hiddenCommand))
            .createRuntime();

    CommandManager commandManager = runtime.getInstance(CommandManager.class);

    assertEquals(3, commandManager.getAllCommands().size());

    ManagedCommand hiddenManaged = commandManager.getAllCommands().get("xyz");
    assertSame(hiddenCommand, hiddenManaged.getCommand());
    assertTrue(hiddenManaged.isHidden());
}
 
Example #23
Source File: BQRuntimeChecker.java    From bootique with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that runtime contains expected modules.
 *
 * @param runtime         a Bootique runtime whose contents we are testing.
 * @param expectedModules a vararg array of expected module types.
 */
@SafeVarargs
public static void testModulesLoaded(BQRuntime runtime, Class<? extends BQModule>... expectedModules) {

    ModulesMetadata modulesMetadata = runtime.getInstance(ModulesMetadata.class);

    List<String> actualModules = modulesMetadata
            .getModules()
            .stream()
            .map(ModuleMetadata::getName)
            .collect(toList());

    List<String> missingModules = new ArrayList<>();
    Stream.of(expectedModules)
            .map(Class::getSimpleName)
            .forEach(n -> {

                // Using class names for checking module existing - weak.
                if (!actualModules.contains(n)) {
                    missingModules.add(n);
                }
            });


    if(!missingModules.isEmpty()) {
        fail("The following expected modules are missing: " + missingModules);
    }
}
 
Example #24
Source File: BQInternalWebServerTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Override
public Builder app(String... args) {
    Function<BQRuntime, Boolean> startupCheck = r -> r.getInstance(Server.class).isStarted();
    return new Builder(runtimes, executor, args)
            .startupCheck(startupCheck)
            .module(new InternalJettyModule());
}
 
Example #25
Source File: CommandManagerIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelpAndModuleCommands() {
    BQRuntime runtime = runtimeFactory.app().modules(M0.class, M1.class).createRuntime();

    CommandManager commandManager = runtime.getInstance(CommandManager.class);
    assertEquals(4, commandManager.getAllCommands().size(), "help, helpconfig and module commands must be present");

    assertSame(M0.mockCommand, commandManager.lookupByName("m0command").getCommand());
    assertSame(M1.mockCommand, commandManager.lookupByName("m1command").getCommand());

    assertFalse(commandManager.getPublicDefaultCommand().isPresent());
    assertSame(runtime.getInstance(HelpCommand.class), commandManager.getPublicHelpCommand().get());
}
 
Example #26
Source File: BQInternalTestFactory.java    From bootique with Apache License 2.0 5 votes vote down vote up
protected Builder(Collection<BQRuntime> runtimes, String[] args) {
    this.runtimes = runtimes;
    this.properties = new HashMap<>();
    this.variables = new HashMap<>();
    this.declaredVars = new HashMap<>();
    this.valueObjectsDescriptors = new HashMap<>();
    this.declaredDescriptions = new HashMap<>();
    this.bootique = Bootique.app(args).moduleProvider(createPropertiesProvider()).moduleProvider(createVariablesProvider());
}
 
Example #27
Source File: CommandDecorator_CommandsIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
private BQRuntime createRuntime(BQModuleProvider commandsOverride, CommandDecorator decorator) {
    return testFactory
            .app("--a")
            .module(b -> BQCoreModule.extend(b)
                    .addCommand(MainCommand.class)
                    .addCommand(SuccessfulCommand.class)
                    .decorateCommand(MainCommand.class, decorator))
            .moduleProvider(commandsOverride)
            .createRuntime();
}
 
Example #28
Source File: ApplicationMetadataIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomDescription() {
    BQRuntime runtime = runtimeFactory.app()
            .module(b -> BQCoreModule.extend(b).setApplicationDescription("app desc"))
            .createRuntime();

    ApplicationMetadata md = runtime.getInstance(ApplicationMetadata.class);

    // we really don't know what the generated name is. It varies depending on the unit test execution environment
    assertNotNull(md.getName());
    assertEquals("app desc", md.getDescription());
    assertEquals(2, md.getCommands().size());
    assertEquals(1, md.getOptions().size());
}
 
Example #29
Source File: CommandDecorator_CommandsIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testBeforeRun_DecorateWithPrivate() {

    // use private "-s" command in decorator
    BQModuleProvider commandsOverride = Commands.builder().add(MainCommand.class).noModuleCommands().build();
    CommandDecorator decorator = CommandDecorator.beforeRun("s");

    BQRuntime runtime = createRuntime(commandsOverride, decorator);
    CommandOutcome outcome = runtime.run();

    assertTrue(outcome.isSuccess());
    assertTrue(getCommand(runtime, MainCommand.class).isExecuted());
    assertTrue(getCommand(runtime, SuccessfulCommand.class).isExecuted());
}
 
Example #30
Source File: ApplicationMetadataIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefault() {
    BQRuntime runtime = runtimeFactory.app().createRuntime();

    ApplicationMetadata md = runtime.getInstance(ApplicationMetadata.class);

    // we really don't know what the generated name is. It varies depending on the unit test execution environment
    assertNotNull(md.getName());
    assertNull(md.getDescription());
    assertEquals(2, md.getCommands().size());
    assertEquals(1, md.getOptions().size());
}