How to force Batch mode executing in any case for Batch class? - batch-processing

I need to force in any case the Batch mode processing for my custom class extends RunBaseBatch by code. The user can't change the execution mode.
The shedule mode must only to be in Batch.
I try to use in main method, before promt command
these code line:
className.mustGoBatch();
className.parmInBatch(true);
className.doBatch();
BUT not work, I see the flag Batch processing switch off.
Thanks

use className.batchInfo().parmBatchExecute(NoYes::Yes);
see Tutorial_RunbaseBatch class for example:
static void main(Args args)
{
Tutorial_RunbaseBatch tutorial_RunBase;
;
tutorial_RunBase = Tutorial_RunbaseBatch::construct();
// add this parm to switch on a batch processing
tutorial_RunBase.batchInfo().parmBatchExecute(NoYes::Yes);
if (tutorial_RunBase.prompt())
tutorial_RunBase.run();
}

Related

Configure LocalSearch UnionMove via JavaAPI

Various aspects of OptaPlanner configuration can be specified in the XML config then overridden via JavaAPI. For example you can set a default TerminationConfig in your XML then at runtime switch it for a user specified value.
The docs seem to indicate that it should be possible, but I haven't found any examples. The context is that I'm hoping to dynamically alter the UnionMove section of the config and omit Swap moves if the instance to be solved doesn't have at least 2 planning entities. Currently this results in lots of Bailing from infinite logging when users are experimenting with small problems.
Taken from https://www.optaplanner.org/docs/optaplanner/latest/planner-configuration/planner-configuration.html#solverConfigurationByJavaAPI :
private SolverConfig template;
public void init() {
template = SolverConfig.createFromXmlResource(
"org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
template.setTerminationConfig(new TerminationConfig());
}
// Called concurrently from different threads
public void userRequest(..., long userInput) {
SolverConfig solverConfig = new SolverConfig(template); // Copy it
solverConfig.getTerminationConfig().setMinutesSpentLimit(userInput);
SolverFactory<NQueens> solverFactory = SolverFactory.create(solverConfig);
Solver<NQueens> solver = solverFactory.buildSolver();
...
}
In your case, you would need to modify the Phase List of the SolverConfig (see the SolverConfig Javadocs ); the move selectors can be gotten and set via LocalSearchPhaseConfig and ConstructionHeuristicPhaseConfig (you need to use instanceof when iterating phase list to determine which one to cast to).
The bailing from infinite logging sound like a bug.

Karate start-up feature

Need to execute a 'healthcheck' test(feature) before all the test-cases execute .
This is like a preliminary test before executing the bunch of test-cases. Need a solutions to exit the platform if any of this pre check fails .
Execute your health check feature from karate-config.js using karate.call/karatecallSingle,
if you feature fails to use java System.exit to force kill your test.
snippet for karate-config.js
try{
var healthCheckInput = {};
var healthcheckCall = karate.callSingle("healthCheck.feature",healthCheckInput );
if (!<healcheckCondition>){
java.lang.System.exit(0);
}
}
catch(e){
java.lang.System.exit(0);
}
if your health check condition failed this would force exit your execution.
Not sure whether karate.abort() will give a soft exit from the platform, but if you are planning to implement try this as well.
Note: since System.exit() force kills your execution you will not get any reports properly, but you can refer console logs/karate logs
for further investigation.
EDIT:
Another Approach,
You can use karate Java API inside Junit #BeforeClass run your health status check feature.
#BeforeClass
public static void startUpCheck() {
Map<String, Object> args = new HashMap();
args.put("inputOne", "valueOne");
Map<String, Object> result = Runner.runFeature("classpath:stackoverflow/demo/healthCheck.feature", args, true);
// also assert the 'result' if you want OR keep some assertions/match in your feature
}

Batch Method with Argument

Is there a way to put a argument into a method in batch script? I know I can do that in java programming.
Example #1 (Java)
public class Test {
public static void main (String [] args) {
Test t1=new Test();
System.out.print(t1.method1(false));
}
public int method1 (boolean val1) {
if (val1==false) {
return 0;}
else {
return 1;}
}
}
I want to have something like this so when the method runs, depending on the argument, the method will produce varying results.
Example #2 (Batch - partial pseudocode)
:method1
::With an argument a1 (by default a1=1)
if %a1%==1 echo Option #1
if %a1%==2 echo Option #2
So when I call method1, depending on the argument, I could have two results.
Is there a way to do that? Or suggestions on how one method can have different results? Thanx
Try the inline help for the call built-in statement.
C:\>call /?
Calls one batch program from another.
CALL [drive:][path]filename [batch-parameters]
batch-parameters Specifies any command-line information required by the
batch program.
If Command Extensions are enabled CALL changes as follows:
CALL command now accepts labels as the target of the CALL. The syntax
is:
CALL :label arguments
A new batch file context is created with the specified arguments and
control is passed to the statement after the label specified. You must
"exit" twice by reaching the end of the batch script file twice. The
first time you read the end, control will return to just after the CALL
statement. The second time will exit the batch script. Type GOTO /?
for a description of the GOTO :EOF extension that will allow you to
"return" from a batch script.
<continutes>

Is it possible to skip a scenario with Cucumber-JVM at run-time

I want to add a tag #skiponchrome to a scenario, this should skip the scenario when running a Selenium test with the Chrome browser. The reason to-do this is because some scenario's work in some environments and not in others, this might not even be browser testing specific and could be applied in other situation for example OS platforms.
Example hook:
#Before("#skiponchrome") // this works
public void beforeScenario() {
if(currentBrowser == 'chrome') { // this works
// Skip scenario code here
}
}
I know it is possible to define ~#skiponchrome in the cucumber tags to skip the tag, but I would like to skip a tag at run-time. This way I don't have to think about which steps to skip in advance when I starting a test run on a certain environment.
I would like to create a hook that catches the tag and skips the scenario without reporting a fail/error. Is this possible?
I realized that this is a late update to an already answered question, but I want to add one more option directly supported by cucumber-jvm:
#Before //(cucumber one)
public void setup(){
Assume.assumeTrue(weAreInPreProductionEnvironment);
}
"and the scenario will be marked as ignored (but the test will pass) if weAreInPreProductionEnvironment is false."
You will need to add
import org.junit.Assume;
The major difference with the accepted answer is that JUnit assume failures behave just like pending
Important Because of a bug fix you will need cucumber-jvm release 1.2.5 which as of this writing is the latest. For example, the above will generate a failure instead of a pending in cucumber-java8-1.2.3.jar
I really prefer to be explicit about which tests are being run, by having separate run configurations defined for each environment. I also like to keep the number of tags I use to a minimum, to keep the number of configurations manageable.
I don't think it's possible to achieve what you want with tags alone. You would need to write a custom jUnit test runner to use in place of #RunWith(Cucumber.class). Take a look at the Cucumber implementation to see how things work. You would need to alter the RuntimeOptions created by the RuntimeOptionsFactory to include/exclude tags depending on the browser, or other runtime condition.
Alternatively, you could consider writing a small script which invokes your test suite, building up a list of tags to include/exclude dynamically, depending on the environment you're running in. I would consider this to be a more maintainable, cleaner solution.
It's actually really easy. If you dig though the Cucumber-JVM and JUnit 4 source code, you'll find that JUnit makes skipping during runtime very easy (just undocumented).
Take a look at the following source code for JUnit 4's ParentRunner, which Cucumber-JVM's FeatureRunner (which is used in Cucumber, the default Cucumber runner):
#Override
public void run(final RunNotifier notifier) {
EachTestNotifier testNotifier = new EachTestNotifier(notifier,
getDescription());
try {
Statement statement = classBlock(notifier);
statement.evaluate();
} catch (AssumptionViolatedException e) {
testNotifier.fireTestIgnored();
} catch (StoppedByUserException e) {
throw e;
} catch (Throwable e) {
testNotifier.addFailure(e);
}
}
This is how JUnit decides what result to show. If it's successful it will show a pass, but it's possible to #Ignore in JUnit, so what happens in that case? Well, an AssumptionViolatedException is thrown by the RunNotifier (or Cucumber FeatureRunner in this case).
So your example becomes:
#Before("#skiponchrome") // this works
public void beforeScenario() {
if(currentBrowser == 'chrome') { // this works
throw new AssumptionViolatedException("Not supported on Chrome")
}
}
If you've used vanilla JUnit 4 before, you'd remember that #Ignore takes an optional message that is displayed when a test is ignored by the runner. AssumptionViolatedException carries the message, so you should see it in your test output after a test is skipped this way without having to write your own custom runner.
I too had the same challenge, where in I need to skip a scenario from running based on a flag which I obtain from the application dynamically in run-time, which tells whether the feature to be tested is enabled on the application or not..
so this is how I wrote my logic in the scenarios file, where we have the glue code for each step.
I have used a unique tag '#Feature-01AXX' to mark my scenarios that need to be run only when that feature(code) is available on the application.
so for every scenario, the tag '#Feature-01XX' is checked first, if its present then the check for the availability of the feature is made, only then the scenario will be picked for running. Else it will be merely skipped, and Junit will not mark this as failure, instead it will me marked as Pass. So the final result if these tests did not run due to the un-availability of the feature will be pass, that's cool...
#Before
public void before(final Scenario scenario) throws Exception {
/*
my other pre-setup tasks for each scenario.
*/
// get all the scenario tags from the scenario head.
final ArrayList<String> scenarioTags = new ArrayList<>();
scenarioTags.addAll(scenario.getSourceTagNames());
// check if the feature is enabled on the appliance, so that the tests can be run.
if (checkForSkipScenario(scenarioTags)) {
throw new AssumptionViolatedException("The feature 'Feature-01AXX' is not enabled on this appliance, so skipping");
}
}
private boolean checkForSkipScenario(final ArrayList<String> scenarioTags) {
// I use a tag "#Feature-01AXX" on the scenarios which needs to be run when the feature is enabled on the appliance/application
if (scenarioTags.contains("#Feature-01AXX") && !isTheFeatureEnabled()) { // if feature is not enabled, then we need to skip the scenario.
return true;
}
return false;
}
private boolean isTheFeatureEnabled(){
/*
my logic to check if the feature is available/enabled on the application.
in my case its an REST api call, I parse the JSON and check if the feature is enabled.
if it is enabled return 'true', else return 'false'
*/
}
I've implemented a customized junit runner as below. The idea is to add tags during runtime.
So say for a scenario we need new users, we tag the scenarios as "#requires_new_user". Then if we run our test in an environment (say production environment which dose not allow you to register new user easily), then we will figure out that we are not able to get new user. Then the ""not #requires_new_user" will be added to cucumber options to skip the scenario.
This is the most clean solution I can imagine now.
public class WebuiCucumberRunner extends ParentRunner<FeatureRunner> {
private final JUnitReporter jUnitReporter;
private final List<FeatureRunner> children = new ArrayList<FeatureRunner>();
private final Runtime runtime;
private final Formatter formatter;
/**
* Constructor called by JUnit.
*
* #param clazz the class with the #RunWith annotation.
* #throws java.io.IOException if there is a problem
* #throws org.junit.runners.model.InitializationError if there is another problem
*/
public WebuiCucumberRunner(Class clazz) throws InitializationError, IOException {
super(clazz);
ClassLoader classLoader = clazz.getClassLoader();
Assertions.assertNoCucumberAnnotatedMethods(clazz);
RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz);
RuntimeOptions runtimeOptions = runtimeOptionsFactory.create();
addTagFiltersAsPerTestRuntimeEnvironment(runtimeOptions);
ResourceLoader resourceLoader = new MultiLoader(classLoader);
runtime = createRuntime(resourceLoader, classLoader, runtimeOptions);
formatter = runtimeOptions.formatter(classLoader);
final JUnitOptions junitOptions = new JUnitOptions(runtimeOptions.getJunitOptions());
final List<CucumberFeature> cucumberFeatures = runtimeOptions.cucumberFeatures(resourceLoader, runtime.getEventBus());
jUnitReporter = new JUnitReporter(runtime.getEventBus(), runtimeOptions.isStrict(), junitOptions);
addChildren(cucumberFeatures);
}
private void addTagFiltersAsPerTestRuntimeEnvironment(RuntimeOptions runtimeOptions)
{
String channel = Configuration.TENANT_NAME.getValue().toLowerCase();
runtimeOptions.getTagFilters().add("#" + channel);
if (!TestEnvironment.getEnvironment().isNewUserAvailable()) {
runtimeOptions.getTagFilters().add("not #requires_new_user");
}
}
...
}
Or you can extends the official Cucumber Junit test runner cucumber.api.junit.Cucumber and override method
/**
* Create the Runtime. Can be overridden to customize the runtime or backend.
*
* #param resourceLoader used to load resources
* #param classLoader used to load classes
* #param runtimeOptions configuration
* #return a new runtime
* #throws InitializationError if a JUnit error occurred
* #throws IOException if a class or resource could not be loaded
* #deprecated Neither the runtime nor the backend or any of the classes involved in their construction are part of
* the public API. As such they should not be exposed. The recommended way to observe the cucumber process is to
* listen to events by using a plugin. For example the JSONFormatter.
*/
#Deprecated
protected Runtime createRuntime(ResourceLoader resourceLoader, ClassLoader classLoader,
RuntimeOptions runtimeOptions) throws InitializationError, IOException {
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
return new Runtime(resourceLoader, classFinder, classLoader, runtimeOptions);
}
You can manipulate runtimeOptions here as you wish. But the method is marked as deprecated, so use it with caution.
If you're using Maven, you could read use a browser profile and then set the appropriate ~ exclude tags there?
Unless you're asking how to run this from command line, in which case you tag the scenario with #skipchrome and then when you run cucumber set the cucumber options to tags = {"~#skipchrome"}
If you wish simply to temporarily skip a scenario (for example, while writing the scenarios), you can comment it out (ctrl+/ in Eclipse or Intellij).

How to get notified when the process invoked using Apache Commons Exec has stopped?

I am invoking a java process using Apache exec library. I need to do some operation if the process is forcefully stopped ( using task manager or some other way). Is there any option available in exec library ? I found a waitfor() operation in ResultHandler, which is doing a busy wait. Is there any notification mechanism available ?
I would expect the exit status to reflect if the process had been forceably killed.
See the tutorial and in particular reference to your comment, this section:
Your worker thread will block until the print process has finished or
was killed by the watchdog. Therefore executing the print job
asynchronously will do the trick. In this example we create an
instance of 'ExecuteResultHandler' and pass it to the 'Executor'
instance in order to execute the process asynchronously. The
'resultHandler' picks up any offending exception or the process exit
code
This has been asked a long time ago but I stumbled upon it today...
Here is the solution: you just have to setup a ExecuteResultHandler and pass it to the execute method. Then no active wait involved. Like this:
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler() {
#Override
public void onProcessComplete(int exitValue) {
super.onProcessComplete(exitValue);
log.info("Process finished");
}
#Override
public void onProcessFailed(ExecuteException e) {
super.onProcessFailed(e);
log.info("Process failed miserably");
}
};
String process = "C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroRd32.exe";
CommandLine cmdLine = new CommandLine(process);
cmdLine.addArgument("C:\\Users\\francois.marot\\Downloads\\UtiliserLesDernieres DLL.pdf");
DefaultExecutor executor = new DefaultExecutor();
// the watchdog purpose is to kill the process after a specified timeout
SphereExecutionWatchdog watchdog = new SphereExecutionWatchdog(5000);
executor.setWatchdog(watchdog);
executor.execute(cmdLine, resultHandler);