From 5c3795e2894f57d521fcb40f3d7ddd98d9e602da Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Tue, 15 Dec 2015 20:14:48 -0500 Subject: [PATCH 1/7] Formatting ! --- .gitignore | 2 + .../org/finra/jtaf/core/AutomationEngine.java | 582 ++++---- .../org/finra/jtaf/core/CommandRegistry.java | 63 +- .../core/DefaultAutomationClassLoader.java | 33 +- .../jtaf/core/IAutomationClassLoader.java | 16 +- .../core/asserts/AssertionFailedError.java | 18 +- .../jtaf/core/asserts/ErrorAccumulator.java | 265 ++-- .../jtaf/core/asserts/IgnoreErrorsAssert.java | 344 ++--- .../org/finra/jtaf/core/commands/Block.java | 15 +- .../jtaf/core/commands/ExpectFailure.java | 16 +- .../finra/jtaf/core/commands/FailHere.java | 14 +- .../jtaf/core/commands/IgnoreErrors.java | 11 +- .../org/finra/jtaf/core/commands/Invoke.java | 15 +- .../finra/jtaf/core/commands/Multipath.java | 15 +- .../jtaf/core/commands/RandomGenerator.java | 496 ++++--- .../org/finra/jtaf/core/commands/Repeat.java | 9 +- .../jtaf/core/commands/ReplaceContext.java | 19 +- .../jtaf/core/commands/TryRecoverCleanup.java | 27 +- .../jtaf/core/commands/VerifyException.java | 14 +- .../commands/context/AbstractContextCmd.java | 35 +- .../commands/context/AddListToListCmd.java | 53 +- .../commands/context/AddObjectToListCmd.java | 53 +- .../context/ManipulateContextHelper.java | 781 +++++------ .../commands/context/PutObjectInMapCmd.java | 39 +- .../context/RemoveObjectFromContextCmd.java | 17 +- .../context/StoreDefaultObjectCmd.java | 33 +- .../context/StoreObjectAsStringCmd.java | 31 +- .../context/StoreObjectFromListCmd.java | 1 - .../context/StoreObjectFromMapCmd.java | 27 +- .../context/StoreObjectInContextCmd.java | 22 +- .../context/VerifyObjectInContextCmd.java | 46 +- .../core/exceptions/DependencyException.java | 38 +- .../exceptions/ExpectedFailureException.java | 11 +- .../MissingInvocationTargetException.java | 43 +- .../core/model/exceptions/ModelException.java | 35 +- .../exceptions/NameCollisionException.java | 34 +- .../model/exceptions/NameFormatException.java | 48 +- .../model/execution/CorrectiveContext.java | 421 +++--- .../model/execution/IInterpreterContext.java | 65 +- .../model/execution/IInvocationContext.java | 87 +- .../core/model/execution/Interpreter.java | 734 +++++----- .../execution/exceptions/TestFailure.java | 52 +- .../exceptions/UndefinedParameterError.java | 31 +- .../exceptions/UndefinedProductionError.java | 29 +- .../core/model/invocationtarget/Command.java | 117 +- .../invocationtarget/ContextKeyHandler.java | 13 +- .../ContextKeyNotFoundException.java | 27 +- .../core/model/invocationtarget/Function.java | 12 +- .../IInvocationTargetVisitor.java | 11 +- .../invocationtarget/InvocationTarget.java | 62 +- .../statement/IInvocationListVisitor.java | 13 +- .../model/statement/IInvocationVisitor.java | 13 +- .../jtaf/core/model/statement/Invocation.java | 88 +- .../core/model/statement/InvocationList.java | 19 +- .../model/test/ITestComponentFactory.java | 17 +- .../jtaf/core/model/test/ITestVisitor.java | 44 +- .../jtaf/core/model/test/Requirement.java | 31 +- .../jtaf/core/model/test/TestAgenda.java | 113 +- .../jtaf/core/model/test/TestComponent.java | 252 ++-- .../jtaf/core/model/test/TestNamespace.java | 276 ++-- .../finra/jtaf/core/model/test/TestPath.java | 114 +- .../jtaf/core/model/test/TestResult.java | 170 +-- .../jtaf/core/model/test/TestScript.java | 364 ++--- .../core/model/test/TestScriptCollector.java | 66 +- .../jtaf/core/model/test/TestStatus.java | 3 +- .../core/model/test/TestStepsDetails.java | 80 +- .../finra/jtaf/core/model/test/TestSuite.java | 90 +- .../core/model/test/digraph/Dependencies.java | 40 +- .../jtaf/core/model/test/digraph/DiEdge.java | 38 +- .../jtaf/core/model/test/digraph/DiNode.java | 80 +- .../model/test/digraph/DigraphFactory.java | 246 ++-- .../core/model/test/digraph/TestDigraph.java | 112 +- .../core/parallel/ConcurrentScheduler.java | 279 ++-- .../jtaf/core/parallel/JTAFMasterSuite.java | 33 +- .../parallel/MasterSuiteRunnersBuilder.java | 60 +- .../core/parallel/ParallelScriptRunner.java | 129 +- .../jtaf/core/parallel/ResultUpdate.java | 31 +- .../jtaf/core/parallel/TestCaseRunner.java | 43 +- .../parsing/AutomationValueFilterPlugin.java | 38 +- .../core/parsing/AutomationValuePlugin.java | 23 +- .../finra/jtaf/core/parsing/BaseParser.java | 145 +- .../core/parsing/CommandLibraryParser.java | 662 +++++---- .../jtaf/core/parsing/DigraphPlugin.java | 64 +- .../jtaf/core/parsing/ExceptionPlugin.java | 38 +- .../finra/jtaf/core/parsing/LoopPlugin.java | 153 ++- .../jtaf/core/parsing/MaxThreadsPlugin.java | 23 +- .../finra/jtaf/core/parsing/ScriptParser.java | 66 +- .../jtaf/core/parsing/StatementParser.java | 513 ++++--- .../core/parsing/SuiteDependenciesPlugin.java | 83 +- .../core/parsing/SuiteExclusionsPlugin.java | 84 +- .../jtaf/core/parsing/TestDataPlugin.java | 390 +++--- .../core/parsing/TestDependenciesPlugin.java | 97 +- .../core/parsing/TestExclusionsPlugin.java | 97 +- .../jtaf/core/parsing/TestStrategyParser.java | 168 ++- .../exceptions/AttributeFormatException.java | 20 +- .../exceptions/ExceptionAccumulator.java | 62 +- .../exceptions/MissingAttributeException.java | 38 +- .../MissingRequiredElementException.java | 20 +- .../exceptions/MultipleMatchesException.java | 38 +- .../exceptions/NestedXPathException.java | 21 +- .../parsing/exceptions/ParsingException.java | 38 +- .../UnexpectedElementException.java | 20 +- .../core/parsing/helpers/AttributeHelper.java | 282 ++-- .../core/parsing/helpers/ElementScanner.java | 90 +- .../core/parsing/helpers/ParserHelper.java | 165 ++- .../jtaf/core/plugins/PluginManager.java | 132 +- .../execution/CommandRunnerPluginContext.java | 46 +- .../execution/ICommandRunnerPlugin.java | 27 +- .../plugins/execution/ITearDownPlugin.java | 17 +- .../plugins/execution/ITestRunnerPlugin.java | 32 +- .../execution/RunnerPluginException.java | 20 +- .../execution/TearDownPluginContext.java | 50 +- .../execution/TestRunnerPluginContext.java | 60 +- .../plugins/parsing/IPostParseAllPlugin.java | 14 +- .../IPostParseStrategyElementPlugin.java | 17 +- .../parsing/IPostParseSuitePlugin.java | 26 +- .../plugins/parsing/IPostParseTestPlugin.java | 26 +- .../parsing/ParserPluginException.java | 41 +- .../parsing/PostAllParserPluginContext.java | 53 +- ...ostStrategyElementParserPluginContext.java | 58 +- .../parsing/PostSuiteParserPluginContext.java | 81 +- .../parsing/PostTestParserPluginContext.java | 71 +- .../core/traceability/TraceabilityMatrix.java | 92 +- .../TraceabilityMatrixPlugin.java | 26 +- .../core/utilities/Base64EncoderDecoder.java | 122 +- .../utilities/CompositeDataComparator.java | 385 +++--- .../jtaf/core/utilities/ExcelFileParser.java | 200 +-- .../core/utilities/JTAFPropertyManager.java | 36 +- .../jtaf/core/utilities/PropertyManager.java | 82 +- .../jtaf/core/utilities/StringHelper.java | 160 +-- .../jtaf/core/utilities/logging/Message.java | 39 +- .../utilities/logging/MessageCollector.java | 181 ++- .../jtaf/core/utilities/logging/Section.java | 243 ++-- .../asserts/AssertionFailedErrorTest.java | 48 +- .../core/asserts/ErrorAccumulatorTest.java | 203 ++- .../core/asserts/IgnoreErrorsAssertTest.java | 1184 ++++++++--------- .../finra/jtaf/core/commands/ByeCommand.java | 18 +- .../core/commands/ExtendedByeCommand.java | 18 +- .../core/commands/ExtendedHelloCommand.java | 22 +- .../commands/ExtendedVerifyByeCommand.java | 18 +- .../commands/ExtendedVerifyHelloCommand.java | 18 +- .../jtaf/core/commands/HelloCommand.java | 18 +- .../core/commands/RandomGeneratorTest.java | 143 +- .../finra/jtaf/core/commands/RepeatTest.java | 14 +- .../jtaf/core/commands/VerifyByeCommand.java | 18 +- .../core/commands/VerifyHelloCommand.java | 18 +- .../context/ManipulateContextHelperTest.java | 6 +- .../jtaf/core/driver/XMLTestParrelDriver.java | 4 +- .../jtaf/core/mock/DebugPrintCommand.java | 24 +- .../jtaf/core/mock/IThrowExceptionCmd.java | 20 +- .../finra/jtaf/core/mock/MockCommand1.java | 22 +- .../finra/jtaf/core/mock/MockCommand2.java | 28 +- .../java/org/finra/jtaf/core/mock/Repeat.java | 20 +- .../jtaf/core/mock/TestParamFetchingCmd.java | 154 +-- .../parallel/ConcurrentSchedulerTest.java | 22 +- .../MasterSuiteRunnersBuilderTest.java | 4 +- .../parallel/ParallelScriptRunnerTest.java | 12 +- .../AutomationValueFilterPluginTest.java | 246 ++-- .../parsing/AutomationValuePluginTest.java | 65 +- .../jtaf/core/parsing/DigraphPluginTest.java | 58 +- .../jtaf/core/parsing/LoopPluginTest.java | 51 +- .../core/parsing/MaxThreadsPluginTest.java | 63 +- .../jtaf/core/parsing/ParserPluginTest.java | 47 +- .../jtaf/core/parsing/ScriptParserTests.java | 72 +- .../core/parsing/StatementParserTest.java | 262 ++-- .../parsing/SuiteDependenciesPluginTest.java | 74 +- .../parsing/SuiteExclusionsPluginTest.java | 74 +- .../jtaf/core/parsing/TestDataPluginTest.java | 55 +- .../parsing/TestDependenciesPluginTest.java | 44 +- .../parsing/TestExclusionsPluginTest.java | 44 +- .../core/parsing/TestStrategyParserTest.java | 46 +- .../execution/DummyCommandRunnerPlugin.java | 50 +- .../execution/DummyTestRunnerPlugin.java | 56 +- .../execution/ExecutionPluginsTest.java | 308 ++--- .../plugins/execution/TearDownTestPlugin.java | 12 +- .../TraceabilityMatrixPluginTest.java | 85 +- .../utilities/JTAFPropertyManagerTests.java | 64 +- .../jtaf/core/ztest/DuplicateRepeatTest.java | 37 +- 178 files changed, 8516 insertions(+), 8954 deletions(-) diff --git a/.gitignore b/.gitignore index f7ac515..8cd7282 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,5 @@ hs_err_pid* /.project /commandNames.txt /Traceability_Matrix.txt +.idea/ +*.iml diff --git a/src/main/java/org/finra/jtaf/core/AutomationEngine.java b/src/main/java/org/finra/jtaf/core/AutomationEngine.java index c910437..1986745 100644 --- a/src/main/java/org/finra/jtaf/core/AutomationEngine.java +++ b/src/main/java/org/finra/jtaf/core/AutomationEngine.java @@ -61,293 +61,299 @@ * components. All of its subcomponents are instantiated from a Spring factory. */ public class AutomationEngine { - private static AutomationEngine s_instance; - - public static final Logger logger = Logger - .getLogger(AutomationEngine.class); - public MessageCollector mc = new MessageCollector("Building model"); - private static final String FRAMEWORK_XML = "framework.xml"; - - // FIXME: Rewrite this parser - private final ScriptParser scriptParser; - private final CommandLibraryParser commandlibParser; - - // FIXME: And rewrite this one while you're at it :-D - private final TestStrategyParser testStrategyParser; - - private TestNamespace testRoot; - private Interpreter interpreter; - private PluginManager pluginManager; - private TestAgenda testAgenda; - private CommandRegistry commandRegistry; - - private TestDigraph digraph; - - private List postParseAllPlugins; - - private AutomationEngine() { - try { - InputStream fi = getFrameworkFile(); - GenericApplicationContext ctx = new GenericApplicationContext(); - - XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); - xmlReader - .setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); - - xmlReader.loadBeanDefinitions(new InputSource(fi)); - - ctx.refresh(); - - this.pluginManager = (PluginManager) ctx.getBean("PluginManager"); - - digraph = new TestDigraph( - new ClassBasedEdgeFactory(DiEdge.class)); - commandlibParser = new CommandLibraryParser(); - scriptParser = new ScriptParser(); - scriptParser.setDigraph(digraph); - commandlibParser - .setAutomationClassLoader(new DefaultAutomationClassLoader()); - testStrategyParser = new TestStrategyParser(); - testStrategyParser.setDigraph(digraph); - initPostParseStrategyElementPlugins(); - testRoot = null; - - this.interpreter = (Interpreter) ctx.getBean("Interpreter"); - - this.interpreter.setCommandRunnerPlugins(pluginManager - .getCommandRunnerPlugins()); - this.interpreter.setTestRunnerPlugins(pluginManager - .getTestRunnerPlugins()); - this.interpreter.setTearDownPlugins(pluginManager.getTearDownPlugins()); - - initPostParseAllPlugins(); - initPostParseSuitePlugins(); - initPostParseTestPlugins(); - - } catch (Exception e) { - // If something goes wrong here, we have a serious issue - logger.fatal(e); - throw new RuntimeException(e); - } - } - - private void initPostParseStrategyElementPlugins() { - List postParseStrategyElementPlugins = new ArrayList(); - postParseStrategyElementPlugins.add(new AutomationValuePlugin()); - postParseStrategyElementPlugins.add(new MaxThreadsPlugin()); - List postParseStrategyElementPluginsFromManager = pluginManager - .getPostParseStrategyElementPlugins(); - if (postParseStrategyElementPluginsFromManager != null) { - postParseStrategyElementPlugins - .addAll(postParseStrategyElementPluginsFromManager); - } - testStrategyParser - .setPostParseStrategyElementPlugins(postParseStrategyElementPlugins); - } - - private void initPostParseAllPlugins() { - postParseAllPlugins = new ArrayList(); - postParseAllPlugins.add(new DigraphPlugin()); - postParseAllPlugins.add(new TraceabilityMatrixPlugin()); - List postParseAllPluginsFromManager = pluginManager - .getPostParseAllPlugins(); - if (postParseAllPluginsFromManager != null) { - postParseAllPlugins.addAll(postParseAllPluginsFromManager); - } - postParseAllPlugins.add(new AutomationValueFilterPlugin()); - } - - private void initPostParseSuitePlugins() { - List postParseSuitePlugins = new ArrayList(); - postParseSuitePlugins.add(new SuiteDependenciesPlugin()); - postParseSuitePlugins.add(new SuiteExclusionsPlugin()); - List postParseSuitePluginsFromManager = pluginManager - .getPostParseSuitePlugins(); - if (postParseSuitePluginsFromManager != null) { - postParseSuitePlugins.addAll(postParseSuitePluginsFromManager); - } - scriptParser.setPostParseSuitePlugins(postParseSuitePlugins); - } - - private void initPostParseTestPlugins() { - List postParseTestPlugins = new ArrayList(); - postParseTestPlugins.add(new ExceptionPlugin()); - List postParseTestPluginsFromManager = pluginManager - .getPostParseTestPlugins(); - if (postParseTestPluginsFromManager != null) { - postParseTestPlugins.addAll(postParseTestPluginsFromManager); - } - scriptParser.setPostParseTestPlugins(postParseTestPlugins); - - List postParseSuitePlugins = new ArrayList(); - postParseSuitePlugins.add(new SuiteDependenciesPlugin()); - postParseSuitePlugins.add(new SuiteExclusionsPlugin()); - List postParseSuitePluginsFromManager = pluginManager - .getPostParseSuitePlugins(); - if (postParseSuitePluginsFromManager != null) { - postParseSuitePlugins.addAll(postParseSuitePluginsFromManager); - } - scriptParser.setPostParseSuitePlugins(postParseSuitePlugins); - } - - private static InputStream getFrameworkFile() { - InputStream is = AutomationEngine.class.getClassLoader() - .getResourceAsStream(FRAMEWORK_XML); - try { - if (is == null) { - is = new FileInputStream(new File(FRAMEWORK_XML)); - } - - } catch (IOException e) { - throw new RuntimeException("Could not load :" + FRAMEWORK_XML, e); - } - return is; - } - - /** - * Singleton accessor method. - * - * @return - */ - public static final AutomationEngine getInstance() { - if (AutomationEngine.s_instance == null) { - AutomationEngine.s_instance = new AutomationEngine(); - } - return AutomationEngine.s_instance; - } - - /** - * Gets the test root. - * - * @return - */ - public final TestNamespace getTestRoot() { - return testRoot; - } - - /** - * Builds test model from the specified test library folder and test scripts - * folder. By default it would also load the test libraries from the - * classpath. The test libraries are assumed to have extension - * *.commands.xml and expected to be under testlibrary folder/package - * - * @param librarySource - * @param testSource - */ - public final void buildModel(File librarySource, File testSource) { - System.out.println("Building model..."); - logger.info("Building model..."); - - boolean isFailed = false; - - try { - commandRegistry = new CommandRegistry(); - commandlibParser.parseCommandLibraries(commandRegistry, - librarySource, mc); - - } catch (Exception e) { - mc.error(e.getMessage()); - e.printStackTrace(); - isFailed = true; - } - - - interpreter.setCommandRegistry(commandRegistry); - scriptParser.setCommandRegistry(commandRegistry); - try { - testRoot = scriptParser.handleTestSource(testSource, mc); - - // build agenda - String fileLocation = JTAFPropertyManager.getInstance() - .getProperty("strategy"); - buildTestAgenda(new File(fileLocation)); - // run post all parsing plugins - - if (postParseAllPlugins != null) { - for (IPostParseAllPlugin p : postParseAllPlugins) { - p.execute(new PostAllParserPluginContext(testAgenda, - commandRegistry)); - } - } - } catch (Exception e) { - mc.error(e.getMessage()); - logger.error(e.getMessage()); - isFailed = true; - } - - if (isFailed) { - mc.dump(logger); - logger.fatal("Failed to build test model. See logs for details"); - throw new RuntimeException( - "Failed to build test model. See logs for details"); - } - - logger.info("Building model... Done"); - System.out.println("Building model... Done"); - - } - - private TestAgenda buildTestAgenda(File file) throws ParsingException, - SAXException, IOException { - // System.out.println("Building test agenda..."); - logger.info("Building test agenda..."); - testStrategyParser.parse(file); - // TODO: add step to connect parsed object to test objects and - // dependency graph - testStrategyParser.getErrorCollector().dump(logger); - testAgenda = testStrategyParser.getTestPlan(); - logger.info("Building test agenda... Done."); - return testAgenda; - } - - /** - * Gets the test agenda or the strategy object. - * @return - */ - public TestAgenda getTestAgenda() { - return testAgenda; - } - - /** - * Gets the test interpreter. - * @return - */ - public final Interpreter getInterpreter() { - - return interpreter; - } - - /** - * Gets the plugin manager - * @return - */ - public PluginManager getPluginManager() { - return pluginManager; - } - - /** - * Gets the digraph of tests. - * @return - */ - public final TestDigraph getTestDigraph() { - return digraph; - } - - /** - * Gets the command registry - * @return - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - - - /** - * Gets the script parser. - * @return - */ - public ScriptParser getScriptParser() { - return scriptParser; - } + private static AutomationEngine s_instance; + + public static final Logger logger = Logger + .getLogger(AutomationEngine.class); + public MessageCollector mc = new MessageCollector("Building model"); + private static final String FRAMEWORK_XML = "framework.xml"; + + // FIXME: Rewrite this parser + private final ScriptParser scriptParser; + private final CommandLibraryParser commandlibParser; + + // FIXME: And rewrite this one while you're at it :-D + private final TestStrategyParser testStrategyParser; + + private TestNamespace testRoot; + private Interpreter interpreter; + private PluginManager pluginManager; + private TestAgenda testAgenda; + private CommandRegistry commandRegistry; + + private TestDigraph digraph; + + private List postParseAllPlugins; + + private AutomationEngine() { + try { + InputStream fi = getFrameworkFile(); + GenericApplicationContext ctx = new GenericApplicationContext(); + + XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); + xmlReader + .setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); + + xmlReader.loadBeanDefinitions(new InputSource(fi)); + + ctx.refresh(); + + this.pluginManager = (PluginManager) ctx.getBean("PluginManager"); + + digraph = new TestDigraph( + new ClassBasedEdgeFactory(DiEdge.class)); + commandlibParser = new CommandLibraryParser(); + scriptParser = new ScriptParser(); + scriptParser.setDigraph(digraph); + commandlibParser + .setAutomationClassLoader(new DefaultAutomationClassLoader()); + testStrategyParser = new TestStrategyParser(); + testStrategyParser.setDigraph(digraph); + initPostParseStrategyElementPlugins(); + testRoot = null; + + this.interpreter = (Interpreter) ctx.getBean("Interpreter"); + + this.interpreter.setCommandRunnerPlugins(pluginManager + .getCommandRunnerPlugins()); + this.interpreter.setTestRunnerPlugins(pluginManager + .getTestRunnerPlugins()); + this.interpreter.setTearDownPlugins(pluginManager.getTearDownPlugins()); + + initPostParseAllPlugins(); + initPostParseSuitePlugins(); + initPostParseTestPlugins(); + + } catch (Exception e) { + // If something goes wrong here, we have a serious issue + logger.fatal(e); + throw new RuntimeException(e); + } + } + + private void initPostParseStrategyElementPlugins() { + List postParseStrategyElementPlugins = new ArrayList(); + postParseStrategyElementPlugins.add(new AutomationValuePlugin()); + postParseStrategyElementPlugins.add(new MaxThreadsPlugin()); + List postParseStrategyElementPluginsFromManager = pluginManager + .getPostParseStrategyElementPlugins(); + if (postParseStrategyElementPluginsFromManager != null) { + postParseStrategyElementPlugins + .addAll(postParseStrategyElementPluginsFromManager); + } + testStrategyParser + .setPostParseStrategyElementPlugins(postParseStrategyElementPlugins); + } + + private void initPostParseAllPlugins() { + postParseAllPlugins = new ArrayList(); + postParseAllPlugins.add(new DigraphPlugin()); + postParseAllPlugins.add(new TraceabilityMatrixPlugin()); + List postParseAllPluginsFromManager = pluginManager + .getPostParseAllPlugins(); + if (postParseAllPluginsFromManager != null) { + postParseAllPlugins.addAll(postParseAllPluginsFromManager); + } + postParseAllPlugins.add(new AutomationValueFilterPlugin()); + } + + private void initPostParseSuitePlugins() { + List postParseSuitePlugins = new ArrayList(); + postParseSuitePlugins.add(new SuiteDependenciesPlugin()); + postParseSuitePlugins.add(new SuiteExclusionsPlugin()); + List postParseSuitePluginsFromManager = pluginManager + .getPostParseSuitePlugins(); + if (postParseSuitePluginsFromManager != null) { + postParseSuitePlugins.addAll(postParseSuitePluginsFromManager); + } + scriptParser.setPostParseSuitePlugins(postParseSuitePlugins); + } + + private void initPostParseTestPlugins() { + List postParseTestPlugins = new ArrayList(); + postParseTestPlugins.add(new ExceptionPlugin()); + List postParseTestPluginsFromManager = pluginManager + .getPostParseTestPlugins(); + if (postParseTestPluginsFromManager != null) { + postParseTestPlugins.addAll(postParseTestPluginsFromManager); + } + scriptParser.setPostParseTestPlugins(postParseTestPlugins); + + List postParseSuitePlugins = new ArrayList(); + postParseSuitePlugins.add(new SuiteDependenciesPlugin()); + postParseSuitePlugins.add(new SuiteExclusionsPlugin()); + List postParseSuitePluginsFromManager = pluginManager + .getPostParseSuitePlugins(); + if (postParseSuitePluginsFromManager != null) { + postParseSuitePlugins.addAll(postParseSuitePluginsFromManager); + } + scriptParser.setPostParseSuitePlugins(postParseSuitePlugins); + } + + private static InputStream getFrameworkFile() { + InputStream is = AutomationEngine.class.getClassLoader() + .getResourceAsStream(FRAMEWORK_XML); + try { + if (is == null) { + is = new FileInputStream(new File(FRAMEWORK_XML)); + } + + } catch (IOException e) { + throw new RuntimeException("Could not load :" + FRAMEWORK_XML, e); + } + return is; + } + + /** + * Singleton accessor method. + * + * @return + */ + public static final AutomationEngine getInstance() { + if (AutomationEngine.s_instance == null) { + AutomationEngine.s_instance = new AutomationEngine(); + } + return AutomationEngine.s_instance; + } + + /** + * Gets the test root. + * + * @return + */ + public final TestNamespace getTestRoot() { + return testRoot; + } + + /** + * Builds test model from the specified test library folder and test scripts + * folder. By default it would also load the test libraries from the + * classpath. The test libraries are assumed to have extension + * *.commands.xml and expected to be under testlibrary folder/package + * + * @param librarySource + * @param testSource + */ + public final void buildModel(File librarySource, File testSource) { + System.out.println("Building model..."); + logger.info("Building model..."); + + boolean isFailed = false; + + try { + commandRegistry = new CommandRegistry(); + commandlibParser.parseCommandLibraries(commandRegistry, + librarySource, mc); + + } catch (Exception e) { + mc.error(e.getMessage()); + e.printStackTrace(); + isFailed = true; + } + + + interpreter.setCommandRegistry(commandRegistry); + scriptParser.setCommandRegistry(commandRegistry); + try { + testRoot = scriptParser.handleTestSource(testSource, mc); + + // build agenda + String fileLocation = JTAFPropertyManager.getInstance() + .getProperty("strategy"); + buildTestAgenda(new File(fileLocation)); + // run post all parsing plugins + + if (postParseAllPlugins != null) { + for (IPostParseAllPlugin p : postParseAllPlugins) { + p.execute(new PostAllParserPluginContext(testAgenda, + commandRegistry)); + } + } + } catch (Exception e) { + mc.error(e.getMessage()); + logger.error(e.getMessage()); + isFailed = true; + } + + if (isFailed) { + mc.dump(logger); + logger.fatal("Failed to build test model. See logs for details"); + throw new RuntimeException( + "Failed to build test model. See logs for details"); + } + + logger.info("Building model... Done"); + System.out.println("Building model... Done"); + + } + + private TestAgenda buildTestAgenda(File file) throws ParsingException, + SAXException, IOException { + // System.out.println("Building test agenda..."); + logger.info("Building test agenda..."); + testStrategyParser.parse(file); + // TODO: add step to connect parsed object to test objects and + // dependency graph + testStrategyParser.getErrorCollector().dump(logger); + testAgenda = testStrategyParser.getTestPlan(); + logger.info("Building test agenda... Done."); + return testAgenda; + } + + /** + * Gets the test agenda or the strategy object. + * + * @return + */ + public TestAgenda getTestAgenda() { + return testAgenda; + } + + /** + * Gets the test interpreter. + * + * @return + */ + public final Interpreter getInterpreter() { + + return interpreter; + } + + /** + * Gets the plugin manager + * + * @return + */ + public PluginManager getPluginManager() { + return pluginManager; + } + + /** + * Gets the digraph of tests. + * + * @return + */ + public final TestDigraph getTestDigraph() { + return digraph; + } + + /** + * Gets the command registry + * + * @return + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + + + /** + * Gets the script parser. + * + * @return + */ + public ScriptParser getScriptParser() { + return scriptParser; + } } diff --git a/src/main/java/org/finra/jtaf/core/CommandRegistry.java b/src/main/java/org/finra/jtaf/core/CommandRegistry.java index ca0a852..2ae3a25 100644 --- a/src/main/java/org/finra/jtaf/core/CommandRegistry.java +++ b/src/main/java/org/finra/jtaf/core/CommandRegistry.java @@ -25,42 +25,43 @@ * This class is for the commands registered in the *.commands.xml files in * testlibrary folder. It is a property of the Automation Engine. It saves * pair for each command. - * */ public class CommandRegistry { - private final Map invocationTargetMap; + private final Map invocationTargetMap; + + public CommandRegistry() { + this.invocationTargetMap = new HashMap(); + } - public CommandRegistry() { - this.invocationTargetMap = new HashMap(); - } - - - /** - * Registers the specified command/invocation target. - * @param name - * @param invocationTarget - */ - public void registerInvocationTarget(String name, InvocationTarget invocationTarget){ - this.invocationTargetMap.put(name, invocationTarget); - } + /** + * Registers the specified command/invocation target. + * + * @param name + * @param invocationTarget + */ + public void registerInvocationTarget(String name, InvocationTarget invocationTarget) { + this.invocationTargetMap.put(name, invocationTarget); + } - /** - * Returns true if the invocation target is present - * @param name - * @return - */ - public final boolean containsInvocationTarget(String name) { - return invocationTargetMap.containsKey(name.toLowerCase()); - } + /** + * Returns true if the invocation target is present + * + * @param name + * @return + */ + public final boolean containsInvocationTarget(String name) { + return invocationTargetMap.containsKey(name.toLowerCase()); + } - /** - * Gets the specified invocation target - * @param name - * @return - */ - public final InvocationTarget getInvocationTarget(String name) { - return invocationTargetMap.get(name.toLowerCase()); - } + /** + * Gets the specified invocation target + * + * @param name + * @return + */ + public final InvocationTarget getInvocationTarget(String name) { + return invocationTargetMap.get(name.toLowerCase()); + } } diff --git a/src/main/java/org/finra/jtaf/core/DefaultAutomationClassLoader.java b/src/main/java/org/finra/jtaf/core/DefaultAutomationClassLoader.java index c6a725d..d118bb8 100644 --- a/src/main/java/org/finra/jtaf/core/DefaultAutomationClassLoader.java +++ b/src/main/java/org/finra/jtaf/core/DefaultAutomationClassLoader.java @@ -19,25 +19,22 @@ /** * Implementation of the {@link IAutomationClassLoader} - * */ -public class DefaultAutomationClassLoader implements IAutomationClassLoader{ +public class DefaultAutomationClassLoader implements IAutomationClassLoader { + + /* (non-Javadoc) + * @see org.finra.jtaf.core.IAutomationClassLoader#loadClass(java.lang.String) + */ + @Override + public Class loadClass(String commandClass) throws ClassNotFoundException { - /* (non-Javadoc) - * @see org.finra.jtaf.core.IAutomationClassLoader#loadClass(java.lang.String) - */ - @Override - public Class loadClass(String commandClass) throws ClassNotFoundException { - - try{ - return Class.forName(commandClass); - } - catch(ClassNotFoundException e){ - throw new ClassNotFoundException("Unable to Load command class " + commandClass, e); - } - catch(NoClassDefFoundError e1){ - throw new NoClassDefFoundError("Unable to Load command class " + commandClass + "Exception "+ e1); - } - } + try { + return Class.forName(commandClass); + } catch (ClassNotFoundException e) { + throw new ClassNotFoundException("Unable to Load command class " + commandClass, e); + } catch (NoClassDefFoundError e1) { + throw new NoClassDefFoundError("Unable to Load command class " + commandClass + "Exception " + e1); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/IAutomationClassLoader.java b/src/main/java/org/finra/jtaf/core/IAutomationClassLoader.java index 2dceec6..704fa6e 100644 --- a/src/main/java/org/finra/jtaf/core/IAutomationClassLoader.java +++ b/src/main/java/org/finra/jtaf/core/IAutomationClassLoader.java @@ -21,13 +21,13 @@ */ public interface IAutomationClassLoader { - /** - * Returns the class object associated with the given classname - * @param commandClass - * => The class the object of which is needed - * @return - * @throws ClassNotFoundException - */ - Class loadClass(String commandClass) throws ClassNotFoundException; + /** + * Returns the class object associated with the given classname + * + * @param commandClass => The class the object of which is needed + * @return + * @throws ClassNotFoundException + */ + Class loadClass(String commandClass) throws ClassNotFoundException; } diff --git a/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java b/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java index bfacf1a..2ce54e0 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java +++ b/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java @@ -21,16 +21,16 @@ */ public class AssertionFailedError extends AssertionError { - private static final long serialVersionUID= 1L; + private static final long serialVersionUID = 1L; - public AssertionFailedError() { - } + public AssertionFailedError() { + } - public AssertionFailedError(String message) { - super(defaultString(message)); - } + public AssertionFailedError(String message) { + super(defaultString(message)); + } - private static String defaultString(String message) { - return message == null ? "" : message; - } + private static String defaultString(String message) { + return message == null ? "" : message; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java b/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java index 129cfdb..61cd8b4 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java +++ b/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java @@ -22,138 +22,143 @@ import org.apache.commons.lang.exception.ExceptionUtils; /** - * * This class can be used to collect errors. - * */ public class ErrorAccumulator { - private String name; - private ArrayList errors; - - // needed for ignore errors at script level: - boolean errorsThrown = false; - - /** - * Create a named error accumulator - * @param name - */ - public ErrorAccumulator(String name) { - this.name = name; - errors = new ArrayList(); - } - - - - /** - * Gets the name of the accumulator - * @return - */ - public String getName() { - return name; - } - - /** - * Gets the number of errors. - * @return - */ - public int getNumErrors() { - return errors.size(); - } - - /** - * Adds and Error to accumulate - * @param th - * @return - */ - public boolean addError(Throwable th) { - return errors.add(th); - } - - /** - * returns true if no errors - * @return - */ - public boolean isEmpty() { - return errors.isEmpty(); - } - - /** - * Returns error messages - * @return - */ - public String getErrorMessages() { - String errorInfo = ""; - - for (int i = 0; i < errors.size(); i++) { - errorInfo = errorInfo + "\n " + errors.get(i).getLocalizedMessage(); - } - - return errorInfo; - } - - /** - * Returns error stack traces - * @return - */ - public String getErrorStackTraces() { - String errorInfo = ""; - // TODO: use static access - // TODO: determine if this dependency is really necessary, do we need to - // depend on commons-lang to make stack trace printing easier? - for (int i = 0; i < errors.size(); i++) { - errorInfo = errorInfo + "\n " + ExceptionUtils.getStackTrace(errors.get(i)); - } - - return errorInfo; - } - - /** - * Returns list of stack trace elements - * @return - */ - public List getErrorStackTraceElementsList() { - List list = new ArrayList(); - ArrayList errors = getErrors(); - for (Throwable th : errors) { - list.add(th.getStackTrace()); - } - - return list; - } - - /** - * Throws accumulated errors - */ - public void throwErrors() { - AssertionFailedError e = getWrappedErrors(); - if (e != null) { - errorsThrown = true; - throw e; - } - } - - public boolean hasThrown() { - return errorsThrown; - } - - public ArrayList getErrors() { - return errors; - } - - public AssertionFailedError getWrappedErrors() { - - if (isEmpty()) - return null; - - String message = getErrorStackTraces(); - - if (message.equals("")) - return null; - - return new AssertionFailedError( - "Error accumulator found and ignored the following errors in " - + getName() + ":" + message); - - } + private String name; + private ArrayList errors; + + // needed for ignore errors at script level: + boolean errorsThrown = false; + + /** + * Create a named error accumulator + * + * @param name + */ + public ErrorAccumulator(String name) { + this.name = name; + errors = new ArrayList(); + } + + + /** + * Gets the name of the accumulator + * + * @return + */ + public String getName() { + return name; + } + + /** + * Gets the number of errors. + * + * @return + */ + public int getNumErrors() { + return errors.size(); + } + + /** + * Adds and Error to accumulate + * + * @param th + * @return + */ + public boolean addError(Throwable th) { + return errors.add(th); + } + + /** + * returns true if no errors + * + * @return + */ + public boolean isEmpty() { + return errors.isEmpty(); + } + + /** + * Returns error messages + * + * @return + */ + public String getErrorMessages() { + String errorInfo = ""; + + for (int i = 0; i < errors.size(); i++) { + errorInfo = errorInfo + "\n " + errors.get(i).getLocalizedMessage(); + } + + return errorInfo; + } + + /** + * Returns error stack traces + * + * @return + */ + public String getErrorStackTraces() { + String errorInfo = ""; + // TODO: use static access + // TODO: determine if this dependency is really necessary, do we need to + // depend on commons-lang to make stack trace printing easier? + for (int i = 0; i < errors.size(); i++) { + errorInfo = errorInfo + "\n " + ExceptionUtils.getStackTrace(errors.get(i)); + } + + return errorInfo; + } + + /** + * Returns list of stack trace elements + * + * @return + */ + public List getErrorStackTraceElementsList() { + List list = new ArrayList(); + ArrayList errors = getErrors(); + for (Throwable th : errors) { + list.add(th.getStackTrace()); + } + + return list; + } + + /** + * Throws accumulated errors + */ + public void throwErrors() { + AssertionFailedError e = getWrappedErrors(); + if (e != null) { + errorsThrown = true; + throw e; + } + } + + public boolean hasThrown() { + return errorsThrown; + } + + public ArrayList getErrors() { + return errors; + } + + public AssertionFailedError getWrappedErrors() { + + if (isEmpty()) + return null; + + String message = getErrorStackTraces(); + + if (message.equals("")) + return null; + + return new AssertionFailedError( + "Error accumulator found and ignored the following errors in " + + getName() + ":" + message); + + } } diff --git a/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java b/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java index 7d89ce6..7e48b75 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java +++ b/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java @@ -22,7 +22,6 @@ * This class is mainly a wrapper for Junits Assert class. Instead of * immediately throwing an error, the error is stored in an ErrorAccumulator to * be thrown when needed. - * */ public class IgnoreErrorsAssert { @@ -30,9 +29,8 @@ public class IgnoreErrorsAssert { /** * Called to instantiate this class - * - * @param ea - * the ErrorAccumulator to be used to collect all exceptions + * + * @param ea the ErrorAccumulator to be used to collect all exceptions */ public IgnoreErrorsAssert(ErrorAccumulator ea) { this.ea = ea; @@ -41,11 +39,9 @@ public IgnoreErrorsAssert(ErrorAccumulator ea) { /** * Asserts that a condition is true. If it isn't, it stores a Throwable in * the accumulator with the given message. - * - * @param message - * message to be thrown if condition is false - * @param condition - * the condition to be evaluated + * + * @param message message to be thrown if condition is false + * @param condition the condition to be evaluated */ @SuppressWarnings("deprecation") public void assertTrue(String message, boolean condition) { @@ -59,9 +55,8 @@ public void assertTrue(String message, boolean condition) { /** * Asserts that a condition is true. If it isn't, it stores a Throwable in * the accumulator. - * - * @param condition - * the condition to be evaluated + * + * @param condition the condition to be evaluated */ @SuppressWarnings("deprecation") public void assertTrue(boolean condition) { @@ -75,12 +70,9 @@ public void assertTrue(boolean condition) { /** * Asserts that a condition is false. If it isn't, it stores a Throwable in * the accumulator with the given message. - * - * @param message - * message to be thrown if condition is true - * - * @param condition - * the condition to be evaluated + * + * @param message message to be thrown if condition is true + * @param condition the condition to be evaluated */ @SuppressWarnings("deprecation") public void assertFalse(String message, boolean condition) { @@ -94,9 +86,8 @@ public void assertFalse(String message, boolean condition) { /** * Asserts that a condition is false. If it isn't, it stores a Throwable in * the accumulator. - * - * @param condition - * the condition to be evaluated + * + * @param condition the condition to be evaluated */ @SuppressWarnings("deprecation") public void assertFalse(boolean condition) { @@ -110,9 +101,8 @@ public void assertFalse(boolean condition) { /** * Fails a test with a Throwable being stored in the accumulator with the * given message. - * - * @param message - * message to be thrown + * + * @param message message to be thrown */ @SuppressWarnings("deprecation") public void fail(String message) { @@ -139,13 +129,10 @@ public void fail() { /** * Asserts that two objects are equal. If they are not, a Throwable is * stored in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") @@ -160,11 +147,9 @@ public void assertEquals(String message, Object expected, Object actual) { /** * Asserts that two objects are equal. If they are not an Throwable is * stored in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(Object expected, Object actual) { @@ -178,13 +163,10 @@ public void assertEquals(Object expected, Object actual) { /** * Asserts that two Strings are equal. If they are not, a Throwable is * stored in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, String expected, String actual) { @@ -198,11 +180,9 @@ public void assertEquals(String message, String expected, String actual) { /** * Asserts that two Strings are equal. If they are not, a Throwable is * stored in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String expected, String actual) { @@ -217,15 +197,11 @@ public void assertEquals(String expected, String actual) { * Asserts that two doubles are equal concerning a delta. If they are not, a * Throwable is stored in the accumulator with the given message. If the * expected value is infinity then the delta value is ignored. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked - * @param delta - * the difference allowed between the two values + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values */ @SuppressWarnings("deprecation") public void assertEquals(String message, double expected, double actual, double delta) { @@ -240,13 +216,10 @@ public void assertEquals(String message, double expected, double actual, double * Asserts that two doubles are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. If they are not, a * Throwable is stored in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked - * @param delta - * the difference allowed between the two values + * + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values */ @SuppressWarnings("deprecation") public void assertEquals(double expected, double actual, double delta) { @@ -261,15 +234,11 @@ public void assertEquals(double expected, double actual, double delta) { * Asserts that two floats are equal concerning a positive delta. If they * are not, a Throwable is stored in the accumulator with the given message. * If the expected value is infinity then the delta value is ignored. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked - * @param delta - * the difference allowed between the two values + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values */ @SuppressWarnings("deprecation") public void assertEquals(String message, float expected, float actual, float delta) { @@ -284,13 +253,10 @@ public void assertEquals(String message, float expected, float actual, float del * Asserts that two floats are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. If they are not, a * Throwable is stored in the accumulator - * - * @param expected - * expected value - * @param actual - * actual value that is being checked - * @param delta - * the difference allowed between the two values + * + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values */ @SuppressWarnings("deprecation") public void assertEquals(float expected, float actual, float delta) { @@ -305,13 +271,10 @@ public void assertEquals(float expected, float actual, float delta) { * Asserts that two longs are equal. If they are not, a Throwable is stored * in the accumulator with the given message. If they are not, a Throwable * is stored in the accumulator - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, long expected, long actual) { @@ -326,11 +289,9 @@ public void assertEquals(String message, long expected, long actual) { * Asserts that two longs are equal. If they are not, a Throwable is stored * in the accumulator. If they are not, a Throwable is stored in the * accumulator - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(long expected, long actual) { @@ -344,13 +305,10 @@ public void assertEquals(long expected, long actual) { /** * Asserts that two booleans are equal. If they are not, a Throwable is * stored in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, boolean expected, boolean actual) { @@ -364,11 +322,9 @@ public void assertEquals(String message, boolean expected, boolean actual) { /** * Asserts that two booleans are equal. If they are not, a Throwable is * stored in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(boolean expected, boolean actual) { @@ -382,13 +338,10 @@ public void assertEquals(boolean expected, boolean actual) { /** * Asserts that two bytes are equal. If they are not an Throwable is thrown * with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, byte expected, byte actual) { @@ -402,11 +355,9 @@ public void assertEquals(String message, byte expected, byte actual) { /** * Asserts that two bytes are equal. If they are not, a Throwable is stored * in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(byte expected, byte actual) { @@ -420,13 +371,10 @@ public void assertEquals(byte expected, byte actual) { /** * Asserts that two chars are equal. If they are not, a Throwable is stored * in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, char expected, char actual) { @@ -440,11 +388,9 @@ public void assertEquals(String message, char expected, char actual) { /** * Asserts that two chars are equal. If they are not, a Throwable is stored * in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(char expected, char actual) { @@ -458,13 +404,10 @@ public void assertEquals(char expected, char actual) { /** * Asserts that two shorts are equal. If they are not, a Throwable is stored * in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked **/ @SuppressWarnings("deprecation") public void assertEquals(String message, short expected, short actual) { @@ -478,11 +421,9 @@ public void assertEquals(String message, short expected, short actual) { /** * Asserts that two shorts are equal. If they are not, a Throwable is stored * in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(short expected, short actual) { @@ -496,13 +437,10 @@ public void assertEquals(short expected, short actual) { /** * Asserts that two ints are equal. If they are not, a Throwable is stored * in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(String message, int expected, int actual) { @@ -516,11 +454,9 @@ public void assertEquals(String message, int expected, int actual) { /** * Asserts that two ints are equal. If they are not, a Throwable is stored * in the accumulator. - * - * @param expected - * expected value - * @param actual - * actual value that is being checked + * + * @param expected expected value + * @param actual actual value that is being checked */ @SuppressWarnings("deprecation") public void assertEquals(int expected, int actual) { @@ -534,9 +470,8 @@ public void assertEquals(int expected, int actual) { /** * Asserts that an object isn't null. If they are not, a Throwable is stored * in the accumulator. - * - * @param object - * object to be checked to see if it is null or not + * + * @param object object to be checked to see if it is null or not */ @SuppressWarnings("deprecation") public void assertNotNull(Object object) { @@ -550,11 +485,9 @@ public void assertNotNull(Object object) { /** * Asserts that an object isn't null. If they are not, a Throwable is stored * in the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param object - * object to be checked to see if it is null or not + * + * @param message message to be thrown if not equal + * @param object object to be checked to see if it is null or not */ @SuppressWarnings("deprecation") public void assertNotNull(String message, Object object) { @@ -568,9 +501,8 @@ public void assertNotNull(String message, Object object) { /** * Asserts that an object is null. If they are not, a Throwable is stored in * the accumulator. - * - * @param object - * Object to check to see if it is null + * + * @param object Object to check to see if it is null */ @SuppressWarnings("deprecation") public void assertNull(Object object) { @@ -584,11 +516,9 @@ public void assertNull(Object object) { /** * Asserts that an object is null. If they are not, a Throwable is stored in * the accumulator with the given message. - * - * @param message - * message to be thrown if not equal - * @param object - * object to be checked to see if it is null or not + * + * @param message message to be thrown if not equal + * @param object object to be checked to see if it is null or not */ @SuppressWarnings("deprecation") public void assertNull(String message, Object object) { @@ -602,13 +532,10 @@ public void assertNull(String message, Object object) { /** * Asserts that two objects refer to the same object. If they are not, a * Throwable is stored in the accumulator with the given message. - * - * @param message - * message to be thrown if not the same - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param message message to be thrown if not the same + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void assertSame(String message, Object expected, Object actual) { @@ -622,11 +549,9 @@ public void assertSame(String message, Object expected, Object actual) { /** * Asserts that two objects refer to the same object. If they are not, a * Throwable is stored in the accumulator. - * - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void assertSame(Object expected, Object actual) { @@ -640,13 +565,10 @@ public void assertSame(Object expected, Object actual) { /** * Asserts that two objects do not refer to the same object. If they are * not, a Throwable is stored in the accumulator with the given message. - * - * @param message - * message to be thrown if they are the same - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void assertNotSame(String message, Object expected, Object actual) { @@ -661,11 +583,9 @@ public void assertNotSame(String message, Object expected, Object actual) { /** * Asserts that two objects do not refer to the same object. If they are * not, a Throwable is stored in the accumulator. - * - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void assertNotSame(Object expected, Object actual) { @@ -679,9 +599,8 @@ public void assertNotSame(Object expected, Object actual) { /** * Asserts that two objects do refer to the same object. If they are not, a * Throwable is stored in the accumulator with the given message. - * - * @param message - * message to be thrown if they are the same + * + * @param message message to be thrown if they are the same */ @SuppressWarnings("deprecation") public void failSame(String message) { @@ -695,13 +614,10 @@ public void failSame(String message) { /** * Calls the Assert classes failNotSame method which creates an exception * using the given message and object - * - * @param message - * message to be thrown if they are the same - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void failNotSame(String message, Object expected, Object actual) { @@ -716,13 +632,10 @@ public void failNotSame(String message, Object expected, Object actual) { /** * Calls the Assert classes failNotEquals method which creates an exception * using the given message and objects - * - * @param message - * message to be thrown if they are the same - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public void failNotEquals(String message, Object expected, Object actual) { @@ -736,13 +649,10 @@ public void failNotEquals(String message, Object expected, Object actual) { /** * Calls the Assert classes format method which creates a formatted string * using the given message and objects to be used for an exception - * - * @param message - * message to be thrown if they are the same - * @param expected - * expected object - * @param actual - * actual object that is being checked + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked */ @SuppressWarnings("deprecation") public String format(String message, Object expected, Object actual) { @@ -759,7 +669,7 @@ public void endOfCommand() { /** * Used to check if there are any recorded errors. - * + * * @return returns the errors that have been recorded. */ public String checkErrors() { diff --git a/src/main/java/org/finra/jtaf/core/commands/Block.java b/src/main/java/org/finra/jtaf/core/commands/Block.java index a3f6c7b..f2237f0 100644 --- a/src/main/java/org/finra/jtaf/core/commands/Block.java +++ b/src/main/java/org/finra/jtaf/core/commands/Block.java @@ -27,7 +27,6 @@ /** * This is a collection of commands that are to be executed. - * */ public class Block extends Command { @@ -36,9 +35,8 @@ public class Block extends Command { * interpreter.The recordResult variable is set to false because details * about the Block step aren't needed, unlike the commands within the * Block block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ public Block(String name) throws NameFormatException { @@ -49,12 +47,9 @@ public Block(String name) throws NameFormatException { /** * This goes through all commands in the context and executes them. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the Block. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within the Block. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/ExpectFailure.java b/src/main/java/org/finra/jtaf/core/commands/ExpectFailure.java index 7d19b86..c9fa369 100644 --- a/src/main/java/org/finra/jtaf/core/commands/ExpectFailure.java +++ b/src/main/java/org/finra/jtaf/core/commands/ExpectFailure.java @@ -29,7 +29,6 @@ * to throw an exception. If one of them throws an exception, no more commands * from the block are executed and the remainder of the script is run through. * If no exception is thrown, an ExpectedFailureException to signify this. - * */ public class ExpectFailure extends Command { @@ -38,9 +37,8 @@ public class ExpectFailure extends Command { * interpreter. The recordResult variable is set to false because details * about the ExpectFailure step aren't needed, unlike the commands within * the ExpectFailure block. - * - * @param name - * - The name of the command + * + * @param name - The name of the command * @throws NameFormatException */ public ExpectFailure(String name) throws NameFormatException { @@ -58,12 +56,10 @@ public ExpectFailure(String name) throws NameFormatException { * exception is an ExpectedFailureException, it is thrown and if no * exception is encountered when executing the block, a new * ExpectedFailureException is thrown. - * - * @param ctx - * - The current context when this method is executed. - * @throws Throwable - * - Either a ExpectedFailureException or the exception thrown - * by a command in the block + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Either a ExpectedFailureException or the exception thrown + * by a command in the block */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/FailHere.java b/src/main/java/org/finra/jtaf/core/commands/FailHere.java index 01b4e09..9c3817a 100644 --- a/src/main/java/org/finra/jtaf/core/commands/FailHere.java +++ b/src/main/java/org/finra/jtaf/core/commands/FailHere.java @@ -24,16 +24,14 @@ /** * This command is used to force a failure. This is mainly used for testing * other commands to make sure that they work correctly. - * */ public class FailHere extends Command { /** * This called when instantiating the command before it is executed by the * interpreter - * - * @param name - * - The name of the command + * + * @param name - The name of the command * @throws NameFormatException */ public FailHere(String name) throws NameFormatException { @@ -43,11 +41,9 @@ public FailHere(String name) throws NameFormatException { /** * This method throws an AssertionFailedException to force a failure. - * - * @param ctx - * - The current context when this method is executed. - * @throws Throwable - * - The AssertionFailedException + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - The AssertionFailedException */ @Override protected void execute(IInvocationContext ctx) throws Throwable { diff --git a/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java b/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java index b5aded9..dedd6a2 100644 --- a/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java +++ b/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java @@ -27,7 +27,6 @@ * This command surrounds a block of commands to be executed. If one of them * throws an exception, it is stored to be reported at the end of the test and * any commands after this block are then executed. - * */ public class IgnoreErrors extends Command { @@ -36,9 +35,8 @@ public class IgnoreErrors extends Command { * interpreter. The recordResult variable is set to false because details * about the IgnoreErrors step aren't needed, unlike the commands within the * IgnoreErrors block. - * - * @param name - * - The name of the command + * + * @param name - The name of the command * @throws NameFormatException */ public IgnoreErrors(String name) throws NameFormatException { @@ -52,9 +50,8 @@ public IgnoreErrors(String name) throws NameFormatException { * block and executes them until they have all been executed or an exception * has been thrown. If an exception is thrown, it is stored in the * ErrorAccumulator to be reported at the end of the test. - * - * @param ctx - * - The current context when this method is executed. + * + * @param ctx - The current context when this method is executed. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/Invoke.java b/src/main/java/org/finra/jtaf/core/commands/Invoke.java index b8c8e55..104deaa 100644 --- a/src/main/java/org/finra/jtaf/core/commands/Invoke.java +++ b/src/main/java/org/finra/jtaf/core/commands/Invoke.java @@ -28,7 +28,6 @@ /** * This class allows functions to invoke blocks of code. It gives some degree of * functional programming within a test script. - * */ public class Invoke extends Command { @@ -37,9 +36,8 @@ public class Invoke extends Command { * interpreter.The recordResult variable is set to false because details * about the Invoke step aren't needed, unlike the commands within the * Invoke block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ public Invoke(String name) throws NameFormatException { @@ -51,12 +49,9 @@ public Invoke(String name) throws NameFormatException { /** * This goes through all commands in the context and executes the block that * has the same name. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the Repeat block. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within the Repeat block. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/Multipath.java b/src/main/java/org/finra/jtaf/core/commands/Multipath.java index c9083c8..fdf957c 100644 --- a/src/main/java/org/finra/jtaf/core/commands/Multipath.java +++ b/src/main/java/org/finra/jtaf/core/commands/Multipath.java @@ -29,11 +29,9 @@ * Used to specify control paths that have the same end result. This allows * testers to write their scripts at a higher level of abstraction rather than * paying attention to an explicit set of actions that need to be performed. - * + *

* TODO: Add an optional weight to each of the paths. This will cause certain * paths to be executed w/ a higher probability. - * - * */ public class Multipath extends Command { @@ -42,7 +40,7 @@ public class Multipath extends Command { * interpreter.The recordResult variable is set to false because details * about the Multipath step aren't needed, unlike the commands within the * Multipath block. - * + * * @param name - name of the command * @throws NameFormatException */ @@ -55,12 +53,9 @@ public Multipath(String name) throws NameFormatException { /** * This randomly picks a path and executes all commands in the block. For * this command, 'Path' is a named Block command. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the Repeat block. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within the Repeat block. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/RandomGenerator.java b/src/main/java/org/finra/jtaf/core/commands/RandomGenerator.java index 595fa9d..3384284 100644 --- a/src/main/java/org/finra/jtaf/core/commands/RandomGenerator.java +++ b/src/main/java/org/finra/jtaf/core/commands/RandomGenerator.java @@ -36,304 +36,292 @@ /** * This class is used to generate a random string, phone number, regex, US * state, or US state abbreviation. - * */ public class RandomGenerator extends Command { - static Logger logger = Logger.getLogger(RandomGenerator.class.getPackage().getName()); + static Logger logger = Logger.getLogger(RandomGenerator.class.getPackage().getName()); - /** + /** * This called when instantiating the command before it is executed by the * interpreter.The recordResult variable is set to false because details * about the RandomGenerator step aren't needed, unlike the commands within * the RandomGenerator block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ - public RandomGenerator(String name) throws NameFormatException { - super(name); - } + public RandomGenerator(String name) throws NameFormatException { + super(name); + } - final static public List abbrevUSState = new ArrayList(Arrays.asList("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", - "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); - final static public List USState = new ArrayList(Arrays.asList("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", - "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", - "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", - "Wisconsin", "Wyoming")); - public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; + final static public List abbrevUSState = new ArrayList(Arrays.asList("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", + "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); + final static public List USState = new ArrayList(Arrays.asList("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", + "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", + "Wisconsin", "Wyoming")); + public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; - /** + /** * Use a regular expression to generate a string or use methods to select US * state name or abbreviations and generate phone numbers and strings. - * - * @param method - * - the method to be used. Either abbrevUSState, USState, phone, - * number, or string - * @param length - * - length of number or string to be generated. lengthMin, - * lengthMax, min, and max should not be specified when using - * this parameter. - * @param lengthMin - * - used to specify minimum length of random string generated - * @param lengthMax - * - used to specify maximum length of random string generated - * @param min - * - used to specify minimum length of random number generated - * @param max - * - used to specify maximum length of random number generated - * @param regexp - * - regular expression to be used for string generation. This - * should not be specified if method parameter is. + * + * @param method - the method to be used. Either abbrevUSState, USState, phone, + * number, or string + * @param length - length of number or string to be generated. lengthMin, + * lengthMax, min, and max should not be specified when using + * this parameter. + * @param lengthMin - used to specify minimum length of random string generated + * @param lengthMax - used to specify maximum length of random string generated + * @param min - used to specify minimum length of random number generated + * @param max - used to specify maximum length of random number generated + * @param regexp - regular expression to be used for string generation. This + * should not be specified if method parameter is. * @return the randomly generated string */ - public static String generate(String method, String length, String lengthMin, String lengthMax, String min, String max, String regexp) { - String valueGenerated = null; + public static String generate(String method, String length, String lengthMin, String lengthMax, String min, String max, String regexp) { + String valueGenerated = null; - if (regexp != null && !regexp.equalsIgnoreCase("")) { - if (method != null && !method.equalsIgnoreCase("")) { - logger.fatal("Oops! Specified 'method' ('" + method + "') and 'regexp' ('" + regexp + "') simulteneously. Use only one of it, please. Will use 'regexp' here..."); - } - valueGenerated = generateRegexp(regexp); - } else { - if (method != null && !method.equalsIgnoreCase("")) { - if (method.equalsIgnoreCase("abbrevUSState")) { - valueGenerated = generateAbbrevUSState(); - } else if (method.equalsIgnoreCase("USState")) { - valueGenerated = generateUSState(); - } else if (method.equalsIgnoreCase("phone")) { - valueGenerated = generatePhone(); - } else if (method.equalsIgnoreCase("number")) { - // verify input parameters - if ((length != null && !length.equalsIgnoreCase("")) && (min != null && !min.equalsIgnoreCase("")) && (max != null && !max.equalsIgnoreCase(""))) { - logger.fatal("Oops! Specified 'length', 'min' and 'max' parameters... You can use 'length' or 'max + min' only. Fix your test script, please! Will use 'length' here only..."); - min = null; - max = null; - } - if (((min != null && !min.equalsIgnoreCase("")) && (max == null)) || ((min == null) && (max != null && !max.equalsIgnoreCase("")))) { - logger.fatal("Oops! Specified only one of 'min', 'max' parameters... You have specify 'max' and 'min' both. Fix your test script, please! Will use default 'length' here..."); - min = null; - max = null; - } - if ((length == null || length.equalsIgnoreCase("")) && (min == null || min.equalsIgnoreCase("")) && (max == null || max.equalsIgnoreCase(""))) { - length = "5"; - } + if (regexp != null && !regexp.equalsIgnoreCase("")) { + if (method != null && !method.equalsIgnoreCase("")) { + logger.fatal("Oops! Specified 'method' ('" + method + "') and 'regexp' ('" + regexp + "') simulteneously. Use only one of it, please. Will use 'regexp' here..."); + } + valueGenerated = generateRegexp(regexp); + } else { + if (method != null && !method.equalsIgnoreCase("")) { + if (method.equalsIgnoreCase("abbrevUSState")) { + valueGenerated = generateAbbrevUSState(); + } else if (method.equalsIgnoreCase("USState")) { + valueGenerated = generateUSState(); + } else if (method.equalsIgnoreCase("phone")) { + valueGenerated = generatePhone(); + } else if (method.equalsIgnoreCase("number")) { + // verify input parameters + if ((length != null && !length.equalsIgnoreCase("")) && (min != null && !min.equalsIgnoreCase("")) && (max != null && !max.equalsIgnoreCase(""))) { + logger.fatal("Oops! Specified 'length', 'min' and 'max' parameters... You can use 'length' or 'max + min' only. Fix your test script, please! Will use 'length' here only..."); + min = null; + max = null; + } + if (((min != null && !min.equalsIgnoreCase("")) && (max == null)) || ((min == null) && (max != null && !max.equalsIgnoreCase("")))) { + logger.fatal("Oops! Specified only one of 'min', 'max' parameters... You have specify 'max' and 'min' both. Fix your test script, please! Will use default 'length' here..."); + min = null; + max = null; + } + if ((length == null || length.equalsIgnoreCase("")) && (min == null || min.equalsIgnoreCase("")) && (max == null || max.equalsIgnoreCase(""))) { + length = "5"; + } - try { - int maxInt = Integer.valueOf(max); - int minInt = Integer.valueOf(min); - valueGenerated = String.valueOf(minInt + (int) (Math.random() * (maxInt - minInt))); - } catch (Exception e) { - Generex generex = new Generex("[0-9]{" + length + "}"); - valueGenerated = generex.random(); - } - } else if (method.equalsIgnoreCase("string")) { - // verify input parameters - if ((length != null && !length.equalsIgnoreCase("")) && (lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))) { - logger.fatal("Oops! Specified 'length', 'lengthMin' and 'lengthMax' parameters... You can use 'length' or 'lengthMax + lengthMin' only. Fix your test script, please! Will use 'length' here only..."); - lengthMin = null; - lengthMax = null; - } - if (length == null && (((lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax == null)) || ((lengthMin == null) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))))) { - logger.fatal("Oops! Specified only one of 'lengthMin', 'lengthMax' parameters... You have specify 'lengthMax' and 'lengthMin' both. Fix your test script, please! Will use default 'length' here..."); - lengthMin = null; - lengthMax = null; - } + try { + int maxInt = Integer.valueOf(max); + int minInt = Integer.valueOf(min); + valueGenerated = String.valueOf(minInt + (int) (Math.random() * (maxInt - minInt))); + } catch (Exception e) { + Generex generex = new Generex("[0-9]{" + length + "}"); + valueGenerated = generex.random(); + } + } else if (method.equalsIgnoreCase("string")) { + // verify input parameters + if ((length != null && !length.equalsIgnoreCase("")) && (lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))) { + logger.fatal("Oops! Specified 'length', 'lengthMin' and 'lengthMax' parameters... You can use 'length' or 'lengthMax + lengthMin' only. Fix your test script, please! Will use 'length' here only..."); + lengthMin = null; + lengthMax = null; + } + if (length == null && (((lengthMin != null && !lengthMin.equalsIgnoreCase("")) && (lengthMax == null)) || ((lengthMin == null) && (lengthMax != null && !lengthMax.equalsIgnoreCase(""))))) { + logger.fatal("Oops! Specified only one of 'lengthMin', 'lengthMax' parameters... You have specify 'lengthMax' and 'lengthMin' both. Fix your test script, please! Will use default 'length' here..."); + lengthMin = null; + lengthMax = null; + } - int lengthInt = 5; - try { - int lengthMinInt = Integer.valueOf(lengthMin); - int lengthMaxInt = Integer.valueOf(lengthMax); - lengthInt = lengthMinInt + (int) (Math.random() * (lengthMaxInt - lengthMinInt)); - } catch (Exception e) { - try { - lengthInt = Integer.valueOf(length); - } catch (Exception e2) { - } - } + int lengthInt = 5; + try { + int lengthMinInt = Integer.valueOf(lengthMin); + int lengthMaxInt = Integer.valueOf(lengthMax); + lengthInt = lengthMinInt + (int) (Math.random() * (lengthMaxInt - lengthMinInt)); + } catch (Exception e) { + try { + lengthInt = Integer.valueOf(length); + } catch (Exception e2) { + } + } - valueGenerated = generateString(charsForRandomString, lengthInt); - } - } - } - return valueGenerated; - } + valueGenerated = generateString(charsForRandomString, lengthInt); + } + } + } + return valueGenerated; + } - /** + /** * Generate a string using a specified regular expression. - * - * @param regexp - * - regular expression to be used to generate the string + * + * @param regexp - regular expression to be used to generate the string * @return the randomly generated string */ - public static String generateRegexp(String regexp) { - Generex generex = new Generex(regexp); - return generex.random(); - } + public static String generateRegexp(String regexp) { + Generex generex = new Generex(regexp); + return generex.random(); + } - /** + /** * Generates a random phone number. - * + * * @return the randomly generated phone number. */ - public static String generatePhone() { - Generex generex = new Generex("[0-9]{10}"); - return generex.random(); - } + public static String generatePhone() { + Generex generex = new Generex("[0-9]{10}"); + return generex.random(); + } - /** + /** * Randomly selects a US state abbreviation from the list. - * + * * @return the randomly selected state abbreviation */ - public static String generateAbbrevUSState() { - return abbrevUSState.get((new Random()).nextInt(abbrevUSState.size())); - } + public static String generateAbbrevUSState() { + return abbrevUSState.get((new Random()).nextInt(abbrevUSState.size())); + } - /** + /** * Randomly selects a US state from the list. - * + * * @return the randomly selected state */ - public static String generateUSState() { - return USState.get((new Random()).nextInt(USState.size())); - } + public static String generateUSState() { + return USState.get((new Random()).nextInt(USState.size())); + } - /** + /** * This randomly generates a string given a set of characters and a desired * length. - * - * @param chars - * - The characters to be used - * @param length - * - The length of the resulting string + * + * @param chars - The characters to be used + * @param length - The length of the resulting string * @return The generated string */ - public static String generateString(String chars, int length) { - Generex generex = new Generex("[" + chars + "]{" + length + "}"); - return generex.random(); - } + public static String generateString(String chars, int length) { + Generex generex = new Generex("[" + chars + "]{" + length + "}"); + return generex.random(); + } + + @SuppressWarnings("unchecked") + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + recordResult = true; + String name = getOptionalString("name"); + String method = getOptionalString("method"); + String length = getOptionalString("length"); + String lengthMin = getOptionalString("lengthMin"); + String lengthMax = getOptionalString("lengthMax"); + String min = getOptionalString("min"); + String max = getOptionalString("max"); + String regexp = getOptionalString("regexp"); + String saveToGlobalContextAs = getOptionalString("saveToGlobalContextAs"); + + // process simple case + + String randomValue = generate(method, length, lengthMin, lengthMax, min, max, regexp); + + if (randomValue != null) { + ctx.putObject(name, randomValue); + if (saveToGlobalContextAs != null) { + Command.putToGlobalContext(saveToGlobalContextAs, randomValue); + } + logger.info("Generated new value: " + name + "='" + randomValue + "' (" + method + ", " + length + ", " + lengthMin + ", " + lengthMax + ", " + min + ", " + max + ", " + regexp + ", " + saveToGlobalContextAs + ")"); + + } + + // process List + Map allObjects = ctx.getAllObjects(); + Map newObjects = new HashMap(); + for (String key : allObjects.keySet()) { + Object obj = allObjects.get(key); - @SuppressWarnings("unchecked") - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - recordResult = true; - String name = getOptionalString("name"); - String method = getOptionalString("method"); - String length = getOptionalString("length"); - String lengthMin = getOptionalString("lengthMin"); - String lengthMax = getOptionalString("lengthMax"); - String min = getOptionalString("min"); - String max = getOptionalString("max"); - String regexp = getOptionalString("regexp"); - String saveToGlobalContextAs = getOptionalString("saveToGlobalContextAs"); + if (obj.getClass().equals(ArrayList.class)) { + ArrayList ar = (ArrayList) obj; + ArrayList arNew = new ArrayList(); + Iterator listIterator = ar.iterator(); - // process simple case - - String randomValue = generate(method, length, lengthMin, lengthMax, min, max, regexp); - - if (randomValue != null) { - ctx.putObject(name, randomValue); - if (saveToGlobalContextAs != null) { - Command.putToGlobalContext(saveToGlobalContextAs, randomValue); - } - logger.info("Generated new value: " + name + "='" + randomValue + "' (" + method + ", " + length + ", " + lengthMin + ", " + lengthMax + ", " + min + ", " + max + ", " + regexp + ", " + saveToGlobalContextAs + ")"); + while (listIterator.hasNext()) { + Object value = listIterator.next(); + if (value.getClass().equals(AttributeHelper.class)) { + AttributeHelper ah = (AttributeHelper) value; + if (ah.containsKey("method")) { + method = ah.getOptionalString("method"); + } + if (ah.containsKey("length")) { + length = ah.getOptionalString("length"); + } + if (ah.containsKey("lengthMin")) { + lengthMin = ah.getOptionalString("lengthMin"); + } + if (ah.containsKey("lengthMax")) { + lengthMax = ah.getOptionalString("lengthMax"); + } + if (ah.containsKey("min")) { + min = ah.getOptionalString("min"); + } + if (ah.containsKey("max")) { + max = ah.getOptionalString("max"); + } + if (ah.containsKey("regexp")) { + regexp = ah.getOptionalString("regexp"); + } + arNew.add(generate(method, length, lengthMin, lengthMax, min, max, regexp)); + } else { + arNew.add(value); + } + } + newObjects.put(key, arNew); + ctx.putObject(key, arNew); - } + if (saveToGlobalContextAs != null) { + Command.putToGlobalContext(saveToGlobalContextAs, arNew); + } + } else if (obj.getClass().equals(HashMap.class)) { + Map ar = (Map) obj; + Map arNew = new HashMap(); + for (String key2 : ar.keySet()) { + Object value = ar.get(key2); + if (value.getClass().equals(AttributeHelper.class)) { + AttributeHelper ah = (AttributeHelper) value; + if (ah.containsKey("method")) { + method = ah.getOptionalString("method"); + } + if (ah.containsKey("length")) { + length = ah.getOptionalString("length"); + } + if (ah.containsKey("lengthMin")) { + lengthMin = ah.getOptionalString("lengthMin"); + } + if (ah.containsKey("lengthMax")) { + lengthMax = ah.getOptionalString("lengthMax"); + } + if (ah.containsKey("min")) { + min = ah.getOptionalString("min"); + } + if (ah.containsKey("max")) { + max = ah.getOptionalString("max"); + } + if (ah.containsKey("regexp")) { + regexp = ah.getOptionalString("regexp"); + } + arNew.put(key2, generate(method, length, lengthMin, lengthMax, min, max, regexp)); + } else { + arNew.put(key2, value); + } + } - // process List - Map allObjects = ctx.getAllObjects(); - Map newObjects = new HashMap(); - for (String key : allObjects.keySet()) { - Object obj = allObjects.get(key); + newObjects.put(key, arNew); + ctx.putObject(key, arNew); - if (obj.getClass().equals(ArrayList.class)) { - ArrayList ar = (ArrayList) obj; - ArrayList arNew = new ArrayList(); - Iterator listIterator = ar.iterator(); + if (saveToGlobalContextAs != null) { + Command.putToGlobalContext(saveToGlobalContextAs, arNew); + } + } - while (listIterator.hasNext()) { - Object value = listIterator.next(); - if (value.getClass().equals(AttributeHelper.class)) { - AttributeHelper ah = (AttributeHelper) value; - if (ah.containsKey("method")) { - method = ah.getOptionalString("method"); - } - if (ah.containsKey("length")) { - length = ah.getOptionalString("length"); - } - if (ah.containsKey("lengthMin")) { - lengthMin = ah.getOptionalString("lengthMin"); - } - if (ah.containsKey("lengthMax")) { - lengthMax = ah.getOptionalString("lengthMax"); - } - if (ah.containsKey("min")) { - min = ah.getOptionalString("min"); - } - if (ah.containsKey("max")) { - max = ah.getOptionalString("max"); - } - if (ah.containsKey("regexp")) { - regexp = ah.getOptionalString("regexp"); - } - arNew.add(generate(method, length, lengthMin, lengthMax, min, max, regexp)); - } else { - arNew.add(value); - } - } - newObjects.put(key, arNew); - ctx.putObject(key, arNew); - - if (saveToGlobalContextAs != null) { - Command.putToGlobalContext(saveToGlobalContextAs, arNew); - } - } else if (obj.getClass().equals(HashMap.class)) { - Map ar = (Map) obj; - Map arNew = new HashMap(); - for(String key2 : ar.keySet()) { - Object value = ar.get(key2); - if (value.getClass().equals(AttributeHelper.class)) { - AttributeHelper ah = (AttributeHelper) value; - if (ah.containsKey("method")) { - method = ah.getOptionalString("method"); - } - if (ah.containsKey("length")) { - length = ah.getOptionalString("length"); - } - if (ah.containsKey("lengthMin")) { - lengthMin = ah.getOptionalString("lengthMin"); - } - if (ah.containsKey("lengthMax")) { - lengthMax = ah.getOptionalString("lengthMax"); - } - if (ah.containsKey("min")) { - min = ah.getOptionalString("min"); - } - if (ah.containsKey("max")) { - max = ah.getOptionalString("max"); - } - if (ah.containsKey("regexp")) { - regexp = ah.getOptionalString("regexp"); - } - arNew.put(key2, generate(method, length, lengthMin, lengthMax, min, max, regexp)); - } else { - arNew.put(key2, value); - } - } - - newObjects.put(key, arNew); - ctx.putObject(key, arNew); - - if (saveToGlobalContextAs != null) { - Command.putToGlobalContext(saveToGlobalContextAs, arNew); - } - } - - if ((obj != null) && (obj.getClass().equals(ArrayList.class))) { - logger.info("Generated new List: " + obj + "'"); - } - } - allObjects.putAll(newObjects); - } + if ((obj != null) && (obj.getClass().equals(ArrayList.class))) { + logger.info("Generated new List: " + obj + "'"); + } + } + allObjects.putAll(newObjects); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/Repeat.java b/src/main/java/org/finra/jtaf/core/commands/Repeat.java index c1ec887..34a0fb3 100644 --- a/src/main/java/org/finra/jtaf/core/commands/Repeat.java +++ b/src/main/java/org/finra/jtaf/core/commands/Repeat.java @@ -27,7 +27,6 @@ /** * This command surrounds a block of commands to be repeatedly executed based on * the value of the iterations parameter. - * */ public class Repeat extends Command { @@ -36,7 +35,7 @@ public class Repeat extends Command { * interpreter.The recordResult variable is set to false because details * about the Repeat step aren't needed, unlike the commands within the * Repeat block. - * + * * @param name - name of the command * @throws NameFormatException */ @@ -49,11 +48,9 @@ public Repeat(String name) throws NameFormatException { /** * This simply loops through and executes all commands within the Repeat * block. This is repeated for the specified iterations. - * + * * @param ctx - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the Repeat block. + * @throws Throwable - Any exception thrown by a command within the Repeat block. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/ReplaceContext.java b/src/main/java/org/finra/jtaf/core/commands/ReplaceContext.java index f3ae48b..e7e6753 100644 --- a/src/main/java/org/finra/jtaf/core/commands/ReplaceContext.java +++ b/src/main/java/org/finra/jtaf/core/commands/ReplaceContext.java @@ -27,7 +27,6 @@ /** * This command overwrites the values in the current context. - * */ public class ReplaceContext extends Command { @@ -36,9 +35,8 @@ public class ReplaceContext extends Command { * interpreter.The recordResult variable is set to false because details * about the ReplaceContext step aren't needed, unlike the commands within * the ReplaceContext block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ public ReplaceContext(String name) throws NameFormatException { @@ -50,13 +48,10 @@ public ReplaceContext(String name) throws NameFormatException { /** * This clears the current context and then puts all values from within the * ReplaceContext block into the context. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the ReplaceContext - * block. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within the ReplaceContext + * block. */ @Override protected void execute(IInvocationContext ctx) throws Throwable { @@ -83,7 +78,7 @@ protected void execute(IInvocationContext ctx) throws Throwable { ((CorrectiveContext) ctx).putObject(key, params.get(key)); } else if (!previousParams.keySet().contains(key) || (previousParams.keySet().contains(key) && previousParams.get(key) != params - .get(key))) { + .get(key))) { ((CorrectiveContext) ctx).putObject(key, params.get(key)); // ((CorrectiveContext) ctx).getAllObjects().p } diff --git a/src/main/java/org/finra/jtaf/core/commands/TryRecoverCleanup.java b/src/main/java/org/finra/jtaf/core/commands/TryRecoverCleanup.java index 1c38708..3713336 100644 --- a/src/main/java/org/finra/jtaf/core/commands/TryRecoverCleanup.java +++ b/src/main/java/org/finra/jtaf/core/commands/TryRecoverCleanup.java @@ -26,7 +26,6 @@ /** * Allows for try-catch-finally type logic to be performed within a test script. - * */ public class TryRecoverCleanup extends Command { @@ -35,9 +34,8 @@ public class TryRecoverCleanup extends Command { * interpreter.The recordResult variable is set to false because details * about the TryRecoverCleanup step aren't needed, unlike the commands * within the TryRecoverCleanup block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ public TryRecoverCleanup(String name) throws NameFormatException { @@ -51,12 +49,9 @@ public TryRecoverCleanup(String name) throws NameFormatException { * an exception is thrown, it will then try to execute all commands in the * recover block, if it exists, and finally execute all commands in the * cleanup block if it exists. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within one of the blocks. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within one of the blocks. */ @SuppressWarnings("unchecked") @Override @@ -83,12 +78,12 @@ protected void execute(IInvocationContext ctx) throws Throwable { try { Invocation cleanupInvocation = (Invocation) params.get(cleanup); if (cleanupInvocation.getTargetName().equalsIgnoreCase("cleanup")) { - // handle tearDown block - Object isTearDownParameter = cleanupInvocation.getParameters().get("isteardown"); - boolean isTearDown = isTearDownParameter != null && isTearDownParameter.toString().equalsIgnoreCase("true"); - if(isTearDown) - interpreter.executeTearDownPlugins(error, ctx); - executeInvocation(cleanupInvocation); + // handle tearDown block + Object isTearDownParameter = cleanupInvocation.getParameters().get("isteardown"); + boolean isTearDown = isTearDownParameter != null && isTearDownParameter.toString().equalsIgnoreCase("true"); + if (isTearDown) + interpreter.executeTearDownPlugins(error, ctx); + executeInvocation(cleanupInvocation); } } catch (Throwable ignore) { // Only handle cleanup exceptions if there was no other diff --git a/src/main/java/org/finra/jtaf/core/commands/VerifyException.java b/src/main/java/org/finra/jtaf/core/commands/VerifyException.java index 1708290..6ec34fb 100644 --- a/src/main/java/org/finra/jtaf/core/commands/VerifyException.java +++ b/src/main/java/org/finra/jtaf/core/commands/VerifyException.java @@ -37,9 +37,8 @@ public class VerifyException extends Command { * interpreter.The recordResult variable is set to false because details * about the VerifyException step aren't needed, unlike the commands within * the VerifyException block. - * - * @param name - * - name of the command + * + * @param name - name of the command * @throws NameFormatException */ public VerifyException(String name) throws NameFormatException { @@ -54,12 +53,9 @@ public VerifyException(String name) throws NameFormatException { * parameter. If it is not the same, an exception is thrown. If no exception * is encountered, an exception will be thrown. Otherwise, no exception is * thrown. - * - * @param ctx - * - The current context when this method is executed. - * - * @throws Throwable - * - Any exception thrown by a command within the Repeat block. + * + * @param ctx - The current context when this method is executed. + * @throws Throwable - Any exception thrown by a command within the Repeat block. */ @SuppressWarnings("unchecked") @Override diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java index 0541098..f7eae99 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java @@ -22,26 +22,25 @@ /** * Base class for context-manipulating commands - * */ public abstract class AbstractContextCmd extends Command { - protected final ManipulateContextHelper mch = new ManipulateContextHelper(this, Command.getGlobalContext()); - protected IInvocationContext ctx = null; + protected final ManipulateContextHelper mch = new ManipulateContextHelper(this, Command.getGlobalContext()); + protected IInvocationContext ctx = null; + + public AbstractContextCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected final void execute(IInvocationContext ctx) throws Throwable { + this.ctx = ctx; + execute(); + } + + protected abstract void execute() throws Throwable; - public AbstractContextCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected final void execute(IInvocationContext ctx) throws Throwable { - this.ctx = ctx; - execute(); - } - - protected abstract void execute() throws Throwable; - - IInvocationContext ctx() { - return this.getContext(); - } + IInvocationContext ctx() { + return this.getContext(); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java index 60f27e8..91663f1 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java @@ -23,36 +23,35 @@ /** * Gets a list from context and adds all elements to another list stored in context - * */ public class AddListToListCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "addlist"; - public static final String INDEX_ATTRIBUTE = "index"; - public static final String VALUE_OUT_ATTRIBUTE = "tolist"; + public static final String VALUE_IN_ATTRIBUTE = "addlist"; + public static final String INDEX_ATTRIBUTE = "index"; + public static final String VALUE_OUT_ATTRIBUTE = "tolist"; - public AddListToListCmd(String name) throws NameFormatException { - super(name); - } + public AddListToListCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - @SuppressWarnings("unchecked") - List valueIn = (List) getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - List valueOut = (List) getOptionalObject(valueOutAttribute); - if(valueOut == null) { - List suppression = new ArrayList(); - valueOut = suppression; - } - Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); - if(index == null || index < 0) { - index = valueOut.size(); - } else if(index > 0) { // for one-based - index -= 1; - } - valueOut.addAll(index, valueIn); - mch.setValueOut(valueOutAttribute, valueOut); - } + @Override + protected void execute() throws Throwable { + @SuppressWarnings("unchecked") + List valueIn = (List) getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + List valueOut = (List) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + List suppression = new ArrayList(); + valueOut = suppression; + } + Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); + if (index == null || index < 0) { + index = valueOut.size(); + } else if (index > 0) { // for one-based + index -= 1; + } + valueOut.addAll(index, valueIn); + mch.setValueOut(valueOutAttribute, valueOut); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java index 1a1ee2c..bd168c1 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java @@ -23,36 +23,35 @@ /** * Gets an object from context and stores that object into a list in context - * */ public class AddObjectToListCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "object"; - public static final String INDEX_ATTRIBUTE = "index"; - public static final String VALUE_OUT_ATTRIBUTE = "list"; + public static final String VALUE_IN_ATTRIBUTE = "object"; + public static final String INDEX_ATTRIBUTE = "index"; + public static final String VALUE_OUT_ATTRIBUTE = "list"; - public AddObjectToListCmd(String name) throws NameFormatException { - super(name); - } + public AddObjectToListCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - List valueOut = (List) getOptionalObject(valueOutAttribute); - if(valueOut == null) { - List suppression = new ArrayList(); - valueOut = suppression; - } - Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); - if(index == null || index < 0 || index > valueOut.size()) { - mch.setValueOut(valueOutAttribute, valueOut, valueIn); - } else { - if(index > 0) { // for one-based - index -= 1; - } - mch.setValueOut(valueOutAttribute, valueOut, valueIn, index); - } - } + @Override + protected void execute() throws Throwable { + Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + List valueOut = (List) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + List suppression = new ArrayList(); + valueOut = suppression; + } + Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); + if (index == null || index < 0 || index > valueOut.size()) { + mch.setValueOut(valueOutAttribute, valueOut, valueIn); + } else { + if (index > 0) { // for one-based + index -= 1; + } + mch.setValueOut(valueOutAttribute, valueOut, valueIn, index); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java b/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java index 6b82f14..d5ae8f2 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java @@ -24,400 +24,415 @@ /** * Helper class used for context commands - * + *

* plan for context manipulation: - * + *

* action = {replace out with in|prepend in to out|append in to out} - * + *

* valuein * indexin|keyin|null * foreach = {value in list|key in map|value in map|int|null} * change = {expand to singleton list|collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list} - * + *

* valueout * indexout|keyout|null * foreach = {value in list|key in map|value in map|int|null} * change = {collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list - * - * - * */ public class ManipulateContextHelper { - public static final String ACTION_ATTRIBUTE = "action"; - public static final String REPLACE_ACTION = "replace"; - public static final String PREPEND_ACTION = "prepend"; - public static final String APPEND_ACTION = "append"; - public static final String VALUE_IN_ATTRIBUTE = "valuein"; - public static final String INDEX_IN_ATTRIBUTE = "indexin"; - public static final String KEY_IN_ATTRIBUTE = "keyin"; - public static final String CHANGE_IN_ATTRIBUTE = "changein"; - public static final String SINGLETON_CHANGE = "singleton"; - public static final String VALUE_OUT_ATTRIBUTE = "valueout"; - public static final String INDEX_OUT_ATTRIBUTE = "indexout"; - public static final String KEY_OUT_ATTRIBUTE = "keyout"; - public static final String NONE_CHANGE = "none"; - private AbstractContextCmd cmd; - private IInvocationContext ctx; - private Map globalCtx; - - public ManipulateContextHelper(AbstractContextCmd cmd, Map globalCtx) { - this.cmd = cmd; - this.ctx = null; - this.globalCtx = globalCtx; - } - - private String name() { - return cmd.getName(); - } - - private IInvocationContext ctx() { - if(ctx != null) { - return ctx; - } - return cmd.ctx(); - } - - /** - * Sets a context to use instead of the global context provided in the constructor - * @param ctx The context to use - */ - public void setContext(IInvocationContext ctx) { - this.ctx = ctx; - } - - /** - * Checks to make sure the current "action" in context is an acceptable value - * @return - */ - public String getVerifiedAction() { - String action = getStringOrDefault(ACTION_ATTRIBUTE, REPLACE_ACTION); - if(!(action.equalsIgnoreCase(REPLACE_ACTION) || action.equalsIgnoreCase(APPEND_ACTION) || action.equalsIgnoreCase(PREPEND_ACTION))) { - throw new IllegalArgumentException(this.name() + ": attribute '" + ACTION_ATTRIBUTE + "' must be '" + REPLACE_ACTION + "' or '" + APPEND_ACTION + "' or '" + PREPEND_ACTION + "' (or left unspecified)"); - } - return action; - } - - /** - * Returns the values stored in an object in the context - * @param valueInAttribute The location of the object in the context - * @param index The index, if valueInAttribute refers to a list - * @param key The key if valueInAttribute refers to a map - * @return - */ - public Object getValueIn(String valueInAttribute, Integer index, Object key) { - if(index != null) { - return getValueIn(valueInAttribute, index); - } else if(key != null) { - return getValueIn(valueInAttribute, key); - } else { - return getOptionalObject(valueInAttribute); - } - - } - - /** - * Returns the value stored in a map in the context - * @param valueInAttribute The location of the map in the context - * @param key the key in the map stored in the context where to retrieve the value - * @return - */ - public Object getValueIn(String valueInAttribute, Object key) { - return ((Map) getOptionalObject(valueInAttribute)).get(key); - } - - /** - * Returns the value stored in a list in the context - * @param valueInAttribute The location of the list in the context - * @param index The index in the list stored in the context from where to retrieve the value - * @return - */ - public Object getValueIn(String valueInAttribute, Integer index) { - List list = (List) getOptionalObject(valueInAttribute); - if(index < 0) { - index += list.size(); - } - return list.get(index); - } - - /** - * Stores a value in a list in the context - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the value - * @param value The value to store in the list - * @param index The index in the list in which to store the value - */ - public void setValueOut(String valueOutAttribute, List list, Object value, int index) { - list.add(index, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Appends an object to a list stored in the context - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the value - * @param value The value to store in the list - */ - public void setValueOut(String valueOutAttribute, List list, Object value) { - list.add(value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Appends all the values of a list into another list that is stored in the context - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the values - * @param value The list of values being stored - */ - public void setValueOut(String valueOutAttribute, List list, List value) { - list.addAll(value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stores all the values of a list into another list that is stored in the context - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the values - * @param value The list of values being stored - * @param index The index in the list in which to store the value - */ - public void setValueOut(String valueOutAttribute, List list, List value, int index) { - list.addAll(index, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stores a value in a map stored in the context - * @param valueOutAttribute Where to store the resulting map in the context - * @param list The map in which to store the values - * @param value The value being stored in the map - * @param key The key at which to store the value in the map - */ - public void setValueOut(String valueOutAttribute, Map list, T value, K key) { - list.put(key, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stored an object in the context - * @param valueOutAttribute Where to store the object in the context - * @param value The object to store in the context - */ - public void setValueOut(String valueOutAttribute, Object value) { - ctx().putObject(valueOutAttribute, value); - } - - - /** - * Grabs an Object from the Context. - * @param key - * @return - */ - public Object getOptionalObject(String key) { - // We cannot assume that a parameter is optional just because getOptionalObject was - // called. Most commands failed to distinguish between optional and required parameters. - - Object result = ctx().getObject(key); - - // process 'contextKey' parameter - if ((result != null) && (result.getClass().equals(String.class))) { - String[] resultSplitted = ((String) result).split("\\$contextKey"); - StringBuffer resultString = new StringBuffer(resultSplitted[0]); - - int i = 1; - while (resultSplitted.length > i) { - int beginIndex = resultSplitted[i].indexOf("("); - if (beginIndex >= 0) { - int endIndex = resultSplitted[i].indexOf(")", beginIndex); - if (endIndex > 0) { - String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, endIndex); - runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); - - if (globalCtx.get(runTimeKeyName) != null) { - resultString.append(globalCtx.get(runTimeKeyName) + resultSplitted[i].substring(endIndex + 1)); - } else { - throw new RuntimeException("Oops! Processing '" + key + "'='" + result + "' key fails! Can't find run time parameter '" + runTimeKeyName - + "'! You have put it to global content before..."); - } - } - } - i++; - } - return resultString.toString(); - } - return result; - } - - - /** - * Grabs an object from the Context, or throws an exception - * if the Object does not exist. - * @param key - * @return - */ - public Object getRequiredObject(String key) { - Object param = this.getOptionalObject(key); - if (param == null) { - throw new IllegalArgumentException(this.name() + " : The parameter with key [" + key + "] is not set."); - } - return param; - } - - - /** - * Returns an integer value, or throws a NullPointerException if the value is not present - * - * @param attributeName - * @param ctx - * @return - */ - public int getRequiredInteger(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - throw new NullPointerException(this.name() + ": missing required integer attribute '"+ attributeName +"'"); - } - return Integer.parseInt(value); - } - - - /** - * Like the above, except it returns a default value if the attribute is not set - * @param attributeName - * @param ctx - * @param defaultValue - * @return - */ - public int getIntegerOrDefault(String attributeName, int defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - return defaultValue; - } - return Integer.parseInt(value); - } - - /** - * Returns a float stored in the context or throws a NullPointerException is one isn't - * @param attributeName Where in the context the float is stored - * @return The float stored in attributeName - */ - public float getRequiredFloat(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - throw new NullPointerException(this.name() + ": missing required float attribute '"+ attributeName +"'"); - } - return Float.parseFloat(value); - } - - /** - * Like the above, except it returns a default value if the attribute is not set - * @param attributeName Where in the context the float is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The float stored in attributeName or defaultValue if one wasn't present - */ - public float getFloatOrDefault(String attributeName, float defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - return defaultValue; - } - return Float.parseFloat(value); - } - - - /** - * Returns a String stored in the context or throws a NullPointerException is one isn't - * @param attributeName Where in the context the String is stored - * @return The String stored in attributeName - */ - public String getRequiredString(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - throw new NullPointerException(this.name() + ": missing required String attribute '"+ attributeName +"'"); - } - return value; - } - - - /** - * Like the above, except it returns a default value if the attribute is not set - * @param attributeName attributeName Where in the context the String is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The String stored in attributeName or defaultValue if one wasn't present - */ - public String getStringOrDefault(String attributeName, String defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if(value == null) { - return defaultValue; - } - return value; - } - - /** - * Returns a String stored in the context or null if there isn't one - * @param attributeName Where in the context the String is stored - * @return The string stored in attributeName or null if there isn't one - */ - public String getOptionalString(String attributeName) { - return (String) this.getOptionalObject(attributeName); - } - - /** - * Returns a float stored in the context or throws a NullPointerException is one isn't - * @param attributeName Where in the context the boolean is stored - * @return The boolean stored in attributeName - */ - public boolean getRequiredBoolean(String attributeName) { - String temp = (String) this.getOptionalObject(attributeName); - if(temp == null) { - throw new NullPointerException(this.name() + ": missing required boolean attribute '" + attributeName + "'"); - } - - temp = temp.trim(); - if(temp.equalsIgnoreCase("true")) { - return true; - } - else if(temp.equalsIgnoreCase("false")) { - return false; - } - else { - throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false'"); - } - } - - /** - * Like the above, except it returns a default value if the attribute is not set - * @param attributeName Where in the context the boolean is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The boolean stored in attributeName or defaultValue if one wasn't present - */ - public boolean getBooleanOrDefault(String attributeName, boolean defaultValue) { - String temp = (String) this.getOptionalObject(attributeName); - if(temp == null) { - return defaultValue; - } - - temp = temp.trim(); - if(temp.equalsIgnoreCase("true")) { - return true; - } - else if(temp.equalsIgnoreCase("false")) { - return false; - } - else { - throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false' (or left unspecified)"); - } - } - - /** - * Returns an Integer stored in the context or null if there isn't one - * @param key Where in the context the Integer is stored - * @return The string stored in key or null if there isn't one - */ - public Integer getOptionalInteger(String key) { - String integerAsString = (String) getOptionalObject(key); - if(integerAsString == null) { - return null; - } else { - return Integer.parseInt(integerAsString); - } - } + public static final String ACTION_ATTRIBUTE = "action"; + public static final String REPLACE_ACTION = "replace"; + public static final String PREPEND_ACTION = "prepend"; + public static final String APPEND_ACTION = "append"; + public static final String VALUE_IN_ATTRIBUTE = "valuein"; + public static final String INDEX_IN_ATTRIBUTE = "indexin"; + public static final String KEY_IN_ATTRIBUTE = "keyin"; + public static final String CHANGE_IN_ATTRIBUTE = "changein"; + public static final String SINGLETON_CHANGE = "singleton"; + public static final String VALUE_OUT_ATTRIBUTE = "valueout"; + public static final String INDEX_OUT_ATTRIBUTE = "indexout"; + public static final String KEY_OUT_ATTRIBUTE = "keyout"; + public static final String NONE_CHANGE = "none"; + private AbstractContextCmd cmd; + private IInvocationContext ctx; + private Map globalCtx; + + public ManipulateContextHelper(AbstractContextCmd cmd, Map globalCtx) { + this.cmd = cmd; + this.ctx = null; + this.globalCtx = globalCtx; + } + + private String name() { + return cmd.getName(); + } + + private IInvocationContext ctx() { + if (ctx != null) { + return ctx; + } + return cmd.ctx(); + } + + /** + * Sets a context to use instead of the global context provided in the constructor + * + * @param ctx The context to use + */ + public void setContext(IInvocationContext ctx) { + this.ctx = ctx; + } + + /** + * Checks to make sure the current "action" in context is an acceptable value + * + * @return + */ + public String getVerifiedAction() { + String action = getStringOrDefault(ACTION_ATTRIBUTE, REPLACE_ACTION); + if (!(action.equalsIgnoreCase(REPLACE_ACTION) || action.equalsIgnoreCase(APPEND_ACTION) || action.equalsIgnoreCase(PREPEND_ACTION))) { + throw new IllegalArgumentException(this.name() + ": attribute '" + ACTION_ATTRIBUTE + "' must be '" + REPLACE_ACTION + "' or '" + APPEND_ACTION + "' or '" + PREPEND_ACTION + "' (or left unspecified)"); + } + return action; + } + + /** + * Returns the values stored in an object in the context + * + * @param valueInAttribute The location of the object in the context + * @param index The index, if valueInAttribute refers to a list + * @param key The key if valueInAttribute refers to a map + * @return + */ + public Object getValueIn(String valueInAttribute, Integer index, Object key) { + if (index != null) { + return getValueIn(valueInAttribute, index); + } else if (key != null) { + return getValueIn(valueInAttribute, key); + } else { + return getOptionalObject(valueInAttribute); + } + + } + + /** + * Returns the value stored in a map in the context + * + * @param valueInAttribute The location of the map in the context + * @param key the key in the map stored in the context where to retrieve the value + * @return + */ + public Object getValueIn(String valueInAttribute, Object key) { + return ((Map) getOptionalObject(valueInAttribute)).get(key); + } + + /** + * Returns the value stored in a list in the context + * + * @param valueInAttribute The location of the list in the context + * @param index The index in the list stored in the context from where to retrieve the value + * @return + */ + public Object getValueIn(String valueInAttribute, Integer index) { + List list = (List) getOptionalObject(valueInAttribute); + if (index < 0) { + index += list.size(); + } + return list.get(index); + } + + /** + * Stores a value in a list in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the value + * @param value The value to store in the list + * @param index The index in the list in which to store the value + */ + public void setValueOut(String valueOutAttribute, List list, Object value, int index) { + list.add(index, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Appends an object to a list stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the value + * @param value The value to store in the list + */ + public void setValueOut(String valueOutAttribute, List list, Object value) { + list.add(value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Appends all the values of a list into another list that is stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the values + * @param value The list of values being stored + */ + public void setValueOut(String valueOutAttribute, List list, List value) { + list.addAll(value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stores all the values of a list into another list that is stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the values + * @param value The list of values being stored + * @param index The index in the list in which to store the value + */ + public void setValueOut(String valueOutAttribute, List list, List value, int index) { + list.addAll(index, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stores a value in a map stored in the context + * + * @param valueOutAttribute Where to store the resulting map in the context + * @param list The map in which to store the values + * @param value The value being stored in the map + * @param key The key at which to store the value in the map + */ + public void setValueOut(String valueOutAttribute, Map list, T value, K key) { + list.put(key, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stored an object in the context + * + * @param valueOutAttribute Where to store the object in the context + * @param value The object to store in the context + */ + public void setValueOut(String valueOutAttribute, Object value) { + ctx().putObject(valueOutAttribute, value); + } + + + /** + * Grabs an Object from the Context. + * + * @param key + * @return + */ + public Object getOptionalObject(String key) { + // We cannot assume that a parameter is optional just because getOptionalObject was + // called. Most commands failed to distinguish between optional and required parameters. + + Object result = ctx().getObject(key); + + // process 'contextKey' parameter + if ((result != null) && (result.getClass().equals(String.class))) { + String[] resultSplitted = ((String) result).split("\\$contextKey"); + StringBuffer resultString = new StringBuffer(resultSplitted[0]); + + int i = 1; + while (resultSplitted.length > i) { + int beginIndex = resultSplitted[i].indexOf("("); + if (beginIndex >= 0) { + int endIndex = resultSplitted[i].indexOf(")", beginIndex); + if (endIndex > 0) { + String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, endIndex); + runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); + + if (globalCtx.get(runTimeKeyName) != null) { + resultString.append(globalCtx.get(runTimeKeyName) + resultSplitted[i].substring(endIndex + 1)); + } else { + throw new RuntimeException("Oops! Processing '" + key + "'='" + result + "' key fails! Can't find run time parameter '" + runTimeKeyName + + "'! You have put it to global content before..."); + } + } + } + i++; + } + return resultString.toString(); + } + return result; + } + + + /** + * Grabs an object from the Context, or throws an exception + * if the Object does not exist. + * + * @param key + * @return + */ + public Object getRequiredObject(String key) { + Object param = this.getOptionalObject(key); + if (param == null) { + throw new IllegalArgumentException(this.name() + " : The parameter with key [" + key + "] is not set."); + } + return param; + } + + + /** + * Returns an integer value, or throws a NullPointerException if the value is not present + * + * @param attributeName + * @param ctx + * @return + */ + public int getRequiredInteger(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required integer attribute '" + attributeName + "'"); + } + return Integer.parseInt(value); + } + + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName + * @param ctx + * @param defaultValue + * @return + */ + public int getIntegerOrDefault(String attributeName, int defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return Integer.parseInt(value); + } + + /** + * Returns a float stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the float is stored + * @return The float stored in attributeName + */ + public float getRequiredFloat(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required float attribute '" + attributeName + "'"); + } + return Float.parseFloat(value); + } + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName Where in the context the float is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The float stored in attributeName or defaultValue if one wasn't present + */ + public float getFloatOrDefault(String attributeName, float defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return Float.parseFloat(value); + } + + + /** + * Returns a String stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the String is stored + * @return The String stored in attributeName + */ + public String getRequiredString(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required String attribute '" + attributeName + "'"); + } + return value; + } + + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName attributeName Where in the context the String is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The String stored in attributeName or defaultValue if one wasn't present + */ + public String getStringOrDefault(String attributeName, String defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return value; + } + + /** + * Returns a String stored in the context or null if there isn't one + * + * @param attributeName Where in the context the String is stored + * @return The string stored in attributeName or null if there isn't one + */ + public String getOptionalString(String attributeName) { + return (String) this.getOptionalObject(attributeName); + } + + /** + * Returns a float stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the boolean is stored + * @return The boolean stored in attributeName + */ + public boolean getRequiredBoolean(String attributeName) { + String temp = (String) this.getOptionalObject(attributeName); + if (temp == null) { + throw new NullPointerException(this.name() + ": missing required boolean attribute '" + attributeName + "'"); + } + + temp = temp.trim(); + if (temp.equalsIgnoreCase("true")) { + return true; + } else if (temp.equalsIgnoreCase("false")) { + return false; + } else { + throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false'"); + } + } + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName Where in the context the boolean is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The boolean stored in attributeName or defaultValue if one wasn't present + */ + public boolean getBooleanOrDefault(String attributeName, boolean defaultValue) { + String temp = (String) this.getOptionalObject(attributeName); + if (temp == null) { + return defaultValue; + } + + temp = temp.trim(); + if (temp.equalsIgnoreCase("true")) { + return true; + } else if (temp.equalsIgnoreCase("false")) { + return false; + } else { + throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false' (or left unspecified)"); + } + } + + /** + * Returns an Integer stored in the context or null if there isn't one + * + * @param key Where in the context the Integer is stored + * @return The string stored in key or null if there isn't one + */ + public Integer getOptionalInteger(String key) { + String integerAsString = (String) getOptionalObject(key); + if (integerAsString == null) { + return null; + } else { + return Integer.parseInt(integerAsString); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java index 6714575..e07cdbf 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java @@ -23,29 +23,28 @@ /** * Gets an object from context and stores that object into a map in context - * */ public class PutObjectInMapCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "object"; - public static final String KEY_ATTRIBUTE = "key"; - public static final String VALUE_OUT_ATTRIBUTE = "map"; + public static final String VALUE_IN_ATTRIBUTE = "object"; + public static final String KEY_ATTRIBUTE = "key"; + public static final String VALUE_OUT_ATTRIBUTE = "map"; - public PutObjectInMapCmd(String name) throws NameFormatException { - super(name); - } + public PutObjectInMapCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - Map valueOut = (Map) getOptionalObject(valueOutAttribute); - if(valueOut == null) { - Map suppression = new HashMap(); - valueOut = suppression; - } - Object key = mch.getRequiredObject(KEY_ATTRIBUTE); - mch.setValueOut(valueOutAttribute, valueOut, valueIn, key); - } + @Override + protected void execute() throws Throwable { + Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + Map valueOut = (Map) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + Map suppression = new HashMap(); + valueOut = suppression; + } + Object key = mch.getRequiredObject(KEY_ATTRIBUTE); + mch.setValueOut(valueOutAttribute, valueOut, valueIn, key); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java index 768e86e..e34bb19 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java @@ -20,18 +20,17 @@ /** * Removes an object from context by replacing it with null - * */ public class RemoveObjectFromContextCmd extends AbstractContextCmd { - public static final String VALUE_ATTRIBUTE = "object"; + public static final String VALUE_ATTRIBUTE = "object"; - public RemoveObjectFromContextCmd(String name) throws NameFormatException { - super(name); - } + public RemoveObjectFromContextCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - mch.setValueOut(getRequiredString(VALUE_ATTRIBUTE), (Object) null); - } + @Override + protected void execute() throws Throwable { + mch.setValueOut(getRequiredString(VALUE_ATTRIBUTE), (Object) null); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java index b65f926..8712bcb 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java @@ -20,26 +20,25 @@ /** * Stores a default value into context unless the object already exists in context - * */ public class StoreDefaultObjectCmd extends AbstractContextCmd { - public static final String DEFAULT_ATTRIBUTE = "defaultKey"; - public static final String DEFAULT= "default"; - public static final String VALUE_OUT_ATTRIBUTE = "contextKey"; + public static final String DEFAULT_ATTRIBUTE = "defaultKey"; + public static final String DEFAULT = "default"; + public static final String VALUE_OUT_ATTRIBUTE = "contextKey"; - public StoreDefaultObjectCmd(String name) throws NameFormatException { - super(name); - } + public StoreDefaultObjectCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() { - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - Object valueOut = getOptionalObject(valueOutAttribute); - if(valueOut == null) { - String defaultAttribute = getStringOrDefault(DEFAULT_ATTRIBUTE, DEFAULT); - valueOut = getRequiredObject(defaultAttribute); - } - mch.setValueOut(valueOutAttribute, valueOut); - } + @Override + protected void execute() { + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + Object valueOut = getOptionalObject(valueOutAttribute); + if (valueOut == null) { + String defaultAttribute = getStringOrDefault(DEFAULT_ATTRIBUTE, DEFAULT); + valueOut = getRequiredObject(defaultAttribute); + } + mch.setValueOut(valueOutAttribute, valueOut); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java index 919e980..5824601 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java @@ -20,25 +20,24 @@ /** * Gets an object from context and stores that object into context as its .toString() value - * */ public class StoreObjectAsStringCmd extends AbstractContextCmd { - public static final String VALUE_ATTRIBUTE = "key"; + public static final String VALUE_ATTRIBUTE = "key"; - public StoreObjectAsStringCmd(String name) throws NameFormatException { - super(name); - } + public StoreObjectAsStringCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - String valueName = getRequiredString(VALUE_ATTRIBUTE); - Object value = getOptionalObject(valueName); - if(value == null) { - value = "null"; - } else { - value = value.toString(); - } - getContext().putObject(valueName, value); - } + @Override + protected void execute() throws Throwable { + String valueName = getRequiredString(VALUE_ATTRIBUTE); + Object value = getOptionalObject(valueName); + if (value == null) { + value = "null"; + } else { + value = value.toString(); + } + getContext().putObject(valueName, value); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java index 455bd3f..cef36b2 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java @@ -20,7 +20,6 @@ /** * Gets an object from a list in context and stores that object into context - * */ public class StoreObjectFromListCmd extends AbstractContextCmd { public static final String VALUE_IN_ATTRIBUTE = "list"; diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java index f015ba6..d04c307 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java @@ -20,23 +20,22 @@ /** * Gets an object from a map in context and stores that object into context - * */ public class StoreObjectFromMapCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "map"; - public static final String INDEX_ATTRIBUTE = "mapKey"; - public static final String VALUE_OUT_ATTRIBUTE = "objectKey"; + public static final String VALUE_IN_ATTRIBUTE = "map"; + public static final String INDEX_ATTRIBUTE = "mapKey"; + public static final String VALUE_OUT_ATTRIBUTE = "objectKey"; - public StoreObjectFromMapCmd(String name) throws NameFormatException { - super(name); - } + public StoreObjectFromMapCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute() throws Throwable { - Object key = mch.getRequiredObject(INDEX_ATTRIBUTE); - Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), key); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - mch.setValueOut(valueOutAttribute, valueIn); - } + @Override + protected void execute() throws Throwable { + Object key = mch.getRequiredObject(INDEX_ATTRIBUTE); + Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), key); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + mch.setValueOut(valueOutAttribute, valueIn); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java index 1f8a81c..edc58f0 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java @@ -25,17 +25,17 @@ */ public class StoreObjectInContextCmd extends Command { - public StoreObjectInContextCmd(String name) throws NameFormatException { - super(name); - } + public StoreObjectInContextCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext arg0) throws Throwable { - String newKey = getRequiredString("storeKey"); - String key = getRequiredString("loadKey"); - - Object o = getRequiredObject(key); - arg0.putObject(newKey, o); - } + @Override + protected void execute(IInvocationContext arg0) throws Throwable { + String newKey = getRequiredString("storeKey"); + String key = getRequiredString("loadKey"); + + Object o = getRequiredObject(key); + arg0.putObject(newKey, o); + } } diff --git a/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java index 7828727..a801d70 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java @@ -30,28 +30,28 @@ */ public class VerifyObjectInContextCmd extends Command { - public VerifyObjectInContextCmd(String name) throws NameFormatException { - super(name); - } + public VerifyObjectInContextCmd(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext arg0) throws Throwable { - String actualKey = getRequiredString("actualKey"); - String expectedKey = getRequiredString("expectedKey"); - String title = getOptionalString("title"); - boolean failOnNotEqual = getBooleanOrDefault("failOnNotEqual", true); - Object actual = getRequiredObject(actualKey); - Object expected = getRequiredObject(expectedKey); - CompositeDataComparator cdc = new CompositeDataComparator(); - cdc.setAccumulateErrors(true); - cdc.compareObject(title, null, expected, actual); - List errorList = cdc.getErrorList(); - if(failOnNotEqual && errorList != null && !errorList.isEmpty()) { - if(title != null) { - throw new AssertionError("Expected " + title + " did not match actual:\n" + StringUtils.join(errorList, "\n")); - } - throw new AssertionError("Expected did not match actual:\n" + StringUtils.join(errorList, "\n")); - } - arg0.putObject("errorList", errorList); - } + @Override + protected void execute(IInvocationContext arg0) throws Throwable { + String actualKey = getRequiredString("actualKey"); + String expectedKey = getRequiredString("expectedKey"); + String title = getOptionalString("title"); + boolean failOnNotEqual = getBooleanOrDefault("failOnNotEqual", true); + Object actual = getRequiredObject(actualKey); + Object expected = getRequiredObject(expectedKey); + CompositeDataComparator cdc = new CompositeDataComparator(); + cdc.setAccumulateErrors(true); + cdc.compareObject(title, null, expected, actual); + List errorList = cdc.getErrorList(); + if (failOnNotEqual && errorList != null && !errorList.isEmpty()) { + if (title != null) { + throw new AssertionError("Expected " + title + " did not match actual:\n" + StringUtils.join(errorList, "\n")); + } + throw new AssertionError("Expected did not match actual:\n" + StringUtils.join(errorList, "\n")); + } + arg0.putObject("errorList", errorList); + } } diff --git a/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java b/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java index 168e122..95072bc 100644 --- a/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java +++ b/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java @@ -18,24 +18,24 @@ public class DependencyException extends RuntimeException { - /** - * Auto-generated - */ - private static final long serialVersionUID = 4864467896129227737L; + /** + * Auto-generated + */ + private static final long serialVersionUID = 4864467896129227737L; - public DependencyException() { - super(); - } - - public DependencyException(String message) { - super(message); - } - - public DependencyException(String message, Throwable th) { - super(message, th); - } - - public DependencyException(Throwable th) { - super(th); - } + public DependencyException() { + super(); + } + + public DependencyException(String message) { + super(message); + } + + public DependencyException(String message, Throwable th) { + super(message, th); + } + + public DependencyException(Throwable th) { + super(th); + } } diff --git a/src/main/java/org/finra/jtaf/core/model/exceptions/ExpectedFailureException.java b/src/main/java/org/finra/jtaf/core/model/exceptions/ExpectedFailureException.java index 41d5594..092a48a 100644 --- a/src/main/java/org/finra/jtaf/core/model/exceptions/ExpectedFailureException.java +++ b/src/main/java/org/finra/jtaf/core/model/exceptions/ExpectedFailureException.java @@ -21,14 +21,13 @@ * block. This allows us to reverse the normal * logic of our testing and verify that our validation commands * are doing what they are supposed to do. - * */ public class ExpectedFailureException extends ModelException { - - private static final long serialVersionUID = -8114949982502430018L; - public ExpectedFailureException() { - super("Expected this script to fail, but it did not"); - } + private static final long serialVersionUID = -8114949982502430018L; + + public ExpectedFailureException() { + super("Expected this script to fail, but it did not"); + } } diff --git a/src/main/java/org/finra/jtaf/core/model/exceptions/MissingInvocationTargetException.java b/src/main/java/org/finra/jtaf/core/model/exceptions/MissingInvocationTargetException.java index d782a6c..63606bd 100644 --- a/src/main/java/org/finra/jtaf/core/model/exceptions/MissingInvocationTargetException.java +++ b/src/main/java/org/finra/jtaf/core/model/exceptions/MissingInvocationTargetException.java @@ -21,30 +21,27 @@ /** * This will be used by the Interpreter to report broken invocation - * targets during test execution. - * - * + * targets during test execution. */ public class MissingInvocationTargetException extends Exception { - - private static final long serialVersionUID = 1616653146326672452L; - - private final Invocation invocation; - - /** - * @param invocation - * This will be called from interpreter when invocation target is missing during test execution - */ - public MissingInvocationTargetException(Invocation invocation) { - super("The invocation " + invocation.toString() + " refers to a non-existent InvocationTarget"); - this.invocation = invocation; - } - - /** - * @return The Invocation associated with this exception - */ - public final Invocation getInvocation() { - return this.invocation; - } + + private static final long serialVersionUID = 1616653146326672452L; + + private final Invocation invocation; + + /** + * @param invocation This will be called from interpreter when invocation target is missing during test execution + */ + public MissingInvocationTargetException(Invocation invocation) { + super("The invocation " + invocation.toString() + " refers to a non-existent InvocationTarget"); + this.invocation = invocation; + } + + /** + * @return The Invocation associated with this exception + */ + public final Invocation getInvocation() { + return this.invocation; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/exceptions/ModelException.java b/src/main/java/org/finra/jtaf/core/model/exceptions/ModelException.java index c09fa02..661592d 100644 --- a/src/main/java/org/finra/jtaf/core/model/exceptions/ModelException.java +++ b/src/main/java/org/finra/jtaf/core/model/exceptions/ModelException.java @@ -18,26 +18,25 @@ /** * Generic base class for every model-related exception - * */ public class ModelException extends Exception { - - private static final long serialVersionUID = 4621730379026731543L; - public ModelException() { - super(); - } - - public ModelException(String message) { - super(message); - } - - public ModelException(String message, Throwable th) { - super(message, th); - } - - public ModelException(Throwable th) { - super(th); - } + private static final long serialVersionUID = 4621730379026731543L; + + public ModelException() { + super(); + } + + public ModelException(String message) { + super(message); + } + + public ModelException(String message, Throwable th) { + super(message, th); + } + + public ModelException(Throwable th) { + super(th); + } } diff --git a/src/main/java/org/finra/jtaf/core/model/exceptions/NameCollisionException.java b/src/main/java/org/finra/jtaf/core/model/exceptions/NameCollisionException.java index d9e5f26..b5dacdf 100644 --- a/src/main/java/org/finra/jtaf/core/model/exceptions/NameCollisionException.java +++ b/src/main/java/org/finra/jtaf/core/model/exceptions/NameCollisionException.java @@ -18,26 +18,24 @@ /** * This is thrown whenever an element with the same name - * already exists - * + * already exists */ public class NameCollisionException extends Exception { - - private static final long serialVersionUID = -3361740674217851439L; - private final String name; - - /** - * @param name - * This is called when same test name exist during building model - */ - public NameCollisionException(String name) { - super("The name '" + name + "' is already in use"); - this.name = name; - } - - public String getName() { - return this.name; - } + private static final long serialVersionUID = -3361740674217851439L; + + private final String name; + + /** + * @param name This is called when same test name exist during building model + */ + public NameCollisionException(String name) { + super("The name '" + name + "' is already in use"); + this.name = name; + } + + public String getName() { + return this.name; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/exceptions/NameFormatException.java b/src/main/java/org/finra/jtaf/core/model/exceptions/NameFormatException.java index c80adf4..e18cd90 100644 --- a/src/main/java/org/finra/jtaf/core/model/exceptions/NameFormatException.java +++ b/src/main/java/org/finra/jtaf/core/model/exceptions/NameFormatException.java @@ -23,32 +23,30 @@ * Exception stating that a given name does not satisfy some regular * expression. This is completely opaque for test script writers, * but it may be useful for test command writers. - * */ public class NameFormatException extends Exception { - private static final long serialVersionUID = 1625699244250298524L; - - private final String invalidName; - private final Pattern pattern; - - /** - * @param invalidName - * @param pattern - * - */ - - public NameFormatException(String invalidName, Pattern pattern) { - super("'" + invalidName + "' does not satisfy the pattern " + pattern.pattern()); - this.invalidName = invalidName; - this.pattern = pattern; - } - - public final String getInvalidName() { - return this.invalidName; - } - - public final Pattern getPattern() { - return this.pattern; - } + private static final long serialVersionUID = 1625699244250298524L; + + private final String invalidName; + private final Pattern pattern; + + /** + * @param invalidName + * @param pattern + */ + + public NameFormatException(String invalidName, Pattern pattern) { + super("'" + invalidName + "' does not satisfy the pattern " + pattern.pattern()); + this.invalidName = invalidName; + this.pattern = pattern; + } + + public final String getInvalidName() { + return this.invalidName; + } + + public final Pattern getPattern() { + return this.pattern; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/CorrectiveContext.java b/src/main/java/org/finra/jtaf/core/model/execution/CorrectiveContext.java index ace32ed..d0b13c9 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/CorrectiveContext.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/CorrectiveContext.java @@ -38,216 +38,215 @@ */ public class CorrectiveContext implements IInterpreterContext { - private static final Set modifications = new HashSet(); - - private static class ContextFrame { - public final InvocationTarget target; - public Map parameters; - public Map produced; - - public ContextFrame(InvocationTarget target) { - this.target = target; - this.parameters = new HashMap(); - this.produced = new HashMap(); - } - } - - private final Stack frameStack; - private TestScript testScript; - - public CorrectiveContext() { - this.frameStack = new Stack(); - this.frameStack.push(new ContextFrame(null)); - this.testScript = null; - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInterpreterContext#pushInvocation - * (org.finra.jtaf.core.model.statement.Invocation, - * org.finra.jtaf.core.model.invocationtarget.InvocationTarget) - */ - public void pushInvocation(Invocation inv, InvocationTarget target) - throws MissingInvocationTargetException { - - final ContextFrame next = new ContextFrame(target); - next.parameters = new HashMap( - this.frameStack.peek().parameters); - for (Entry e : inv.getParameters().entrySet()) { - next.parameters.put(e.getKey().toLowerCase(), e.getValue()); - } - this.frameStack.push(next); - - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInterpreterContext#pushInvocation - * (java.util.Map) - */ - public void setParameters(Map vars) { - HashMap p = new HashMap(); - for (Entry e : vars.entrySet()) { - p.put(e.getKey().toLowerCase(), e.getValue()); - } - this.frameStack.peek().parameters = p; - } - - /** - * Clears the current context for all the invocations in the stack - */ - public void clearContext() { - int size = this.frameStack.size(); - ArrayList stack = new ArrayList(); - for (int x = 0; x < size; x++) { - ContextFrame previousCommand = this.frameStack.pop(); - ContextFrame newFrame = new ContextFrame(previousCommand.target); - stack.add(newFrame); - } - - for (int x = size - 1; x >= 0; x--) { - this.frameStack.push(stack.get(x)); - - } - - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.core.model.execution.IInterpreterContext#popFrame() - */ - public void popFrame() { - final ContextFrame popped = this.frameStack.pop(); - final ContextFrame top = this.frameStack.peek(); - for (Entry e : popped.produced.entrySet()) { - top.parameters.put(e.getKey(), e.getValue()); - - if ((top.target != null) - && !top.target.getProductions().contains(e.getKey())) { - modifications.add(top.target); - top.target.addProduction(e.getKey()); - } - top.produced.put(e.getKey(), e.getValue()); - } - - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#contains(java. - * lang.String) - */ - public boolean contains(String name) { - return this.frameStack.peek().parameters - .containsKey(name.toLowerCase()); - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#getObject(java - * .lang.String) - */ - public Object getObject(String name) throws UndefinedParameterError { - final String lookupName = name.toLowerCase(); - final InvocationTarget t = frameStack.peek().target; - if (!t.getAllParameters().contains(lookupName)) { - modifications.add(t); - // Assume the parameter is required until I'm shown otherwise - t.addRequiredParameter(lookupName); - } - - return this.frameStack.peek().parameters.get(lookupName); - } - - /** - * Return all objects in context based on a certain type - * - * @param objectType - * => Object of the type you are looking for - * @return => list of all objects of type passed in the parameter - * @throws UndefinedParameterError - */ - public List getObjectByType(Object objectType) - throws UndefinedParameterError { - List results = new ArrayList(); - for (String key : frameStack.peek().parameters.keySet()) { - if (frameStack.peek().parameters.get(key).getClass() - .equals(objectType.getClass())) { - results.add(frameStack.peek().parameters.get(key)); - } - } - return results; - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#getAllObjects() - */ - public Map getAllObjects() { - return frameStack.peek().parameters; - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#putObject(java - * .lang.String, java.lang.Object) - */ - public void putObject(String name, Object value) - throws UndefinedProductionError { - final String lookupName = name.toLowerCase(); - final InvocationTarget t = frameStack.peek().target; - if (!t.getProductions().contains(lookupName)) { - modifications.add(t); - t.addProduction(lookupName); - } - - this.frameStack.peek().produced.put(lookupName, value); - this.frameStack.peek().parameters.put(lookupName, value); - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#removeObject(java - * .lang.String) - */ - public void removeObject(String name) { - this.frameStack.peek().parameters.remove(name.toLowerCase()); - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInvocationContext#getTestScript() - */ - public TestScript getTestScript() { - return this.testScript; - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.execution.IInterpreterContext#setTestScript - * (org.finra.jtaf.core.model.test.TestScript) - */ - public void setTestScript(TestScript ts) { - this.testScript = ts; - } + private static final Set modifications = new HashSet(); + + private static class ContextFrame { + public final InvocationTarget target; + public Map parameters; + public Map produced; + + public ContextFrame(InvocationTarget target) { + this.target = target; + this.parameters = new HashMap(); + this.produced = new HashMap(); + } + } + + private final Stack frameStack; + private TestScript testScript; + + public CorrectiveContext() { + this.frameStack = new Stack(); + this.frameStack.push(new ContextFrame(null)); + this.testScript = null; + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInterpreterContext#pushInvocation + * (org.finra.jtaf.core.model.statement.Invocation, + * org.finra.jtaf.core.model.invocationtarget.InvocationTarget) + */ + public void pushInvocation(Invocation inv, InvocationTarget target) + throws MissingInvocationTargetException { + + final ContextFrame next = new ContextFrame(target); + next.parameters = new HashMap( + this.frameStack.peek().parameters); + for (Entry e : inv.getParameters().entrySet()) { + next.parameters.put(e.getKey().toLowerCase(), e.getValue()); + } + this.frameStack.push(next); + + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInterpreterContext#pushInvocation + * (java.util.Map) + */ + public void setParameters(Map vars) { + HashMap p = new HashMap(); + for (Entry e : vars.entrySet()) { + p.put(e.getKey().toLowerCase(), e.getValue()); + } + this.frameStack.peek().parameters = p; + } + + /** + * Clears the current context for all the invocations in the stack + */ + public void clearContext() { + int size = this.frameStack.size(); + ArrayList stack = new ArrayList(); + for (int x = 0; x < size; x++) { + ContextFrame previousCommand = this.frameStack.pop(); + ContextFrame newFrame = new ContextFrame(previousCommand.target); + stack.add(newFrame); + } + + for (int x = size - 1; x >= 0; x--) { + this.frameStack.push(stack.get(x)); + + } + + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.core.model.execution.IInterpreterContext#popFrame() + */ + public void popFrame() { + final ContextFrame popped = this.frameStack.pop(); + final ContextFrame top = this.frameStack.peek(); + for (Entry e : popped.produced.entrySet()) { + top.parameters.put(e.getKey(), e.getValue()); + + if ((top.target != null) + && !top.target.getProductions().contains(e.getKey())) { + modifications.add(top.target); + top.target.addProduction(e.getKey()); + } + top.produced.put(e.getKey(), e.getValue()); + } + + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#contains(java. + * lang.String) + */ + public boolean contains(String name) { + return this.frameStack.peek().parameters + .containsKey(name.toLowerCase()); + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#getObject(java + * .lang.String) + */ + public Object getObject(String name) throws UndefinedParameterError { + final String lookupName = name.toLowerCase(); + final InvocationTarget t = frameStack.peek().target; + if (!t.getAllParameters().contains(lookupName)) { + modifications.add(t); + // Assume the parameter is required until I'm shown otherwise + t.addRequiredParameter(lookupName); + } + + return this.frameStack.peek().parameters.get(lookupName); + } + + /** + * Return all objects in context based on a certain type + * + * @param objectType => Object of the type you are looking for + * @return => list of all objects of type passed in the parameter + * @throws UndefinedParameterError + */ + public List getObjectByType(Object objectType) + throws UndefinedParameterError { + List results = new ArrayList(); + for (String key : frameStack.peek().parameters.keySet()) { + if (frameStack.peek().parameters.get(key).getClass() + .equals(objectType.getClass())) { + results.add(frameStack.peek().parameters.get(key)); + } + } + return results; + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#getAllObjects() + */ + public Map getAllObjects() { + return frameStack.peek().parameters; + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#putObject(java + * .lang.String, java.lang.Object) + */ + public void putObject(String name, Object value) + throws UndefinedProductionError { + final String lookupName = name.toLowerCase(); + final InvocationTarget t = frameStack.peek().target; + if (!t.getProductions().contains(lookupName)) { + modifications.add(t); + t.addProduction(lookupName); + } + + this.frameStack.peek().produced.put(lookupName, value); + this.frameStack.peek().parameters.put(lookupName, value); + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#removeObject(java + * .lang.String) + */ + public void removeObject(String name) { + this.frameStack.peek().parameters.remove(name.toLowerCase()); + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInvocationContext#getTestScript() + */ + public TestScript getTestScript() { + return this.testScript; + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.execution.IInterpreterContext#setTestScript + * (org.finra.jtaf.core.model.test.TestScript) + */ + public void setTestScript(TestScript ts) { + this.testScript = ts; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/IInterpreterContext.java b/src/main/java/org/finra/jtaf/core/model/execution/IInterpreterContext.java index 2d95c9a..ec7da11 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/IInterpreterContext.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/IInterpreterContext.java @@ -25,43 +25,42 @@ import org.finra.jtaf.core.model.test.TestScript; /** - * The interpreter pushes and pops Invocation Context frames during execution - * + * The interpreter pushes and pops Invocation Context frames during execution */ public interface IInterpreterContext extends IInvocationContext { - /** - * Prepares the context for the invocation. In most cases, this means - * building the parameter set, filtering unwanted parameters, and marking - * the productions. - * - * Throws MissingInvocationTargetException if no target exists for the - * invocation. - * - * @param inv - * @throws MissingInvocationTargetException - */ - void pushInvocation(Invocation inv, InvocationTarget target) - throws MissingInvocationTargetException; + /** + * Prepares the context for the invocation. In most cases, this means + * building the parameter set, filtering unwanted parameters, and marking + * the productions. + *

+ * Throws MissingInvocationTargetException if no target exists for the + * invocation. + * + * @param inv + * @throws MissingInvocationTargetException + */ + void pushInvocation(Invocation inv, InvocationTarget target) + throws MissingInvocationTargetException; - /** - * Used by ReplaceContext to set the values within the Context. This does - * not impact the Productions - * - * @param vars - */ - void setParameters(Map vars); + /** + * Used by ReplaceContext to set the values within the Context. This does + * not impact the Productions + * + * @param vars + */ + void setParameters(Map vars); - /** - * Pops the current frame. Anything that was listed in the set of - * productions will be moved into the previous frame. - */ - void popFrame(); + /** + * Pops the current frame. Anything that was listed in the set of + * productions will be moved into the previous frame. + */ + void popFrame(); - /** - * Sets the TestScript that is being executed. - * - * @param ts - */ - void setTestScript(TestScript ts); + /** + * Sets the TestScript that is being executed. + * + * @param ts + */ + void setTestScript(TestScript ts); } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/IInvocationContext.java b/src/main/java/org/finra/jtaf/core/model/execution/IInvocationContext.java index 87791ed..3cf237a 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/IInvocationContext.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/IInvocationContext.java @@ -25,57 +25,56 @@ /** * InvocationTargets can access objects currently inside the context. They are not allowed to push or pop frames. - * */ public interface IInvocationContext { - /** - * Returns an Object associated w/ the given name, or null if no such Object - * is available in the current Context - * - * @param name - * @return - * @throws UndefinedParameterError - */ - Object getObject(String name) throws UndefinedParameterError; + /** + * Returns an Object associated w/ the given name, or null if no such Object + * is available in the current Context + * + * @param name + * @return + * @throws UndefinedParameterError + */ + Object getObject(String name) throws UndefinedParameterError; - /** - * Returns map of all objects in the current Context - * - * @return - */ - Map getAllObjects(); + /** + * Returns map of all objects in the current Context + * + * @return + */ + Map getAllObjects(); - /** - * Inserts the specified Object into the current Context. - * - * @param name - * @param value - */ - void putObject(String name, Object value) throws UndefinedProductionError; + /** + * Inserts the specified Object into the current Context. + * + * @param name + * @param value + */ + void putObject(String name, Object value) throws UndefinedProductionError; - /** - * TODO: This should probably throw some type of exception if the name is - * not specified in the script contract - * - * @param name - * @return True if the given name is associated w/ an Object; False - * otherwise - */ - boolean contains(String name); + /** + * TODO: This should probably throw some type of exception if the name is + * not specified in the script contract + * + * @param name + * @return True if the given name is associated w/ an Object; False + * otherwise + */ + boolean contains(String name); - /** - * Removes the object w/ the given name TODO: This should probably throw - * some kind of exception if the name is not specified in the script - * contract - * - * @param name - */ - void removeObject(String name); + /** + * Removes the object w/ the given name TODO: This should probably throw + * some kind of exception if the name is not specified in the script + * contract + * + * @param name + */ + void removeObject(String name); - /** - * @return The TestScript that is being executed. - */ - TestScript getTestScript(); + /** + * @return The TestScript that is being executed. + */ + TestScript getTestScript(); } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java b/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java index 42c4f06..70f1549 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java @@ -44,378 +44,370 @@ /** * This class is invoked by the Automation Engine to begin execution - * */ public class Interpreter { - private static final Logger logger = Logger.getLogger(Interpreter.class); - private CommandRegistry commandRegistry; - private static IInterpreterContext context; - private TestStatus testStatus; - public ErrorAccumulator ea; - - private List testRunnerPlugins; - private List commandRunnerPlugins; - private List tearDownPlugins; - private IAutomationClassLoader automationClassLoader; - private List testStepDetails; - - /** - * Add plugins that should run before or after a test - * - * @param testRunnerPlugins - * => the list of test level plugins - */ - public void setTestRunnerPlugins(List testRunnerPlugins) { - this.testRunnerPlugins = testRunnerPlugins; - } - - /** - * Add plugins that should run before or after a command - * - * @param commandRunnerPlugins - * => the list of command level plugins - */ - public void setCommandRunnerPlugins( - List commandRunnerPlugins) { - this.commandRunnerPlugins = commandRunnerPlugins; - } - - public void setTearDownPlugins(List tearDownPlugins) { - this.tearDownPlugins = tearDownPlugins; - } - - /** - * Set the command registry - * - * @param commandRegistry - */ - public void setCommandRegistry(CommandRegistry commandRegistry) { - this.commandRegistry = commandRegistry; - } - - /** - * Execute the commands in the testscript passed to the Interpreter. Execute - * custom plugins that are supposed to run before and after each test or - * each command. The test passes if this method executes without throwing an - * exception. - * - * @param test - * =>testscript object passed by the Automation Engine - * @throws Throwable - */ - public final TestResult interpret(TestScript test) throws Throwable { - logger.info(test.getFullName()); - Throwable failure = null; - context = new CorrectiveContext(); - context.setTestScript(test); - - ea = new ErrorAccumulator("Accumulator"); - // Multithreaded use - automationClassLoader = new DefaultAutomationClassLoader(); - testStatus = TestStatus.Running; - testStepDetails = new ArrayList(); - executeTestStartPlugins(test); - try { - visitInvocationList(test.getBody()); - failure = ea.getWrappedErrors(); - } catch (Throwable t) { - failure = t; - this.testStatus = TestStatus.Failed; - } - finally { - if (failure == null) - this.testStatus = TestStatus.Passed; - else { - this.testStatus = TestStatus.Failed; - } - - executeTestFinishPlugins(); - - } - if (failure != null - && failure.getClass().getSimpleName() - .equalsIgnoreCase(test.getException())) { - failure = null; - this.testStatus = TestStatus.Passed; - } - return new TestResult(this.getTestStepDetails(), testStatus, failure); - } - - /** - * Return the list of test steps in the current test - * - * @return - */ - public List getTestStepDetails() { - return testStepDetails; - } - - /** - * Execute the list of commands in the test - * - * @param invocationtList - * @throws Throwable - */ - public void visitInvocationList(InvocationList invocationtList) - throws Throwable { - - try { - - for (Invocation invocation : invocationtList) { - try { - - visitInvocation((Invocation) invocation); - } catch (Throwable th) { - if (!ea.isEmpty() && !ea.hasThrown()) { - ea.addError((Throwable) th); - - ea.throwErrors(); - } else { - throw th; - } - } - } - } catch (Throwable th) { - this.testStatus = TestStatus.Failed; - throw th; - } - } - - /** - * Invoke the command's launch API. Responsible of actual execution of the - * command - * - * @param command - * => current command object to be executed - * @throws Throwable - */ - public void visitCommand(Command command) throws Throwable { - executeCommandStartPlugins(command); - try { - command.launch(context, this); - } catch (Throwable t) { - throw t; - } finally { - executeCommandFinishPlugins(command); - } - - } - - /** - * Execute the function, if any, present in the test - * - * @param function - * @throws Throwable - */ - public void visitFunction(Function function) throws Throwable { - this.visitInvocationList(function.getBody()); - - } - - /** - * Execute the commands in the testscript passed to the Interpreter. - * - * @param invocation - * =>testscript object passed by the Automation Engine - * @throws Throwable - */ - public final void visitInvocation(Invocation invocation) throws Throwable { - if (invocation.getTargetName().equals("TryRecoverCleanup")) { - // Ignore logging TryRecoverCleanup statement - } else { - logger.info(invocation.toString()); - } - if (this.commandRegistry.containsInvocationTarget(invocation - .getTargetName())) { - final InvocationTarget target = this.commandRegistry - .getInvocationTarget(invocation.getTargetName()); - context.pushInvocation(invocation, target); - } else { - throw new MissingInvocationTargetException(invocation); - } - - try { - InvocationTarget target = getInvocationTarget(invocation); - - target.acceptInvocationTargetVisitor(this); - - } finally { - - context.popFrame(); - } - } - - /** - * Get the invocation target instance if it exists in the Command Registry - * else throw exception 'Invocation not found' - * - * @param invocation - * @return - * @throws Throwable - */ - public InvocationTarget getInvocationTarget(Invocation invocation) - throws Throwable { - // Check if it exists in the local map already - InvocationTarget target = null; - // Get the InvocationTarget from the previously mapped ones. - InvocationTarget mappedInvocationTarget = this.commandRegistry - .getInvocationTarget(invocation.getTargetName()); - - if (mappedInvocationTarget == null) { - throw new IllegalArgumentException("Invocation " - + invocation.getTargetName() + " not found"); - } - - if (mappedInvocationTarget instanceof Function) { - target = mappedInvocationTarget; - } else { - // Instantiate the InvocationTarget. - Class targetClass = automationClassLoader - .loadClass(mappedInvocationTarget.getClass().getName()); - if (InvocationTarget.class.isAssignableFrom(targetClass)) { - Constructor constructor = targetClass - .getConstructor(String.class); - target = (InvocationTarget) constructor.newInstance(invocation - .getTargetName()); - - // This is to reload the parameters from preparsed Map of - // InvocationTargets (ScriptParser) - for (String s : mappedInvocationTarget.getRequiredParameters()) { - target.addRequiredParameter(s); - } - - for (String s : mappedInvocationTarget.getOptionalParameters()) { - target.addOptionalParameter(s); - } - - for (String s : mappedInvocationTarget.getProductions()) { - target.addProduction(s); - } - } else { - throw new IllegalArgumentException("Invocation not found"); - } - } - return target; - } - - /** - * Add details of the invocation to the list of test steps - * - */ - public void addDetails(TestStepsDetails details) { - testStepDetails.add(details); - } - - /** - * Add exception to the Error Accumulator and set the Test Status to 'Failed' - * @param th - */ - public void addError(Throwable th) { - ea.addError(th); - this.testStatus = TestStatus.Failed; - - } - - /** - * Run TestRunner plugins after a test finishes execution - */ - private void executeTestFinishPlugins() { - - if (testRunnerPlugins != null) { - for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { - try { - testPlugin - .handleTestFinish(new TestRunnerPluginContext( - context.getTestScript(), new TestResult( - this.getTestStepDetails(), - testStatus), context)); - } catch (Throwable e) { - logger.error(e); - - } - - } - } - } - - /** - * Run TestRunner plugins before a test starts execution - * - * @param test - * => the current testscript in context - */ - private void executeTestStartPlugins(TestScript test) { - // handleTestStart - try { - if (testRunnerPlugins != null) { - for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { - testPlugin.handleTestStart(new TestRunnerPluginContext( - test, new TestResult(this.getTestStepDetails(), - testStatus), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - /** - * Run CommandRunner plugins after a command is executed - * - * @param command - */ - private void executeCommandFinishPlugins(Command command) { - - try { - if (commandRunnerPlugins != null) { - for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { - commandPlugin - .handleCommandAfter(new CommandRunnerPluginContext( - new TestStepsDetails(command.getName(), - command.getUsage()), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - /** - * Run CommandRunner plugins before a command is executed - * - * @param command - */ - private void executeCommandStartPlugins(Command command) { - try { - // handle command start - if (commandRunnerPlugins != null) { - for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { - commandPlugin - .handleCommandBefore(new CommandRunnerPluginContext( - new TestStepsDetails(command.getName(), - command.getUsage()), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - public void executeTearDownPlugins(Throwable failureReason, IInvocationContext invocationContext) { - try { - if(tearDownPlugins != null) { - for(ITearDownPlugin tearDownPlugin : tearDownPlugins) { - TestScript testScript = context.getTestScript(); - TearDownPluginContext tearDownPluginContext = new TearDownPluginContext(testScript, failureReason, invocationContext); - tearDownPlugin.handleBeforeTearDown(tearDownPluginContext); - } - } - } catch (Throwable throwable) { - logger.error("Error while executing teardown plugins", throwable); - } - } + private static final Logger logger = Logger.getLogger(Interpreter.class); + private CommandRegistry commandRegistry; + private static IInterpreterContext context; + private TestStatus testStatus; + public ErrorAccumulator ea; + + private List testRunnerPlugins; + private List commandRunnerPlugins; + private List tearDownPlugins; + private IAutomationClassLoader automationClassLoader; + private List testStepDetails; + + /** + * Add plugins that should run before or after a test + * + * @param testRunnerPlugins => the list of test level plugins + */ + public void setTestRunnerPlugins(List testRunnerPlugins) { + this.testRunnerPlugins = testRunnerPlugins; + } + + /** + * Add plugins that should run before or after a command + * + * @param commandRunnerPlugins => the list of command level plugins + */ + public void setCommandRunnerPlugins( + List commandRunnerPlugins) { + this.commandRunnerPlugins = commandRunnerPlugins; + } + + public void setTearDownPlugins(List tearDownPlugins) { + this.tearDownPlugins = tearDownPlugins; + } + + /** + * Set the command registry + * + * @param commandRegistry + */ + public void setCommandRegistry(CommandRegistry commandRegistry) { + this.commandRegistry = commandRegistry; + } + + /** + * Execute the commands in the testscript passed to the Interpreter. Execute + * custom plugins that are supposed to run before and after each test or + * each command. The test passes if this method executes without throwing an + * exception. + * + * @param test =>testscript object passed by the Automation Engine + * @throws Throwable + */ + public final TestResult interpret(TestScript test) throws Throwable { + logger.info(test.getFullName()); + Throwable failure = null; + context = new CorrectiveContext(); + context.setTestScript(test); + + ea = new ErrorAccumulator("Accumulator"); + // Multithreaded use + automationClassLoader = new DefaultAutomationClassLoader(); + testStatus = TestStatus.Running; + testStepDetails = new ArrayList(); + executeTestStartPlugins(test); + try { + visitInvocationList(test.getBody()); + failure = ea.getWrappedErrors(); + } catch (Throwable t) { + failure = t; + this.testStatus = TestStatus.Failed; + } finally { + if (failure == null) + this.testStatus = TestStatus.Passed; + else { + this.testStatus = TestStatus.Failed; + } + + executeTestFinishPlugins(); + + } + if (failure != null + && failure.getClass().getSimpleName() + .equalsIgnoreCase(test.getException())) { + failure = null; + this.testStatus = TestStatus.Passed; + } + return new TestResult(this.getTestStepDetails(), testStatus, failure); + } + + /** + * Return the list of test steps in the current test + * + * @return + */ + public List getTestStepDetails() { + return testStepDetails; + } + + /** + * Execute the list of commands in the test + * + * @param invocationtList + * @throws Throwable + */ + public void visitInvocationList(InvocationList invocationtList) + throws Throwable { + + try { + + for (Invocation invocation : invocationtList) { + try { + + visitInvocation((Invocation) invocation); + } catch (Throwable th) { + if (!ea.isEmpty() && !ea.hasThrown()) { + ea.addError((Throwable) th); + + ea.throwErrors(); + } else { + throw th; + } + } + } + } catch (Throwable th) { + this.testStatus = TestStatus.Failed; + throw th; + } + } + + /** + * Invoke the command's launch API. Responsible of actual execution of the + * command + * + * @param command => current command object to be executed + * @throws Throwable + */ + public void visitCommand(Command command) throws Throwable { + executeCommandStartPlugins(command); + try { + command.launch(context, this); + } catch (Throwable t) { + throw t; + } finally { + executeCommandFinishPlugins(command); + } + + } + + /** + * Execute the function, if any, present in the test + * + * @param function + * @throws Throwable + */ + public void visitFunction(Function function) throws Throwable { + this.visitInvocationList(function.getBody()); + + } + + /** + * Execute the commands in the testscript passed to the Interpreter. + * + * @param invocation =>testscript object passed by the Automation Engine + * @throws Throwable + */ + public final void visitInvocation(Invocation invocation) throws Throwable { + if (invocation.getTargetName().equals("TryRecoverCleanup")) { + // Ignore logging TryRecoverCleanup statement + } else { + logger.info(invocation.toString()); + } + if (this.commandRegistry.containsInvocationTarget(invocation + .getTargetName())) { + final InvocationTarget target = this.commandRegistry + .getInvocationTarget(invocation.getTargetName()); + context.pushInvocation(invocation, target); + } else { + throw new MissingInvocationTargetException(invocation); + } + + try { + InvocationTarget target = getInvocationTarget(invocation); + + target.acceptInvocationTargetVisitor(this); + + } finally { + + context.popFrame(); + } + } + + /** + * Get the invocation target instance if it exists in the Command Registry + * else throw exception 'Invocation not found' + * + * @param invocation + * @return + * @throws Throwable + */ + public InvocationTarget getInvocationTarget(Invocation invocation) + throws Throwable { + // Check if it exists in the local map already + InvocationTarget target = null; + // Get the InvocationTarget from the previously mapped ones. + InvocationTarget mappedInvocationTarget = this.commandRegistry + .getInvocationTarget(invocation.getTargetName()); + + if (mappedInvocationTarget == null) { + throw new IllegalArgumentException("Invocation " + + invocation.getTargetName() + " not found"); + } + + if (mappedInvocationTarget instanceof Function) { + target = mappedInvocationTarget; + } else { + // Instantiate the InvocationTarget. + Class targetClass = automationClassLoader + .loadClass(mappedInvocationTarget.getClass().getName()); + if (InvocationTarget.class.isAssignableFrom(targetClass)) { + Constructor constructor = targetClass + .getConstructor(String.class); + target = (InvocationTarget) constructor.newInstance(invocation + .getTargetName()); + + // This is to reload the parameters from preparsed Map of + // InvocationTargets (ScriptParser) + for (String s : mappedInvocationTarget.getRequiredParameters()) { + target.addRequiredParameter(s); + } + + for (String s : mappedInvocationTarget.getOptionalParameters()) { + target.addOptionalParameter(s); + } + + for (String s : mappedInvocationTarget.getProductions()) { + target.addProduction(s); + } + } else { + throw new IllegalArgumentException("Invocation not found"); + } + } + return target; + } + + /** + * Add details of the invocation to the list of test steps + */ + public void addDetails(TestStepsDetails details) { + testStepDetails.add(details); + } + + /** + * Add exception to the Error Accumulator and set the Test Status to 'Failed' + * + * @param th + */ + public void addError(Throwable th) { + ea.addError(th); + this.testStatus = TestStatus.Failed; + + } + + /** + * Run TestRunner plugins after a test finishes execution + */ + private void executeTestFinishPlugins() { + + if (testRunnerPlugins != null) { + for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { + try { + testPlugin + .handleTestFinish(new TestRunnerPluginContext( + context.getTestScript(), new TestResult( + this.getTestStepDetails(), + testStatus), context)); + } catch (Throwable e) { + logger.error(e); + + } + + } + } + } + + /** + * Run TestRunner plugins before a test starts execution + * + * @param test => the current testscript in context + */ + private void executeTestStartPlugins(TestScript test) { + // handleTestStart + try { + if (testRunnerPlugins != null) { + for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { + testPlugin.handleTestStart(new TestRunnerPluginContext( + test, new TestResult(this.getTestStepDetails(), + testStatus), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + /** + * Run CommandRunner plugins after a command is executed + * + * @param command + */ + private void executeCommandFinishPlugins(Command command) { + + try { + if (commandRunnerPlugins != null) { + for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { + commandPlugin + .handleCommandAfter(new CommandRunnerPluginContext( + new TestStepsDetails(command.getName(), + command.getUsage()), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + /** + * Run CommandRunner plugins before a command is executed + * + * @param command + */ + private void executeCommandStartPlugins(Command command) { + try { + // handle command start + if (commandRunnerPlugins != null) { + for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { + commandPlugin + .handleCommandBefore(new CommandRunnerPluginContext( + new TestStepsDetails(command.getName(), + command.getUsage()), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + public void executeTearDownPlugins(Throwable failureReason, IInvocationContext invocationContext) { + try { + if (tearDownPlugins != null) { + for (ITearDownPlugin tearDownPlugin : tearDownPlugins) { + TestScript testScript = context.getTestScript(); + TearDownPluginContext tearDownPluginContext = new TearDownPluginContext(testScript, failureReason, invocationContext); + tearDownPlugin.handleBeforeTearDown(tearDownPluginContext); + } + } + } catch (Throwable throwable) { + logger.error("Error while executing teardown plugins", throwable); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/TestFailure.java b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/TestFailure.java index cd80238..01e8b67 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/TestFailure.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/TestFailure.java @@ -20,33 +20,33 @@ * This should be thrown whenever a test fails. Originally, we were * using the jUnit AssertionFailedException, but this won't work if * we begin using different execution drivers. - * - * */ public class TestFailure extends Error { - - private static final long serialVersionUID = 9025217872075585782L; - - /** - * @param message - */ - public TestFailure(String message) { - super(message); - } - /** - * @param Throwable - */ - - public TestFailure(Throwable e) { - super(e); - } - /** - * @param message - * @param throwable - */ - - public TestFailure(String message, Throwable e) { - super(message, e); - } + + private static final long serialVersionUID = 9025217872075585782L; + + /** + * @param message + */ + public TestFailure(String message) { + super(message); + } + + /** + * @param Throwable + */ + + public TestFailure(Throwable e) { + super(e); + } + + /** + * @param message + * @param throwable + */ + + public TestFailure(String message, Throwable e) { + super(message, e); + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedParameterError.java b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedParameterError.java index 7151537..bd8db9c 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedParameterError.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedParameterError.java @@ -21,24 +21,23 @@ * Some implementations of IInvocationContext will throw this error * when a Command tries to retrieve a parameter that was not specified * in the Script Contract. - * */ public class UndefinedParameterError extends Error { - private static final long serialVersionUID = 364767996067850085L; + private static final long serialVersionUID = 364767996067850085L; + + private final String parameter; + + /** + * @param name + */ + + public UndefinedParameterError(String name) { + super("The parameter '" + name + "' was not specified in the Script Contract"); + this.parameter = name; + } - private final String parameter; - - /** - * @param name - */ - - public UndefinedParameterError(String name) { - super("The parameter '" + name + "' was not specified in the Script Contract"); - this.parameter = name; - } - - public final String getParameter() { - return this.parameter; - } + public final String getParameter() { + return this.parameter; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedProductionError.java b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedProductionError.java index 7c47da7..3d2ce1d 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedProductionError.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/exceptions/UndefinedProductionError.java @@ -21,27 +21,24 @@ * This is thrown when an InvocationTarget tries to place something in * the Context without explicitly stating that the value can be returned. * In other words: this forces people to annotate their Commands properly :-D - * - * */ public class UndefinedProductionError extends Error { - private static final long serialVersionUID = 8548760217888120440L; + private static final long serialVersionUID = 8548760217888120440L; + + private final String productionName; - private final String productionName; - - /** - * ProductionName associated with the InvocationTarget - * - */ + /** + * ProductionName associated with the InvocationTarget + */ - public UndefinedProductionError(String productionName) { - super("'" + productionName + "' was not specified in the invocation target's definition"); - this.productionName = productionName; - } + public UndefinedProductionError(String productionName) { + super("'" + productionName + "' was not specified in the invocation target's definition"); + this.productionName = productionName; + } - public final String getProductionName() { - return this.productionName; - } + public final String getProductionName() { + return this.productionName; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/Command.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/Command.java index c5fb52e..fdf9d0b 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/Command.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/Command.java @@ -27,7 +27,6 @@ /** * Implements basic methods, but leaves execution phase abstract - * */ public abstract class Command extends InvocationTarget { private static Logger logger = Logger.getLogger(Command.class.getPackage().getName()); @@ -48,7 +47,7 @@ public Command(String name) throws NameFormatException { * Internal method: Used to share the current Context between methods * without having to pass it explicitly. The current Context is set * automatically when launch() is called. - * + * * @return the context of this method */ protected final IInvocationContext getContext() { @@ -58,11 +57,9 @@ protected final IInvocationContext getContext() { /** * Sets up the context before executing the actual command. Also handles the * updating of the TestStepDetails to record information on step execution. - * - * @param ctx - * - the current context when the command is being executed - * @param interpreter - * - the interpreter that is executing the command + * + * @param ctx - the current context when the command is being executed + * @param interpreter - the interpreter that is executing the command * @throws Throwable */ public final void launch(IInvocationContext ctx, Interpreter interpreter) throws Throwable { @@ -111,11 +108,11 @@ public final void launch(IInvocationContext ctx, Interpreter interpreter) throws throw th; } finally { - - try{ - this.deinitialize(this.getContext()); - }catch(Throwable th){ - logger.error("Error in Command deinitialization", th); + + try { + this.deinitialize(this.getContext()); + } catch (Throwable th) { + logger.error("Error in Command deinitialization", th); } } @@ -123,7 +120,7 @@ public final void launch(IInvocationContext ctx, Interpreter interpreter) throws /** * Optional method to initialize a command before execution - * + * * @param ctx */ protected void initialize(IInvocationContext ctx) throws Throwable { @@ -132,7 +129,7 @@ protected void initialize(IInvocationContext ctx) throws Throwable { /** * This method should be overridden by every Command object. - * + * * @param ctx * @throws Exception */ @@ -140,7 +137,7 @@ protected void initialize(IInvocationContext ctx) throws Throwable { /** * Optional method to deinitialize a command after execution. - * + * * @param ctx */ protected void deinitialize(IInvocationContext ctx) throws Throwable { @@ -149,7 +146,7 @@ protected void deinitialize(IInvocationContext ctx) throws Throwable { /** * Grabs an Object from the Context. - * + * * @param key * @return */ @@ -178,6 +175,7 @@ protected Object getOptionalObject(String key) { /** * Processing the paramters for RandomGenerator before execution. + * * @param params the paramters of the RandomGenerator instance. * @return the randomly generated string. */ @@ -233,9 +231,8 @@ private Object processRandomGenerator(String params) { /** * Replace a key of an object in the context. - * - * @param result - * - the new key to be used to replace + * + * @param result - the new key to be used to replace * @return */ // TODO: add $ escape @@ -246,9 +243,8 @@ private Object replaceContextKey(Object result) { /** * Get an object that was stored in the context as an required parameter. - * - * @param key - * - key of object in context + * + * @param key - key of object in context * @return the object value */ protected Object getRequiredObject(String key) { @@ -262,9 +258,8 @@ protected Object getRequiredObject(String key) { /** * Get an integer that was stored in the context as an required parameter. - * - * @param attributeName - * - key of object in context + * + * @param attributeName - key of object in context * @return the integer value */ protected final int getRequiredInteger(String attributeName) { @@ -278,12 +273,10 @@ protected final int getRequiredInteger(String attributeName) { /** * Get an integer stored in the context or return a default value. - * - * @param attributeName - * - key of object in context - * @param defaultValue - * - the default value if the attributeName has no associated - * value in the context. + * + * @param attributeName - key of object in context + * @param defaultValue - the default value if the attributeName has no associated + * value in the context. * @return the default value or the value from the context. */ protected final int getIntegerOrDefault(String attributeName, int defaultValue) { @@ -296,9 +289,8 @@ protected final int getIntegerOrDefault(String attributeName, int defaultValue) /** * Get a float that was stored in the context as an required parameter. - * - * @param attributeName - * - key of object in context + * + * @param attributeName - key of object in context * @return the float value */ protected final float getRequiredFloat(String attributeName) { @@ -312,12 +304,10 @@ protected final float getRequiredFloat(String attributeName) { /** * Get a float stored in the context or return a default value. - * - * @param attributeName - * - key of object in context - * @param defaultValue - * - the default value if the attributeName has no associated - * value in the context. + * + * @param attributeName - key of object in context + * @param defaultValue - the default value if the attributeName has no associated + * value in the context. * @return the default value or the value from the context. */ protected final float getFloatOrDefault(String attributeName, float defaultValue) { @@ -330,9 +320,8 @@ protected final float getFloatOrDefault(String attributeName, float defaultValue /** * Get a string that was stored in the context as an required parameter. - * - * @param attributeName - * - key of object in context + * + * @param attributeName - key of object in context * @return the string value */ protected final String getRequiredString(String attributeName) { @@ -347,12 +336,10 @@ protected final String getRequiredString(String attributeName) { /** * Get a string stored in the context or return a default value. - * - * @param attributeName - * - key of object in context - * @param defaultValue - * - the default value if the attributeName has no associated - * value in the context. + * + * @param attributeName - key of object in context + * @param defaultValue - the default value if the attributeName has no associated + * value in the context. * @return the default value or the value from the context. */ protected final String getStringOrDefault(String attributeName, String defaultValue) { @@ -365,9 +352,8 @@ protected final String getStringOrDefault(String attributeName, String defaultVa /** * Get a string that was stored in the context as an optional parameter. - * - * @param attributeName - * - key of object in context + * + * @param attributeName - key of object in context * @return the string value */ protected final String getOptionalString(String attributeName) { @@ -376,9 +362,8 @@ protected final String getOptionalString(String attributeName) { /** * Get a boolean that was stored in the context as a required parameter. - * - * @param attributeName - * - key of object in context + * + * @param attributeName - key of object in context * @return the boolean value */ protected final boolean getRequiredBoolean(String attributeName) { @@ -401,12 +386,10 @@ protected final boolean getRequiredBoolean(String attributeName) { /** * Get a boolean stored in the context or return a default value. - * - * @param attributeName - * - key of object in context - * @param defaultValue - * - the default value if the attributeName has no associated - * value in the context. + * + * @param attributeName - key of object in context + * @param defaultValue - the default value if the attributeName has no associated + * value in the context. * @return the default value or the value from the context. */ protected final boolean getBooleanOrDefault(String attributeName, boolean defaultValue) { @@ -430,9 +413,8 @@ protected final boolean getBooleanOrDefault(String attributeName, boolean defaul * This is used by the interpreter so that the visitCommand method is * called, allowing the interpreter to not have to know what kind of * InvocationTarget it is executing. - * - * @param v - * - the interpreter executing this command + * + * @param v - the interpreter executing this command */ public final void acceptInvocationTargetVisitor(Interpreter v) throws Throwable { v.visitCommand(this); @@ -441,7 +423,7 @@ public final void acceptInvocationTargetVisitor(Interpreter v) throws Throwable /** * Used to check whether or not this command needs to have its details * recorded in testStepDetails. - * + * * @return */ protected boolean recordResult() { @@ -450,9 +432,8 @@ protected boolean recordResult() { /** * Used by other commands to execute invocations in their bodies. - * - * @param child - * - the command in the block + * + * @param child - the command in the block * @throws Throwable */ protected void executeInvocation(Invocation child) throws Throwable { diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java index bac6d0c..5f46a6d 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java @@ -26,7 +26,6 @@ /** * Used to replace keys in the context. - * */ public class ContextKeyHandler { @@ -36,21 +35,19 @@ public class ContextKeyHandler { /** * Called when instantiated - * - * @param context - * - the current context when this is executed. + * + * @param context - the current context when this is executed. */ public ContextKeyHandler(IInvocationContext context) { this.context = context; } /** - * - * @param value - the key + * @param value - the key * @return - */ @SuppressWarnings("unchecked") - public Object replaceContextKey(Object value) { + public Object replaceContextKey(Object value) { // This is to avoid replaceContext from getting into an infinite loop of // recursive calls. resolveCount++; @@ -115,7 +112,7 @@ public Object replaceContextKey(Object value) { /** * Get the current context. - * + * * @return the current context. */ public IInvocationContext getContext() { diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java index ccc81e9..eddb173 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java @@ -19,16 +19,15 @@ /** * This is an exception thrown when a key, that hasn't been stored in the * context, is used to get a value from the context. - * */ public class ContextKeyNotFoundException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 1L; + * + */ + private static final long serialVersionUID = 1L; - /** + /** * A constructor used without specifying the message or throwable. */ public ContextKeyNotFoundException() { @@ -38,11 +37,9 @@ public ContextKeyNotFoundException() { /** * A constructor used with specifying the message or throwable. - * - * @param message - * - The message to be thrown. - * @param cause - * - The exception encountered that will be thrown. + * + * @param message - The message to be thrown. + * @param cause - The exception encountered that will be thrown. */ public ContextKeyNotFoundException(String message, Throwable cause) { super(message, cause); @@ -51,9 +48,8 @@ public ContextKeyNotFoundException(String message, Throwable cause) { /** * A constructor used without specifying the message. - * - * @param message - * - The message to be thrown. + * + * @param message - The message to be thrown. */ public ContextKeyNotFoundException(String message) { super(message); @@ -62,9 +58,8 @@ public ContextKeyNotFoundException(String message) { /** * A constructor used without specifying the throwable. - * - * @param cause - * - The exception encountered that will be thrown. + * + * @param cause - The exception encountered that will be thrown. */ public ContextKeyNotFoundException(Throwable cause) { super(cause); diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/Function.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/Function.java index 717203b..9f8e939 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/Function.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/Function.java @@ -31,9 +31,8 @@ public final class Function extends InvocationTarget { /** * This called when instantiating the function before it is executed by the * interpreter. - * - * @param name - * - name of the function + * + * @param name - name of the function * @throws NameFormatException */ public Function(String name) throws NameFormatException { @@ -43,7 +42,7 @@ public Function(String name) throws NameFormatException { /** * Get the invocations that make up this function. - * + * * @return The InvocationList associated with this function */ public final InvocationList getBody() { @@ -52,9 +51,8 @@ public final InvocationList getBody() { /** * Set the body of this function. - * - * @param invocations - * - the invocation list that will be used as the function body. + * + * @param invocations - the invocation list that will be used as the function body. */ public final void setBody(InvocationList invocations) { this.invocations = invocations; diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/IInvocationTargetVisitor.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/IInvocationTargetVisitor.java index 8440b54..988da95 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/IInvocationTargetVisitor.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/IInvocationTargetVisitor.java @@ -19,24 +19,21 @@ /** * This is used when an InvocationTarget's acceptInvocationTargetVisitor method * is called by the interpreter. - * */ public interface IInvocationTargetVisitor { /** * Operates on the Function object - * - * @param c - * - The function to be executed + * + * @param c - The function to be executed * @throws Throwable */ void visitFunction(Function c) throws Throwable; /** * Operates on a Command object - * - * @param abstractCommand - * - The command to be executed + * + * @param abstractCommand - The command to be executed * @throws Throwable */ void visitCommand(Command abstractCommand) throws Throwable; diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/InvocationTarget.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/InvocationTarget.java index a722a7c..81bc9df 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/InvocationTarget.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/InvocationTarget.java @@ -29,10 +29,8 @@ /** * Common base class for any form of invocation target. - * + *

* TODO: Throw an exception if a parameter has already been defined? - * - * */ public abstract class InvocationTarget { // TODO: Come to a consensus on what should be a valid name, potentially @@ -47,7 +45,7 @@ public abstract class InvocationTarget { // TODO: Determine if allParameters is really better as a separately managed // set. private final Set allParameters; // union of required and optional - // parameters + // parameters private final Set productions; protected static Map globalContext = new HashMap(); @@ -58,9 +56,8 @@ protected static Map getGlobalContext() { /** * Used to set global context to be used by the command. - * - * @param contextGlobal - * - The map to be used as the global context. + * + * @param contextGlobal - The map to be used as the global context. */ protected static void setGlobalContext(Map contextGlobal) { Command.globalContext = contextGlobal; @@ -68,11 +65,9 @@ protected static void setGlobalContext(Map contextGlobal) { /** * Used to add values to the global context of the command. - * - * @param key - * - the key to be used in the map. - * @param value - * - the value to be stored in the context. + * + * @param key - the key to be used in the map. + * @param value - the value to be stored in the context. */ protected static void putToGlobalContext(String key, Object value) { Command.globalContext.put(key, value); @@ -81,9 +76,8 @@ protected static void putToGlobalContext(String key, Object value) { /** * Used to get an object from the global context that is associated with the * passed in key. - * - * @param key - * - the key associated with the value in the global context + * + * @param key - the key associated with the value in the global context * @return the value in the context. */ public static Object getFromGlobalContext(String key) { @@ -101,9 +95,8 @@ protected static void cleanGlobalContext() { * This is called when the InvocationTarget is instantiated by the * interpreter. All sets used to keep track of the invocation targets * parameters are instantiated as well. - * - * @param name - * - name of the invocation target. + * + * @param name - name of the invocation target. * @throws NameFormatException */ public InvocationTarget(String name) throws NameFormatException { @@ -121,7 +114,7 @@ public InvocationTarget(String name) throws NameFormatException { /** * Get the name of this InvocationTarget - * + * * @return the name of the target. */ public final String getName() { @@ -130,7 +123,7 @@ public final String getName() { /** * Get the usage of this InvocationTarget - * + * * @return the usage of the target. */ public final String getUsage() { @@ -139,9 +132,8 @@ public final String getUsage() { /** * Set the usage of this InvocationTarget - * - * @param usage - * - the new value for this InvocationTargets usage + * + * @param usage - the new value for this InvocationTargets usage */ public final void setUsage(String usage) { this.usage = usage; @@ -149,7 +141,7 @@ public final void setUsage(String usage) { /** * Get all of the required parameters of this InvocationTarget - * + * * @return A read-only set of required parameters */ public final Set getRequiredParameters() { @@ -158,9 +150,8 @@ public final Set getRequiredParameters() { /** * Add a new value as a required parameter. - * - * @param name - * - the name to be used for this required parameter. + * + * @param name - the name to be used for this required parameter. */ public final void addRequiredParameter(String name) { name = name.toLowerCase(); @@ -170,7 +161,7 @@ public final void addRequiredParameter(String name) { /** * Get all of the registered optional parameters of this InvocationTarget. - * + * * @return the set containing all of the optional parameters. */ public final Set getOptionalParameters() { @@ -179,9 +170,8 @@ public final Set getOptionalParameters() { /** * Add a new value as an optional parameter. - * - * @param name - * - the name to be used for this optional parameter. + * + * @param name - the name to be used for this optional parameter. */ public final void addOptionalParameter(String name) { name = name.toLowerCase(); @@ -191,7 +181,7 @@ public final void addOptionalParameter(String name) { /** * Get all of the parameters of this InvocationTarget. - * + * * @return the set containing all of the parameters. */ public final Set getAllParameters() { @@ -200,7 +190,7 @@ public final Set getAllParameters() { /** * Get all of the productions of this InvocationTarget. - * + * * @return the set containing all of the productions. */ public final Set getProductions() { @@ -209,9 +199,8 @@ public final Set getProductions() { /** * Add a new value to the production set. - * - * @param name - * - the name to be used for this production. + * + * @param name - the name to be used for this production. */ public final void addProduction(String name) { this.productions.add(name.toLowerCase()); @@ -219,6 +208,7 @@ public final void addProduction(String name) { /** * This is used by the interpreter to either execute the command or the function. + * * @param v - The interpreter that is executing this InvocationTarget. * @throws Throwable */ diff --git a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationListVisitor.java b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationListVisitor.java index cf42511..17328f3 100644 --- a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationListVisitor.java +++ b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationListVisitor.java @@ -21,10 +21,11 @@ */ public interface IInvocationListVisitor { - /** - * Perform some operation on a statement list - * @param sl - * @throws Throwable - */ - void visitStatementList(InvocationList sl) throws Throwable; + /** + * Perform some operation on a statement list + * + * @param sl + * @throws Throwable + */ + void visitStatementList(InvocationList sl) throws Throwable; } diff --git a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java index 51ffda9..b839de3 100644 --- a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java +++ b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java @@ -21,11 +21,12 @@ */ public interface IInvocationVisitor { - /** - * Visit Invocation - * @param Invocation - represent calls to Commands, Functions, etc - * @throws Throwable - */ - void visitInvocation(Invocation invocation) throws Throwable; + /** + * Visit Invocation + * + * @param Invocation - represent calls to Commands, Functions, etc + * @throws Throwable + */ + void visitInvocation(Invocation invocation) throws Throwable; } diff --git a/src/main/java/org/finra/jtaf/core/model/statement/Invocation.java b/src/main/java/org/finra/jtaf/core/model/statement/Invocation.java index ac6ea29..9222a6d 100644 --- a/src/main/java/org/finra/jtaf/core/model/statement/Invocation.java +++ b/src/main/java/org/finra/jtaf/core/model/statement/Invocation.java @@ -26,54 +26,50 @@ * A class representing an invocable test step. * Primarily used to validate a Command's registration in the command library */ -public class Invocation { - private final String targetName; - private Map parameters; - - public Invocation(String targetName) { - this.targetName = targetName; - this.parameters = new HashMap(); - } +public class Invocation { + private final String targetName; + private Map parameters; - /*** - * - * @return targetName - name of the target - */ - public final String getTargetName() { - return this.targetName; - } + public Invocation(String targetName) { + this.targetName = targetName; + this.parameters = new HashMap(); + } - /*** - * - * @return parameters - map of parameter key-values - */ - public final Map getParameters() { - return this.parameters; - } - - /*** - * - * @param parameters - map of parameter key-values - */ - public final void setParameters(Map parameters) { - this.parameters = new HashMap(); - this.parameters.putAll(parameters); - } + /*** + * @return targetName - name of the target + */ + public final String getTargetName() { + return this.targetName; + } - /*** - * - * @return a String representation of the Invocation in the following format: - * Target Name(key1=value1, key2=value2) - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.getTargetName()); - sb.append("("); - sb.append(StringHelper.join(this.getParameters().entrySet(), ", ")); - sb.append(")"); - - return sb.toString(); - } + /*** + * @return parameters - map of parameter key-values + */ + public final Map getParameters() { + return this.parameters; + } + + /*** + * @param parameters - map of parameter key-values + */ + public final void setParameters(Map parameters) { + this.parameters = new HashMap(); + this.parameters.putAll(parameters); + } + + /*** + * @return a String representation of the Invocation in the following format: + * Target Name(key1=value1, key2=value2) + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(this.getTargetName()); + sb.append("("); + sb.append(StringHelper.join(this.getParameters().entrySet(), ", ")); + sb.append(")"); + + return sb.toString(); + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/statement/InvocationList.java b/src/main/java/org/finra/jtaf/core/model/statement/InvocationList.java index f3131cd..2707846 100644 --- a/src/main/java/org/finra/jtaf/core/model/statement/InvocationList.java +++ b/src/main/java/org/finra/jtaf/core/model/statement/InvocationList.java @@ -24,14 +24,15 @@ * This is a object to manage an ordered list of IStatement nodes */ public class InvocationList extends ArrayList { - private static final long serialVersionUID = -7720009887819987235L; + private static final long serialVersionUID = -7720009887819987235L; - /*** - * Accept an automation node visitor - * @param v - IScriptVisitor object of any type - * @throws Throwable - */ - public void acceptAutomationNodeVisitor(IScriptVisitor v) throws Throwable { - v.visitStatementList(this); - } + /*** + * Accept an automation node visitor + * + * @param v - IScriptVisitor object of any type + * @throws Throwable + */ + public void acceptAutomationNodeVisitor(IScriptVisitor v) throws Throwable { + v.visitStatementList(this); + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/ITestComponentFactory.java b/src/main/java/org/finra/jtaf/core/model/test/ITestComponentFactory.java index 17e53dc..d2beefb 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/ITestComponentFactory.java +++ b/src/main/java/org/finra/jtaf/core/model/test/ITestComponentFactory.java @@ -19,16 +19,15 @@ /** * Retrieves test model elements from some backend. The backend is the file * system and certain XML files - * */ public interface ITestComponentFactory { - /** - * Retrieves a component given its TestPath. TODO: Perhaps this should just - * be a URI? - * - * @param path - * @return - */ - TestComponent getComponent(TestPath path); + /** + * Retrieves a component given its TestPath. TODO: Perhaps this should just + * be a URI? + * + * @param path + * @return + */ + TestComponent getComponent(TestPath path); } diff --git a/src/main/java/org/finra/jtaf/core/model/test/ITestVisitor.java b/src/main/java/org/finra/jtaf/core/model/test/ITestVisitor.java index a7f1e94..d16a2cd 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/ITestVisitor.java +++ b/src/main/java/org/finra/jtaf/core/model/test/ITestVisitor.java @@ -18,28 +18,30 @@ /** * Visitor for different test elements - * */ public interface ITestVisitor { - /** - * Operates on a folder level - * @param testSuite - * @throws Exception - */ - void visitTestNamespace(TestNamespace suite) throws Exception; - - - /** - * Operates on a Test element - * @param test - * @throws Exception - */ - void visitTestScript(TestScript test) throws Exception; - - /** - * Operates on a file level - * @param testSuite - */ - void visitTestSuite(TestSuite testSuite) throws Exception; + /** + * Operates on a folder level + * + * @param testSuite + * @throws Exception + */ + void visitTestNamespace(TestNamespace suite) throws Exception; + + + /** + * Operates on a Test element + * + * @param test + * @throws Exception + */ + void visitTestScript(TestScript test) throws Exception; + + /** + * Operates on a file level + * + * @param testSuite + */ + void visitTestSuite(TestSuite testSuite) throws Exception; } diff --git a/src/main/java/org/finra/jtaf/core/model/test/Requirement.java b/src/main/java/org/finra/jtaf/core/model/test/Requirement.java index 4bab221..b393faf 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/Requirement.java +++ b/src/main/java/org/finra/jtaf/core/model/test/Requirement.java @@ -20,19 +20,22 @@ * Represents the requirement the test is addressing. */ public class Requirement { - String type; - String value; + String type; + String value; - public String getType() { - return type; - } - public void setType(String key) { - this.type = key; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } + public String getType() { + return type; + } + + public void setType(String key) { + this.type = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestAgenda.java b/src/main/java/org/finra/jtaf/core/model/test/TestAgenda.java index c8ceeea..68f53eb 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestAgenda.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestAgenda.java @@ -24,68 +24,67 @@ /** * Maintains a list of TestScripts that have been executed and TestScripts that still need to be executed - * */ public class TestAgenda { - private final List testScripts; + private final List testScripts; + + private Set automationValues; + private int maxThreads = 1; + + public TestAgenda() { + testScripts = new ArrayList(); + automationValues = new HashSet(); + } + + public List getTestScripts() { + return testScripts; + } + + /** + * This is a set operation and values are converted to lowercase first + * + * @param automationValue + * @return + */ + public boolean addAutomationValue(String automationValue) { + return this.automationValues.add(automationValue.toLowerCase()); + } - private Set automationValues; - private int maxThreads = 1; + /** + * returns a read only version of the set of automation values for the test agenda + * + * @return read only set of automation values + */ + public Set getAutomationValues() { + Set setToWrap = automationValues == null ? (new HashSet()) : automationValues; + return Collections.unmodifiableSet(setToWrap); + } - public TestAgenda() { - testScripts = new ArrayList(); - automationValues = new HashSet(); - } + /** + * Checks whether the automationValues set contains the given value. + * Ensures correct case sensitivity. + * + * @param value to check for + * @return true if value exists, case insensitive + */ + public boolean containsAutomationValue(String value) { + return value != null && (automationValues == null ? false : automationValues.contains(value.toLowerCase())); + } - public List getTestScripts() { - return testScripts; - } + /** + * pass through of is empty for the automationValues set . + * + * @return true if null or empty + */ + public boolean isAutomationValuesEmpty() { + return automationValues == null ? true : automationValues.isEmpty(); + } - /** - * This is a set operation and values are converted to lowercase first - * - * @param automationValue - * @return - */ - public boolean addAutomationValue(String automationValue) { - return this.automationValues.add(automationValue.toLowerCase()); - } - - /** - * returns a read only version of the set of automation values for the test agenda - * - * @return read only set of automation values - */ - public Set getAutomationValues() { - Set setToWrap = automationValues == null ? (new HashSet()) : automationValues; - return Collections.unmodifiableSet(setToWrap); - } - - /** - * Checks whether the automationValues set contains the given value. - * Ensures correct case sensitivity. - * - * @param value to check for - * @return true if value exists, case insensitive - */ - public boolean containsAutomationValue(String value) { - return value != null && (automationValues == null ? false : automationValues.contains(value.toLowerCase())); - } - - /** - * pass through of is empty for the automationValues set . - * - * @return true if null or empty - */ - public boolean isAutomationValuesEmpty() { - return automationValues == null ? true : automationValues.isEmpty(); - } + public void setThreadCount(String threads) { + maxThreads = Integer.parseInt(threads); + } - public void setThreadCount(String threads){ - maxThreads = Integer.parseInt(threads); - } - - public int getThreadCount(){ - return maxThreads; - } + public int getThreadCount() { + return maxThreads; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestComponent.java b/src/main/java/org/finra/jtaf/core/model/test/TestComponent.java index 7d5b5d2..b20cf90 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestComponent.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestComponent.java @@ -25,134 +25,132 @@ /** * Base class of all test-related components within the model, includes only TestScripts and TestNamespaces. - * + *

* This class serves a few primary tasks: 1. It ensures that all subcomponents have proper names 2. It provides generic methods that can be used to crawl the model - * */ public abstract class TestComponent { - // TODO: This needs to be stricter - private static final Pattern VALID_NAME = Pattern.compile("[^/]+"); - - private String name; - private TestNamespace parent; - - /** - * - * @param name - * @param parent - * @throws NameFormatException - */ - public TestComponent(String name) throws NameFormatException { - if (!TestComponent.VALID_NAME.matcher(name).matches()) { - throw new NameFormatException(name, TestComponent.VALID_NAME); - } - this.name = name; - this.parent = null; - } - - public final String getName() { - return name; - } - - public final void setName(String name) { - this.name = name; - } - - /** - * @return The full name of the component, including names of parent components - */ - public final String getFullName() { - StringBuilder sb = new StringBuilder(); - getFullNameHelper(sb); - return sb.toString(); - } - - private final void getFullNameHelper(StringBuilder sb) { - if (getParent() != null) { - TestComponent p = getParent(); - p.getFullNameHelper(sb); - } - sb.append("/"); - sb.append(getName()); - } - - /** - * @return The TestGroup object that owns this TestTarget, or null if none exists - */ - public final TestNamespace getParent() { - return parent; - } - - /** - * Invoked by TestNamespace.addChild(). TestNamespace handles the details of disconnecting the previous parent. - * - * @param parent - */ - protected final void setParent(TestNamespace parent) { - this.parent = parent; - } - - /** - * Returns a parent or child of the current node depending upon the token provided. Subclasses should invoke super.getNeighbor() before implementing their own logic - * - * @param token - * @return - */ - public List getNeighbor(String token) { - List newComponentMap = new ArrayList(); - - if ((token == null) || (token.equals("")) || (token.equals(TestPath.CURRENT))) { - newComponentMap.add(this); - } else if (token.equals(TestPath.PARENT)) { - newComponentMap.add(getParent()); - } else { - return null; - } - return newComponentMap; - } - - /** - * Travel from this component to another component via the given path. This just calls getNeighbor() repeatedly against the components of the path until the destination is reached. - * - * @param path - * @return - */ - public final List toComponent(TestPath path) { - List newComponentMap = new ArrayList(); - - TestComponent current = this; - // If this is an absolute path, then we need to start from the root. - if (path.isAbsolute()) { - while (current.getParent() != null) { - current = current.getParent(); - } - } - //This is the root namespace ("testscripts") - newComponentMap.add(current); - - //This cycles through the provided components of the TestPath delimited by "/" to get to the right componentmap - if (path.getComponents().length > 0) { - for (String c : path.getComponents()) { - newComponentMap = newComponentMap.get(0).getNeighbor(c); - if (newComponentMap == null) { - return null; - } - } - } else { - newComponentMap.add(current); - } - return newComponentMap; - } - - /** - * Convenience method: Converts a String to a TestPath - * - * @param path - * @return - */ - public final List toComponent(String path) { - return toComponent(new TestPath(path)); - } - - public abstract void acceptTestVisitor(ITestVisitor v) throws Exception; + // TODO: This needs to be stricter + private static final Pattern VALID_NAME = Pattern.compile("[^/]+"); + + private String name; + private TestNamespace parent; + + /** + * @param name + * @param parent + * @throws NameFormatException + */ + public TestComponent(String name) throws NameFormatException { + if (!TestComponent.VALID_NAME.matcher(name).matches()) { + throw new NameFormatException(name, TestComponent.VALID_NAME); + } + this.name = name; + this.parent = null; + } + + public final String getName() { + return name; + } + + public final void setName(String name) { + this.name = name; + } + + /** + * @return The full name of the component, including names of parent components + */ + public final String getFullName() { + StringBuilder sb = new StringBuilder(); + getFullNameHelper(sb); + return sb.toString(); + } + + private final void getFullNameHelper(StringBuilder sb) { + if (getParent() != null) { + TestComponent p = getParent(); + p.getFullNameHelper(sb); + } + sb.append("/"); + sb.append(getName()); + } + + /** + * @return The TestGroup object that owns this TestTarget, or null if none exists + */ + public final TestNamespace getParent() { + return parent; + } + + /** + * Invoked by TestNamespace.addChild(). TestNamespace handles the details of disconnecting the previous parent. + * + * @param parent + */ + protected final void setParent(TestNamespace parent) { + this.parent = parent; + } + + /** + * Returns a parent or child of the current node depending upon the token provided. Subclasses should invoke super.getNeighbor() before implementing their own logic + * + * @param token + * @return + */ + public List getNeighbor(String token) { + List newComponentMap = new ArrayList(); + + if ((token == null) || (token.equals("")) || (token.equals(TestPath.CURRENT))) { + newComponentMap.add(this); + } else if (token.equals(TestPath.PARENT)) { + newComponentMap.add(getParent()); + } else { + return null; + } + return newComponentMap; + } + + /** + * Travel from this component to another component via the given path. This just calls getNeighbor() repeatedly against the components of the path until the destination is reached. + * + * @param path + * @return + */ + public final List toComponent(TestPath path) { + List newComponentMap = new ArrayList(); + + TestComponent current = this; + // If this is an absolute path, then we need to start from the root. + if (path.isAbsolute()) { + while (current.getParent() != null) { + current = current.getParent(); + } + } + //This is the root namespace ("testscripts") + newComponentMap.add(current); + + //This cycles through the provided components of the TestPath delimited by "/" to get to the right componentmap + if (path.getComponents().length > 0) { + for (String c : path.getComponents()) { + newComponentMap = newComponentMap.get(0).getNeighbor(c); + if (newComponentMap == null) { + return null; + } + } + } else { + newComponentMap.add(current); + } + return newComponentMap; + } + + /** + * Convenience method: Converts a String to a TestPath + * + * @param path + * @return + */ + public final List toComponent(String path) { + return toComponent(new TestPath(path)); + } + + public abstract void acceptTestVisitor(ITestVisitor v) throws Exception; } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestNamespace.java b/src/main/java/org/finra/jtaf/core/model/test/TestNamespace.java index 8915678..03d2d1e 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestNamespace.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestNamespace.java @@ -31,144 +31,146 @@ /** * These are the internal nodes of our testing model. - * */ public class TestNamespace extends TestComponent implements Iterable { - // The set of all objects and namespaces. Used for efficiency - private final Map componentMap; - private final List componentList; - //This might not be necessary after TestSuite.java has been done - // TODO: determine if suiteMap is still necessary - // TODO: if the above is true, implement suiteMap as singleton - private final Map suiteMap; - - protected static TestNamespace root = null; - /** - * Instantiates a new TestGroup without a parent. The - * parent is assigned when the TestGroup is added to - * - * @param name - * @throws NameFormatException - */ - public TestNamespace(String name) throws NameFormatException { - super(name); - - componentMap = new TreeMap(); - componentList = new LinkedList(); - //This logic is so that only the TestNamespace root has the suiteMapping. - if (root == null){ - suiteMap = new HashMap(); - root = this; - }else{ - suiteMap = null; - } - } - - - /** - * @param name - * @return True if this namespace contains a component w/ the supplied name - */ - public final boolean isComponentMapContain(String name) { - return componentMap.containsKey(name); - } - - /** - * @param c - * @return True if this contains the given component - */ - public final boolean contains(TestComponent c) { - return componentMap.containsValue(c); - } - - - public final void add(TestComponent testComponent) throws NameCollisionException { - // Don't allow multiple components to have the same name - if(isComponentMapContain(testComponent.getName())) { - throw new NameCollisionException(testComponent.getName()); - } - componentMap.put(testComponent.getName(), testComponent); - componentList.add(testComponent); - testComponent.setParent(this); - - if (this instanceof TestNamespace && testComponent instanceof TestSuite){ - setSuiteMapping((TestSuite) testComponent); - } - } - - //MULTITHREAD 2012.4--START----------------------------------- - //This needs to find the testScripts TestNamespace and then propogate the testSuiteName - //and the TestScript name up to that level - //This should only set the suitemapping on the main root - private void setSuiteMapping(TestSuite ts) throws NameCollisionException{ - String suiteName = ts.getTestSuiteName(); - if (root.suiteMap.containsKey(suiteName)){ - //this exists already throw exception - throw new NameCollisionException(suiteName); - } - root.suiteMap.put(suiteName, ts); - } - - public Map getTestSuiteMapping(){ - return root.suiteMap; - } - - //MULTITHREAD 2012.4-------END------------------------------ - - @Override - public final List getNeighbor(String name) { - List newComponentMap = new ArrayList(); - List neighbors = super.getNeighbor(name); - if (neighbors != null && neighbors.size() > 0) { - newComponentMap.addAll(neighbors); - } else { - newComponentMap.addAll(getWithOutTestDataInfo(name)); - } - return newComponentMap; - } - - - public final List getWithOutTestDataInfo(String name) { - List newComponentMap = new ArrayList(); - - Set keys = componentMap.keySet(); - for (String key: keys) { - if (removeTestDataAdditionalInfo(key).equalsIgnoreCase(name)) { - newComponentMap.add(componentMap.get(key)); - } - } - return newComponentMap; - } - - - private String removeTestDataAdditionalInfo(String name) { - // remove ' []' section - String[] names = name.split("[ ]*\\["); - return names[0]; - } - - - /** - * This returns a copy of the component list in order to - * prevent people from muddling w/ the internal state of - * the class. - * @return A copy of the component list - */ - public final List getComponentList() { - return componentList; - } - - // TODO: remove if truly not used - /** - * FIXME: This should return a read-only iterator - * NOT USED - */ - public final Iterator iterator() { - return this.getComponentList().iterator(); - } - - public final void acceptTestVisitor(ITestVisitor v) throws Exception { - v.visitTestNamespace(this); - } + // The set of all objects and namespaces. Used for efficiency + private final Map componentMap; + private final List componentList; + //This might not be necessary after TestSuite.java has been done + // TODO: determine if suiteMap is still necessary + // TODO: if the above is true, implement suiteMap as singleton + private final Map suiteMap; + + protected static TestNamespace root = null; + + /** + * Instantiates a new TestGroup without a parent. The + * parent is assigned when the TestGroup is added to + * + * @param name + * @throws NameFormatException + */ + public TestNamespace(String name) throws NameFormatException { + super(name); + + componentMap = new TreeMap(); + componentList = new LinkedList(); + //This logic is so that only the TestNamespace root has the suiteMapping. + if (root == null) { + suiteMap = new HashMap(); + root = this; + } else { + suiteMap = null; + } + } + + + /** + * @param name + * @return True if this namespace contains a component w/ the supplied name + */ + public final boolean isComponentMapContain(String name) { + return componentMap.containsKey(name); + } + + /** + * @param c + * @return True if this contains the given component + */ + public final boolean contains(TestComponent c) { + return componentMap.containsValue(c); + } + + + public final void add(TestComponent testComponent) throws NameCollisionException { + // Don't allow multiple components to have the same name + if (isComponentMapContain(testComponent.getName())) { + throw new NameCollisionException(testComponent.getName()); + } + componentMap.put(testComponent.getName(), testComponent); + componentList.add(testComponent); + testComponent.setParent(this); + + if (this instanceof TestNamespace && testComponent instanceof TestSuite) { + setSuiteMapping((TestSuite) testComponent); + } + } + + //MULTITHREAD 2012.4--START----------------------------------- + //This needs to find the testScripts TestNamespace and then propogate the testSuiteName + //and the TestScript name up to that level + //This should only set the suitemapping on the main root + private void setSuiteMapping(TestSuite ts) throws NameCollisionException { + String suiteName = ts.getTestSuiteName(); + if (root.suiteMap.containsKey(suiteName)) { + //this exists already throw exception + throw new NameCollisionException(suiteName); + } + root.suiteMap.put(suiteName, ts); + } + + public Map getTestSuiteMapping() { + return root.suiteMap; + } + + //MULTITHREAD 2012.4-------END------------------------------ + + @Override + public final List getNeighbor(String name) { + List newComponentMap = new ArrayList(); + List neighbors = super.getNeighbor(name); + if (neighbors != null && neighbors.size() > 0) { + newComponentMap.addAll(neighbors); + } else { + newComponentMap.addAll(getWithOutTestDataInfo(name)); + } + return newComponentMap; + } + + + public final List getWithOutTestDataInfo(String name) { + List newComponentMap = new ArrayList(); + + Set keys = componentMap.keySet(); + for (String key : keys) { + if (removeTestDataAdditionalInfo(key).equalsIgnoreCase(name)) { + newComponentMap.add(componentMap.get(key)); + } + } + return newComponentMap; + } + + + private String removeTestDataAdditionalInfo(String name) { + // remove ' []' section + String[] names = name.split("[ ]*\\["); + return names[0]; + } + + + /** + * This returns a copy of the component list in order to + * prevent people from muddling w/ the internal state of + * the class. + * + * @return A copy of the component list + */ + public final List getComponentList() { + return componentList; + } + + // TODO: remove if truly not used + + /** + * FIXME: This should return a read-only iterator + * NOT USED + */ + public final Iterator iterator() { + return this.getComponentList().iterator(); + } + + public final void acceptTestVisitor(ITestVisitor v) throws Exception { + v.visitTestNamespace(this); + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestPath.java b/src/main/java/org/finra/jtaf/core/model/test/TestPath.java index 6c9b6f7..bdfd0dc 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestPath.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestPath.java @@ -22,73 +22,73 @@ * - Removes unnecessary '/' characters * - Determines if the path is absolute * - Splits the components - * */ public class TestPath { - public static final String SEPARATOR = "/"; - public static final String CURRENT = "."; - public static final String PARENT = ".."; + public static final String SEPARATOR = "/"; + public static final String CURRENT = "."; + public static final String PARENT = ".."; + + + private final String path; + private final String normalizedPath; + private final String[] components; + private final boolean absolute; - - private final String path; - private final String normalizedPath; - private final String[] components; - private final boolean absolute; + public TestPath(final String path) { + this.path = path; + normalizedPath = path.replaceAll("/+", "/"); - public TestPath(final String path) { - this.path = path; - normalizedPath = path.replaceAll("/+", "/"); + String[] temp = normalizedPath.split(TestPath.SEPARATOR); + if (normalizedPath.charAt(0) == '/') { + absolute = true; + } else { + absolute = false; + } + components = temp; + } - String[] temp = normalizedPath.split(TestPath.SEPARATOR); - if(normalizedPath.charAt(0) == '/') { - absolute = true; - } - else { - absolute = false; - } - components = temp; - } + /** + * @return True if this is an absolute path; false otherwise + */ + public final boolean isAbsolute() { + return absolute; + } - /** - * @return True if this is an absolute path; false otherwise - */ - public final boolean isAbsolute() { - return absolute; - } + /** + * @return True if this is a relative path; false otherwise + */ + public final boolean isRelative() { + return !absolute; + } - /** - * @return True if this is a relative path; false otherwise - */ - public final boolean isRelative() { - return !absolute; - } + /** + * This is identical to toString + * + * @return + */ + public final String getPath() { + return path; + } - /** - * This is identical to toString - * @return - */ - public final String getPath() { - return path; - } - - /** - * @return The path wo/ duplicate / characters - */ - public final String getNormalizedPath() { - return normalizedPath; - } + /** + * @return The path wo/ duplicate / characters + */ + public final String getNormalizedPath() { + return normalizedPath; + } - /** - * TODO: It may be necessary to return a copy of the components - * @return - */ - public String[] getComponents() { - return components; - } + /** + * TODO: It may be necessary to return a copy of the components + * + * @return + */ + public String[] getComponents() { + return components; + } - public String toString() { - return path; - } + public String toString() { + return path; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestResult.java b/src/main/java/org/finra/jtaf/core/model/test/TestResult.java index 3108d05..fef131a 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestResult.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestResult.java @@ -22,85 +22,93 @@ * This class represents the test result for the test */ public class TestResult { - private final List testStepsDetails; - private Throwable failureReason; - private TestStatus testStatus; - - - /** - * Initialize the TestResult with the current list of test steps, and the test status - * @param testStepsDetails - * @param teststatus - */ - public TestResult(List testStepsDetails, TestStatus teststatus) { - this.testStepsDetails = testStepsDetails; - this.testStatus = teststatus; - } - - /** - * Initialize the TestResult with the current list of test steps, and the test status, and the failure reason - * @param testStepsDetails - * @param teststatus - * @param failureReason - */ - public TestResult(List testStepsDetails, TestStatus teststatus, Throwable failureReason) { - this.testStepsDetails = testStepsDetails; - this.testStatus = teststatus; - this.failureReason = failureReason; - } - - - /** - * Return if the current test passed - * @return - */ - public boolean isTestPassed() { - if(failureReason == null) { - return true; - }else { - return false; - } - } - - - /** - * Return the list of test steps for the current test - * @return - */ - public List getTestStepsDetails() { - return testStepsDetails; - } - - /** - * Set the failure reason for the current test - * @param failureReason - */ - public void setFailureReason(Throwable failureReason){ - this.failureReason = failureReason; - } - - /** - * Return the failure reason for the current test - * @return - */ - public Throwable getFailureReason() { - return failureReason; - } - - /** - * Update the test status - * @param testStatus - */ - public void updateTestStatus(TestStatus testStatus){ - this.testStatus = testStatus; - } - - /** - * Get the test status - * @return - */ - public TestStatus getTestStatus(){ - return this.testStatus; - } - + private final List testStepsDetails; + private Throwable failureReason; + private TestStatus testStatus; + + + /** + * Initialize the TestResult with the current list of test steps, and the test status + * + * @param testStepsDetails + * @param teststatus + */ + public TestResult(List testStepsDetails, TestStatus teststatus) { + this.testStepsDetails = testStepsDetails; + this.testStatus = teststatus; + } + + /** + * Initialize the TestResult with the current list of test steps, and the test status, and the failure reason + * + * @param testStepsDetails + * @param teststatus + * @param failureReason + */ + public TestResult(List testStepsDetails, TestStatus teststatus, Throwable failureReason) { + this.testStepsDetails = testStepsDetails; + this.testStatus = teststatus; + this.failureReason = failureReason; + } + + + /** + * Return if the current test passed + * + * @return + */ + public boolean isTestPassed() { + if (failureReason == null) { + return true; + } else { + return false; + } + } + + + /** + * Return the list of test steps for the current test + * + * @return + */ + public List getTestStepsDetails() { + return testStepsDetails; + } + + /** + * Set the failure reason for the current test + * + * @param failureReason + */ + public void setFailureReason(Throwable failureReason) { + this.failureReason = failureReason; + } + + /** + * Return the failure reason for the current test + * + * @return + */ + public Throwable getFailureReason() { + return failureReason; + } + + /** + * Update the test status + * + * @param testStatus + */ + public void updateTestStatus(TestStatus testStatus) { + this.testStatus = testStatus; + } + + /** + * Get the test status + * + * @return + */ + public TestStatus getTestStatus() { + return this.testStatus; + } + } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestScript.java b/src/main/java/org/finra/jtaf/core/model/test/TestScript.java index 3bac8d3..c99c5cc 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestScript.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestScript.java @@ -27,190 +27,190 @@ /** * This class represents a test script object - * */ public final class TestScript extends TestComponent { - private InvocationList body; - - // TODO: Build generatic annotation support - private String issue; - private List crs; - // TODO: Status should be lists/sets/not Strings - private String status; - private String testCaseID; - private String automationValue; - private String coverage; - private ArrayList requirements; - private String description; - private String fileName; - private String testSuiteName; - private static boolean isCaptureSystemInformationGlobally = false; - private boolean isCaptureSystemInformation = false; - private Dependencies dependencies; - private Dependencies exclusions; - - private String exception=""; - - public TestScript(String name, boolean isCaptureSystemInformation) throws NameFormatException { - super(name); - this.body = new InvocationList(); - this.crs = new ArrayList(); - this.status = null; - this.requirements = new ArrayList(); - this.isCaptureSystemInformation = isCaptureSystemInformation; - if (isCaptureSystemInformation) { - isCaptureSystemInformationGlobally = true; - } - } - - /** - * These are the primary statements executed by the Test - * @return - */ - public final InvocationList getBody() { - return this.body; - } - - /** - * Sets this test's body to the given statement list - * @param statements - */ - public final void setBody(InvocationList statements) { - this.body = statements; - } - - public final List getCRs() { - return this.crs; - } - - public void setCRs(final List crs) { - this.crs = crs; - } - - public void setIssue(String issue) { - this.issue = issue; - } - - public String getIssue() { - return issue; - } - - public final String getStatus() { - return this.status; - } - - public void setStatus(final String status) { - this.status = status; - } - - public void setAutomationValue(String automationValue) { - this.automationValue = automationValue; - } - - public String getAutomationValue() { - return automationValue; - } - - public String getCoverage() { - return coverage; - } - - public void setCoverage(String coverage) { - this.coverage = coverage; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setTestCaseID(String testCaseID) { - this.testCaseID = testCaseID; - } - - public String getTestCaseID() { - return testCaseID; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getFileName() { - return fileName; - } - - public void setTestSuiteName(String testSuiteName) { - this.testSuiteName = testSuiteName; - } - - public String getTestSuiteName() { - return testSuiteName; - } - - public void acceptTestVisitor(ITestVisitor v) throws Exception { - v.visitTestScript(this); - } - public ArrayList getRequirements() { - return requirements; - } - - public void setRequirements(ArrayList requirements) { - this.requirements = requirements; - } - - public static boolean isCaptureSystemInformationGlobally() { - return isCaptureSystemInformationGlobally; - } - - public boolean isCaptureSystemInformation() { - return isCaptureSystemInformation; - } - - public Dependencies getDependencies() { - return dependencies; - } - - public void setDependencies(Set suite, Set test) { - dependencies = new Dependencies(suite, test); - } - - public Dependencies getExclusions() { - return exclusions; - } - - public void setExclusions(Set suite, Set test) { - exclusions = new Dependencies(suite, test); - } - - - public void setException(String expectedException){ - exception=expectedException; - } - - public String getException(){ + private InvocationList body; + + // TODO: Build generatic annotation support + private String issue; + private List crs; + // TODO: Status should be lists/sets/not Strings + private String status; + private String testCaseID; + private String automationValue; + private String coverage; + private ArrayList requirements; + private String description; + private String fileName; + private String testSuiteName; + private static boolean isCaptureSystemInformationGlobally = false; + private boolean isCaptureSystemInformation = false; + private Dependencies dependencies; + private Dependencies exclusions; + + private String exception = ""; + + public TestScript(String name, boolean isCaptureSystemInformation) throws NameFormatException { + super(name); + this.body = new InvocationList(); + this.crs = new ArrayList(); + this.status = null; + this.requirements = new ArrayList(); + this.isCaptureSystemInformation = isCaptureSystemInformation; + if (isCaptureSystemInformation) { + isCaptureSystemInformationGlobally = true; + } + } + + /** + * These are the primary statements executed by the Test + * + * @return + */ + public final InvocationList getBody() { + return this.body; + } + + /** + * Sets this test's body to the given statement list + * + * @param statements + */ + public final void setBody(InvocationList statements) { + this.body = statements; + } + + public final List getCRs() { + return this.crs; + } + + public void setCRs(final List crs) { + this.crs = crs; + } + + public void setIssue(String issue) { + this.issue = issue; + } + + public String getIssue() { + return issue; + } + + public final String getStatus() { + return this.status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public void setAutomationValue(String automationValue) { + this.automationValue = automationValue; + } + + public String getAutomationValue() { + return automationValue; + } + + public String getCoverage() { + return coverage; + } + + public void setCoverage(String coverage) { + this.coverage = coverage; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setTestCaseID(String testCaseID) { + this.testCaseID = testCaseID; + } + + public String getTestCaseID() { + return testCaseID; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getFileName() { + return fileName; + } + + public void setTestSuiteName(String testSuiteName) { + this.testSuiteName = testSuiteName; + } + + public String getTestSuiteName() { + return testSuiteName; + } + + public void acceptTestVisitor(ITestVisitor v) throws Exception { + v.visitTestScript(this); + } + + public ArrayList getRequirements() { + return requirements; + } + + public void setRequirements(ArrayList requirements) { + this.requirements = requirements; + } + + public static boolean isCaptureSystemInformationGlobally() { + return isCaptureSystemInformationGlobally; + } + + public boolean isCaptureSystemInformation() { + return isCaptureSystemInformation; + } + + public Dependencies getDependencies() { + return dependencies; + } + + public void setDependencies(Set suite, Set test) { + dependencies = new Dependencies(suite, test); + } + + public Dependencies getExclusions() { + return exclusions; + } + + public void setExclusions(Set suite, Set test) { + exclusions = new Dependencies(suite, test); + } + + + public void setException(String expectedException) { + exception = expectedException; + } + + public String getException() { return exception; } - - @Override - public boolean equals(Object o){ - if (!(o instanceof TestScript)){ - return false; - } - else { - TestScript ts = (TestScript) o; - if (this.getName().equals(ts.getName()) - && this.getBody().equals(ts.getBody()) - && this.getFileName().equals(ts.getFileName()) - && this.getFullName().equals(ts.getFullName())){ - return true; - } - else{ - return false; - } - } - } + + @Override + public boolean equals(Object o) { + if (!(o instanceof TestScript)) { + return false; + } else { + TestScript ts = (TestScript) o; + if (this.getName().equals(ts.getName()) + && this.getBody().equals(ts.getBody()) + && this.getFileName().equals(ts.getFileName()) + && this.getFullName().equals(ts.getFullName())) { + return true; + } else { + return false; + } + } + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestScriptCollector.java b/src/main/java/org/finra/jtaf/core/model/test/TestScriptCollector.java index 42d2833..3c6b6ed 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestScriptCollector.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestScriptCollector.java @@ -22,40 +22,40 @@ /** * Crawls the TestComponent model to discover TestScript elements - * */ public class TestScriptCollector implements ITestVisitor { - private final List testScripts; - - public TestScriptCollector() { - testScripts = new ArrayList(); - } - - /** - * @return A copy of the list of testScripts - */ - public final List getTestScripts() { - return new ArrayList(testScripts); - } - - public final void addToTestScripts(TestScript c){ - this.testScripts.add(c); - } - public void visitTestNamespace(TestNamespace ns) throws Exception { - for(TestComponent c : ns) { - c.acceptTestVisitor(this); - } - } - - public void visitTestScript(TestScript test) throws Exception { - this.testScripts.add(test); - } - - @Override - public void visitTestSuite(TestSuite testSuite) throws Exception { - for(TestComponent c : testSuite) { - c.acceptTestVisitor(this); - } - } + private final List testScripts; + + public TestScriptCollector() { + testScripts = new ArrayList(); + } + + /** + * @return A copy of the list of testScripts + */ + public final List getTestScripts() { + return new ArrayList(testScripts); + } + + public final void addToTestScripts(TestScript c) { + this.testScripts.add(c); + } + + public void visitTestNamespace(TestNamespace ns) throws Exception { + for (TestComponent c : ns) { + c.acceptTestVisitor(this); + } + } + + public void visitTestScript(TestScript test) throws Exception { + this.testScripts.add(test); + } + + @Override + public void visitTestSuite(TestSuite testSuite) throws Exception { + for (TestComponent c : testSuite) { + c.acceptTestVisitor(this); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java b/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java index bf2e96e..0b104bd 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java @@ -18,10 +18,9 @@ /** * Enum to maintain status of the current test - * */ public enum TestStatus { - Running, // Test failed, but we still need to run plugins + Running, // Test failed, but we still need to run plugins Failed, // Test passed, but we still need to run plugins Passed } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestStepsDetails.java b/src/main/java/org/finra/jtaf/core/model/test/TestStepsDetails.java index 5a5e47b..7ec5b4c 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestStepsDetails.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestStepsDetails.java @@ -18,56 +18,56 @@ /** * This class represents a single test step object i.e. a command in the test - * */ public class TestStepsDetails { - String name; - String usage; - boolean expectedResult = true; - boolean actualResult = true; - String type = "general"; + String name; + String usage; + boolean expectedResult = true; + boolean actualResult = true; + String type = "general"; + + public TestStepsDetails(String name, String usage) { + this.name = name; + this.usage = usage; + } - public TestStepsDetails(String name, String usage){ - this.name=name; - this.usage=usage; - } - public String getUsage() { - return usage; - } + public String getUsage() { + return usage; + } - public void setUsage(String usage) { - this.usage = usage; - } + public void setUsage(String usage) { + this.usage = usage; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public boolean getExpectedResult() { - return expectedResult; - } + public boolean getExpectedResult() { + return expectedResult; + } - public void setExpectedResult(boolean expectedResult) { - this.expectedResult = expectedResult; - } + public void setExpectedResult(boolean expectedResult) { + this.expectedResult = expectedResult; + } - public boolean getActualResult() { - return actualResult; - } + public boolean getActualResult() { + return actualResult; + } - public void setActualResult(boolean actualResult) { - this.actualResult = actualResult; - } + public void setActualResult(boolean actualResult) { + this.actualResult = actualResult; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java b/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java index 6db0b43..ca0f715 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java @@ -21,53 +21,57 @@ /** * This class represents a testsuite object - * */ -public class TestSuite extends TestNamespace{ - private Dependencies dependencies; - private Dependencies exclusions; - private String testSuiteName; - public TestSuite(String name) throws NameFormatException { - super(name); - } +public class TestSuite extends TestNamespace { + private Dependencies dependencies; + private Dependencies exclusions; + private String testSuiteName; + + public TestSuite(String name) throws NameFormatException { + super(name); + } + + /** + * Return the tests this testsuite depends upon + * + * @return + */ + public Dependencies getDependencies() { + return dependencies; + } - /** - * Return the tests this testsuite depends upon - * @return - */ - public Dependencies getDependencies() { - return dependencies; - } + /** + * Set the dependencies for this testsuite + * + * @param dp + */ + public void setDependencies(Dependencies dp) { + dependencies = dp; + } - /** - * Set the dependencies for this testsuite - * @param dp - */ - public void setDependencies(Dependencies dp) { - dependencies = dp; - } + public Dependencies getExclusions() { + return exclusions; + } - public Dependencies getExclusions() { - return exclusions; - } + public void setExclusions(Dependencies exc) { + exclusions = exc; + } - public void setExclusions(Dependencies exc) { - exclusions = exc; - } + /** + * Return the name of the testsuite + * + * @return + */ + public String getTestSuiteName() { + return testSuiteName; + } - /** - * Return the name of the testsuite - * @return - */ - public String getTestSuiteName() { - return testSuiteName; - } - - /** - * Set the name of the testsuite - * @param tsn - */ - public void setTestSuiteName(String tsn){ - testSuiteName = tsn; - } + /** + * Set the name of the testsuite + * + * @param tsn + */ + public void setTestSuiteName(String tsn) { + testSuiteName = tsn; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java index 7f7903d..564e6f4 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java @@ -21,25 +21,25 @@ /** * Set of Test Case and Test Suite Dependencies - * */ -public class Dependencies{ - private Set dependentSuites = new HashSet(); - private Set dependentTests = new HashSet(); - - public Dependencies(Set suite, Set test){ - if (suite != null){ - dependentSuites = suite; - } - if (test != null){ - dependentTests = test; - } - } - - public Set getDependenciesSuites(){ - return dependentSuites; - } - public Set getDependenciesTests(){ - return dependentTests; - } +public class Dependencies { + private Set dependentSuites = new HashSet(); + private Set dependentTests = new HashSet(); + + public Dependencies(Set suite, Set test) { + if (suite != null) { + dependentSuites = suite; + } + if (test != null) { + dependentTests = test; + } + } + + public Set getDependenciesSuites() { + return dependentSuites; + } + + public Set getDependenciesTests() { + return dependentTests; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java index 938d646..9adcf81 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java @@ -20,24 +20,26 @@ /** * This class represents an edge in the digraph - * */ -public class DiEdge extends DefaultEdge{ - private static final long serialVersionUID = 1L; - - private boolean isExclusionEdge = false; - private boolean isDependencyEdge = false; +public class DiEdge extends DefaultEdge { + private static final long serialVersionUID = 1L; + + private boolean isExclusionEdge = false; + private boolean isDependencyEdge = false; + + public boolean isDependency() { + return isDependencyEdge; + } + + public boolean isExclusion() { + return isExclusionEdge; + } + + public void setDependencyEdge() { + isDependencyEdge = true; + } - public boolean isDependency(){ - return isDependencyEdge; - } - public boolean isExclusion(){ - return isExclusionEdge; - } - public void setDependencyEdge(){ - isDependencyEdge = true; - } - public void setExclusionEdge(){ - isExclusionEdge = true; - } + public void setExclusionEdge() { + isExclusionEdge = true; + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java index 40e21b7..d8e3057 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java @@ -15,45 +15,49 @@ * */ package org.finra.jtaf.core.model.test.digraph; + import org.finra.jtaf.core.model.test.TestScript; + /** * This class represents a vertex in the digraph - * */ -public class DiNode{ - private String testName = ""; //This shouldnt change after being set initially - private String testStatus = ""; - private TestScript testScript = null; //This shouldnt change after being set initially - - public DiNode(TestScript ts){ - this.testName = ts.getName(); - this.testScript = ts; - } - public String getTestStatus(){ - return testStatus; - } - protected void setTestStatus(String newTestStatus){ - testStatus = newTestStatus; - } - public String getTestName(){ - return testName; - } - - public TestScript getTestScript() { - return testScript; - } - @Override - public boolean equals(Object o){ - if (o instanceof DiNode){ - if (this.getTestName().equalsIgnoreCase(((DiNode) o).getTestName()) - && this.getTestScript().equals(((DiNode) o).getTestScript())){ - return true; - }else{ - return false; - } - } - else { - return false; - } - } - } \ No newline at end of file +public class DiNode { + private String testName = ""; //This shouldnt change after being set initially + private String testStatus = ""; + private TestScript testScript = null; //This shouldnt change after being set initially + + public DiNode(TestScript ts) { + this.testName = ts.getName(); + this.testScript = ts; + } + + public String getTestStatus() { + return testStatus; + } + + protected void setTestStatus(String newTestStatus) { + testStatus = newTestStatus; + } + + public String getTestName() { + return testName; + } + + public TestScript getTestScript() { + return testScript; + } + + @Override + public boolean equals(Object o) { + if (o instanceof DiNode) { + if (this.getTestName().equalsIgnoreCase(((DiNode) o).getTestName()) + && this.getTestScript().equals(((DiNode) o).getTestScript())) { + return true; + } else { + return false; + } + } else { + return false; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java index 09c34c0..c03fca0 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java @@ -32,132 +32,128 @@ /** * This factory class allows for the addition of nodes and edges into the digraph. - * */ public class DigraphFactory { - private TestDigraph digraph; - private MessageCollector mc; - - public DigraphFactory(TestDigraph digraph2, MessageCollector mc2){ - digraph = digraph2; - mc = mc2; - } - - public void createGraph(TestNamespace testNamespace){ - //First we have to do a replace on all the dependencies that specify a TestSuite name. - Map tsMap = testNamespace.getTestSuiteMapping(); - //Iterate across all the TestSuites and then assign the dependencies to the correct mapping - for (String s: tsMap.keySet()){ - Set tsDependenciesAsTests = new HashSet(); - Set tsExclusionsAsTests = new HashSet(); - //For each TestSuite object in the suitemapping, grab dependencies and convert - - TestSuite currentSuite = tsMap.get(s); - Dependencies dependSuite = currentSuite.getDependencies(); - Dependencies excludeSuite = currentSuite.getExclusions(); - - //Appending all the tests to the list - tsDependenciesAsTests.addAll(dependSuite.getDependenciesTests()); - tsExclusionsAsTests.addAll(excludeSuite.getDependenciesTests()); - - //Grabbing the TestSuite dependencies and converting - for (String dependentSuites: dependSuite.getDependenciesSuites()){ - //Given a supplied dependent suite go into the actual suite and get the test info - if (tsMap.get(dependentSuites) != null){ - for (TestComponent ts: tsMap.get(dependentSuites).getComponentList()){ - tsDependenciesAsTests.add(ts.getName()); - } - } - else{ - throw new DependencyException("The TestSuite '"+dependentSuites+"' specified for TestSuite '" + s +"' dependencies does not exist!"); - } - } - //Grabbing the TestSuite exclusions and converting - for (String excludedSuites: excludeSuite.getDependenciesSuites()){ - //Given a supplied dependent suite go into the actual suite and get the test info - if (tsMap.get(excludedSuites) != null){ - for (TestComponent ts: tsMap.get(excludedSuites).getComponentList()){ - tsExclusionsAsTests.add(ts.getName()); - } - }else{ - throw new DependencyException("The TestSuite '"+excludedSuites+"' specified for TestSuite '" + s +"' exclusions does not exist!"); - } - } - //Now all the TestSuite dependencies have been converted and placed into a list. - //Go down into the Test level and grab its dependencies. - for (TestComponent tc: currentSuite.getComponentList()){ - Dependencies dependTest = ((TestScript) tc).getDependencies(); - Dependencies excludeTest = ((TestScript) tc).getExclusions(); - Set testScriptDependencies = dependTest.getDependenciesTests(); - Set testScriptExclusions = excludeTest.getDependenciesTests(); + private TestDigraph digraph; + private MessageCollector mc; + + public DigraphFactory(TestDigraph digraph2, MessageCollector mc2) { + digraph = digraph2; + mc = mc2; + } + + public void createGraph(TestNamespace testNamespace) { + //First we have to do a replace on all the dependencies that specify a TestSuite name. + Map tsMap = testNamespace.getTestSuiteMapping(); + //Iterate across all the TestSuites and then assign the dependencies to the correct mapping + for (String s : tsMap.keySet()) { + Set tsDependenciesAsTests = new HashSet(); + Set tsExclusionsAsTests = new HashSet(); + //For each TestSuite object in the suitemapping, grab dependencies and convert + + TestSuite currentSuite = tsMap.get(s); + Dependencies dependSuite = currentSuite.getDependencies(); + Dependencies excludeSuite = currentSuite.getExclusions(); + + //Appending all the tests to the list + tsDependenciesAsTests.addAll(dependSuite.getDependenciesTests()); + tsExclusionsAsTests.addAll(excludeSuite.getDependenciesTests()); + + //Grabbing the TestSuite dependencies and converting + for (String dependentSuites : dependSuite.getDependenciesSuites()) { + //Given a supplied dependent suite go into the actual suite and get the test info + if (tsMap.get(dependentSuites) != null) { + for (TestComponent ts : tsMap.get(dependentSuites).getComponentList()) { + tsDependenciesAsTests.add(ts.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + dependentSuites + "' specified for TestSuite '" + s + "' dependencies does not exist!"); + } + } + //Grabbing the TestSuite exclusions and converting + for (String excludedSuites : excludeSuite.getDependenciesSuites()) { + //Given a supplied dependent suite go into the actual suite and get the test info + if (tsMap.get(excludedSuites) != null) { + for (TestComponent ts : tsMap.get(excludedSuites).getComponentList()) { + tsExclusionsAsTests.add(ts.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + excludedSuites + "' specified for TestSuite '" + s + "' exclusions does not exist!"); + } + } + //Now all the TestSuite dependencies have been converted and placed into a list. + //Go down into the Test level and grab its dependencies. + for (TestComponent tc : currentSuite.getComponentList()) { + Dependencies dependTest = ((TestScript) tc).getDependencies(); + Dependencies excludeTest = ((TestScript) tc).getExclusions(); + Set testScriptDependencies = dependTest.getDependenciesTests(); + Set testScriptExclusions = excludeTest.getDependenciesTests(); + + for (String tsDepend : dependTest.getDependenciesSuites()) { + //Given tsDepend as the testSuite + if (tsMap.get(tsDepend) != null) { + for (TestComponent tcTest : tsMap.get(tsDepend).getComponentList()) { + testScriptDependencies.add(tcTest.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + tsDepend + "' specified @ '" + ((TestScript) tc).getFullName() + "' dependencies does not exist!"); + } + } + for (String tsExclude : excludeTest.getDependenciesSuites()) { + //Given tsDepend as the testSuite + if (tsMap.get(tsExclude) != null) { + for (TestComponent tcTest : tsMap.get(tsExclude).getComponentList()) { + testScriptExclusions.add(tcTest.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + tsExclude + "' specified @ '" + ((TestScript) tc).getFullName() + "' exclusions does not exist!"); + } + } + testScriptDependencies.addAll(tsDependenciesAsTests); + testScriptExclusions.addAll(tsExclusionsAsTests); + addEdges(digraph.getVertex(tc.getName()), testScriptDependencies, testScriptExclusions); + } + } + checkDependencyCycles(); + } + + private void checkDependencyCycles() { + TestDigraph forCyclesGraph = new TestDigraph(new ClassBasedEdgeFactory(DiEdge.class)); + for (DiNode d : digraph.vertexSet()) { + forCyclesGraph.addVertex(d); + } + Set tempEdgeSet = new HashSet(); + tempEdgeSet.addAll(digraph.edgeSet()); + for (DiEdge e : tempEdgeSet) { + if (e.isDependency()) { + forCyclesGraph.addEdge(forCyclesGraph.getVertex(digraph.getEdgeSource(e).getTestName()), forCyclesGraph.getVertex(digraph.getEdgeTarget(e).getTestName())); + } + } + CycleDetector cd = new CycleDetector(forCyclesGraph); + Set cycleList = cd.findCycles(); + if (cycleList.size() > 0) { + mc.fatal("Cycle(s) detected"); + for (DiNode d : cycleList) { + mc.fatal("@" + d.getTestScript().getFullName()); + } + throw new DependencyException("Found cycle(s)"); + } + } - for (String tsDepend: dependTest.getDependenciesSuites()){ - //Given tsDepend as the testSuite - if (tsMap.get(tsDepend) != null){ - for(TestComponent tcTest: tsMap.get(tsDepend).getComponentList()){ - testScriptDependencies.add(tcTest.getName()); - } - } - else{ - throw new DependencyException("The TestSuite '"+tsDepend+"' specified @ '" + ((TestScript) tc).getFullName() + "' dependencies does not exist!"); - } - } - for (String tsExclude: excludeTest.getDependenciesSuites()){ - //Given tsDepend as the testSuite - if (tsMap.get(tsExclude) != null){ - for(TestComponent tcTest: tsMap.get(tsExclude).getComponentList()){ - testScriptExclusions.add(tcTest.getName()); - } - } - else{ - throw new DependencyException("The TestSuite '"+tsExclude+"' specified @ '" + ((TestScript) tc).getFullName() + "' exclusions does not exist!"); - } - } - testScriptDependencies.addAll(tsDependenciesAsTests); - testScriptExclusions.addAll(tsExclusionsAsTests); - addEdges(digraph.getVertex(tc.getName()), testScriptDependencies, testScriptExclusions); - } - } - checkDependencyCycles(); - } - private void checkDependencyCycles(){ - TestDigraph forCyclesGraph = new TestDigraph(new ClassBasedEdgeFactory(DiEdge.class)); - for (DiNode d: digraph.vertexSet()){ - forCyclesGraph.addVertex(d); - } - Set tempEdgeSet = new HashSet(); - tempEdgeSet.addAll(digraph.edgeSet()); - for(DiEdge e: tempEdgeSet){ - if (e.isDependency()){ - forCyclesGraph.addEdge(forCyclesGraph.getVertex(digraph.getEdgeSource(e).getTestName()), forCyclesGraph.getVertex(digraph.getEdgeTarget(e).getTestName())); - } - } - CycleDetector cd = new CycleDetector(forCyclesGraph); - Set cycleList = cd.findCycles(); - if (cycleList.size() > 0){ - mc.fatal("Cycle(s) detected"); - for (DiNode d: cycleList){ - mc.fatal("@"+ d.getTestScript().getFullName()); - } - throw new DependencyException("Found cycle(s)"); - } - } - private void addEdges(DiNode edgeFrom, Set dependencies, Set exclusions){ - for (String d: dependencies){ - if (digraph.getVertex(d) != null){ - digraph.addEdge(edgeFrom, digraph.getVertex(d)).setDependencyEdge(); - } - else{ - throw new DependencyException("The Test dependency: '" + d + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); - } - } - for (String e: exclusions){ - if (digraph.getVertex(e) != null){ - digraph.addEdge(edgeFrom, digraph.getVertex(e)).setExclusionEdge(); - } - else{ - throw new DependencyException("The Test exclusion: '" + e + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); - } - } - } + private void addEdges(DiNode edgeFrom, Set dependencies, Set exclusions) { + for (String d : dependencies) { + if (digraph.getVertex(d) != null) { + digraph.addEdge(edgeFrom, digraph.getVertex(d)).setDependencyEdge(); + } else { + throw new DependencyException("The Test dependency: '" + d + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); + } + } + for (String e : exclusions) { + if (digraph.getVertex(e) != null) { + digraph.addEdge(edgeFrom, digraph.getVertex(e)).setExclusionEdge(); + } else { + throw new DependencyException("The Test exclusion: '" + e + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); + } + } + } } diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java index dc02e67..64c0808 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java @@ -28,62 +28,62 @@ /** * This is a container class that houses the dependencies and exclusions across the tests. - * */ -public class TestDigraph extends AbstractBaseGraph implements DirectedGraph{ - private static final long serialVersionUID = 1L; - private Map digraphVertexMapping = new HashMap(); - - public TestDigraph(EdgeFactory arg0) { - super(arg0, true, true); - } - - - public void updateTestStatus(String testName, String status){ - digraphVertexMapping.get(testName).setTestStatus(status); - } - - public DiNode getVertex(String testName){ - return digraphVertexMapping.get(testName); - } - - @Override - public boolean addVertex(DiNode d) { - if (getVertex(d.getTestName()) != null){ - return false; - } - digraphVertexMapping.put(d.getTestName(), d); - return super.addVertex(d); - } - - @Override - public boolean removeVertex(DiNode d) { - if (getVertex(d.getTestName()) != null){ - return false; - } +public class TestDigraph extends AbstractBaseGraph implements DirectedGraph { + private static final long serialVersionUID = 1L; + private Map digraphVertexMapping = new HashMap(); + + public TestDigraph(EdgeFactory arg0) { + super(arg0, true, true); + } + + + public void updateTestStatus(String testName, String status) { + digraphVertexMapping.get(testName).setTestStatus(status); + } + + public DiNode getVertex(String testName) { + return digraphVertexMapping.get(testName); + } + + @Override + public boolean addVertex(DiNode d) { + if (getVertex(d.getTestName()) != null) { + return false; + } + digraphVertexMapping.put(d.getTestName(), d); + return super.addVertex(d); + } + + @Override + public boolean removeVertex(DiNode d) { + if (getVertex(d.getTestName()) != null) { + return false; + } // digraphVertexMapping.put(d.getTestName(), d); - digraphVertexMapping.remove(d.getTestName()); - return super.removeVertex(d); - } - - public List getAllDependencies(String testName){ - DiNode associatedNode = getVertex(testName); - List dependentNodes = new ArrayList(); - for (DiEdge edge: outgoingEdgesOf(associatedNode)){ - if (edge.isDependency()){ - dependentNodes.add(getEdgeTarget(edge)); - } - } - return dependentNodes; - } - public List getAllExclusions(String testName){ - DiNode associatedNode = getVertex(testName); - List exclusionNodes= new ArrayList(); - for (DiEdge edge: outgoingEdgesOf(associatedNode)){ - if (edge.isExclusion()){ - exclusionNodes.add(getEdgeTarget(edge)); - } - } - return exclusionNodes; - } + digraphVertexMapping.remove(d.getTestName()); + return super.removeVertex(d); + } + + public List getAllDependencies(String testName) { + DiNode associatedNode = getVertex(testName); + List dependentNodes = new ArrayList(); + for (DiEdge edge : outgoingEdgesOf(associatedNode)) { + if (edge.isDependency()) { + dependentNodes.add(getEdgeTarget(edge)); + } + } + return dependentNodes; + } + + public List getAllExclusions(String testName) { + DiNode associatedNode = getVertex(testName); + List exclusionNodes = new ArrayList(); + for (DiEdge edge : outgoingEdgesOf(associatedNode)) { + if (edge.isExclusion()) { + exclusionNodes.add(getEdgeTarget(edge)); + } + } + return exclusionNodes; + } } diff --git a/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java b/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java index 75ca1b2..74d983c 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java @@ -34,149 +34,148 @@ /** * Control the execution of your tests with this Scheduler - * */ public class ConcurrentScheduler implements RunnerScheduler { - private int NTHREADS = 1; - - // we need a thread pool executor - private ExecutorService execService; - // wrap it in a CompletionService so we have a nicer interface. Our tasks have no return value (void) - private CompletionService completionService; - - // this list contains all of the tests that are ready for execution. - private List> tasks = new LinkedList>(); - - // Before we begin running the tests we store all test threads in a linkedlist - private List theTests = new LinkedList(); - - // We also store the test names alongside the test threads - private static List testNames = new LinkedList(); - - // As threads complete test scripts, they drop their updates in a queue that the main thread uses to - // update test state - private static Queue testUpdates = new ConcurrentLinkedQueue(); - private TestDigraph digraph; - public ConcurrentScheduler(){ - - int threadCount = AutomationEngine.getInstance().getTestAgenda().getThreadCount(); - if (threadCount <= 0){ - NTHREADS = 1; - }else{ - NTHREADS = threadCount; - } - execService = Executors.newFixedThreadPool(NTHREADS); - completionService = new ExecutorCompletionService(execService); - digraph = AutomationEngine.getInstance().getTestDigraph(); - - } - - protected static void updateWithStatus(ResultUpdate theUpdate){ - testUpdates.add(theUpdate); - } - - /** - * - * Tasks are scheduled by submitting them to our threadpool - * and adding the return Future to our tasks collection. - */ - @Override - public void schedule(Runnable test) { - theTests.add(test); - //tasks.add(completionService.submit(test, null)); - } - - /** - * When this method exits, all tasks must be finished. - */ - @Override - public void finished() { - try { - while (!testNames.isEmpty()) { - checkTestsStatus(); - tasks.remove(completionService.take()); - - //update test results - updateTestState(); - } - } - catch(Exception e){ - e.printStackTrace(); - } finally { - for (Future task : tasks) { - task.cancel(true); // if there was an error, attempt to cancel the other tasks - } - execService.shutdown(); // shutdown regardless - } - } - - private void updateTestState(){ - while(!testUpdates.isEmpty()){ - ResultUpdate curr = testUpdates.remove(); - theTests.remove(testNames.indexOf(curr.getTestName())); - testNames.remove(curr.getTestName()); - digraph.updateTestStatus(curr.getTestName(), curr.getTestStatus()); - } - } - private void checkTestsStatus() { - for(String currentTest: testNames){ - String theTestName = currentTest.toString(); - DiNode theTestNode = digraph.getVertex(theTestName); - - //test complete -skip - if(theTestNode.getTestStatus().equalsIgnoreCase("FAILED") || - theTestNode.getTestStatus().equalsIgnoreCase("PASSED")|| - theTestNode.getTestStatus().equalsIgnoreCase("READY")){ - continue; - } - - boolean isAllDepFinished = true; - boolean depTestsFailed = false; - //Check Dependencies - for(DiNode dependency: digraph.getAllDependencies(theTestName)){ - if(dependency.getTestStatus().equalsIgnoreCase("FAILED")){ - depTestsFailed = true; - }else if(!dependency.getTestStatus().equalsIgnoreCase("PASSED")){ - isAllDepFinished = false; - break; - } - - } - - //if dependencies aren't done yet. There's no point in checking the Exclusions for - //this test - if(!isAllDepFinished){ - continue; - } - - //Check Exclusions - boolean checkExclusions = true; - for(DiNode exclusion: digraph.getAllExclusions(theTestName)){ - if(exclusion.getTestStatus().equalsIgnoreCase("RUNNING") - ||exclusion.getTestStatus().equalsIgnoreCase("READY")){ - checkExclusions = false; - break; - } - } - - if(isAllDepFinished && checkExclusions){ - int corresponding = testNames.indexOf(currentTest); - tasks.add(completionService.submit(theTests.get(corresponding), theTestName)); - if(!depTestsFailed){ - digraph.updateTestStatus(theTestName, "READY"); - }else{ - digraph.updateTestStatus(theTestName, "FAILED"); - } - } - - } - - } - - public static void registerTestName(String name) { - testNames.add(name); - } + private int NTHREADS = 1; + + // we need a thread pool executor + private ExecutorService execService; + // wrap it in a CompletionService so we have a nicer interface. Our tasks have no return value (void) + private CompletionService completionService; + + // this list contains all of the tests that are ready for execution. + private List> tasks = new LinkedList>(); + + // Before we begin running the tests we store all test threads in a linkedlist + private List theTests = new LinkedList(); + + // We also store the test names alongside the test threads + private static List testNames = new LinkedList(); + + // As threads complete test scripts, they drop their updates in a queue that the main thread uses to + // update test state + private static Queue testUpdates = new ConcurrentLinkedQueue(); + private TestDigraph digraph; + + public ConcurrentScheduler() { + + int threadCount = AutomationEngine.getInstance().getTestAgenda().getThreadCount(); + if (threadCount <= 0) { + NTHREADS = 1; + } else { + NTHREADS = threadCount; + } + execService = Executors.newFixedThreadPool(NTHREADS); + completionService = new ExecutorCompletionService(execService); + digraph = AutomationEngine.getInstance().getTestDigraph(); + + } + + protected static void updateWithStatus(ResultUpdate theUpdate) { + testUpdates.add(theUpdate); + } + + /** + * Tasks are scheduled by submitting them to our threadpool + * and adding the return Future to our tasks collection. + */ + @Override + public void schedule(Runnable test) { + theTests.add(test); + //tasks.add(completionService.submit(test, null)); + } + + /** + * When this method exits, all tasks must be finished. + */ + @Override + public void finished() { + try { + while (!testNames.isEmpty()) { + checkTestsStatus(); + tasks.remove(completionService.take()); + + //update test results + updateTestState(); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + for (Future task : tasks) { + task.cancel(true); // if there was an error, attempt to cancel the other tasks + } + execService.shutdown(); // shutdown regardless + } + } + + private void updateTestState() { + while (!testUpdates.isEmpty()) { + ResultUpdate curr = testUpdates.remove(); + theTests.remove(testNames.indexOf(curr.getTestName())); + testNames.remove(curr.getTestName()); + digraph.updateTestStatus(curr.getTestName(), curr.getTestStatus()); + } + } + + private void checkTestsStatus() { + for (String currentTest : testNames) { + String theTestName = currentTest.toString(); + DiNode theTestNode = digraph.getVertex(theTestName); + + //test complete -skip + if (theTestNode.getTestStatus().equalsIgnoreCase("FAILED") || + theTestNode.getTestStatus().equalsIgnoreCase("PASSED") || + theTestNode.getTestStatus().equalsIgnoreCase("READY")) { + continue; + } + + boolean isAllDepFinished = true; + boolean depTestsFailed = false; + //Check Dependencies + for (DiNode dependency : digraph.getAllDependencies(theTestName)) { + if (dependency.getTestStatus().equalsIgnoreCase("FAILED")) { + depTestsFailed = true; + } else if (!dependency.getTestStatus().equalsIgnoreCase("PASSED")) { + isAllDepFinished = false; + break; + } + + } + + //if dependencies aren't done yet. There's no point in checking the Exclusions for + //this test + if (!isAllDepFinished) { + continue; + } + + //Check Exclusions + boolean checkExclusions = true; + for (DiNode exclusion : digraph.getAllExclusions(theTestName)) { + if (exclusion.getTestStatus().equalsIgnoreCase("RUNNING") + || exclusion.getTestStatus().equalsIgnoreCase("READY")) { + checkExclusions = false; + break; + } + } + + if (isAllDepFinished && checkExclusions) { + int corresponding = testNames.indexOf(currentTest); + tasks.add(completionService.submit(theTests.get(corresponding), theTestName)); + if (!depTestsFailed) { + digraph.updateTestStatus(theTestName, "READY"); + } else { + digraph.updateTestStatus(theTestName, "FAILED"); + } + } + + } + + } + + public static void registerTestName(String name) { + testNames.add(name); + } } diff --git a/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java b/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java index 8fea71f..7ea0bce 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java +++ b/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java @@ -30,23 +30,22 @@ /** * The test suite of the tests that will run together - * */ -public class JTAFMasterSuite extends Suite{ - - public JTAFMasterSuite(Class klass, RunnerBuilder builder) - throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { - super(klass, (new MasterSuiteRunnersBuilder().runners())); - setScheduler(new ConcurrentScheduler()); - - } - - @Override - public Description getDescription() { - Description description = Description.createSuiteDescription("Automated Tests"); - for (Runner child : getChildren()) - description.addChild(describeChild(child)); - return description; - } +public class JTAFMasterSuite extends Suite { + + public JTAFMasterSuite(Class klass, RunnerBuilder builder) + throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { + super(klass, (new MasterSuiteRunnersBuilder().runners())); + setScheduler(new ConcurrentScheduler()); + + } + + @Override + public Description getDescription() { + Description description = Description.createSuiteDescription("Automated Tests"); + for (Runner child : getChildren()) + description.addChild(describeChild(child)); + return description; + } } diff --git a/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java b/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java index 700d364..441cb3d 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java +++ b/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java @@ -34,41 +34,37 @@ /** * Builds the list of runners for the tests in Test Agenda - * */ public class MasterSuiteRunnersBuilder extends RunnerBuilder { - - public MasterSuiteRunnersBuilder() throws IllegalAccessException - { - - } - - public List runners() - throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { - - - AutomationEngine engine = AutomationEngine.getInstance(); - ArrayList tests = new ArrayList(); - - engine.buildModel(new File("testlibrary"), new File("testscripts")); - TestAgenda testAgenda = engine.getTestAgenda(); - for (TestScript testScript : testAgenda.getTestScripts()) { - TestCaseRunner theRunner = new TestCaseRunner(ParallelScriptRunner.class, new ParallelScriptRunner(testScript)); - tests.add(theRunner); - ConcurrentScheduler.registerTestName(testScript.getName()); - } - - return tests; - } + public MasterSuiteRunnersBuilder() throws IllegalAccessException { + + } + + public List runners() + throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { + + + AutomationEngine engine = AutomationEngine.getInstance(); + ArrayList tests = new ArrayList(); + + engine.buildModel(new File("testlibrary"), new File("testscripts")); + TestAgenda testAgenda = engine.getTestAgenda(); + + for (TestScript testScript : testAgenda.getTestScripts()) { + TestCaseRunner theRunner = new TestCaseRunner(ParallelScriptRunner.class, new ParallelScriptRunner(testScript)); + tests.add(theRunner); + ConcurrentScheduler.registerTestName(testScript.getName()); + } + + return tests; + } + + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + // TODO Auto-generated method stub + return null; + } - @Override - public Runner runnerForClass(Class testClass) throws Throwable { - // TODO Auto-generated method stub - return null; - } - - - } diff --git a/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java b/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java index a3cfb0c..1f839b9 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java @@ -31,72 +31,71 @@ /** * Allows more than one script to run in parallel - * */ public class ParallelScriptRunner extends TestCase { - private TestScript theTestScript ; - boolean expectedFailureFlag = false; - public static final Logger logger = Logger.getLogger(ParallelScriptRunner.class); - - public ParallelScriptRunner(TestScript theTestScript) { - super(createJUnitName(theTestScript)); - this.theTestScript = theTestScript; - } - - private static final String createJUnitName(TestScript test) { - StringBuilder sb = new StringBuilder(); - sb.append(test.getFullName()); - boolean issuesExist = false; - if (test.getCRs() != null && test.getCRs().size() > 0) { - sb.append(" CR=\""); - sb.append(StringHelper.join(test.getCRs(), ", ")); - - sb.append("\""); - - issuesExist = true; - } - - if (test.getIssue() != null && !test.getIssue().equals("")) { - issuesExist = true; - } - - if (test.getStatus() != null) { - sb.append(" STATUS=\""); - sb.append(test.getStatus()); - sb.append("\""); - } - - if (issuesExist) { - sb.append(" [ISSUE EXISTS]"); - } - - return sb.toString(); - } - - @Test - public void runJtafTestScript() throws Throwable { - - logger.info("Thread " + Thread.currentThread().getId() + " is executing " + this.getName()); - DiNode theTest = AutomationEngine.getInstance().getTestDigraph().getVertex(this.theTestScript.getName()); - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - try { - if(theTest.getTestStatus().equalsIgnoreCase("FAILED")){ - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); - Assert.fail("One or more Dependent tests failed"); - } - TestResult tr = iv.interpret(this.theTestScript); - if (!tr.isTestPassed()) { - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); - throw tr.getFailureReason(); - } - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "PASSED")); - } catch (Throwable t) { - throw t; - } finally { - - } - - - } + private TestScript theTestScript; + boolean expectedFailureFlag = false; + public static final Logger logger = Logger.getLogger(ParallelScriptRunner.class); + + public ParallelScriptRunner(TestScript theTestScript) { + super(createJUnitName(theTestScript)); + this.theTestScript = theTestScript; + } + + private static final String createJUnitName(TestScript test) { + StringBuilder sb = new StringBuilder(); + sb.append(test.getFullName()); + boolean issuesExist = false; + if (test.getCRs() != null && test.getCRs().size() > 0) { + sb.append(" CR=\""); + sb.append(StringHelper.join(test.getCRs(), ", ")); + + sb.append("\""); + + issuesExist = true; + } + + if (test.getIssue() != null && !test.getIssue().equals("")) { + issuesExist = true; + } + + if (test.getStatus() != null) { + sb.append(" STATUS=\""); + sb.append(test.getStatus()); + sb.append("\""); + } + + if (issuesExist) { + sb.append(" [ISSUE EXISTS]"); + } + + return sb.toString(); + } + + @Test + public void runJtafTestScript() throws Throwable { + + logger.info("Thread " + Thread.currentThread().getId() + " is executing " + this.getName()); + DiNode theTest = AutomationEngine.getInstance().getTestDigraph().getVertex(this.theTestScript.getName()); + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + try { + if (theTest.getTestStatus().equalsIgnoreCase("FAILED")) { + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); + Assert.fail("One or more Dependent tests failed"); + } + TestResult tr = iv.interpret(this.theTestScript); + if (!tr.isTestPassed()) { + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); + throw tr.getFailureReason(); + } + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "PASSED")); + } catch (Throwable t) { + throw t; + } finally { + + } + + + } } diff --git a/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java b/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java index 1a93fdf..d0a3bc8 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java @@ -18,25 +18,24 @@ /** * This class updates the test status and test result - * */ public class ResultUpdate { - private String testName; - private String status; - - public ResultUpdate(String testName, String status){ - this.testName = testName; - this.status = status; - } - - public String getTestName(){ - return testName; - } - - public String getTestStatus(){ - return status; - } + private String testName; + private String status; + + public ResultUpdate(String testName, String status) { + this.testName = testName; + this.status = status; + } + + public String getTestName() { + return testName; + } + + public String getTestStatus() { + return status; + } } diff --git a/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java b/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java index 275b570..ad59a98 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java +++ b/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java @@ -25,37 +25,36 @@ /** * The test case runner class - * */ public class TestCaseRunner extends BlockJUnit4ClassRunner { - - private ParallelScriptRunner scriptWrapper; - public TestCaseRunner(Class klass, ParallelScriptRunner scriptWrapper) - throws InitializationError { - super(klass); - this.scriptWrapper = scriptWrapper; - } + private ParallelScriptRunner scriptWrapper; + + public TestCaseRunner(Class klass, ParallelScriptRunner scriptWrapper) + throws InitializationError { + super(klass); + this.scriptWrapper = scriptWrapper; + } + + protected Object createTest() throws Exception { + return scriptWrapper; + } - protected Object createTest() throws Exception { - return scriptWrapper; - } + @Override + protected Description describeChild(FrameworkMethod method) { - @Override - protected Description describeChild(FrameworkMethod method) { + return Description.createSuiteDescription(scriptWrapper.getName()); - return Description.createSuiteDescription(scriptWrapper.getName()); + } - } - - public Description getDescription() { - return Description.createSuiteDescription(scriptWrapper.getName()); + public Description getDescription() { + return Description.createSuiteDescription(scriptWrapper.getName()); - } + } - @Override - protected void collectInitializationErrors(List errors) { - } + @Override + protected void collectInitializationErrors(List errors) { + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java index 07df37f..b83268a 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java @@ -28,26 +28,22 @@ /** * Core plugin that filters testscripts to run based on the automation value provided in the strategy file - * */ -public class AutomationValueFilterPlugin implements IPostParseAllPlugin -{ - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException - { - TestAgenda testAgenda = ctx.getTestAgenda(); - if(testAgenda.isAutomationValuesEmpty()) - return; - - List testScripts = ctx.getTestAgenda().getTestScripts(); - List testsToRemove = new ArrayList(); - for(TestScript testScript : testScripts) - { - String automationValue = testScript.getAutomationValue(); - if(!testAgenda.containsAutomationValue(automationValue)) - testsToRemove.add(testScript); - } - - testScripts.removeAll(testsToRemove); - } +public class AutomationValueFilterPlugin implements IPostParseAllPlugin { + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestAgenda testAgenda = ctx.getTestAgenda(); + if (testAgenda.isAutomationValuesEmpty()) + return; + + List testScripts = ctx.getTestAgenda().getTestScripts(); + List testsToRemove = new ArrayList(); + for (TestScript testScript : testScripts) { + String automationValue = testScript.getAutomationValue(); + if (!testAgenda.containsAutomationValue(automationValue)) + testsToRemove.add(testScript); + } + + testScripts.removeAll(testsToRemove); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java b/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java index 2f54071..a993a3b 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java @@ -24,17 +24,14 @@ /** * Plugin that runs post parse of the strategy. Takes care of parsing the automation value in the agenda. */ -public class AutomationValuePlugin implements IPostParseStrategyElementPlugin -{ - private static final String AUTOMATION_VALUE_NAME = "automationValue"; - - @Override - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException - { - Element element = ctx.getElement(); - if(element.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) - { - ctx.getTestAgenda().addAutomationValue(element.getTextContent()); - } - } +public class AutomationValuePlugin implements IPostParseStrategyElementPlugin { + private static final String AUTOMATION_VALUE_NAME = "automationValue"; + + @Override + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { + Element element = ctx.getElement(); + if (element.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { + ctx.getTestAgenda().addAutomationValue(element.getTextContent()); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/BaseParser.java b/src/main/java/org/finra/jtaf/core/parsing/BaseParser.java index 4c6b45f..8e176b4 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/BaseParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/BaseParser.java @@ -34,88 +34,81 @@ import org.xml.sax.SAXException; - - /** * I plan to scrap these parsers within a few releases to allow for a more * flexible model. In particular, I want the plugins to be able to extend * the behavior of the parser. For example, if we create a StarTeam plugin, * then we will want to pull CR information from the tests and commands. - * - * - * */ public abstract class BaseParser { - private final DocumentBuilder db; - private Document currentDocument; - private final MessageCollector errorCollector; - - public BaseParser() throws ParserConfigurationException { - this.db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - this.currentDocument = null; - this.errorCollector = new MessageCollector(); - } - - - public final void parse(File f) throws ParsingException, SAXException, IOException { - currentDocument = db.parse(f); - getErrorCollector().reset("In file " + f.getAbsolutePath()); - handleRoot(getCurrentDocument().getDocumentElement()); - currentDocument = null; - } - - - /** - * Do whatever to the document root - * @param root - */ - protected abstract void handleRoot(Element root) throws ParsingException ; - - - - protected final Document getCurrentDocument() { - return this.currentDocument; - } - - /** - * It is the caller's responsibility to print the log, if desired - * @return The ErrorCollector used by this parser - */ - public final MessageCollector getErrorCollector() { - return this.errorCollector; - } - - - - - /** - * TODO: There is probably a more effective way to do this, but this does the trick for now - * @param elem - * @return - */ - protected final List getChildElements(Element elem) { - ArrayList retval = new ArrayList(); - final NodeList children = elem.getChildNodes(); - for(int i = 0; i < children.getLength(); ++i) { - Node child = children.item(i); - if(child.getNodeType() == Node.ELEMENT_NODE) { - retval.add((Element) child); - } - } - return retval; - } - - - - - /** - * Generic method for printing unexpected element errors - * @param elem - */ - protected final void reportUnexpectedElement(Element elem) { - this.getErrorCollector().error("Unexpected element: " + elem.getNodeName()); - } - - + private final DocumentBuilder db; + private Document currentDocument; + private final MessageCollector errorCollector; + + public BaseParser() throws ParserConfigurationException { + this.db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + this.currentDocument = null; + this.errorCollector = new MessageCollector(); + } + + + public final void parse(File f) throws ParsingException, SAXException, IOException { + currentDocument = db.parse(f); + getErrorCollector().reset("In file " + f.getAbsolutePath()); + handleRoot(getCurrentDocument().getDocumentElement()); + currentDocument = null; + } + + + /** + * Do whatever to the document root + * + * @param root + */ + protected abstract void handleRoot(Element root) throws ParsingException; + + + protected final Document getCurrentDocument() { + return this.currentDocument; + } + + /** + * It is the caller's responsibility to print the log, if desired + * + * @return The ErrorCollector used by this parser + */ + public final MessageCollector getErrorCollector() { + return this.errorCollector; + } + + + /** + * TODO: There is probably a more effective way to do this, but this does the trick for now + * + * @param elem + * @return + */ + protected final List getChildElements(Element elem) { + ArrayList retval = new ArrayList(); + final NodeList children = elem.getChildNodes(); + for (int i = 0; i < children.getLength(); ++i) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + retval.add((Element) child); + } + } + return retval; + } + + + /** + * Generic method for printing unexpected element errors + * + * @param elem + */ + protected final void reportUnexpectedElement(Element elem) { + this.getErrorCollector().error("Unexpected element: " + elem.getNodeName()); + } + } diff --git a/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java b/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java index 111119d..d90cbd2 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java @@ -54,341 +54,339 @@ import org.xml.sax.SAXException; /** - * * The class is responsible for discovering and parsing commands.xml files from * the classpath and under the project folder - * */ public class CommandLibraryParser { - private static final String READ_LIBRARY_WARN = "A suspected library %s' was not loaded due to %s"; - private StatementParser stmtParser; - static Logger logger = Logger.getLogger(ScriptParser.class.getPackage() - .getName()); - - private final DocumentBuilder db; - - private IAutomationClassLoader automationClassLoader; - - public CommandLibraryParser() throws ParserConfigurationException { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - stmtParser = new StatementParser(); - } - - public void setAutomationClassLoader( - IAutomationClassLoader automationClassLoader) { - this.automationClassLoader = automationClassLoader; - } - - public CommandRegistry parseCommandLibraries( - CommandRegistry commandRegistry, File additionalLibrarySource, - MessageCollector mc) throws NameFormatException, - NameCollisionException, SAXException, IOException, - ParsingException, URISyntaxException { - - FileWriter fileWriter = null; - try { - fileWriter = new FileWriter("commandNames.txt"); - // process Core commands - for (InvocationTarget t : handleCoreLibrarySource(mc)) { - fileWriter.write(t.getName() - + System.getProperty("line.separator")); - if (commandRegistry.containsInvocationTarget(t.getName() - .toLowerCase())) { - logger.warn("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - mc.push("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - } - commandRegistry.registerInvocationTarget(t.getName() - .toLowerCase(), t); - } - - // process additional library source folder commands which are not - // in the classpath - for (InvocationTarget t : handleLibrarySource( - additionalLibrarySource, mc)) { - fileWriter.write(t.getName() - + System.getProperty("line.separator")); - if (commandRegistry.containsInvocationTarget(t.getName() - .toLowerCase())) { - logger.warn("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - mc.push("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - } - commandRegistry.registerInvocationTarget(t.getName() - .toLowerCase(), t); - } - - return commandRegistry; - } finally { - if (fileWriter != null) { - try { - fileWriter.close(); - } catch (IOException e) { - } - } - } - } - - private List handleCoreLibrarySource(MessageCollector mc) - throws NameFormatException, NameCollisionException, SAXException, - IOException, ParsingException, URISyntaxException { - List retval = new ArrayList(); - - Resource[] resources = getResources(); - - for (Resource resource : resources) { - logger.debug("Parsing library " + resource.getDescription()); - List library = readLibrary(mc, - resource.getInputStream(), resource.getDescription()); - if ((library != null) && (library.size() > 0)) { - // try to read jars (maven or ant setup) - retval.addAll(library); - } else { - logger.debug("Found no commands"); - } - } - return retval; - } - - /** - * for all elements of java.class.path get a Collection of resources under - * testlibrary - * - * @return the resources in the order they are found - */ - - private Resource[] getResources() throws IOException, URISyntaxException { - PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - ArrayList result = new ArrayList(); - - // We want all commands.xml files in testlibrary folder anywhere in the - // hierarchy in the classpath - // There is no single regex to address our requirement. Hence we have - // two regex. - // The first one gets all entries where testLibrary is under root. - // The second gets all - Resource[] firstResultSet = resolver - .getResources("classpath*:/testlibrary/**/*commands.xml"); - if (firstResultSet != null) { - Collections.addAll(result, firstResultSet); - } - // This path does not address testlibrary being directly under the root. - resolver = new PathMatchingResourcePatternResolver(); - Resource[] secondResultSet = resolver - .getResources("classpath*:/**/testlibrary/**/*commands.xml"); - - if (secondResultSet != null) { - if (firstResultSet != null) { - for (Resource secondResource : secondResultSet) { - // check to see if it was already found. - boolean found = false; - for (Resource firstResource : firstResultSet) { - if (firstResource.getDescription().equals( - secondResource.getDescription())) { - found=true; - break; - } - } - if(!found){ - result.add(secondResource); - } - } - } else { - Collections.addAll(result, secondResultSet); - } - } - - return result.toArray(new Resource[] {}); - } - - public final List readLibrary(MessageCollector mc, - InputStream is, String description) { - - List retval = new ArrayList(); - - try { - mc.push("In library '" + description + "'"); - Document d = db.parse(is); - retval.addAll(processLibrary(d.getDocumentElement(), mc)); - - } catch (MalformedURLException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "the url being malformed!"), e); - } catch (IOException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "an io exception while reading it!"), e); - } catch (SAXException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "a SAX exception!"), e); - } catch (ParsingException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "a parsing exception!"), e); - } finally { - mc.pop(); - } - return retval; - } - - private final List handleLibrarySource(File f, - MessageCollector mc) throws NameFormatException, - NameCollisionException, SAXException, IOException, ParsingException { - - List retval = new ArrayList(); - try { - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath()); - } - - if (f.isFile() && f.getName().endsWith(".xml")) { - mc.push("In library " + f.getAbsolutePath()); - - try { - Document d = db.parse(f); - retval.addAll(processLibrary(d.getDocumentElement(), mc)); - } finally { - mc.pop(); - } - } else if (f.isDirectory()) { - ExceptionAccumulator acc = new ExceptionAccumulator(); - for (File child : f.listFiles()) { - try { - retval.addAll(handleLibrarySource(child, mc)); - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - } - } catch (FileNotFoundException e) { - logger.warn("A suspected library file '" + f.getAbsolutePath() - + "' was not found!"); - logger.debug(e); // debug this to slim down the log files - } - return retval; - } - - private final List processLibrary(Element elem, - MessageCollector mc) throws ParsingException { - if (elem.getNodeName().equalsIgnoreCase("library")) { - List invocationTargets = new ArrayList(); - ExceptionAccumulator acc = new ExceptionAccumulator(); - - for (Element child : ParserHelper.getChildren(elem)) { - try { - invocationTargets.add(processInvocationTarget(child, mc)); - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - - return invocationTargets; - } else { - throw new UnexpectedElementException(elem); - } - } - - // This is just called when processing the library. - // It basically just gets what are designated as parameters there and stores - // the names of them - // in the invocation target param list - private final InvocationTarget processInvocationTarget(Element elem, - MessageCollector mc) throws ParsingException { - InvocationTarget retval = null; - final String name = elem.getNodeName().toLowerCase(); - if (name.equals("command")) { - retval = processCommand(elem, mc); - } else if (name.equals("function")) { - retval = processFunction(elem, mc); - } else { - throw new UnexpectedElementException(elem); - } - - final Element usage = ParserHelper.getOptionalElement(elem, "usage"); - if (usage != null) { - retval.setUsage(usage.getTextContent()); - } - - final Element requiredParameters = ParserHelper.getOptionalElement( - elem, "requiredParameters"); - if (requiredParameters != null) { - for (Element child : ParserHelper.getChildren(requiredParameters)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addRequiredParameter(ah.getRequiredString("name")); - } - } - - final Element optionalParameters = ParserHelper.getOptionalElement( - elem, "optionalParameters"); - if (optionalParameters != null) { - for (Element child : ParserHelper.getChildren(optionalParameters)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addOptionalParameter(ah.getRequiredString("name")); - } - } - - final Element produces = ParserHelper.getOptionalElement(elem, - "produces"); - if (produces != null) { - for (Element child : ParserHelper.getChildren(produces)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addProduction(ah.getRequiredString("name")); - } - } - - return retval; - } - - private final Command processCommand(Element elem, MessageCollector mc) - throws ParsingException { - try { - AttributeHelper ah = new AttributeHelper(elem); - final String commandName = ah.getRequiredString("name"); - final String commandClass = ah.getRequiredString("class"); - - Class targetClass = automationClassLoader - .loadClass(commandClass); - if (Command.class.isAssignableFrom(targetClass)) { - Constructor constructor = targetClass - .getConstructor(String.class); - return (Command) constructor.newInstance(commandName); - } else { - throw new IllegalArgumentException( - "All Commands must extend Command"); - } - } catch (Exception e) { - throw new ParsingException(e); - } - } - - private final Function processFunction(Element elem, MessageCollector mc) - throws ParsingException { - try { - - AttributeHelper ah = new AttributeHelper(elem); - Function retval = new Function(ah.getRequiredString("name") - .toLowerCase()); - - retval.setBody(stmtParser.processStatementList( - ParserHelper.getRequireElement(elem, "body"), mc)); - return retval; - } catch (Exception e) { - throw new ParsingException(e); - } - } + private static final String READ_LIBRARY_WARN = "A suspected library %s' was not loaded due to %s"; + private StatementParser stmtParser; + static Logger logger = Logger.getLogger(ScriptParser.class.getPackage() + .getName()); + + private final DocumentBuilder db; + + private IAutomationClassLoader automationClassLoader; + + public CommandLibraryParser() throws ParserConfigurationException { + db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + stmtParser = new StatementParser(); + } + + public void setAutomationClassLoader( + IAutomationClassLoader automationClassLoader) { + this.automationClassLoader = automationClassLoader; + } + + public CommandRegistry parseCommandLibraries( + CommandRegistry commandRegistry, File additionalLibrarySource, + MessageCollector mc) throws NameFormatException, + NameCollisionException, SAXException, IOException, + ParsingException, URISyntaxException { + + FileWriter fileWriter = null; + try { + fileWriter = new FileWriter("commandNames.txt"); + // process Core commands + for (InvocationTarget t : handleCoreLibrarySource(mc)) { + fileWriter.write(t.getName() + + System.getProperty("line.separator")); + if (commandRegistry.containsInvocationTarget(t.getName() + .toLowerCase())) { + logger.warn("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + mc.push("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + } + commandRegistry.registerInvocationTarget(t.getName() + .toLowerCase(), t); + } + + // process additional library source folder commands which are not + // in the classpath + for (InvocationTarget t : handleLibrarySource( + additionalLibrarySource, mc)) { + fileWriter.write(t.getName() + + System.getProperty("line.separator")); + if (commandRegistry.containsInvocationTarget(t.getName() + .toLowerCase())) { + logger.warn("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + mc.push("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + } + commandRegistry.registerInvocationTarget(t.getName() + .toLowerCase(), t); + } + + return commandRegistry; + } finally { + if (fileWriter != null) { + try { + fileWriter.close(); + } catch (IOException e) { + } + } + } + } + + private List handleCoreLibrarySource(MessageCollector mc) + throws NameFormatException, NameCollisionException, SAXException, + IOException, ParsingException, URISyntaxException { + List retval = new ArrayList(); + + Resource[] resources = getResources(); + + for (Resource resource : resources) { + logger.debug("Parsing library " + resource.getDescription()); + List library = readLibrary(mc, + resource.getInputStream(), resource.getDescription()); + if ((library != null) && (library.size() > 0)) { + // try to read jars (maven or ant setup) + retval.addAll(library); + } else { + logger.debug("Found no commands"); + } + } + return retval; + } + + /** + * for all elements of java.class.path get a Collection of resources under + * testlibrary + * + * @return the resources in the order they are found + */ + + private Resource[] getResources() throws IOException, URISyntaxException { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + ArrayList result = new ArrayList(); + + // We want all commands.xml files in testlibrary folder anywhere in the + // hierarchy in the classpath + // There is no single regex to address our requirement. Hence we have + // two regex. + // The first one gets all entries where testLibrary is under root. + // The second gets all + Resource[] firstResultSet = resolver + .getResources("classpath*:/testlibrary/**/*commands.xml"); + if (firstResultSet != null) { + Collections.addAll(result, firstResultSet); + } + // This path does not address testlibrary being directly under the root. + resolver = new PathMatchingResourcePatternResolver(); + Resource[] secondResultSet = resolver + .getResources("classpath*:/**/testlibrary/**/*commands.xml"); + + if (secondResultSet != null) { + if (firstResultSet != null) { + for (Resource secondResource : secondResultSet) { + // check to see if it was already found. + boolean found = false; + for (Resource firstResource : firstResultSet) { + if (firstResource.getDescription().equals( + secondResource.getDescription())) { + found = true; + break; + } + } + if (!found) { + result.add(secondResource); + } + } + } else { + Collections.addAll(result, secondResultSet); + } + } + + return result.toArray(new Resource[]{}); + } + + public final List readLibrary(MessageCollector mc, + InputStream is, String description) { + + List retval = new ArrayList(); + + try { + mc.push("In library '" + description + "'"); + Document d = db.parse(is); + retval.addAll(processLibrary(d.getDocumentElement(), mc)); + + } catch (MalformedURLException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "the url being malformed!"), e); + } catch (IOException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "an io exception while reading it!"), e); + } catch (SAXException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "a SAX exception!"), e); + } catch (ParsingException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "a parsing exception!"), e); + } finally { + mc.pop(); + } + return retval; + } + + private final List handleLibrarySource(File f, + MessageCollector mc) throws NameFormatException, + NameCollisionException, SAXException, IOException, ParsingException { + + List retval = new ArrayList(); + try { + if (!f.exists()) { + throw new FileNotFoundException(f.getAbsolutePath()); + } + + if (f.isFile() && f.getName().endsWith(".xml")) { + mc.push("In library " + f.getAbsolutePath()); + + try { + Document d = db.parse(f); + retval.addAll(processLibrary(d.getDocumentElement(), mc)); + } finally { + mc.pop(); + } + } else if (f.isDirectory()) { + ExceptionAccumulator acc = new ExceptionAccumulator(); + for (File child : f.listFiles()) { + try { + retval.addAll(handleLibrarySource(child, mc)); + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + } + } catch (FileNotFoundException e) { + logger.warn("A suspected library file '" + f.getAbsolutePath() + + "' was not found!"); + logger.debug(e); // debug this to slim down the log files + } + return retval; + } + + private final List processLibrary(Element elem, + MessageCollector mc) throws ParsingException { + if (elem.getNodeName().equalsIgnoreCase("library")) { + List invocationTargets = new ArrayList(); + ExceptionAccumulator acc = new ExceptionAccumulator(); + + for (Element child : ParserHelper.getChildren(elem)) { + try { + invocationTargets.add(processInvocationTarget(child, mc)); + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + + return invocationTargets; + } else { + throw new UnexpectedElementException(elem); + } + } + + // This is just called when processing the library. + // It basically just gets what are designated as parameters there and stores + // the names of them + // in the invocation target param list + private final InvocationTarget processInvocationTarget(Element elem, + MessageCollector mc) throws ParsingException { + InvocationTarget retval = null; + final String name = elem.getNodeName().toLowerCase(); + if (name.equals("command")) { + retval = processCommand(elem, mc); + } else if (name.equals("function")) { + retval = processFunction(elem, mc); + } else { + throw new UnexpectedElementException(elem); + } + + final Element usage = ParserHelper.getOptionalElement(elem, "usage"); + if (usage != null) { + retval.setUsage(usage.getTextContent()); + } + + final Element requiredParameters = ParserHelper.getOptionalElement( + elem, "requiredParameters"); + if (requiredParameters != null) { + for (Element child : ParserHelper.getChildren(requiredParameters)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addRequiredParameter(ah.getRequiredString("name")); + } + } + + final Element optionalParameters = ParserHelper.getOptionalElement( + elem, "optionalParameters"); + if (optionalParameters != null) { + for (Element child : ParserHelper.getChildren(optionalParameters)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addOptionalParameter(ah.getRequiredString("name")); + } + } + + final Element produces = ParserHelper.getOptionalElement(elem, + "produces"); + if (produces != null) { + for (Element child : ParserHelper.getChildren(produces)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addProduction(ah.getRequiredString("name")); + } + } + + return retval; + } + + private final Command processCommand(Element elem, MessageCollector mc) + throws ParsingException { + try { + AttributeHelper ah = new AttributeHelper(elem); + final String commandName = ah.getRequiredString("name"); + final String commandClass = ah.getRequiredString("class"); + + Class targetClass = automationClassLoader + .loadClass(commandClass); + if (Command.class.isAssignableFrom(targetClass)) { + Constructor constructor = targetClass + .getConstructor(String.class); + return (Command) constructor.newInstance(commandName); + } else { + throw new IllegalArgumentException( + "All Commands must extend Command"); + } + } catch (Exception e) { + throw new ParsingException(e); + } + } + + private final Function processFunction(Element elem, MessageCollector mc) + throws ParsingException { + try { + + AttributeHelper ah = new AttributeHelper(elem); + Function retval = new Function(ah.getRequiredString("name") + .toLowerCase()); + + retval.setBody(stmtParser.processStatementList( + ParserHelper.getRequireElement(elem, "body"), mc)); + return retval; + } catch (Exception e) { + throw new ParsingException(e); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java index 597e1d9..18f66b9 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java @@ -34,38 +34,34 @@ /** * Parser plugin that runs post all. Scans through the test scripts to create a Digraph as per denpencies. */ -public class DigraphPlugin implements IPostParseAllPlugin -{ - protected TestNamespace testNamespace; - - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException - { - TestDigraph testDigraph = AutomationEngine.getInstance().getTestDigraph(); - TestAgenda testAgenda = ctx.getTestAgenda(); - testNamespace = AutomationEngine.getInstance().getTestRoot(); - DigraphFactory graphFactory = new DigraphFactory(testDigraph, new MessageCollector()); - graphFactory.createGraph(testNamespace); - - Set dependentTests = new LinkedHashSet(); - for (TestScript t : testAgenda.getTestScripts()) - if(testAgenda.containsAutomationValue(t.getAutomationValue())) - dependentTests.addAll(addDependentTests(testDigraph, (TestScript) t)); - - for (TestScript t : dependentTests) - if(!testAgenda.getTestScripts().contains(t)) - testAgenda.getTestScripts().add(t); - } - - private Set addDependentTests(TestDigraph testDigraph, TestScript test) - { - Set additionalScript = new LinkedHashSet(); - for (DiNode d : testDigraph.getAllDependencies(test.getName())) - { - d.getTestScript().setAutomationValue(test.getAutomationValue()); - additionalScript.add(d.getTestScript()); - additionalScript.addAll(addDependentTests(testDigraph, d.getTestScript())); - } - return additionalScript; - } +public class DigraphPlugin implements IPostParseAllPlugin { + protected TestNamespace testNamespace; + + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestDigraph testDigraph = AutomationEngine.getInstance().getTestDigraph(); + TestAgenda testAgenda = ctx.getTestAgenda(); + testNamespace = AutomationEngine.getInstance().getTestRoot(); + DigraphFactory graphFactory = new DigraphFactory(testDigraph, new MessageCollector()); + graphFactory.createGraph(testNamespace); + + Set dependentTests = new LinkedHashSet(); + for (TestScript t : testAgenda.getTestScripts()) + if (testAgenda.containsAutomationValue(t.getAutomationValue())) + dependentTests.addAll(addDependentTests(testDigraph, (TestScript) t)); + + for (TestScript t : dependentTests) + if (!testAgenda.getTestScripts().contains(t)) + testAgenda.getTestScripts().add(t); + } + + private Set addDependentTests(TestDigraph testDigraph, TestScript test) { + Set additionalScript = new LinkedHashSet(); + for (DiNode d : testDigraph.getAllDependencies(test.getName())) { + d.getTestScript().setAutomationValue(test.getAutomationValue()); + additionalScript.add(d.getTestScript()); + additionalScript.addAll(addDependentTests(testDigraph, d.getTestScript())); + } + return additionalScript; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java index efce276..f690121 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java @@ -26,30 +26,26 @@ /** * This is internal class meant for verification of expected exception in the script */ -public class ExceptionPlugin implements IPostParseTestPlugin -{ - public static final String NODE_NAME = "expectedException"; - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException - { - NodeList childNodes = ctx.getRootNodeTest().getChildNodes(); - for(int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) - { - if(childNodes.item(childNodeIndex).getNodeName().equalsIgnoreCase(NODE_NAME)) - { - int size = ctx.getTestSuite().getComponentList().size(); - TestScript script= (TestScript) ctx.getTestSuite().getComponentList().get(size-1); - script.setException(childNodes.item(childNodeIndex).getTextContent()); - //ctx.getTestAgenda().setThreadCount(maxThreads); - } - } - - } +public class ExceptionPlugin implements IPostParseTestPlugin { + public static final String NODE_NAME = "expectedException"; + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + NodeList childNodes = ctx.getRootNodeTest().getChildNodes(); + for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { + if (childNodes.item(childNodeIndex).getNodeName().equalsIgnoreCase(NODE_NAME)) { + int size = ctx.getTestSuite().getComponentList().size(); + TestScript script = (TestScript) ctx.getTestSuite().getComponentList().get(size - 1); + script.setException(childNodes.item(childNodeIndex).getTextContent()); + //ctx.getTestAgenda().setThreadCount(maxThreads); + } + } + + } @Override public String getTagName() { - + return NODE_NAME; } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java index 7c95e27..7728604 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java @@ -38,91 +38,90 @@ /** * Parser plugin meant to handle the loop element in the script that determines * the number of times a test script needs to be run. - * */ public class LoopPlugin implements IPostParseTestPlugin { - protected TestDigraph testDigraph; + protected TestDigraph testDigraph; - @Override - public String getTagName() { - return "loop"; - } + @Override + public String getTagName() { + return "loop"; + } - public LoopPlugin(AutomationEngine automationEngine) { - this.testDigraph = automationEngine.getTestDigraph(); - } + public LoopPlugin(AutomationEngine automationEngine) { + this.testDigraph = automationEngine.getTestDigraph(); + } - @Override - public void execute(PostTestParserPluginContext ctx) - throws ParserPluginException { - int iterationCount = getIterationCount(ctx.getRootNodeTest()); - if (iterationCount != 1) { - TestScript oldTestScript = getOldTestScript(ctx.getTestSuite()); - List iteratedScripts = createIteratedTestScripts(ctx, - oldTestScript, iterationCount); - removeOldTestScript(ctx.getTestSuite()); - addIteratedTestScripts(ctx.getTestSuite(), iteratedScripts); - } - } + @Override + public void execute(PostTestParserPluginContext ctx) + throws ParserPluginException { + int iterationCount = getIterationCount(ctx.getRootNodeTest()); + if (iterationCount != 1) { + TestScript oldTestScript = getOldTestScript(ctx.getTestSuite()); + List iteratedScripts = createIteratedTestScripts(ctx, + oldTestScript, iterationCount); + removeOldTestScript(ctx.getTestSuite()); + addIteratedTestScripts(ctx.getTestSuite(), iteratedScripts); + } + } - private int getIterationCount(Node rootNodeTest) { - int result = 1; - NodeList children = rootNodeTest.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeName().equalsIgnoreCase("loop")) { - result = Integer.parseInt(children.item(i).getAttributes() - .getNamedItem("iterations").getNodeValue()); - } - } - return result; - } + private int getIterationCount(Node rootNodeTest) { + int result = 1; + NodeList children = rootNodeTest.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase("loop")) { + result = Integer.parseInt(children.item(i).getAttributes() + .getNamedItem("iterations").getNodeValue()); + } + } + return result; + } - private TestScript getOldTestScript(TestSuite testSuite) { - List testComponents = testSuite.getComponentList(); - return (TestScript) testComponents.get(testComponents.size() - 1); - } + private TestScript getOldTestScript(TestSuite testSuite) { + List testComponents = testSuite.getComponentList(); + return (TestScript) testComponents.get(testComponents.size() - 1); + } - List createIteratedTestScripts(PostTestParserPluginContext ctx, - TestScript oldTestScript, int iterationCount) - throws ParserPluginException { - List result = new ArrayList(); - for (int currentIteration = 1; currentIteration <= iterationCount; currentIteration++) { - TestScript newTestScript; - ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); - try { - newTestScript = sp - .processTestScript((Element) ctx.getRootNodeTest(), - new MessageCollector()); - } catch (ParsingException parsingException) { - throw new ParserPluginException("Problem re-parsing test", - parsingException); - } - newTestScript.setName(newTestScript.getName() + " [iteration " - + currentIteration + " of " + iterationCount + "]"); - result.add(newTestScript); - } - return result; - } + List createIteratedTestScripts(PostTestParserPluginContext ctx, + TestScript oldTestScript, int iterationCount) + throws ParserPluginException { + List result = new ArrayList(); + for (int currentIteration = 1; currentIteration <= iterationCount; currentIteration++) { + TestScript newTestScript; + ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); + try { + newTestScript = sp + .processTestScript((Element) ctx.getRootNodeTest(), + new MessageCollector()); + } catch (ParsingException parsingException) { + throw new ParserPluginException("Problem re-parsing test", + parsingException); + } + newTestScript.setName(newTestScript.getName() + " [iteration " + + currentIteration + " of " + iterationCount + "]"); + result.add(newTestScript); + } + return result; + } - private void removeOldTestScript(TestSuite testSuite) { - List testComponents = testSuite.getComponentList(); - testComponents.remove(testComponents.size() - 1); - } + private void removeOldTestScript(TestSuite testSuite) { + List testComponents = testSuite.getComponentList(); + testComponents.remove(testComponents.size() - 1); + } - private void addIteratedTestScripts(TestSuite testSuite, - List iteratedScripts) throws ParserPluginException { - try { - for (TestScript iteratedScript : iteratedScripts) { - testSuite.add(iteratedScript); - // DigraphPlugin dependenciesPlugin = - // DigraphPlugin.getInstance(); - // TestDigraph testDigraph = - // dependenciesPlugin.getTestDigraph(); - testDigraph.addVertex(new DiNode(iteratedScript)); - } - } catch (NameCollisionException nameCollisionException) { - throw new ParserPluginException("Duplicate test name: ", - nameCollisionException); - } - } + private void addIteratedTestScripts(TestSuite testSuite, + List iteratedScripts) throws ParserPluginException { + try { + for (TestScript iteratedScript : iteratedScripts) { + testSuite.add(iteratedScript); + // DigraphPlugin dependenciesPlugin = + // DigraphPlugin.getInstance(); + // TestDigraph testDigraph = + // dependenciesPlugin.getTestDigraph(); + testDigraph.addVertex(new DiNode(iteratedScript)); + } + } catch (NameCollisionException nameCollisionException) { + throw new ParserPluginException("Duplicate test name: ", + nameCollisionException); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java index b2a6846..43ac7a8 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java @@ -25,17 +25,14 @@ /** * Strategy parser plugin that parses maximum parallel threads in strategy. */ -public class MaxThreadsPlugin implements IPostParseStrategyElementPlugin -{ - private static final String MAX_THREADS_NAME = "maxThreads"; - - @Override - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException - { - Element element = ctx.getElement(); - if(element.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) - { - ctx.getTestAgenda().setThreadCount(element.getTextContent()); - } - } +public class MaxThreadsPlugin implements IPostParseStrategyElementPlugin { + private static final String MAX_THREADS_NAME = "maxThreads"; + + @Override + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { + Element element = ctx.getElement(); + if (element.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { + ctx.getTestAgenda().setThreadCount(element.getTextContent()); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java b/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java index 2ad5874..10eadcf 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java @@ -66,7 +66,6 @@ /** * FIXME This is a "just get the job done" implementation. I plan to replace * this class as soon as I get the chance. (I mean... ay ay ay! This is bad!) - * */ public class ScriptParser { @@ -77,9 +76,9 @@ public class ScriptParser { private Document d; private CommandRegistry commandRegistry; - private List postParseSuitePlugins; - private List postParseTestPlugins; - + private List postParseSuitePlugins; + private List postParseTestPlugins; + public ScriptParser() throws ParserConfigurationException { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); @@ -89,19 +88,20 @@ public ScriptParser() throws ParserConfigurationException { public void setDigraph(TestDigraph digraph) { this.digraph = digraph; } - - public void setPostParseSuitePlugins(List plugins) { - postParseSuitePlugins = plugins; - } - - - public void setPostParseTestPlugins(List plugins) { - postParseTestPlugins = plugins; - } - + + public void setPostParseSuitePlugins(List plugins) { + postParseSuitePlugins = plugins; + } + + + public void setPostParseTestPlugins(List plugins) { + postParseTestPlugins = plugins; + } + public void setCommandRegistry(CommandRegistry commandRegistry) { this.commandRegistry = commandRegistry; } + public final TestNamespace handleTestSource(File f, MessageCollector mc) throws NameFormatException, SAXException, IOException, ParsingException { if (!f.exists()) { @@ -125,11 +125,11 @@ public final TestNamespace handleTestSource(File f, MessageCollector mc) if (ts != null) { testNamespace.add(ts); // run all post suite parse plugins - + Node suiteRootNode = (Node) (d.getDocumentElement()); // TODO: This needs to check for null, otherwise it // crashes - + if (postParseSuitePlugins != null) { for (IPostParseSuitePlugin p : postParseSuitePlugins) { if (suiteContainsTheTag(suiteRootNode, p.getTagName())) { @@ -169,7 +169,7 @@ private TestSuite handleTestSuite(File f, MessageCollector mc) throws ParsingExc } TestSuite testSuite = null; if (f.isFile() && f.getName().endsWith(".xml")) { // This should be a - // TestSuite + // TestSuite mc.push("In test file " + f.getAbsolutePath()); try { d = db.parse(f); @@ -248,7 +248,7 @@ public final TestSuite processTestSuite(Element element, MessageCollector mc, St logger.debug("Oops! Test suite has no 'name' attribute! ('" + element.toString() + "')"); } - + testSuite.setDependencies(new Dependencies(null, null)); testSuite.setExclusions(new Dependencies(null, null)); @@ -300,7 +300,7 @@ private final List processTestScripts(Element element, MessageCollec } private List parseTests(List elementList, MessageCollector mc, - String testSuiteName) throws ExceptionAccumulator { + String testSuiteName) throws ExceptionAccumulator { List testScripts = new ArrayList(); ExceptionAccumulator acc = new ExceptionAccumulator(); for (Element child : elementList) { @@ -408,7 +408,7 @@ private final String getSheetName(Element test) { } private final List> getExcelDataFromFile(String testDataFile, String sheetName, - MessageCollector mc, boolean isXlsx) { + MessageCollector mc, boolean isXlsx) { if (testDataFile != null && testDataFile.length() > 0) { ExcelFileParser excelFileParser = null; try { @@ -429,9 +429,9 @@ private final List> getExcelDataFromFile(String testDataFile, Strin private final List> getCSVDataFromFile(String testDataFile, MessageCollector mc) { List> result = new ArrayList>(); - CSVReader reader = null ; + CSVReader reader = null; try { - reader = new CSVReader(new FileReader(testDataFile)); + reader = new CSVReader(new FileReader(testDataFile)); List nextLine; while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { @@ -443,16 +443,16 @@ private final List> getCSVDataFromFile(String testDataFile, Message } catch (Exception e) { logger.fatal("Oops! Can't open file '" + testDataFile + "'!"); return null; - }finally{ - if(reader!=null){ - try{ - reader.close(); - }catch(Exception e){ - //Dont care + } finally { + if (reader != null) { + try { + reader.close(); + } catch (Exception e) { + //Dont care logger.fatal("Oops! Can't close file '" + testDataFile + "'!"); - } - } + } + } } return result; } @@ -498,12 +498,12 @@ private void setTestDataToTestScript(List title, List data, Test /** * if (statement instanceof TryRecoverCleanup) { TryRecoverCleanup * trcSt = (TryRecoverCleanup) statement; - * + * * // StatementList statementList = trcSt.getTry(); // * statementList.addAll(trcSt.getRecover()); // * statementList.addAll(trcSt.getCleanup()); // TODO: Ask author why * this was placed and when? - * + * * for (IStatement currentStatement : statementList) { if * (currentStatement instanceof Invocation) { Map * parameters = ((Invocation) currentStatement) .getParameters(); @@ -598,7 +598,7 @@ public final TestScript processTestScript(Element elem, MessageCollector mc) Element avElem = ParserHelper.getFirstChildElementCaseInsensitive(elem, "automationvalue"); if (avElem != null) { - // not sure why this doesn't just call avElem.getTextContent() + // not sure why this doesn't just call avElem.getTextContent() testScript.setAutomationValue(stmtParser.processString(avElem, mc).toString()); } diff --git a/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java b/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java index 075a125..55f9bf8 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java @@ -41,266 +41,261 @@ * Responsible for parsing statement in test script. */ public class StatementParser { - - private static final List NON_BLOCK_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "list", "string", "map", "boolean")); - private static final List STRING_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "string")); - - public final InvocationList processStatementList(Element elem, MessageCollector mc) - throws ParsingException { - // Create formal try...recover...cleanup blocks - preprocessStatementList(elem, mc); - - InvocationList retval = new InvocationList(); - for (Element child : ParserHelper.getChildren(elem)) { - - retval.add(processStatement(child, mc)); - } - return retval; - } - - //TODO: This needs to come across a TryRecoverCleanup and handle that - private final void preprocessStatementList(Element elem, MessageCollector mc) - throws ParsingException { - - ElementScanner es = new ElementScanner(ParserHelper.getChildren(elem)); - Element next = null; - // Element tRC = - // elem.getOwnerDocument().createElement("TryRecoverCleanup"); - if (!elem.getNodeName().equals("TryRecoverCleanup")) { - while (es.hasNext()) { - - if ((next = es.tryMatch("try")) != null) { - Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); - Element tryBlock = elem.getOwnerDocument().createElement("try"); - NodeList childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - tryBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - elem.replaceChild(safety, next); - safety.appendChild(tryBlock); - - if ((next = es.tryMatch("recover")) != null) { - elem.removeChild(next); - Element recoverBlock = elem.getOwnerDocument().createElement("recover"); - childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - recoverBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - safety.appendChild(recoverBlock); - } - - if ((next = es.tryMatch("cleanup")) != null) { - elem.removeChild(next); - Element cleanUpBlock = elem.getOwnerDocument().createElement("cleanup"); - childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - cleanUpBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - safety.appendChild(cleanUpBlock); - } - - continue; - } else if (((next = es.tryMatch("recover")) != null) - || ((next = es.tryMatch("cleanup")) != null)) { - throw new UnexpectedElementException(next); - } - - // Move on to the next element - es.match(); - } - } - } - - private final Invocation processStatement(Element elem, MessageCollector mc) - throws ParsingException { - try { - mc.push(elem.getNodeName()); - - return processInvocation(elem, mc); - - } catch (ParsingException e) { - mc.error(e.getMessage()); - throw e; - } finally { - mc.pop(); - } - } - - - - - // TODO Use this in order to put the child nodes of the command as the block - // Calls processMap which calls process object. This method then deals with - // strings, maps, and lists - // This can be changed so that it either does processCommand or processX - // depending no what - // the default value is - private final Invocation processInvocation(Element elem, MessageCollector mc) - throws ParsingException { - Invocation retval = new Invocation(elem.getNodeName()); - Map> invocationAttributesMap = new HashMap>(); - - // get properties from children - // TODO: This will process all children of the command - preprocessStatementList(elem, mc); - invocationAttributesMap.putAll(processInvocationChildNodes(elem, mc)); - - // get properties from attributes - final AttributeHelper attrs = new AttributeHelper(elem); - - // invocationAttributesMap.putAll(temp); - retval.setParameters(invocationAttributesMap); - retval.getParameters().putAll(attrs.getMap()); - retval.getParameters().putAll(processMap(elem, mc)); - - return retval; - } - - // TODO: This needs to send a child node to processInvocation if it is a - // command - private final Map> processInvocationChildNodes(Element elem, - MessageCollector mc) throws ParsingException { - boolean blockCreated = false; - try { - mc.push(elem.getNodeName()); - Map> result = new HashMap>(); - List block = new ArrayList(); - NodeList childNodes = elem.getChildNodes(); - // there used to be a check for null here, but the JavaDoc makes no - // mention that this is possible and I can find no examples online - // of how to cause that - if (childNodes.getLength() > 0) { - for (int i = 0; i < childNodes.getLength(); i++) { - Node currentNode = childNodes.item(i); - if (currentNode.getNodeType() == Node.ELEMENT_NODE - && !isNonBlockParameterType(currentNode.getNodeName())) { - blockCreated = true; - Invocation child = processInvocation((Element) currentNode, mc); - block.add(child); - - /** - * else { Object thing = processObject((Element) - * currentNode, mc); block.add(thing); } - **/ - - // TODO: processInvocation to get a command handled. - // It should then be stored in result - // processInvocation(currentNode, mc); - // String nodeName = currentNode.getNodeName(); - } - - } - if (blockCreated) { - - result.put("blockParam", block); - } - } - return result; - } - finally { - mc.pop(); - } - } - - - private boolean isNonBlockParameterType(String nodeName) - { - return NON_BLOCK_PARAMETER_TYPES.contains(nodeName.toLowerCase()); - } - -private final Map processMap(Element elem, MessageCollector mc) - throws ParsingException { - ExceptionAccumulator acc = new ExceptionAccumulator(); - HashMap retval = new HashMap(); - - for (Element child : ParserHelper.getChildren(elem)) { - try { - final AttributeHelper attrs = new AttributeHelper(child); - Object value = processObject(child, mc); - if (value != null) { - String key = attrs.getRequiredString("name"); - retval.put(key, value); - } - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - - return retval; - } - - private final List processList(Element elem, MessageCollector mc) - throws ParsingException { - - try { - mc.push(elem.getNodeName()); - ArrayList retval = new ArrayList(); - for (Element child : ParserHelper.getChildren(elem)) { - retval.add(processObject(child, mc)); - } - return retval; - } finally { - mc.pop(); - } - - } - - private final Object processObject(Element elem, MessageCollector mc) throws ParsingException { - try { - - mc.push("In data element " + elem.getNodeName()); - final String name = elem.getNodeName().toLowerCase(); + + private static final List NON_BLOCK_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "list", "string", "map", "boolean")); + private static final List STRING_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "string")); + + public final InvocationList processStatementList(Element elem, MessageCollector mc) + throws ParsingException { + // Create formal try...recover...cleanup blocks + preprocessStatementList(elem, mc); + + InvocationList retval = new InvocationList(); + for (Element child : ParserHelper.getChildren(elem)) { + + retval.add(processStatement(child, mc)); + } + return retval; + } + + //TODO: This needs to come across a TryRecoverCleanup and handle that + private final void preprocessStatementList(Element elem, MessageCollector mc) + throws ParsingException { + + ElementScanner es = new ElementScanner(ParserHelper.getChildren(elem)); + Element next = null; + // Element tRC = + // elem.getOwnerDocument().createElement("TryRecoverCleanup"); + if (!elem.getNodeName().equals("TryRecoverCleanup")) { + while (es.hasNext()) { + + if ((next = es.tryMatch("try")) != null) { + Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); + Element tryBlock = elem.getOwnerDocument().createElement("try"); + NodeList childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + tryBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + elem.replaceChild(safety, next); + safety.appendChild(tryBlock); + + if ((next = es.tryMatch("recover")) != null) { + elem.removeChild(next); + Element recoverBlock = elem.getOwnerDocument().createElement("recover"); + childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + recoverBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + safety.appendChild(recoverBlock); + } + + if ((next = es.tryMatch("cleanup")) != null) { + elem.removeChild(next); + Element cleanUpBlock = elem.getOwnerDocument().createElement("cleanup"); + childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + cleanUpBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + safety.appendChild(cleanUpBlock); + } + + continue; + } else if (((next = es.tryMatch("recover")) != null) + || ((next = es.tryMatch("cleanup")) != null)) { + throw new UnexpectedElementException(next); + } + + // Move on to the next element + es.match(); + } + } + } + + private final Invocation processStatement(Element elem, MessageCollector mc) + throws ParsingException { + try { + mc.push(elem.getNodeName()); + + return processInvocation(elem, mc); + + } catch (ParsingException e) { + mc.error(e.getMessage()); + throw e; + } finally { + mc.pop(); + } + } + + + // TODO Use this in order to put the child nodes of the command as the block + // Calls processMap which calls process object. This method then deals with + // strings, maps, and lists + // This can be changed so that it either does processCommand or processX + // depending no what + // the default value is + private final Invocation processInvocation(Element elem, MessageCollector mc) + throws ParsingException { + Invocation retval = new Invocation(elem.getNodeName()); + Map> invocationAttributesMap = new HashMap>(); + + // get properties from children + // TODO: This will process all children of the command + preprocessStatementList(elem, mc); + invocationAttributesMap.putAll(processInvocationChildNodes(elem, mc)); + + // get properties from attributes + final AttributeHelper attrs = new AttributeHelper(elem); + + // invocationAttributesMap.putAll(temp); + retval.setParameters(invocationAttributesMap); + retval.getParameters().putAll(attrs.getMap()); + retval.getParameters().putAll(processMap(elem, mc)); + + return retval; + } + + // TODO: This needs to send a child node to processInvocation if it is a + // command + private final Map> processInvocationChildNodes(Element elem, + MessageCollector mc) throws ParsingException { + boolean blockCreated = false; + try { + mc.push(elem.getNodeName()); + Map> result = new HashMap>(); + List block = new ArrayList(); + NodeList childNodes = elem.getChildNodes(); + // there used to be a check for null here, but the JavaDoc makes no + // mention that this is possible and I can find no examples online + // of how to cause that + if (childNodes.getLength() > 0) { + for (int i = 0; i < childNodes.getLength(); i++) { + Node currentNode = childNodes.item(i); + if (currentNode.getNodeType() == Node.ELEMENT_NODE + && !isNonBlockParameterType(currentNode.getNodeName())) { + blockCreated = true; + Invocation child = processInvocation((Element) currentNode, mc); + block.add(child); + + /** + * else { Object thing = processObject((Element) + * currentNode, mc); block.add(thing); } + **/ + + // TODO: processInvocation to get a command handled. + // It should then be stored in result + // processInvocation(currentNode, mc); + // String nodeName = currentNode.getNodeName(); + } + + } + if (blockCreated) { + + result.put("blockParam", block); + } + } + return result; + } finally { + mc.pop(); + } + } + + + private boolean isNonBlockParameterType(String nodeName) { + return NON_BLOCK_PARAMETER_TYPES.contains(nodeName.toLowerCase()); + } + + private final Map processMap(Element elem, MessageCollector mc) + throws ParsingException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + HashMap retval = new HashMap(); + + for (Element child : ParserHelper.getChildren(elem)) { + try { + final AttributeHelper attrs = new AttributeHelper(child); + Object value = processObject(child, mc); + if (value != null) { + String key = attrs.getRequiredString("name"); + retval.put(key, value); + } + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + + return retval; + } + + private final List processList(Element elem, MessageCollector mc) + throws ParsingException { + + try { + mc.push(elem.getNodeName()); + ArrayList retval = new ArrayList(); + for (Element child : ParserHelper.getChildren(elem)) { + retval.add(processObject(child, mc)); + } + return retval; + } finally { + mc.pop(); + } + + } + + private final Object processObject(Element elem, MessageCollector mc) throws ParsingException { + try { + + mc.push("In data element " + elem.getNodeName()); + final String name = elem.getNodeName().toLowerCase(); // if (name.equals("param") || name.equals("string")) { - if (isStringParameterType(name)) { - return processString(elem, mc); - } else if (name.equals("map")) { - return processMap(elem, mc); - } else if (name.equals("list")) { - return processList(elem, mc); - } else { - return null; - } - } finally { - mc.pop(); - } - } - - private boolean isStringParameterType(String parameterType) - { - return STRING_PARAMETER_TYPES.contains(parameterType.toLowerCase()); - } - - // something strange is going on here. why can 's have child nodes? why is this public? - public Object processString(Element elem, MessageCollector mc) throws ParsingException { - try { - mc.push(elem.getNodeName()); - Map> childNodeValue = processInvocationChildNodes(elem, mc); - AttributeHelper ah = new AttributeHelper(elem); - if (ah != null && ah.entrySet().size() > 0) { - if (ah.containsKey("name") && (ah.entrySet().size() == 1)) { - // this is map... - } else { - return ah; - } - } else if (!childNodeValue.isEmpty()) { - for (String key : childNodeValue.keySet()) { - return childNodeValue.get(key); - } - } - - return elem.getTextContent(); - } finally { - mc.pop(); - } - } + if (isStringParameterType(name)) { + return processString(elem, mc); + } else if (name.equals("map")) { + return processMap(elem, mc); + } else if (name.equals("list")) { + return processList(elem, mc); + } else { + return null; + } + } finally { + mc.pop(); + } + } + + private boolean isStringParameterType(String parameterType) { + return STRING_PARAMETER_TYPES.contains(parameterType.toLowerCase()); + } + + // something strange is going on here. why can 's have child nodes? why is this public? + public Object processString(Element elem, MessageCollector mc) throws ParsingException { + try { + mc.push(elem.getNodeName()); + Map> childNodeValue = processInvocationChildNodes(elem, mc); + AttributeHelper ah = new AttributeHelper(elem); + if (ah != null && ah.entrySet().size() > 0) { + if (ah.containsKey("name") && (ah.entrySet().size() == 1)) { + // this is map... + } else { + return ah; + } + } else if (!childNodeValue.isEmpty()) { + for (String key : childNodeValue.keySet()) { + return childNodeValue.get(key); + } + } + + return elem.getTextContent(); + } finally { + mc.pop(); + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java index 99c0f7d..f22ef91 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java @@ -31,53 +31,40 @@ /** * Parser plugin to parse test suite dependencies */ -public class SuiteDependenciesPlugin implements IPostParseSuitePlugin -{ - private static final String DEPENDENCIES_NAME = "dependencies"; - private static Logger logger = Logger.getLogger(SuiteDependenciesPlugin.class.getPackage().getName()); - - @Override - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException - { - ExceptionAccumulator acc = new ExceptionAccumulator(); - Set dependentTests = ctx.getTestSuite().getDependencies().getDependenciesTests(); - Set dependentTestSuites = ctx.getTestSuite().getDependencies().getDependenciesSuites(); - Element dependenciesElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), DEPENDENCIES_NAME); - for (Element e : ParserHelper.getChildren(dependenciesElement)) - { - try - { - AttributeHelper depAttributeHelper = new AttributeHelper(e); - String dependentValue = depAttributeHelper.getRequiredString("name"); - if(e.getNodeName().equalsIgnoreCase("test")) - { - dependentTests.add(dependentValue); - } - else if(e.getNodeName().equalsIgnoreCase("testsuite")) - { - dependentTestSuites.add(dependentValue); - } - else - { - throw new UnexpectedElementException(e); - } - } - catch (Throwable th) - { - logger.fatal(th.getMessage()); +public class SuiteDependenciesPlugin implements IPostParseSuitePlugin { + private static final String DEPENDENCIES_NAME = "dependencies"; + private static Logger logger = Logger.getLogger(SuiteDependenciesPlugin.class.getPackage().getName()); + + @Override + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + Set dependentTests = ctx.getTestSuite().getDependencies().getDependenciesTests(); + Set dependentTestSuites = ctx.getTestSuite().getDependencies().getDependenciesSuites(); + Element dependenciesElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), DEPENDENCIES_NAME); + for (Element e : ParserHelper.getChildren(dependenciesElement)) { + try { + AttributeHelper depAttributeHelper = new AttributeHelper(e); + String dependentValue = depAttributeHelper.getRequiredString("name"); + if (e.getNodeName().equalsIgnoreCase("test")) { + dependentTests.add(dependentValue); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + dependentTestSuites.add(dependentValue); + } else { + throw new UnexpectedElementException(e); + } + } catch (Throwable th) { + logger.fatal(th.getMessage()); // mc.error(th.getMessage()); - acc.add(th); - } - } - if(!acc.isEmpty()) - { - throw new ParserPluginException(acc); - } - } - - @Override - public String getTagName() - { - return DEPENDENCIES_NAME; - } + acc.add(th); + } + } + if (!acc.isEmpty()) { + throw new ParserPluginException(acc); + } + } + + @Override + public String getTagName() { + return DEPENDENCIES_NAME; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java index ab288b8..23e8432 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java @@ -30,55 +30,41 @@ /** * Parser plugin to handle exclusions defined in a test suite. - * */ -public class SuiteExclusionsPlugin implements IPostParseSuitePlugin -{ - private static final String EXCLUSIONS_NAME = "exclusions"; - private static Logger logger = Logger.getLogger(SuiteExclusionsPlugin.class.getPackage().getName()); - - @Override - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException - { - ExceptionAccumulator acc = new ExceptionAccumulator(); - Set exclusionTests = ctx.getTestSuite().getExclusions().getDependenciesTests(); - Set exclusionTestSuites = ctx.getTestSuite().getExclusions().getDependenciesSuites(); - Element exclusionsElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), EXCLUSIONS_NAME); - for (Element e : ParserHelper.getChildren(exclusionsElement)) - { - try - { - AttributeHelper excAttributeHelper = new AttributeHelper(e); - String exclusionValue = excAttributeHelper.getRequiredString("name"); - if(e.getNodeName().equalsIgnoreCase("test")) - { - exclusionTests.add(exclusionValue); - } - else if(e.getNodeName().equalsIgnoreCase("testsuite")) - { - exclusionTestSuites.add(exclusionValue); - } - else - { - throw new UnexpectedElementException(e); - } - } - catch (Throwable th) - { - logger.fatal(th.getMessage()); +public class SuiteExclusionsPlugin implements IPostParseSuitePlugin { + private static final String EXCLUSIONS_NAME = "exclusions"; + private static Logger logger = Logger.getLogger(SuiteExclusionsPlugin.class.getPackage().getName()); + + @Override + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + Set exclusionTests = ctx.getTestSuite().getExclusions().getDependenciesTests(); + Set exclusionTestSuites = ctx.getTestSuite().getExclusions().getDependenciesSuites(); + Element exclusionsElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), EXCLUSIONS_NAME); + for (Element e : ParserHelper.getChildren(exclusionsElement)) { + try { + AttributeHelper excAttributeHelper = new AttributeHelper(e); + String exclusionValue = excAttributeHelper.getRequiredString("name"); + if (e.getNodeName().equalsIgnoreCase("test")) { + exclusionTests.add(exclusionValue); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + exclusionTestSuites.add(exclusionValue); + } else { + throw new UnexpectedElementException(e); + } + } catch (Throwable th) { + logger.fatal(th.getMessage()); // mc.error(th.getMessage()); - acc.add(th); - } - } - if(!acc.isEmpty()) - { - throw new ParserPluginException(acc); - } - } - - @Override - public String getTagName() - { - return EXCLUSIONS_NAME; - } + acc.add(th); + } + } + if (!acc.isEmpty()) { + throw new ParserPluginException(acc); + } + } + + @Override + public String getTagName() { + return EXCLUSIONS_NAME; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java index c4040a6..ed9bfb3 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java @@ -44,231 +44,177 @@ /** * Parser plugin to handle testdata element in a test script. */ -public class TestDataPlugin implements IPostParseTestPlugin -{ - protected TestDigraph testDigraph; - - public TestDataPlugin(AutomationEngine automationEngine) - { - this.testDigraph = automationEngine.getTestDigraph(); - } - - @Override - public String getTagName() - { - return "testdata"; - } - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException - { - String testDataFile = getTestDataAttribute(ctx, "file"); - String testDataSheet = getTestDataAttribute(ctx, "sheet"); - List> testData = getTestData(testDataFile, testDataSheet); - int tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); - - List testComponents = ctx.getTestSuite().getComponentList(); - testComponents.remove(testComponents.size() - 1); - for(int testDataRow = 1; testDataRow < testData.size(); testDataRow++) - { +public class TestDataPlugin implements IPostParseTestPlugin { + protected TestDigraph testDigraph; + + public TestDataPlugin(AutomationEngine automationEngine) { + this.testDigraph = automationEngine.getTestDigraph(); + } + + @Override + public String getTagName() { + return "testdata"; + } + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + String testDataFile = getTestDataAttribute(ctx, "file"); + String testDataSheet = getTestDataAttribute(ctx, "sheet"); + List> testData = getTestData(testDataFile, testDataSheet); + int tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); + + List testComponents = ctx.getTestSuite().getComponentList(); + testComponents.remove(testComponents.size() - 1); + for (int testDataRow = 1; testDataRow < testData.size(); testDataRow++) { // TestScript ts = null; - TestScript ts = reparseScript(ctx); - renameScript(ts, tsNamefromFilePosition, testData.get(testDataRow), testDataRow); - - setTestDataToTestScript(testData.get(0), testData.get(testDataRow), ts); - - addToSuite(ctx, ts); - - -// DigraphPlugin dependenciesPlugin = DigraphPlugin.getInstance(); -// TestDigraph testDigraph = dependenciesPlugin.getTestDigraph(); - testDigraph.addVertex(new DiNode(ts)); - } - } - - private String getTestDataAttribute(PostTestParserPluginContext ctx, String attributeName) - { - NodeList children = ctx.getRootNodeTest().getChildNodes(); - String result = null; - - for(int i = 0; i < children.getLength(); i++) - { - if(children.item(i).getNodeName().equalsIgnoreCase("testData")) - { - Node attribute = children.item(i).getAttributes().getNamedItem(attributeName); - if(attribute == null) - continue; - result = attribute.getNodeValue(); - } - } - - return result; - } - - private List> getTestData(String file, String sheet) throws ParserPluginException - { - if(file.endsWith(".xlsx")) - { - return getExcelDataFromFile(file, sheet, true); - } + TestScript ts = reparseScript(ctx); + renameScript(ts, tsNamefromFilePosition, testData.get(testDataRow), testDataRow); - if(file.endsWith(".xls")) - { - return getExcelDataFromFile(file, sheet, false); - } + setTestDataToTestScript(testData.get(0), testData.get(testDataRow), ts); - if(file.endsWith(".csv")) - { - return getCSVDataFromFile(file); - } + addToSuite(ctx, ts); - throw new ParserPluginException("Oops! can't parse test data file ('" + file + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); - } - private int getTSNameFromDataFilePosition(List> testData) - { - // try to findout 'JTAF.test.name' column. Value from this column - // necessary to add to ts name. - if(testData != null && testData.size() > 0) - { - List firstLine = testData.get(0); - int pos = 0; - for(String firstLineItem : firstLine) - { - if(firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) - { - return pos; - } - else - { - pos++; - } - } - } - return -1; - } - - private final List> getExcelDataFromFile(String testDataFile, String sheetName, boolean isXlsx) throws ParserPluginException - { - if(testDataFile != null && testDataFile.length() > 0) - { - ExcelFileParser excelFileParser = null; - try - { - if(sheetName != null) - { - excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); - } - else - { - excelFileParser = new ExcelFileParser(testDataFile, isXlsx); - } - return excelFileParser.parseExcelFile(isXlsx); - } - catch(Exception e) - { - throw new ParserPluginException("Oops! Can't parse excel file '" + testDataFile + "'!"); - } - } - return null; - } - - private List> getCSVDataFromFile(String file) throws ParserPluginException - { - List> result = new ArrayList>(); - CSVReader reader = null; - try - { - reader = new CSVReader(new FileReader(file)); - List nextLine; - - while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) - { - if((nextLine != null) && (nextLine.size() > 0) && (!nextLine.get(0).startsWith("#"))) - { - result.add(nextLine); - } - } - } - catch(Exception exception) - { - throw new ParserPluginException("Oops! Can't open file '" + file + "'!", exception); - } - finally - { - try - { - if(reader != null) - reader.close(); - } - catch(IOException ioException) - { - throw new ParserPluginException("Problem closing CSVReader", ioException); - } - } - return result; - } - - private TestScript reparseScript(PostTestParserPluginContext ctx) throws ParserPluginException - { - ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); - try - { - return sp.processTestScript((Element) ctx.getRootNodeTest(), new MessageCollector()); - } - catch(Exception exception) - { - throw new ParserPluginException(exception); - } - } - - private void addToSuite(PostTestParserPluginContext ctx, TestScript ts) throws ParserPluginException - { - try - { - ctx.getTestSuite().add(ts); - } - catch(NameCollisionException nameCollisionException) - { - throw new ParserPluginException(nameCollisionException); - } - } - - private void setTestDataToTestScript(List title, List data, TestScript ts) - { - for(Invocation statement : ts.getBody()) - { - if(statement instanceof Invocation) - { - Map parameters = ((Invocation) statement).getParameters(); - for(int i = 0; i < title.size(); i++) - { - if(i < data.size()) - { - parameters.put(title.get(i), data.get(i)); - } - else - { - parameters.put(title.get(i), ""); - } - } - } - } - } - - private void renameScript(TestScript ts, int tsNamefromFilePosition, List row, int rowNumber) - { - // TODO Auto-generated method stub - - String tsNamefromFile = ""; - if(tsNamefromFilePosition >= 0) - { - tsNamefromFile = "testNameFromDataFile-" + row.get(tsNamefromFilePosition); - } - - String newName = ts.getName(); - newName += " [data file row #" + rowNumber + "] ; " + tsNamefromFile; - - ts.setName(newName); - } +// DigraphPlugin dependenciesPlugin = DigraphPlugin.getInstance(); +// TestDigraph testDigraph = dependenciesPlugin.getTestDigraph(); + testDigraph.addVertex(new DiNode(ts)); + } + } + + private String getTestDataAttribute(PostTestParserPluginContext ctx, String attributeName) { + NodeList children = ctx.getRootNodeTest().getChildNodes(); + String result = null; + + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase("testData")) { + Node attribute = children.item(i).getAttributes().getNamedItem(attributeName); + if (attribute == null) + continue; + result = attribute.getNodeValue(); + } + } + + return result; + } + + private List> getTestData(String file, String sheet) throws ParserPluginException { + if (file.endsWith(".xlsx")) { + return getExcelDataFromFile(file, sheet, true); + } + + if (file.endsWith(".xls")) { + return getExcelDataFromFile(file, sheet, false); + } + + if (file.endsWith(".csv")) { + return getCSVDataFromFile(file); + } + + throw new ParserPluginException("Oops! can't parse test data file ('" + file + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); + } + + private int getTSNameFromDataFilePosition(List> testData) { + // try to findout 'JTAF.test.name' column. Value from this column + // necessary to add to ts name. + if (testData != null && testData.size() > 0) { + List firstLine = testData.get(0); + int pos = 0; + for (String firstLineItem : firstLine) { + if (firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) { + return pos; + } else { + pos++; + } + } + } + return -1; + } + + private final List> getExcelDataFromFile(String testDataFile, String sheetName, boolean isXlsx) throws ParserPluginException { + if (testDataFile != null && testDataFile.length() > 0) { + ExcelFileParser excelFileParser = null; + try { + if (sheetName != null) { + excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); + } else { + excelFileParser = new ExcelFileParser(testDataFile, isXlsx); + } + return excelFileParser.parseExcelFile(isXlsx); + } catch (Exception e) { + throw new ParserPluginException("Oops! Can't parse excel file '" + testDataFile + "'!"); + } + } + return null; + } + + private List> getCSVDataFromFile(String file) throws ParserPluginException { + List> result = new ArrayList>(); + CSVReader reader = null; + try { + reader = new CSVReader(new FileReader(file)); + List nextLine; + + while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { + if ((nextLine != null) && (nextLine.size() > 0) && (!nextLine.get(0).startsWith("#"))) { + result.add(nextLine); + } + } + } catch (Exception exception) { + throw new ParserPluginException("Oops! Can't open file '" + file + "'!", exception); + } finally { + try { + if (reader != null) + reader.close(); + } catch (IOException ioException) { + throw new ParserPluginException("Problem closing CSVReader", ioException); + } + } + return result; + } + + private TestScript reparseScript(PostTestParserPluginContext ctx) throws ParserPluginException { + ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); + try { + return sp.processTestScript((Element) ctx.getRootNodeTest(), new MessageCollector()); + } catch (Exception exception) { + throw new ParserPluginException(exception); + } + } + + private void addToSuite(PostTestParserPluginContext ctx, TestScript ts) throws ParserPluginException { + try { + ctx.getTestSuite().add(ts); + } catch (NameCollisionException nameCollisionException) { + throw new ParserPluginException(nameCollisionException); + } + } + + private void setTestDataToTestScript(List title, List data, TestScript ts) { + for (Invocation statement : ts.getBody()) { + if (statement instanceof Invocation) { + Map parameters = ((Invocation) statement).getParameters(); + for (int i = 0; i < title.size(); i++) { + if (i < data.size()) { + parameters.put(title.get(i), data.get(i)); + } else { + parameters.put(title.get(i), ""); + } + } + } + } + } + + private void renameScript(TestScript ts, int tsNamefromFilePosition, List row, int rowNumber) { + // TODO Auto-generated method stub + + String tsNamefromFile = ""; + if (tsNamefromFilePosition >= 0) { + tsNamefromFile = "testNameFromDataFile-" + row.get(tsNamefromFilePosition); + } + + String newName = ts.getName(); + newName += " [data file row #" + rowNumber + "] ; " + tsNamefromFile; + + ts.setName(newName); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java index 734f108..ed84ee6 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java @@ -32,63 +32,52 @@ /** * parser plugin to parse the dependencies defined in a test script. */ -public class TestDependenciesPlugin implements IPostParseTestPlugin -{ - public static final String DEPENDENCIES_NAME = "dependencies"; - public static final String TEST_NAME = "test"; - public static final String TEST_SUITE_NAME = "testsuite"; +public class TestDependenciesPlugin implements IPostParseTestPlugin { + public static final String DEPENDENCIES_NAME = "dependencies"; + public static final String TEST_NAME = "test"; + public static final String TEST_SUITE_NAME = "testsuite"; - @Override - public String getTagName() - { - return DEPENDENCIES_NAME; - } + @Override + public String getTagName() { + return DEPENDENCIES_NAME; + } - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException - { - Set exclusionSuites = new HashSet(); - Set exclusionTests = new HashSet(); - - NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); - for(int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) - { - Node testChildNode = testChildNodes.item(testChildNodeIndex); - if(testChildNode.getNodeName().equalsIgnoreCase(DEPENDENCIES_NAME)) - { - handleDependencyNode(testChildNode, exclusionSuites, exclusionTests); - } - } + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + Set exclusionSuites = new HashSet(); + Set exclusionTests = new HashSet(); - List componentList = ctx.getTestSuite().getComponentList(); - TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); - lastTestScript.setDependencies(exclusionSuites, exclusionTests); - } + NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); + for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { + Node testChildNode = testChildNodes.item(testChildNodeIndex); + if (testChildNode.getNodeName().equalsIgnoreCase(DEPENDENCIES_NAME)) { + handleDependencyNode(testChildNode, exclusionSuites, exclusionTests); + } + } - private void handleDependencyNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) - { - NodeList dependencyChildNodes = testChildNode.getChildNodes(); - for(int dependencyChildNodeIndex = 0; dependencyChildNodeIndex < dependencyChildNodes.getLength(); dependencyChildNodeIndex++) - { - Node dependencyChildNode = dependencyChildNodes.item(dependencyChildNodeIndex); - Set addSet = determineSet(dependencyChildNode.getNodeName(), exclusionSuites, exclusionTests); - if(addSet == null) - continue; - String name = dependencyChildNode.getAttributes().getNamedItem("name").getTextContent(); - addSet.add(name); - } - } + List componentList = ctx.getTestSuite().getComponentList(); + TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); + lastTestScript.setDependencies(exclusionSuites, exclusionTests); + } - private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) - { - if(nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) - { - return exclusionSuites; - } - else if(nodeName.equalsIgnoreCase(TEST_NAME)) - { - return exclusionTests; - } - return null; - } + private void handleDependencyNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { + NodeList dependencyChildNodes = testChildNode.getChildNodes(); + for (int dependencyChildNodeIndex = 0; dependencyChildNodeIndex < dependencyChildNodes.getLength(); dependencyChildNodeIndex++) { + Node dependencyChildNode = dependencyChildNodes.item(dependencyChildNodeIndex); + Set addSet = determineSet(dependencyChildNode.getNodeName(), exclusionSuites, exclusionTests); + if (addSet == null) + continue; + String name = dependencyChildNode.getAttributes().getNamedItem("name").getTextContent(); + addSet.add(name); + } + } + + private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { + if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { + return exclusionSuites; + } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { + return exclusionTests; + } + return null; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java index 54afc72..d4243ba 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java @@ -32,63 +32,52 @@ /** * Parser plugin responsible for parsing exclusions in test script. */ -public class TestExclusionsPlugin implements IPostParseTestPlugin -{ - public static final String EXCLUSIONS_NAME = "exclusions"; - public static final String TEST_NAME = "test"; - public static final String TEST_SUITE_NAME = "testsuite"; +public class TestExclusionsPlugin implements IPostParseTestPlugin { + public static final String EXCLUSIONS_NAME = "exclusions"; + public static final String TEST_NAME = "test"; + public static final String TEST_SUITE_NAME = "testsuite"; - @Override - public String getTagName() - { - return EXCLUSIONS_NAME; - } + @Override + public String getTagName() { + return EXCLUSIONS_NAME; + } - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException - { - Set exclusionSuites = new HashSet(); - Set exclusionTests = new HashSet(); - - NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); - for(int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) - { - Node testChildNode = testChildNodes.item(testChildNodeIndex); - if(testChildNode.getNodeName().equalsIgnoreCase(EXCLUSIONS_NAME)) - { - handleExclusionNode(testChildNode, exclusionSuites, exclusionTests); - } - } + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + Set exclusionSuites = new HashSet(); + Set exclusionTests = new HashSet(); - List componentList = ctx.getTestSuite().getComponentList(); - TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); - lastTestScript.setExclusions(exclusionSuites, exclusionTests); - } + NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); + for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { + Node testChildNode = testChildNodes.item(testChildNodeIndex); + if (testChildNode.getNodeName().equalsIgnoreCase(EXCLUSIONS_NAME)) { + handleExclusionNode(testChildNode, exclusionSuites, exclusionTests); + } + } - private void handleExclusionNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) - { - NodeList exclusionChildNodes = testChildNode.getChildNodes(); - for(int exclusionChildNodeIndex = 0; exclusionChildNodeIndex < exclusionChildNodes.getLength(); exclusionChildNodeIndex++) - { - Node exclusionChildNode = exclusionChildNodes.item(exclusionChildNodeIndex); - Set addSet = determineSet(exclusionChildNode.getNodeName(), exclusionSuites, exclusionTests); - if(addSet == null) - continue; - String name = exclusionChildNode.getAttributes().getNamedItem("name").getTextContent(); - addSet.add(name); - } - } + List componentList = ctx.getTestSuite().getComponentList(); + TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); + lastTestScript.setExclusions(exclusionSuites, exclusionTests); + } - private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) - { - if(nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) - { - return exclusionSuites; - } - else if(nodeName.equalsIgnoreCase(TEST_NAME)) - { - return exclusionTests; - } - return null; - } + private void handleExclusionNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { + NodeList exclusionChildNodes = testChildNode.getChildNodes(); + for (int exclusionChildNodeIndex = 0; exclusionChildNodeIndex < exclusionChildNodes.getLength(); exclusionChildNodeIndex++) { + Node exclusionChildNode = exclusionChildNodes.item(exclusionChildNodeIndex); + Set addSet = determineSet(exclusionChildNode.getNodeName(), exclusionSuites, exclusionTests); + if (addSet == null) + continue; + String name = exclusionChildNode.getAttributes().getNamedItem("name").getTextContent(); + addSet.add(name); + } + } + + private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { + if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { + return exclusionSuites; + } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { + return exclusionTests; + } + return null; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestStrategyParser.java b/src/main/java/org/finra/jtaf/core/parsing/TestStrategyParser.java index ab43dd6..729b462 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestStrategyParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestStrategyParser.java @@ -37,92 +37,88 @@ /** - * Parser for TestAgenda or Strategy xml file. - * + * Parser for TestAgenda or Strategy xml file. */ public class TestStrategyParser extends BaseParser { - private static final String EXECUTE = "execute"; - - private static final String TARGET = "target"; - - private static final List EMPTY_LIST = new ArrayList(); - - private TestAgenda testPlan; - - private List postParseStrategyElementPlugins; - - public TestStrategyParser() throws ParserConfigurationException { - testPlan = null; - } - - public final TestAgenda getTestPlan() { - return testPlan; - } - - public void setDigraph(TestDigraph digraph){ - } - @Override - protected final void handleRoot(Element root) throws ParsingException { - testPlan = new TestAgenda(); - - if (root.getNodeName().equalsIgnoreCase(EXECUTE)) { - handleExecute(root); - } else { - reportUnexpectedElement(root); - throw new UnexpectedElementException(root); - } - } - - protected final void handleExecute(Element elem) { - try { - getErrorCollector().push("In " + EXECUTE + "block"); - for (Element child : getChildElements(elem)) { - if(child.getNodeName().equalsIgnoreCase(TARGET) /*|| child.getNodeName().equalsIgnoreCase(UNION)*/) - { - getTestPlan().getTestScripts().addAll(handleTarget(child)); - } - for(IPostParseStrategyElementPlugin postParseStrategyElementPlugin : postParseStrategyElementPlugins) - { - postParseStrategyElementPlugin.execute(new PostStrategyElementParserPluginContext(testPlan, child)); - } - } - } catch (Exception e) { - getErrorCollector().error(e.getMessage()); - } finally { - getErrorCollector().pop(); - } - } - - protected List handleTarget(Element elem) throws MissingAttributeException{ - AttributeHelper attrs = new AttributeHelper(elem); - final String targetName = attrs.getRequiredString("name"); - - try { - getErrorCollector().push("In target " + targetName); - // TODO: pass in TestComponents rather than depending on AutomationEngine - List targets = AutomationEngine.getInstance().getTestRoot().toComponent(targetName); - - if (targets == null || targets.size() == 0) { - getErrorCollector().error("Target does not exist"); - return EMPTY_LIST; - } else { - TestScriptCollector tsc = new TestScriptCollector(); - for (TestComponent target : targets) { - target.acceptTestVisitor(tsc); - } - return tsc.getTestScripts(); - } - } catch (Exception e) { - getErrorCollector().error(e.getMessage()); - return EMPTY_LIST; - } - finally { - getErrorCollector().pop(); - } - } - - public void setPostParseStrategyElementPlugins(List postParseStrategyElementPlugins) - { - this.postParseStrategyElementPlugins = postParseStrategyElementPlugins; - } + private static final String EXECUTE = "execute"; + + private static final String TARGET = "target"; + + private static final List EMPTY_LIST = new ArrayList(); + + private TestAgenda testPlan; + + private List postParseStrategyElementPlugins; + + public TestStrategyParser() throws ParserConfigurationException { + testPlan = null; + } + + public final TestAgenda getTestPlan() { + return testPlan; + } + + public void setDigraph(TestDigraph digraph) { + } + + @Override + protected final void handleRoot(Element root) throws ParsingException { + testPlan = new TestAgenda(); + + if (root.getNodeName().equalsIgnoreCase(EXECUTE)) { + handleExecute(root); + } else { + reportUnexpectedElement(root); + throw new UnexpectedElementException(root); + } + } + + protected final void handleExecute(Element elem) { + try { + getErrorCollector().push("In " + EXECUTE + "block"); + for (Element child : getChildElements(elem)) { + if (child.getNodeName().equalsIgnoreCase(TARGET) /*|| child.getNodeName().equalsIgnoreCase(UNION)*/) { + getTestPlan().getTestScripts().addAll(handleTarget(child)); + } + for (IPostParseStrategyElementPlugin postParseStrategyElementPlugin : postParseStrategyElementPlugins) { + postParseStrategyElementPlugin.execute(new PostStrategyElementParserPluginContext(testPlan, child)); + } + } + } catch (Exception e) { + getErrorCollector().error(e.getMessage()); + } finally { + getErrorCollector().pop(); + } + } + + protected List handleTarget(Element elem) throws MissingAttributeException { + AttributeHelper attrs = new AttributeHelper(elem); + final String targetName = attrs.getRequiredString("name"); + + try { + getErrorCollector().push("In target " + targetName); + // TODO: pass in TestComponents rather than depending on AutomationEngine + List targets = AutomationEngine.getInstance().getTestRoot().toComponent(targetName); + + if (targets == null || targets.size() == 0) { + getErrorCollector().error("Target does not exist"); + return EMPTY_LIST; + } else { + TestScriptCollector tsc = new TestScriptCollector(); + for (TestComponent target : targets) { + target.acceptTestVisitor(tsc); + } + return tsc.getTestScripts(); + } + } catch (Exception e) { + getErrorCollector().error(e.getMessage()); + return EMPTY_LIST; + } finally { + getErrorCollector().pop(); + } + } + + public void setPostParseStrategyElementPlugins(List postParseStrategyElementPlugins) { + this.postParseStrategyElementPlugins = postParseStrategyElementPlugins; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/AttributeFormatException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/AttributeFormatException.java index cedd77f..33a9e3c 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/AttributeFormatException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/AttributeFormatException.java @@ -22,15 +22,15 @@ */ public class AttributeFormatException extends ParsingException { - /** - * Auto-generated - */ - private static final long serialVersionUID = 4579028460955204606L; + /** + * Auto-generated + */ + private static final long serialVersionUID = 4579028460955204606L; - /** - * @param expectedType a String describing the expected format. For example, "Integer" - */ - public AttributeFormatException(final String expectedType) { - super("Illegal attribute format (expected " + expectedType + ")"); - } + /** + * @param expectedType a String describing the expected format. For example, "Integer" + */ + public AttributeFormatException(final String expectedType) { + super("Illegal attribute format (expected " + expectedType + ")"); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/ExceptionAccumulator.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/ExceptionAccumulator.java index 39409b9..cdf115f 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/ExceptionAccumulator.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/ExceptionAccumulator.java @@ -28,38 +28,38 @@ */ public class ExceptionAccumulator extends ParsingException { - /** - * AUTO-GENERATED - */ - private static final long serialVersionUID = 2524703384072863880L; + /** + * AUTO-GENERATED + */ + private static final long serialVersionUID = 2524703384072863880L; - private final List exceptions; - - public ExceptionAccumulator() { - super("Multiple failures reported."); - this.exceptions = new ArrayList(); - } + private final List exceptions; + public ExceptionAccumulator() { + super("Multiple failures reported."); + this.exceptions = new ArrayList(); + } - /** - * @return The exceptions that have been accumulated - */ - public final List getExceptions() { - return this.exceptions; - } - - /** - * @param th A Throwable (Exception, Error, etc.) to add to the accumulator - */ - public final void add(Throwable th) { - this.getExceptions().add(th); - Logger.getLogger(ExceptionAccumulator.class).debug("Exception accumulated", th); - } - - /** - * @return if true, then the accumulator has not accumulated any exceptions - */ - public final boolean isEmpty() { - return this.getExceptions().isEmpty(); - } + + /** + * @return The exceptions that have been accumulated + */ + public final List getExceptions() { + return this.exceptions; + } + + /** + * @param th A Throwable (Exception, Error, etc.) to add to the accumulator + */ + public final void add(Throwable th) { + this.getExceptions().add(th); + Logger.getLogger(ExceptionAccumulator.class).debug("Exception accumulated", th); + } + + /** + * @return if true, then the accumulator has not accumulated any exceptions + */ + public final boolean isEmpty() { + return this.getExceptions().isEmpty(); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingAttributeException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingAttributeException.java index 88fba76..9486a65 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingAttributeException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingAttributeException.java @@ -25,24 +25,24 @@ public class MissingAttributeException extends ParsingException { - - private static final long serialVersionUID = -3806789951904835575L; - private static final String createMessage(Element e, String name) { - StringBuilder sb = new StringBuilder(); - sb.append("The element '"); - sb.append(e.getNodeName()); - sb.append("' is missing the required attribute '"); - sb.append(name); - sb.append("'"); - return sb.toString(); - } - - /** - * @param e The element that is missing the attribute - * @param name The attribute that is missing from the element - */ - public MissingAttributeException(Element e, String name) { - super(MissingAttributeException.createMessage(e, name)); - } + private static final long serialVersionUID = -3806789951904835575L; + + private static final String createMessage(Element e, String name) { + StringBuilder sb = new StringBuilder(); + sb.append("The element '"); + sb.append(e.getNodeName()); + sb.append("' is missing the required attribute '"); + sb.append(name); + sb.append("'"); + return sb.toString(); + } + + /** + * @param e The element that is missing the attribute + * @param name The attribute that is missing from the element + */ + public MissingAttributeException(Element e, String name) { + super(MissingAttributeException.createMessage(e, name)); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingRequiredElementException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingRequiredElementException.java index 94394ba..6648c6f 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingRequiredElementException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MissingRequiredElementException.java @@ -22,15 +22,15 @@ */ public class MissingRequiredElementException extends ParsingException { - /** - * AUTO-GENERATED - */ - private static final long serialVersionUID = 3859741174693262134L; + /** + * AUTO-GENERATED + */ + private static final long serialVersionUID = 3859741174693262134L; - /** - * @param xpath An XPath that describes the missing element - */ - public MissingRequiredElementException(String xpath) { - super("The XPath \"" + xpath + "\" did not match any nodes"); - } + /** + * @param xpath An XPath that describes the missing element + */ + public MissingRequiredElementException(String xpath) { + super("The XPath \"" + xpath + "\" did not match any nodes"); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MultipleMatchesException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MultipleMatchesException.java index 59685fd..e73470f 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/MultipleMatchesException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/MultipleMatchesException.java @@ -23,25 +23,25 @@ */ public class MultipleMatchesException extends ParsingException { - /** - * AUTO-GENERATED - */ - private static final long serialVersionUID = 51467102839218606L; + /** + * AUTO-GENERATED + */ + private static final long serialVersionUID = 51467102839218606L; - private final String xpath; + private final String xpath; - /** - * @param xpath The XPath that is giving multiple matches - */ - public MultipleMatchesException(String xpath) { - super("The XPath query \"" + xpath + "\" matched multiple nodes (only one match was expected)"); - this.xpath = xpath; - } - - /** - * @param xpath The XPath that is giving multiple matches - */ - public final String getXPath() { - return this.xpath; - } + /** + * @param xpath The XPath that is giving multiple matches + */ + public MultipleMatchesException(String xpath) { + super("The XPath query \"" + xpath + "\" matched multiple nodes (only one match was expected)"); + this.xpath = xpath; + } + + /** + * @param xpath The XPath that is giving multiple matches + */ + public final String getXPath() { + return this.xpath; + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/NestedXPathException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/NestedXPathException.java index cd3f85b..55383d3 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/NestedXPathException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/NestedXPathException.java @@ -20,19 +20,18 @@ /** * This is a wrapper for XPath exceptions. - * */ public class NestedXPathException extends ParsingException { - /** - * AUTO-GENERATED - */ - private static final long serialVersionUID = -6483364508583432000L; + /** + * AUTO-GENERATED + */ + private static final long serialVersionUID = -6483364508583432000L; - /** - * @param e The wrapped XPath - */ - public NestedXPathException(XPathException e) { - super(e); - } + /** + * @param e The wrapped XPath + */ + public NestedXPathException(XPathException e) { + super(e); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/ParsingException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/ParsingException.java index 0849b67..805f88c 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/ParsingException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/ParsingException.java @@ -22,24 +22,24 @@ */ public class ParsingException extends Exception { - /** - * Auto-generated - */ - private static final long serialVersionUID = -218747052989712917L; + /** + * Auto-generated + */ + private static final long serialVersionUID = -218747052989712917L; - public ParsingException() { - super(); - } - - public ParsingException(String message) { - super(message); - } - - public ParsingException(String message, Throwable e) { - super(message, e); - } - - public ParsingException(Throwable e) { - super(e); - } + public ParsingException() { + super(); + } + + public ParsingException(String message) { + super(message); + } + + public ParsingException(String message, Throwable e) { + super(message, e); + } + + public ParsingException(Throwable e) { + super(e); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/exceptions/UnexpectedElementException.java b/src/main/java/org/finra/jtaf/core/parsing/exceptions/UnexpectedElementException.java index dfb979b..c42eca9 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/exceptions/UnexpectedElementException.java +++ b/src/main/java/org/finra/jtaf/core/parsing/exceptions/UnexpectedElementException.java @@ -23,15 +23,15 @@ */ public class UnexpectedElementException extends ParsingException { - /** - * Auto-generated - */ - private static final long serialVersionUID = 1270431357009356272L; + /** + * Auto-generated + */ + private static final long serialVersionUID = 1270431357009356272L; - /** - * @param e the element that was not expected - */ - public UnexpectedElementException(Element e) { - super("Unexpected element '" + e.getNodeName() + "' encountered while parsing document"); - } + /** + * @param e the element that was not expected + */ + public UnexpectedElementException(Element e) { + super("Unexpected element '" + e.getNodeName() + "' encountered while parsing document"); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/helpers/AttributeHelper.java b/src/main/java/org/finra/jtaf/core/parsing/helpers/AttributeHelper.java index b938075..2b41ed9 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/helpers/AttributeHelper.java +++ b/src/main/java/org/finra/jtaf/core/parsing/helpers/AttributeHelper.java @@ -29,148 +29,150 @@ import org.w3c.dom.NamedNodeMap; - - /** * Helper class to fetch attributes of an element. */ -public class AttributeHelper { - /** - * I want to remove this class once I figure out how to treat node names - * in a case-insensitive manner. Until this, this is a necessary evil :-D - * - */ - - private static final Pattern integerRegex = Pattern.compile("\\s*\\d+\\s*"); - - private final Map attrs; - private final Element source; - private final Set collisions; - - /** - * Collect the attributes, make sure their names are all cast to lowercase, - * and throw an exception if there are name collisions. - * - * @param qName - * @param attributes - */ - public AttributeHelper(Element e) { - attrs = new HashMap(); - source = e; - collisions = new HashSet(); - NamedNodeMap origAttrs = source.getAttributes(); - - for(int i = 0; i < origAttrs.getLength(); ++i) { - final String name = origAttrs.item(i).getNodeName().toLowerCase(); - if(attrs.containsKey(name)) { - collisions.add(name); - } - attrs.put(name, origAttrs.item(i).getNodeValue()); - } - } - - - /** - * @return A copy of the collision set - */ - public final Set getCollisions() { - return new HashSet(this.collisions); - } - - /** - * @return The entrySet used internally - */ - public Set> entrySet() { - return this.attrs.entrySet(); - } - - - /** - * Make sure you don't modify this return value - * @return The map maintained internally - */ - public final Map getMap() { - return this.attrs; - } - - /** - * Search for the given key, ignoring case - * @param key - * @return - */ - public boolean containsKey(String key) { - return this.attrs.containsKey(key.toLowerCase()); - } - - /** - * Search for the given value - * @param value - * @return - */ - public boolean containsValue(String value) { - return this.attrs.containsValue(value); - } - - - - /** - * Throws an exception if the requested attribute is undefined or an empty string - * @param key - * @return - * @throws MissingAttributeException - */ - public String getRequiredString(String key) throws MissingAttributeException { - String retval = this.getOptionalString(key); - if((retval == null) || (retval.trim().equals(""))) { - throw new MissingAttributeException(this.source, key); - } - return retval; - } - - /** - * Search for the given key, ignoring case - * @param key - * @return - */ - public String getOptionalString(String key) { - return this.attrs.get(key.toLowerCase()); - } - - - /** - * If the requested attribute - * @param key - * @param defaultValue - * @return - */ - public final String getStringOrDefault(String key, String defaultValue) { - String retval = this.getOptionalString(key); - if(retval == null) { - return defaultValue; - } - return retval; - } - - - - /** - * Ensures that the attribute is a properly-formatted integer - * @param key - * @return - * @throws MissingAttributeException - * @throws AttributeFormatException - */ - public final int getRequiredInteger(String key) throws MissingAttributeException, AttributeFormatException { - final String retval = this.getOptionalString(key); - if( (retval == null) || (retval.equals(""))) { - throw new MissingAttributeException(this.source, key); - } - - if(integerRegex.matcher(retval) == null) { - throw new AttributeFormatException("Integer"); - } - - return Integer.parseInt(retval); - } +public class AttributeHelper { + /** + * I want to remove this class once I figure out how to treat node names + * in a case-insensitive manner. Until this, this is a necessary evil :-D + */ + + private static final Pattern integerRegex = Pattern.compile("\\s*\\d+\\s*"); + + private final Map attrs; + private final Element source; + private final Set collisions; + + /** + * Collect the attributes, make sure their names are all cast to lowercase, + * and throw an exception if there are name collisions. + * + * @param qName + * @param attributes + */ + public AttributeHelper(Element e) { + attrs = new HashMap(); + source = e; + collisions = new HashSet(); + NamedNodeMap origAttrs = source.getAttributes(); + + for (int i = 0; i < origAttrs.getLength(); ++i) { + final String name = origAttrs.item(i).getNodeName().toLowerCase(); + if (attrs.containsKey(name)) { + collisions.add(name); + } + attrs.put(name, origAttrs.item(i).getNodeValue()); + } + } + + + /** + * @return A copy of the collision set + */ + public final Set getCollisions() { + return new HashSet(this.collisions); + } + + /** + * @return The entrySet used internally + */ + public Set> entrySet() { + return this.attrs.entrySet(); + } + + + /** + * Make sure you don't modify this return value + * + * @return The map maintained internally + */ + public final Map getMap() { + return this.attrs; + } + + /** + * Search for the given key, ignoring case + * + * @param key + * @return + */ + public boolean containsKey(String key) { + return this.attrs.containsKey(key.toLowerCase()); + } + + /** + * Search for the given value + * + * @param value + * @return + */ + public boolean containsValue(String value) { + return this.attrs.containsValue(value); + } + + + /** + * Throws an exception if the requested attribute is undefined or an empty string + * + * @param key + * @return + * @throws MissingAttributeException + */ + public String getRequiredString(String key) throws MissingAttributeException { + String retval = this.getOptionalString(key); + if ((retval == null) || (retval.trim().equals(""))) { + throw new MissingAttributeException(this.source, key); + } + return retval; + } + + /** + * Search for the given key, ignoring case + * + * @param key + * @return + */ + public String getOptionalString(String key) { + return this.attrs.get(key.toLowerCase()); + } + + + /** + * If the requested attribute + * + * @param key + * @param defaultValue + * @return + */ + public final String getStringOrDefault(String key, String defaultValue) { + String retval = this.getOptionalString(key); + if (retval == null) { + return defaultValue; + } + return retval; + } + + + /** + * Ensures that the attribute is a properly-formatted integer + * + * @param key + * @return + * @throws MissingAttributeException + * @throws AttributeFormatException + */ + public final int getRequiredInteger(String key) throws MissingAttributeException, AttributeFormatException { + final String retval = this.getOptionalString(key); + if ((retval == null) || (retval.equals(""))) { + throw new MissingAttributeException(this.source, key); + } + + if (integerRegex.matcher(retval) == null) { + throw new AttributeFormatException("Integer"); + } + + return Integer.parseInt(retval); + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/helpers/ElementScanner.java b/src/main/java/org/finra/jtaf/core/parsing/helpers/ElementScanner.java index fc116b5..e74f596 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/helpers/ElementScanner.java +++ b/src/main/java/org/finra/jtaf/core/parsing/helpers/ElementScanner.java @@ -24,58 +24,56 @@ * Convenience class that can be used to process a sequence of * Elements. This will most likely be used in the preProcessing * stage. - * - * */ public class ElementScanner { - private final List elements; - private int index; + private final List elements; + private int index; + + public ElementScanner(List elements) { + this.elements = elements; + this.index = 0; + } + + public final boolean hasNext() { + return this.index < this.elements.size(); + } - public ElementScanner(List elements) { - this.elements = elements; - this.index = 0; - } + public Element peek() { + return this.elements.get(this.index); + } - public final boolean hasNext() { - return this.index < this.elements.size(); - } - public Element peek() { - return this.elements.get(this.index); - } + /** + * Shortcut method + * + * @param name + * @return + */ + public Element tryMatch(String name) { + if (this.hasNext()) { + Element next = this.peek(); + if (next.getNodeName().equalsIgnoreCase(name)) { + ++(this.index); + return next; + } + } + return null; + } - - /** - * Shortcut method - * @param name - * @return - */ - public Element tryMatch(String name) { - if(this.hasNext()) { - Element next = this.peek(); - if(next.getNodeName().equalsIgnoreCase(name)) { - ++(this.index); - return next; - } - } - return null; - } - - - /** - * Convenience method: Returns this.peek() and moves to the next element - * @return - */ - public Element match() { - if(this.hasNext()) { - Element retval = this.peek(); - ++(this.index); - return retval; - } - else { - return null; - } - } + /** + * Convenience method: Returns this.peek() and moves to the next element + * + * @return + */ + public Element match() { + if (this.hasNext()) { + Element retval = this.peek(); + ++(this.index); + return retval; + } else { + return null; + } + } } diff --git a/src/main/java/org/finra/jtaf/core/parsing/helpers/ParserHelper.java b/src/main/java/org/finra/jtaf/core/parsing/helpers/ParserHelper.java index 3738abf..e46eda9 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/helpers/ParserHelper.java +++ b/src/main/java/org/finra/jtaf/core/parsing/helpers/ParserHelper.java @@ -33,92 +33,89 @@ import org.w3c.dom.NodeList; - - /** - * Helper class for parsing XML file. + * Helper class for parsing XML file. */ public class ParserHelper { - /** - * This class is mostly here because I cannot figure out how to - * disable case-sensitivity of node names. It also provides a - * handful of other useful methods - */ - private static XPathFactory xpathFactory = null; - private static HashMap compiledMap = new HashMap(); - - private static final XPathFactory getXPathFactory() { - if(ParserHelper.xpathFactory == null) { - ParserHelper.xpathFactory = XPathFactory.newInstance(); - } - return ParserHelper.xpathFactory; - } - - - - /** - * A list of the immediate children of elem - * @param elem - * @return - */ - public static final List getChildren(Element elem) { - ArrayList retval = new ArrayList(); - NodeList nl = elem.getChildNodes(); - for(int i = 0; i < nl.getLength(); ++i) { - Node n = nl.item(i); - if(n.getNodeType() == Node.ELEMENT_NODE) { - retval.add((Element) n); - } - - } - return retval; - } - - public static final Element getOptionalElement(Element root, String xpath) throws MultipleMatchesException, NestedXPathException { - try { - XPathExpression expr = null; - - if((expr = ParserHelper.compiledMap.get(xpath)) == null) { - expr = getXPathFactory().newXPath().compile(xpath); - ParserHelper.compiledMap.put(xpath, expr); - } - - // I use a NodeList here instead of an Element because I want to ensure - // there are not multiple return values - NodeList nl = (NodeList) expr.evaluate(root, XPathConstants.NODESET); - - if(nl.getLength() > 1) { - throw new MultipleMatchesException(xpath); - } - - // TODO: Ensure the return value is an Element? - return (Element) nl.item(0); - } - catch(XPathException e) { - throw new NestedXPathException(e); - } - } - - public static final Element getRequireElement(Element root, String xpath) throws MultipleMatchesException, MissingRequiredElementException, NestedXPathException { - Element retval = getOptionalElement(root, xpath); - if(retval == null) { - throw new MissingRequiredElementException(xpath); - } - return retval; - } - - public static final Element getFirstChildElementCaseInsensitive(Element root, String elementName) { - NodeList nl = root.getChildNodes(); - if(nl.getLength() > 1) { - for(int i = 0; i < nl.getLength(); i++) { - Node node = nl.item(i); - if(node.getNodeType() == Node.ELEMENT_NODE && (node.getNodeName().equalsIgnoreCase(elementName))) { - return (Element)node; - } - } - } - - return null; - } + /** + * This class is mostly here because I cannot figure out how to + * disable case-sensitivity of node names. It also provides a + * handful of other useful methods + */ + private static XPathFactory xpathFactory = null; + private static HashMap compiledMap = new HashMap(); + + private static final XPathFactory getXPathFactory() { + if (ParserHelper.xpathFactory == null) { + ParserHelper.xpathFactory = XPathFactory.newInstance(); + } + return ParserHelper.xpathFactory; + } + + + /** + * A list of the immediate children of elem + * + * @param elem + * @return + */ + public static final List getChildren(Element elem) { + ArrayList retval = new ArrayList(); + NodeList nl = elem.getChildNodes(); + for (int i = 0; i < nl.getLength(); ++i) { + Node n = nl.item(i); + if (n.getNodeType() == Node.ELEMENT_NODE) { + retval.add((Element) n); + } + + } + return retval; + } + + public static final Element getOptionalElement(Element root, String xpath) throws MultipleMatchesException, NestedXPathException { + try { + XPathExpression expr = null; + + if ((expr = ParserHelper.compiledMap.get(xpath)) == null) { + expr = getXPathFactory().newXPath().compile(xpath); + ParserHelper.compiledMap.put(xpath, expr); + } + + // I use a NodeList here instead of an Element because I want to ensure + // there are not multiple return values + NodeList nl = (NodeList) expr.evaluate(root, XPathConstants.NODESET); + + if (nl.getLength() > 1) { + throw new MultipleMatchesException(xpath); + } + + // TODO: Ensure the return value is an Element? + return (Element) nl.item(0); + } catch (XPathException e) { + throw new NestedXPathException(e); + } + } + + public static final Element getRequireElement(Element root, String xpath) throws MultipleMatchesException, MissingRequiredElementException, NestedXPathException { + Element retval = getOptionalElement(root, xpath); + if (retval == null) { + throw new MissingRequiredElementException(xpath); + } + return retval; + } + + public static final Element getFirstChildElementCaseInsensitive(Element root, String elementName) { + NodeList nl = root.getChildNodes(); + if (nl.getLength() > 1) { + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE && (node.getNodeName().equalsIgnoreCase(elementName))) { + return (Element) node; + } + } + } + + return null; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java b/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java index 2dcfa16..b8de85c 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java +++ b/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java @@ -33,71 +33,71 @@ */ public class PluginManager { - private List postParseAllPlugins; - private List postParseSuitePlugins; - private List postParseTestPlugins; - private List postParseStrategyElementPlugins; - private List tearDownPlugins; - - private List testRunnerPlugins; - private List commandRunnerPlugins; - - public void setPostParseAllPlugins(List plugins) { - postParseAllPlugins = plugins; - } - - public List getPostParseAllPlugins() { - return postParseAllPlugins; - } - - public void setPostParseSuitePlugins( - List customPlugins) { - postParseSuitePlugins = customPlugins; - } - - public List getPostParseSuitePlugins() { - return postParseSuitePlugins; - } - - public void setPostParseTestPlugins(List plugins) { - postParseTestPlugins = plugins; - } - - public List getPostParseTestPlugins() { - return postParseTestPlugins; - } - - public void setPostParseStrategyElementPlugins( - List plugins) { - postParseStrategyElementPlugins = plugins; - } - - public List getPostParseStrategyElementPlugins() { - return postParseStrategyElementPlugins; - } - - public void setTestRunnerPlugins(List customPlugins) { - this.testRunnerPlugins = customPlugins; - } - - public List getTestRunnerPlugins() { - return testRunnerPlugins; - } - - public void setCommandRunnerPlugins(List customPlugins) { - this.commandRunnerPlugins = customPlugins; - } - - public List getCommandRunnerPlugins() { - return commandRunnerPlugins; - } - - public void setTearDownPlugins(List tearDownPlugins) { - this.tearDownPlugins = tearDownPlugins; - } - - public List getTearDownPlugins() { - return tearDownPlugins; - } + private List postParseAllPlugins; + private List postParseSuitePlugins; + private List postParseTestPlugins; + private List postParseStrategyElementPlugins; + private List tearDownPlugins; + + private List testRunnerPlugins; + private List commandRunnerPlugins; + + public void setPostParseAllPlugins(List plugins) { + postParseAllPlugins = plugins; + } + + public List getPostParseAllPlugins() { + return postParseAllPlugins; + } + + public void setPostParseSuitePlugins( + List customPlugins) { + postParseSuitePlugins = customPlugins; + } + + public List getPostParseSuitePlugins() { + return postParseSuitePlugins; + } + + public void setPostParseTestPlugins(List plugins) { + postParseTestPlugins = plugins; + } + + public List getPostParseTestPlugins() { + return postParseTestPlugins; + } + + public void setPostParseStrategyElementPlugins( + List plugins) { + postParseStrategyElementPlugins = plugins; + } + + public List getPostParseStrategyElementPlugins() { + return postParseStrategyElementPlugins; + } + + public void setTestRunnerPlugins(List customPlugins) { + this.testRunnerPlugins = customPlugins; + } + + public List getTestRunnerPlugins() { + return testRunnerPlugins; + } + + public void setCommandRunnerPlugins(List customPlugins) { + this.commandRunnerPlugins = customPlugins; + } + + public List getCommandRunnerPlugins() { + return commandRunnerPlugins; + } + + public void setTearDownPlugins(List tearDownPlugins) { + this.tearDownPlugins = tearDownPlugins; + } + + public List getTearDownPlugins() { + return tearDownPlugins; + } } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java index 85bea5e..517c2cf 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java @@ -24,27 +24,27 @@ */ public class CommandRunnerPluginContext { - private TestStepsDetails testStepsDetails; - private IInvocationContext context; - - public CommandRunnerPluginContext(TestStepsDetails ts, IInvocationContext ctx){ - this.context=ctx; - this.testStepsDetails=ts; - } - - /*** - * @return IInovocationContext - holds a map of values over the life of a Test Script - */ - public IInvocationContext getIInvocationContext() { - return context; - } - - /*** - * @return TestStepsDetails - contains some metadata concerning the command - */ - public TestStepsDetails getTestStepsDetails() { - return testStepsDetails; - } - - + private TestStepsDetails testStepsDetails; + private IInvocationContext context; + + public CommandRunnerPluginContext(TestStepsDetails ts, IInvocationContext ctx) { + this.context = ctx; + this.testStepsDetails = ts; + } + + /*** + * @return IInovocationContext - holds a map of values over the life of a Test Script + */ + public IInvocationContext getIInvocationContext() { + return context; + } + + /*** + * @return TestStepsDetails - contains some metadata concerning the command + */ + public TestStepsDetails getTestStepsDetails() { + return testStepsDetails; + } + + } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java index d01ef91..b808721 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java @@ -22,16 +22,19 @@ */ public interface ICommandRunnerPlugin { - /** - * Called before every command is run - * @param ctx - * @throws RunnerPluginException - */ - void handleCommandBefore(CommandRunnerPluginContext ctx) throws RunnerPluginException; - /** - * Called after every command is finished running - * @param ctx - * @throws RunnerPluginException - */ - void handleCommandAfter(CommandRunnerPluginContext ctx) throws RunnerPluginException; + /** + * Called before every command is run + * + * @param ctx + * @throws RunnerPluginException + */ + void handleCommandBefore(CommandRunnerPluginContext ctx) throws RunnerPluginException; + + /** + * Called after every command is finished running + * + * @param ctx + * @throws RunnerPluginException + */ + void handleCommandAfter(CommandRunnerPluginContext ctx) throws RunnerPluginException; } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java index db2ae9b..d0784a7 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java @@ -18,14 +18,13 @@ /** * This is the interface for tearDown plugins - * */ -public interface ITearDownPlugin -{ - /** - * This method is called when a script fails and the tearDown is entered - * @param tearDownPluginContext - * @throws RunnerPluginException - */ - void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException; +public interface ITearDownPlugin { + /** + * This method is called when a script fails and the tearDown is entered + * + * @param tearDownPluginContext + * @throws RunnerPluginException + */ + void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException; } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java index 95d9767..50cf81c 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java @@ -21,19 +21,21 @@ * This is the interface to be used for Test Execution plugins */ public interface ITestRunnerPlugin { - - /** - * Called before every test starts - * @param ctx - * @throws RunnerPluginException - */ - void handleTestStart(TestRunnerPluginContext ctx) throws RunnerPluginException; - - /** - * Called after every test finishes - * @param ctx - * @throws RunnerPluginException - */ - void handleTestFinish(TestRunnerPluginContext ctx) throws RunnerPluginException; - + + /** + * Called before every test starts + * + * @param ctx + * @throws RunnerPluginException + */ + void handleTestStart(TestRunnerPluginContext ctx) throws RunnerPluginException; + + /** + * Called after every test finishes + * + * @param ctx + * @throws RunnerPluginException + */ + void handleTestFinish(TestRunnerPluginContext ctx) throws RunnerPluginException; + } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java b/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java index d731a6d..8815d71 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java @@ -19,16 +19,16 @@ /** * Thrown by Runner Execution Plugins to indicate a general Exception */ -public class RunnerPluginException extends Exception{ +public class RunnerPluginException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + public RunnerPluginException(String message) { + super(message); + } + + public RunnerPluginException(String message, Throwable th) { + super(message, th); + } - public RunnerPluginException(String message){ - super(message); - } - - public RunnerPluginException(String message, Throwable th) { - super(message, th); - } - } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java index f2c0bd3..9cf99cf 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java @@ -21,33 +21,27 @@ /** * This is the context visible to tearDown plugins - * */ -public class TearDownPluginContext -{ - private TestScript testScript; - private Throwable failureReason; - private IInvocationContext invocationContext; - - public TearDownPluginContext(TestScript testScript, Throwable failureReason, IInvocationContext invocationContext) - { - this.testScript = testScript; - this.failureReason = failureReason; - this.invocationContext = invocationContext; - } - - public TestScript getTestScript() - { - return testScript; - } - - public Throwable getFailureReason() - { - return failureReason; - } - - public IInvocationContext getInvocationContext() - { - return invocationContext; - } +public class TearDownPluginContext { + private TestScript testScript; + private Throwable failureReason; + private IInvocationContext invocationContext; + + public TearDownPluginContext(TestScript testScript, Throwable failureReason, IInvocationContext invocationContext) { + this.testScript = testScript; + this.failureReason = failureReason; + this.invocationContext = invocationContext; + } + + public TestScript getTestScript() { + return testScript; + } + + public Throwable getFailureReason() { + return failureReason; + } + + public IInvocationContext getInvocationContext() { + return invocationContext; + } } diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java index 3a6de61..44d013b 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java @@ -24,35 +24,35 @@ * This is the context visible to Test Runner Plugins */ public class TestRunnerPluginContext { - private TestScript testScript; - private TestResult testResult; - private IInvocationContext invocationContext; - - public TestRunnerPluginContext(TestScript ts, TestResult tr, IInvocationContext ctx){ - this.testScript = ts; - this.testResult = tr; - this.invocationContext = ctx; - } - - /*** - * @return TestScript - */ - public TestScript getTestScript() { - return testScript; - } - - /*** - * @return TestResult of the Test Script - */ - public TestResult getTestResult() { - return testResult; - } - - /*** - * @return IInovocationContext - holds a map of values over the life of the Test Script - */ - public IInvocationContext getIInvocationContext() { - return invocationContext; - } + private TestScript testScript; + private TestResult testResult; + private IInvocationContext invocationContext; + + public TestRunnerPluginContext(TestScript ts, TestResult tr, IInvocationContext ctx) { + this.testScript = ts; + this.testResult = tr; + this.invocationContext = ctx; + } + + /*** + * @return TestScript + */ + public TestScript getTestScript() { + return testScript; + } + + /*** + * @return TestResult of the Test Script + */ + public TestResult getTestResult() { + return testResult; + } + + /*** + * @return IInovocationContext - holds a map of values over the life of the Test Script + */ + public IInvocationContext getIInvocationContext() { + return invocationContext; + } } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java index ab5cd1e..8c39b44 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java @@ -22,11 +22,11 @@ */ public interface IPostParseAllPlugin { - /*** - * This method executes after all tests are parsed - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException; + /*** + * This method executes after all tests are parsed + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException; } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java index 486b61f..327b6c3 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java @@ -22,13 +22,12 @@ * parsed */ -public interface IPostParseStrategyElementPlugin -{ - /*** - * This method executes after all the test strategy is parsed - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException; +public interface IPostParseStrategyElementPlugin { + /*** + * This method executes after all the test strategy is parsed + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException; } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java index cfe38a8..a4ff050 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java @@ -22,17 +22,17 @@ */ public interface IPostParseSuitePlugin { - /*** - * This method executes after each suite is parsed which has the tag name returned by getTagName() - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException; - - /*** - * This will return the tag name the ScriptParser will be looking for in the suite. If not found, - * the execute method will not be run. - */ - public String getTagName(); + /*** + * This method executes after each suite is parsed which has the tag name returned by getTagName() + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException; + + /*** + * This will return the tag name the ScriptParser will be looking for in the suite. If not found, + * the execute method will not be run. + */ + public String getTagName(); } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java index 00328ce..19aebf2 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java @@ -22,17 +22,17 @@ */ public interface IPostParseTestPlugin { - /*** - * This method executes after each test is parsed which has the tag name returned by getTagName() - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException; - - /*** - * This will return the tag name the ScriptParser will be looking for in the test body. If not found, - * the execute method will not be run. - */ - public String getTagName(); + /*** + * This method executes after each test is parsed which has the tag name returned by getTagName() + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException; + + /*** + * This will return the tag name the ScriptParser will be looking for in the test body. If not found, + * the execute method will not be run. + */ + public String getTagName(); } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java index 8ff5f26..b491e97 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java @@ -19,30 +19,25 @@ /*** * This exception is thrown by the parser plugins - * */ public class ParserPluginException extends Exception { - - // automatically generated - private static final long serialVersionUID = -195286095131824362L; - public ParserPluginException() - { - super(); - } - - public ParserPluginException(String message) - { - super(message); - } - - public ParserPluginException(Throwable throwable) - { - super(throwable); - } - - public ParserPluginException(String message, Throwable throwable) - { - super(message, throwable); - } + // automatically generated + private static final long serialVersionUID = -195286095131824362L; + + public ParserPluginException() { + super(); + } + + public ParserPluginException(String message) { + super(message); + } + + public ParserPluginException(Throwable throwable) { + super(throwable); + } + + public ParserPluginException(String message, Throwable throwable) { + super(message, throwable); + } } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java index 8215ea7..cb030b4 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java @@ -23,34 +23,33 @@ /*** * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - * */ public class PostAllParserPluginContext { - private TestAgenda testAgenda; - private CommandRegistry commandRegistry; - - public PostAllParserPluginContext(TestAgenda testAgenda, CommandRegistry commandRegistry) { - this.testAgenda = testAgenda; - this.commandRegistry = commandRegistry; - } - - /*** - * Returns the Test Agenda associated with the test run, so plugins can read and modify the data - * - * @return testAgenda - */ - public TestAgenda getTestAgenda() { - return testAgenda; - } - - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - + private TestAgenda testAgenda; + private CommandRegistry commandRegistry; + + public PostAllParserPluginContext(TestAgenda testAgenda, CommandRegistry commandRegistry) { + this.testAgenda = testAgenda; + this.commandRegistry = commandRegistry; + } + + /*** + * Returns the Test Agenda associated with the test run, so plugins can read and modify the data + * + * @return testAgenda + */ + public TestAgenda getTestAgenda() { + return testAgenda; + } + + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java index 45c73e6..44fef85 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java @@ -21,36 +21,32 @@ /*** * Exposes the data that can be used and/or modified by a IPostParseStrategyElementPlugin. - * */ -public class PostStrategyElementParserPluginContext -{ - private TestAgenda testAgenda; - private Element element; - - public PostStrategyElementParserPluginContext(TestAgenda testAgenda, Element element) - { - this.testAgenda = testAgenda; - this.element = element; - } - - /*** - * Returns the Test Agenda associated with the test run, so plugins can read and modify the data - * - * @return testAgenda - */ - public TestAgenda getTestAgenda() { - return testAgenda; - } - - /*** - * Returns the parsed Element object so that the relevant xml data can be used - * in the plugin - * - * @return element - */ - public Element getElement() - { - return element; - } +public class PostStrategyElementParserPluginContext { + private TestAgenda testAgenda; + private Element element; + + public PostStrategyElementParserPluginContext(TestAgenda testAgenda, Element element) { + this.testAgenda = testAgenda; + this.element = element; + } + + /*** + * Returns the Test Agenda associated with the test run, so plugins can read and modify the data + * + * @return testAgenda + */ + public TestAgenda getTestAgenda() { + return testAgenda; + } + + /*** + * Returns the parsed Element object so that the relevant xml data can be used + * in the plugin + * + * @return element + */ + public Element getElement() { + return element; + } } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java index 0cb61a4..97a2737 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java @@ -24,48 +24,47 @@ /*** * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - * */ public class PostSuiteParserPluginContext { - private CommandRegistry commandRegistry; - private TestSuite testSuite; - private Node suiteRoot; - - public PostSuiteParserPluginContext(CommandRegistry commandRegistry, - TestSuite testSuite, Node suiteRoot) { - this.commandRegistry = commandRegistry; - this.testSuite = testSuite; - this.suiteRoot = suiteRoot; - } - - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - - /*** - * Returns the Test Suite the test is a part of, so plugins can add test scripts to the suite - * if needed - * - * @return testSuite - */ - public TestSuite getTestSuite() { - return testSuite; - } - - /*** - * Returns the root Node object of the current suite so that the relevant xml data can be used - * in the plugin - * - * @return elementRoot - */ - public Node getRootNodeSuite() { - return suiteRoot; - } - + private CommandRegistry commandRegistry; + private TestSuite testSuite; + private Node suiteRoot; + + public PostSuiteParserPluginContext(CommandRegistry commandRegistry, + TestSuite testSuite, Node suiteRoot) { + this.commandRegistry = commandRegistry; + this.testSuite = testSuite; + this.suiteRoot = suiteRoot; + } + + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + + /*** + * Returns the Test Suite the test is a part of, so plugins can add test scripts to the suite + * if needed + * + * @return testSuite + */ + public TestSuite getTestSuite() { + return testSuite; + } + + /*** + * Returns the root Node object of the current suite so that the relevant xml data can be used + * in the plugin + * + * @return elementRoot + */ + public Node getRootNodeSuite() { + return suiteRoot; + } + } diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java index 88daf7b..6cf35db 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java @@ -23,47 +23,46 @@ /*** * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - * */ public class PostTestParserPluginContext { - private CommandRegistry commandRegistry; - private TestSuite testSuite; - private Node testRoot; + private CommandRegistry commandRegistry; + private TestSuite testSuite; + private Node testRoot; - public PostTestParserPluginContext(CommandRegistry commandRegistry, - TestSuite testSuite, Node testRoot) { - this.commandRegistry = commandRegistry; - this.testSuite = testSuite; - this.testRoot = testRoot; - } + public PostTestParserPluginContext(CommandRegistry commandRegistry, + TestSuite testSuite, Node testRoot) { + this.commandRegistry = commandRegistry; + this.testSuite = testSuite; + this.testRoot = testRoot; + } - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } - /*** - * Returns the Test Suite the test is a part of, so plugins can add test - * scripts to the suite if needed - * - * @return testSuite - */ - public TestSuite getTestSuite() { - return testSuite; - } + /*** + * Returns the Test Suite the test is a part of, so plugins can add test + * scripts to the suite if needed + * + * @return testSuite + */ + public TestSuite getTestSuite() { + return testSuite; + } - /*** - * Returns the root Node object of the current test so that the relevant xml - * data can be used in the plugin - * - * @return elementRoot - */ - public Node getRootNodeTest() { - return testRoot; - } + /*** + * Returns the root Node object of the current test so that the relevant xml + * data can be used in the plugin + * + * @return elementRoot + */ + public Node getRootNodeTest() { + return testRoot; + } } diff --git a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrix.java b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrix.java index 203f4d0..bb04337 100644 --- a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrix.java +++ b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrix.java @@ -27,50 +27,50 @@ * Responsible for generating the tracability matrix csv file with test suite name, coverage, test case ID, test name, file name and automation value. */ public class TraceabilityMatrix { - - public static final String OUTPUT_FILE = "Traceability_Matrix.txt"; - - public static void produceTraceabilityMatrix(TestAgenda ta) { - FileWriter fw = null; - try { - fw = new FileWriter(OUTPUT_FILE); - fw.write("Test Scenario;Coverage;Test Case ID;Test Name;Automation Script;Automation Value" + "\n"); - - for(TestScript s : ta.getTestScripts()) { - if(!ta.isAutomationValuesEmpty()) { - if(ta.containsAutomationValue(s.getAutomationValue())) { - String test = s.getTestSuiteName() - + ";" + s.getCoverage() - + ";" + s.getTestCaseID() - + ";" + s.getName() - + ";" + s.getFileName() - + ";" + s.getAutomationValue(); - fw.write(test + "\n"); - } - }else { - String test = s.getTestSuiteName() - + ";" + s.getCoverage() - + ";" + s.getTestCaseID() - + ";" + s.getName() - + ";" + s.getFileName() - + ";" + s.getAutomationValue(); - fw.write(test + "\n"); - } - } - } catch (IOException ie) { - // Ignore since we want to still execute the tests regardless of traceability matrix - System.err.println("Problem while trying to create traceability matrix: " + ie.toString()); - ie.printStackTrace(); - } finally { - if(fw != null) { - try { - fw.close(); - } catch (IOException ie) { - // Ignore since we want to still execute the tests regardless of traceability matrix - System.err.println("Problem while trying to create traceability matrix: " + ie.toString()); - ie.printStackTrace(); - } - } - } - } + + public static final String OUTPUT_FILE = "Traceability_Matrix.txt"; + + public static void produceTraceabilityMatrix(TestAgenda ta) { + FileWriter fw = null; + try { + fw = new FileWriter(OUTPUT_FILE); + fw.write("Test Scenario;Coverage;Test Case ID;Test Name;Automation Script;Automation Value" + "\n"); + + for (TestScript s : ta.getTestScripts()) { + if (!ta.isAutomationValuesEmpty()) { + if (ta.containsAutomationValue(s.getAutomationValue())) { + String test = s.getTestSuiteName() + + ";" + s.getCoverage() + + ";" + s.getTestCaseID() + + ";" + s.getName() + + ";" + s.getFileName() + + ";" + s.getAutomationValue(); + fw.write(test + "\n"); + } + } else { + String test = s.getTestSuiteName() + + ";" + s.getCoverage() + + ";" + s.getTestCaseID() + + ";" + s.getName() + + ";" + s.getFileName() + + ";" + s.getAutomationValue(); + fw.write(test + "\n"); + } + } + } catch (IOException ie) { + // Ignore since we want to still execute the tests regardless of traceability matrix + System.err.println("Problem while trying to create traceability matrix: " + ie.toString()); + ie.printStackTrace(); + } finally { + if (fw != null) { + try { + fw.close(); + } catch (IOException ie) { + // Ignore since we want to still execute the tests regardless of traceability matrix + System.err.println("Problem while trying to create traceability matrix: " + ie.toString()); + ie.printStackTrace(); + } + } + } + } } diff --git a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java index 534e9bc..8710caf 100644 --- a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java +++ b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java @@ -21,18 +21,18 @@ import org.finra.jtaf.core.plugins.parsing.ParserPluginException; import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; -/** Plugin to produce a traceability matrix - * +/** + * Plugin to produce a traceability matrix */ -public class TraceabilityMatrixPlugin implements IPostParseAllPlugin -{ - /** Produces a traceability matrix after all parsing has completed - * @param ctx PostAllParserPluginContext - */ - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException - { - TestAgenda testAgenda = ctx.getTestAgenda(); - TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); - } +public class TraceabilityMatrixPlugin implements IPostParseAllPlugin { + /** + * Produces a traceability matrix after all parsing has completed + * + * @param ctx PostAllParserPluginContext + */ + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestAgenda testAgenda = ctx.getTestAgenda(); + TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + } } diff --git a/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java b/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java index 4a78b86..6951806 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java +++ b/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java @@ -30,65 +30,65 @@ * Utility class to encode or decode string using base64. */ public class Base64EncoderDecoder { - private static String fileLocation = "C:\\TEMP\\base64\\test.properties"; - - /* - * main method is used to decode a property file only. It can take one incoming parameter - the location of - * the file to be encoded. If there is no incoming parameter (or more than one provided), then the default 'propertyFileLocation' value used. - */ - public static void main(String[] args) throws Exception{ - if(args.length == 1){ - setPropertyFileLocation(args[0]); - } - - String fileName = fileLocation.split("\\\\")[fileLocation.split("\\\\").length -1]; - String encodedFileName = fileName.split("\\.")[0] + "_Encoded." + fileName.split("\\.")[1]; - String encodedFileLocation = fileLocation.replace(fileName, encodedFileName); - - BufferedReader in = new BufferedReader(new FileReader(fileLocation)); - BufferedWriter out = new BufferedWriter(new FileWriter(encodedFileLocation)); - - String line; - String key; - String value; - - while((line = in.readLine()) != null){ - if(!line.startsWith("#")){ - if(line.contains("=")){ - key = line.substring(0, line.indexOf("=")); - value = line.substring(line.indexOf("=") + 1); - if(key.endsWith(".password")){ - value = encodeString(value); - line = key + "=" + value; - } - } - } - - System.out.println(line); - out.write(line + System.getProperty("line.separator")); - } - - in.close(); - out.close(); - } - - - public static String encodeString(String stringToEncode){ - byte[] encodedBytes = Base64.encodeBase64(stringToEncode.getBytes()); - return new String(encodedBytes); - } - - public static String decodeString(String stringToDecode){ - byte[] decodedBytes = Base64.decodeBase64(stringToDecode.getBytes()); - return new String(decodedBytes); - } - - public static String getPropertyFileLocation() { - return fileLocation; - } - - public static void setPropertyFileLocation(String newPropertyFileLocation) { - fileLocation = newPropertyFileLocation; - } - + private static String fileLocation = "C:\\TEMP\\base64\\test.properties"; + + /* + * main method is used to decode a property file only. It can take one incoming parameter - the location of + * the file to be encoded. If there is no incoming parameter (or more than one provided), then the default 'propertyFileLocation' value used. + */ + public static void main(String[] args) throws Exception { + if (args.length == 1) { + setPropertyFileLocation(args[0]); + } + + String fileName = fileLocation.split("\\\\")[fileLocation.split("\\\\").length - 1]; + String encodedFileName = fileName.split("\\.")[0] + "_Encoded." + fileName.split("\\.")[1]; + String encodedFileLocation = fileLocation.replace(fileName, encodedFileName); + + BufferedReader in = new BufferedReader(new FileReader(fileLocation)); + BufferedWriter out = new BufferedWriter(new FileWriter(encodedFileLocation)); + + String line; + String key; + String value; + + while ((line = in.readLine()) != null) { + if (!line.startsWith("#")) { + if (line.contains("=")) { + key = line.substring(0, line.indexOf("=")); + value = line.substring(line.indexOf("=") + 1); + if (key.endsWith(".password")) { + value = encodeString(value); + line = key + "=" + value; + } + } + } + + System.out.println(line); + out.write(line + System.getProperty("line.separator")); + } + + in.close(); + out.close(); + } + + + public static String encodeString(String stringToEncode) { + byte[] encodedBytes = Base64.encodeBase64(stringToEncode.getBytes()); + return new String(encodedBytes); + } + + public static String decodeString(String stringToDecode) { + byte[] decodedBytes = Base64.decodeBase64(stringToDecode.getBytes()); + return new String(decodedBytes); + } + + public static String getPropertyFileLocation() { + return fileLocation; + } + + public static void setPropertyFileLocation(String newPropertyFileLocation) { + fileLocation = newPropertyFileLocation; + } + } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java b/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java index f0e2b30..3715235 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java +++ b/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java @@ -29,200 +29,199 @@ /** * Utility class to perform comparison of lists and maps - * */ public class CompositeDataComparator { - private List errorList; - private boolean accumulateErrors; - - public CompositeDataComparator() { - accumulateErrors = false; - } - - public CompositeDataComparator(boolean accumulateErrors) { - this.accumulateErrors = accumulateErrors; - errorList = new ArrayList(); - } - - public void compareMap(String title, String element, Map expComp, - Map actualComp) { - String prefix = getPrefix(title, element); - Set keySet = expComp.keySet(); - - for (Iterator iter = keySet.iterator(); iter.hasNext();) { - String obj = (String) iter.next(); - - Object eValue = expComp.get(obj); - - if (!actualComp.containsKey(obj)) { - reportError(prefix + " Couldn't find Element [" + obj - + "] in Actual Data"); - - } - Object aValue = actualComp.get(obj); - - assessAndCompare(prefix, obj, eValue, aValue); - } - } - - public void compareList(String title, String element, List expList, - List actualList) { - String prefix = getPrefix(title, element); - - if (compareSize(prefix, expList, actualList)) { - - for (int i = 0; i < expList.size(); i++) { - Object expected = expList.get(i); - Object actual = actualList.get(i); - - assessAndCompare(prefix + "[position : " + (i + 1) + "]", null, - expected, actual); - } - } - } - - /* - * for comparing untyped objects that may be instances of Boolean, String, String[], Timestamp, List, or Map - * lists and maps are internally tested for the same types recursively - * - * any other types on the basic or internal levels are compared as type Object - * - * if basic or internal Objects are both null they are considered equal - */ - public void compareObject(String title, String element, Object expected, Object actual) { - assessAndCompare(title, element, expected, actual); - } - - public List getErrorList() { - return errorList; - } - - /** - * Sets the accumulate errors flag - * - * @param accumulateErrors determines if the comparator will throw - * an exception with errors found, or accumulate them for later reporting - */ - public void setAccumulateErrors(boolean accumulateErrors) { - this.accumulateErrors = accumulateErrors; - if(accumulateErrors && errorList == null) { - errorList = new ArrayList(); - } - } - - /** - * Gets the accumulate errors flag - * - * @return the accumulate errors flag - */ - public boolean getAccumulateErrors() { - return this.accumulateErrors; - } - - private void reportError(String error) { - if (!accumulateErrors) - throw new AssertionFailedError(error); - else - errorList.add(error); - - } - - private String getPrefix(String title, String element) { - return (element == null && !"".equals(element)) ? title : title + "-> " - + element + " : "; - } - - private void assessAndCompare(String title, String element, - Object expected, Object actual) { - String prefix = getPrefix(title, element); - - if (expected == null && actual == null) { - return; - } else if (expected == null || actual == null) { - if ("".equals(expected) || "".equals(actual)) - return; - reportError(prefix + " didn't match. Expected Value[" + expected - + "] and Actual Value [" + actual + "]."); - } else if (expected instanceof Map) { - compareMap(title, element, (Map) expected, (Map) actual); - } else if (expected instanceof List) { - compareList(title, element, (List) expected, (List) actual); - } else if (expected instanceof Timestamp) { - Timestamp expTimestamp = (Timestamp) expected; - if (!(actual instanceof Timestamp)) - reportError(prefix + " Expected value [" + expTimestamp - + "] and Actual Value [" + actual + "]."); - - else - compareObject(prefix, expTimestamp, (Timestamp) actual); - } else if (expected instanceof String[]) { - String e[] = (String[]) expected; - String a[] = (String[]) actual; - - if (e.length != a.length) - reportError(prefix - + " Length of string array didn't match. Expected [" - + e.length + "] and Actual [" + a.length + "]."); - - for (int i = 0; i < e.length; i++) { - try { - Double expD = Double.valueOf((String) e[i]); - Double actD = Double.valueOf((String) a[i]); - - compareObject(prefix, expD, actD); - } catch (NumberFormatException ignore) { - compareObject(prefix, e[i], a[i]); - } - } - } else if (expected instanceof String) { - - try { - Double expD = Double.valueOf((String) expected); - Double actD = Double.valueOf((String) actual); - - compareObject(prefix, expD, actD); - } catch (NumberFormatException ignore) { - compareObject(prefix, expected, actual); - } - } else if (expected instanceof Boolean && actual instanceof String) { - - try { - - String actualString = Boolean.FALSE.toString(); - if ("y".equalsIgnoreCase((String) actual) - || "true".equalsIgnoreCase((String) actual)) { - actualString = Boolean.TRUE.toString(); - } - - compareObject(prefix, expected.toString(), actualString); - } catch (NumberFormatException ignore) { - compareObject(prefix, expected, actual); - } - } else if (expected instanceof Integer && actual instanceof BigDecimal) { - BigDecimal expectedBigDecimal = new BigDecimal((Integer) expected); - compareObject(prefix, expectedBigDecimal, actual); - - } else { - compareObject(prefix, expected, actual); - } - } - - private void compareObject(String prefix, Object expected, Object actual) { - if (!expected.equals(actual)) { - reportError(prefix + " didn't match. Expected Value[" + expected - + "] and Actual Value [" + actual + "]."); - } - } - - private boolean compareSize(String comp, List expSessions, List actualSessions) { - boolean equal = true; - if (expSessions.size() != actualSessions.size()) { - reportError(comp + "didn't match; Expected List size: " - + expSessions.size() + " -- Actual List size: " - + actualSessions.size()); - equal = false; - } - return equal; - } + private List errorList; + private boolean accumulateErrors; + + public CompositeDataComparator() { + accumulateErrors = false; + } + + public CompositeDataComparator(boolean accumulateErrors) { + this.accumulateErrors = accumulateErrors; + errorList = new ArrayList(); + } + + public void compareMap(String title, String element, Map expComp, + Map actualComp) { + String prefix = getPrefix(title, element); + Set keySet = expComp.keySet(); + + for (Iterator iter = keySet.iterator(); iter.hasNext(); ) { + String obj = (String) iter.next(); + + Object eValue = expComp.get(obj); + + if (!actualComp.containsKey(obj)) { + reportError(prefix + " Couldn't find Element [" + obj + + "] in Actual Data"); + + } + Object aValue = actualComp.get(obj); + + assessAndCompare(prefix, obj, eValue, aValue); + } + } + + public void compareList(String title, String element, List expList, + List actualList) { + String prefix = getPrefix(title, element); + + if (compareSize(prefix, expList, actualList)) { + + for (int i = 0; i < expList.size(); i++) { + Object expected = expList.get(i); + Object actual = actualList.get(i); + + assessAndCompare(prefix + "[position : " + (i + 1) + "]", null, + expected, actual); + } + } + } + + /* + * for comparing untyped objects that may be instances of Boolean, String, String[], Timestamp, List, or Map + * lists and maps are internally tested for the same types recursively + * + * any other types on the basic or internal levels are compared as type Object + * + * if basic or internal Objects are both null they are considered equal + */ + public void compareObject(String title, String element, Object expected, Object actual) { + assessAndCompare(title, element, expected, actual); + } + + public List getErrorList() { + return errorList; + } + + /** + * Sets the accumulate errors flag + * + * @param accumulateErrors determines if the comparator will throw + * an exception with errors found, or accumulate them for later reporting + */ + public void setAccumulateErrors(boolean accumulateErrors) { + this.accumulateErrors = accumulateErrors; + if (accumulateErrors && errorList == null) { + errorList = new ArrayList(); + } + } + + /** + * Gets the accumulate errors flag + * + * @return the accumulate errors flag + */ + public boolean getAccumulateErrors() { + return this.accumulateErrors; + } + + private void reportError(String error) { + if (!accumulateErrors) + throw new AssertionFailedError(error); + else + errorList.add(error); + + } + + private String getPrefix(String title, String element) { + return (element == null && !"".equals(element)) ? title : title + "-> " + + element + " : "; + } + + private void assessAndCompare(String title, String element, + Object expected, Object actual) { + String prefix = getPrefix(title, element); + + if (expected == null && actual == null) { + return; + } else if (expected == null || actual == null) { + if ("".equals(expected) || "".equals(actual)) + return; + reportError(prefix + " didn't match. Expected Value[" + expected + + "] and Actual Value [" + actual + "]."); + } else if (expected instanceof Map) { + compareMap(title, element, (Map) expected, (Map) actual); + } else if (expected instanceof List) { + compareList(title, element, (List) expected, (List) actual); + } else if (expected instanceof Timestamp) { + Timestamp expTimestamp = (Timestamp) expected; + if (!(actual instanceof Timestamp)) + reportError(prefix + " Expected value [" + expTimestamp + + "] and Actual Value [" + actual + "]."); + + else + compareObject(prefix, expTimestamp, (Timestamp) actual); + } else if (expected instanceof String[]) { + String e[] = (String[]) expected; + String a[] = (String[]) actual; + + if (e.length != a.length) + reportError(prefix + + " Length of string array didn't match. Expected [" + + e.length + "] and Actual [" + a.length + "]."); + + for (int i = 0; i < e.length; i++) { + try { + Double expD = Double.valueOf((String) e[i]); + Double actD = Double.valueOf((String) a[i]); + + compareObject(prefix, expD, actD); + } catch (NumberFormatException ignore) { + compareObject(prefix, e[i], a[i]); + } + } + } else if (expected instanceof String) { + + try { + Double expD = Double.valueOf((String) expected); + Double actD = Double.valueOf((String) actual); + + compareObject(prefix, expD, actD); + } catch (NumberFormatException ignore) { + compareObject(prefix, expected, actual); + } + } else if (expected instanceof Boolean && actual instanceof String) { + + try { + + String actualString = Boolean.FALSE.toString(); + if ("y".equalsIgnoreCase((String) actual) + || "true".equalsIgnoreCase((String) actual)) { + actualString = Boolean.TRUE.toString(); + } + + compareObject(prefix, expected.toString(), actualString); + } catch (NumberFormatException ignore) { + compareObject(prefix, expected, actual); + } + } else if (expected instanceof Integer && actual instanceof BigDecimal) { + BigDecimal expectedBigDecimal = new BigDecimal((Integer) expected); + compareObject(prefix, expectedBigDecimal, actual); + + } else { + compareObject(prefix, expected, actual); + } + } + + private void compareObject(String prefix, Object expected, Object actual) { + if (!expected.equals(actual)) { + reportError(prefix + " didn't match. Expected Value[" + expected + + "] and Actual Value [" + actual + "]."); + } + } + + private boolean compareSize(String comp, List expSessions, List actualSessions) { + boolean equal = true; + if (expSessions.size() != actualSessions.size()) { + reportError(comp + "didn't match; Expected List size: " + + expSessions.size() + " -- Actual List size: " + + actualSessions.size()); + equal = false; + } + return equal; + } } diff --git a/src/main/java/org/finra/jtaf/core/utilities/ExcelFileParser.java b/src/main/java/org/finra/jtaf/core/utilities/ExcelFileParser.java index ec8d478..cb29ec6 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/ExcelFileParser.java +++ b/src/main/java/org/finra/jtaf/core/utilities/ExcelFileParser.java @@ -34,106 +34,106 @@ * Parser for testdata excel files. */ public class ExcelFileParser { - private static Logger logger = Logger.getLogger(ExcelFileParser.class.getPackage().getName()); - - // For xlsx type - private XSSFWorkbook workBookXlsx; - private XSSFSheet workBookSheetXlsx; - - // For xls type - private HSSFWorkbook workBookXls; - private HSSFSheet workBookSheetXls; + private static Logger logger = Logger.getLogger(ExcelFileParser.class.getPackage().getName()); - public ExcelFileParser(String fileName, boolean isXlsx) throws Exception { - if(isXlsx) { - workBookXlsx = new XSSFWorkbook(new FileInputStream(fileName)); - workBookSheetXlsx = workBookXlsx.getSheetAt(0); - }else { - workBookXls = new HSSFWorkbook(new FileInputStream(fileName)); - workBookSheetXls = workBookXls.getSheetAt(0); - } - } - - public ExcelFileParser(String fileName, String sheetName, boolean isXlsx) throws Exception { - if(isXlsx) { - workBookXlsx = new XSSFWorkbook(new FileInputStream(fileName)); - workBookSheetXlsx = workBookXlsx.getSheet(sheetName); - }else { - workBookXls = new HSSFWorkbook(new FileInputStream(fileName)); - workBookSheetXls = workBookXls.getSheet(sheetName); - } - } + // For xlsx type + private XSSFWorkbook workBookXlsx; + private XSSFSheet workBookSheetXlsx; - public List> parseExcelFile(boolean isXlsx) throws Exception { - List> parsedExcelFile = new ArrayList>(); - if(isXlsx) { - for (int i = 0, numberOfRows = workBookSheetXlsx.getPhysicalNumberOfRows(); i < numberOfRows + 1; i++) { - XSSFRow row = workBookSheetXlsx.getRow(i); - if (row != null) { - List parsedExcelRow = new ArrayList(); - for (int j = 0, numberOfColumns = row.getLastCellNum(); j < numberOfColumns; j++) { - XSSFCell cell = row.getCell(j); - if (cell != null) { - try { - if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { - parsedExcelRow.add(cell.getStringCellValue()); - } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BLANK) { - parsedExcelRow.add(""); - } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) { - parsedExcelRow.add(String.valueOf(cell.getBooleanCellValue())); - } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { - parsedExcelRow.add(String.valueOf(cell.getNumericCellValue())); - } else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) { - parsedExcelRow.add(""); - } else { - parsedExcelRow.add(cell.getStringCellValue()); - } - } catch (Exception e) { - logger.fatal("Oops! Can't read cell (row = " + i + ", column = " + j + ") in the excel file! Change cell format to 'Text', please!"); - return null; - } - } else { - parsedExcelRow.add(""); - } - } - parsedExcelFile.add(parsedExcelRow); - } - } - }else { - for (int i = 0, numberOfRows = workBookSheetXls.getPhysicalNumberOfRows(); i < numberOfRows + 1; i++) { - HSSFRow row = workBookSheetXls.getRow(i); - if (row != null) { - List parsedExcelRow = new ArrayList(); - for (int j = 0, numberOfColumns = row.getLastCellNum(); j < numberOfColumns; j++) { - HSSFCell cell = row.getCell(j); - if (cell != null) { - try { - if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { - parsedExcelRow.add(cell.getStringCellValue()); - } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { - parsedExcelRow.add(""); - } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { - parsedExcelRow.add(String.valueOf(cell.getBooleanCellValue())); - } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { - parsedExcelRow.add(String.valueOf(cell.getNumericCellValue())); - } else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { - parsedExcelRow.add(String.valueOf("")); - } else { - parsedExcelRow.add(cell.getStringCellValue()); - } - } catch (Exception e) { - logger.fatal("Oops! Can't read cell (row = " + i + ", column = " + j + ") in the excel file! Change cell format to 'Text', please!"); - return null; - } - } else { - parsedExcelRow.add(""); - } - } - parsedExcelFile.add(parsedExcelRow); - } - } - } - - return parsedExcelFile; - } + // For xls type + private HSSFWorkbook workBookXls; + private HSSFSheet workBookSheetXls; + + public ExcelFileParser(String fileName, boolean isXlsx) throws Exception { + if (isXlsx) { + workBookXlsx = new XSSFWorkbook(new FileInputStream(fileName)); + workBookSheetXlsx = workBookXlsx.getSheetAt(0); + } else { + workBookXls = new HSSFWorkbook(new FileInputStream(fileName)); + workBookSheetXls = workBookXls.getSheetAt(0); + } + } + + public ExcelFileParser(String fileName, String sheetName, boolean isXlsx) throws Exception { + if (isXlsx) { + workBookXlsx = new XSSFWorkbook(new FileInputStream(fileName)); + workBookSheetXlsx = workBookXlsx.getSheet(sheetName); + } else { + workBookXls = new HSSFWorkbook(new FileInputStream(fileName)); + workBookSheetXls = workBookXls.getSheet(sheetName); + } + } + + public List> parseExcelFile(boolean isXlsx) throws Exception { + List> parsedExcelFile = new ArrayList>(); + if (isXlsx) { + for (int i = 0, numberOfRows = workBookSheetXlsx.getPhysicalNumberOfRows(); i < numberOfRows + 1; i++) { + XSSFRow row = workBookSheetXlsx.getRow(i); + if (row != null) { + List parsedExcelRow = new ArrayList(); + for (int j = 0, numberOfColumns = row.getLastCellNum(); j < numberOfColumns; j++) { + XSSFCell cell = row.getCell(j); + if (cell != null) { + try { + if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { + parsedExcelRow.add(cell.getStringCellValue()); + } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BLANK) { + parsedExcelRow.add(""); + } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) { + parsedExcelRow.add(String.valueOf(cell.getBooleanCellValue())); + } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { + parsedExcelRow.add(String.valueOf(cell.getNumericCellValue())); + } else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) { + parsedExcelRow.add(""); + } else { + parsedExcelRow.add(cell.getStringCellValue()); + } + } catch (Exception e) { + logger.fatal("Oops! Can't read cell (row = " + i + ", column = " + j + ") in the excel file! Change cell format to 'Text', please!"); + return null; + } + } else { + parsedExcelRow.add(""); + } + } + parsedExcelFile.add(parsedExcelRow); + } + } + } else { + for (int i = 0, numberOfRows = workBookSheetXls.getPhysicalNumberOfRows(); i < numberOfRows + 1; i++) { + HSSFRow row = workBookSheetXls.getRow(i); + if (row != null) { + List parsedExcelRow = new ArrayList(); + for (int j = 0, numberOfColumns = row.getLastCellNum(); j < numberOfColumns; j++) { + HSSFCell cell = row.getCell(j); + if (cell != null) { + try { + if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { + parsedExcelRow.add(cell.getStringCellValue()); + } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { + parsedExcelRow.add(""); + } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { + parsedExcelRow.add(String.valueOf(cell.getBooleanCellValue())); + } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { + parsedExcelRow.add(String.valueOf(cell.getNumericCellValue())); + } else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { + parsedExcelRow.add(String.valueOf("")); + } else { + parsedExcelRow.add(cell.getStringCellValue()); + } + } catch (Exception e) { + logger.fatal("Oops! Can't read cell (row = " + i + ", column = " + j + ") in the excel file! Change cell format to 'Text', please!"); + return null; + } + } else { + parsedExcelRow.add(""); + } + } + parsedExcelFile.add(parsedExcelRow); + } + } + } + + return parsedExcelFile; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java b/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java index 024699e..3adcdc3 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java +++ b/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java @@ -20,24 +20,20 @@ /** * Responsible for reading properties configured in jtaf.properties file. */ -public class JTAFPropertyManager extends PropertyManager -{ - private static JTAFPropertyManager instance; - - public static final String JTAF_PROPERTIES_FILE_NAME = "jtaf.properties"; - public static final String PROPERTY_PREFIX = "jtaf"; - - private JTAFPropertyManager() - { - super(JTAF_PROPERTIES_FILE_NAME, PROPERTY_PREFIX); - } - - public static JTAFPropertyManager getInstance() - { - if(instance == null) - { - instance = new JTAFPropertyManager(); - } - return instance; - } +public class JTAFPropertyManager extends PropertyManager { + private static JTAFPropertyManager instance; + + public static final String JTAF_PROPERTIES_FILE_NAME = "jtaf.properties"; + public static final String PROPERTY_PREFIX = "jtaf"; + + private JTAFPropertyManager() { + super(JTAF_PROPERTIES_FILE_NAME, PROPERTY_PREFIX); + } + + public static JTAFPropertyManager getInstance() { + if (instance == null) { + instance = new JTAFPropertyManager(); + } + return instance; + } } diff --git a/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java b/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java index 6f798fd..0ba9e87 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java +++ b/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java @@ -24,54 +24,54 @@ import java.util.PropertyResourceBundle; /** - * This class is similar to java Properties reader. It takes care of reading properties from the specified file. + * This class is similar to java Properties reader. It takes care of reading properties from the specified file. * The difference however is, it allows to override any property by specifying it as a System * property. */ public class PropertyManager { - protected String fileName; - protected String propertyPrefix; - protected PropertyResourceBundle propertyResourceBundle; + protected String fileName; + protected String propertyPrefix; + protected PropertyResourceBundle propertyResourceBundle; - public PropertyManager(String fileName, String propertyPrefix) { - this.fileName = fileName; - this.propertyPrefix = propertyPrefix; - propertyResourceBundle = getPropertyResourceBundle(); - if (propertyResourceBundle != null) { - loadProperties(); - } - } + public PropertyManager(String fileName, String propertyPrefix) { + this.fileName = fileName; + this.propertyPrefix = propertyPrefix; + propertyResourceBundle = getPropertyResourceBundle(); + if (propertyResourceBundle != null) { + loadProperties(); + } + } - public String getProperty(String propertyName) { - return System.getProperty(propertyPrefix + "." + propertyName); - } + public String getProperty(String propertyName) { + return System.getProperty(propertyPrefix + "." + propertyName); + } - protected PropertyResourceBundle getPropertyResourceBundle() { - try { - InputStream inputStream = PropertyManager.class.getClassLoader() - .getResourceAsStream(fileName); - if (inputStream == null) { - File propertiesFile = new File(fileName); - inputStream = new FileInputStream(propertiesFile); - } - return new PropertyResourceBundle(inputStream); - } catch (FileNotFoundException fileNotFoundException) { - return null; - } catch (Exception exception) { - throw new RuntimeException("Problem loading properties", exception); - } - } + protected PropertyResourceBundle getPropertyResourceBundle() { + try { + InputStream inputStream = PropertyManager.class.getClassLoader() + .getResourceAsStream(fileName); + if (inputStream == null) { + File propertiesFile = new File(fileName); + inputStream = new FileInputStream(propertiesFile); + } + return new PropertyResourceBundle(inputStream); + } catch (FileNotFoundException fileNotFoundException) { + return null; + } catch (Exception exception) { + throw new RuntimeException("Problem loading properties", exception); + } + } - protected void loadProperties() { - Enumeration keys = propertyResourceBundle.getKeys(); - while (keys.hasMoreElements()) { - String key = keys.nextElement(); - String newProperty = propertyResourceBundle.getString(key); - String newKey = propertyPrefix + "." + key; - if (System.getProperty(newKey) == null) { - System.setProperty(newKey, newProperty); - } - } - } + protected void loadProperties() { + Enumeration keys = propertyResourceBundle.getKeys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + String newProperty = propertyResourceBundle.getString(key); + String newKey = propertyPrefix + "." + key; + if (System.getProperty(newKey) == null) { + System.setProperty(newKey, newProperty); + } + } + } } diff --git a/src/main/java/org/finra/jtaf/core/utilities/StringHelper.java b/src/main/java/org/finra/jtaf/core/utilities/StringHelper.java index db4f462..cd779c2 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/StringHelper.java +++ b/src/main/java/org/finra/jtaf/core/utilities/StringHelper.java @@ -25,91 +25,91 @@ /** * Random String-related functions that are generally useful - * */ public class StringHelper { - static Logger logger = Logger.getLogger(StringHelper.class.getPackage().getName()); - private static final String INDENTATION = " "; - private static final List INDENTATION_CACHE = createIndentationArray(); + static Logger logger = Logger.getLogger(StringHelper.class.getPackage().getName()); + private static final String INDENTATION = " "; + private static final List INDENTATION_CACHE = createIndentationArray(); + + private static final List createIndentationArray() { + List retval = new ArrayList(); + retval.add(INDENTATION); + return retval; + } + + + /** + * This method is not thread-safe + * + * @param depth + * @return + */ + public static final String indent(int depth) { + String largestIndentation = INDENTATION_CACHE.get(INDENTATION_CACHE.size() - 1); + for (int i = INDENTATION_CACHE.size(); i <= depth; ++i) { + largestIndentation += INDENTATION; + INDENTATION_CACHE.add(largestIndentation); + } + return INDENTATION_CACHE.get(depth); + } + + public static final String join(Object[] elements, String glue) { + ArrayList temp = new ArrayList(elements.length); + for (Object s : elements) { + temp.add(s); + } + return StringHelper.join(temp, glue); + } + + public static final String join(Collection elements, String glue) { + if (elements.isEmpty()) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + Iterator itr = elements.iterator(); + sb.append(itr.next().toString()); + + while (itr.hasNext()) { + sb.append(glue); + sb.append(itr.next().toString()); + } + return sb.toString(); + } - private static final List createIndentationArray() { - List retval = new ArrayList(); - retval.add(INDENTATION); - return retval; - } + public static String getConcatenatedStringFromList(List input, String delimiter) { + StringBuffer concatenatedString = new StringBuffer(); + for (String data : input) { + concatenatedString.append(data); + concatenatedString.append(delimiter); + } + return concatenatedString.toString(); + } + public static String getZipAndConcatenated(List input1, List input2, String delimiter) { + StringBuffer concatenatedString = new StringBuffer(); - /** - * This method is not thread-safe - * @param depth - * @return - */ - public static final String indent(int depth) { - String largestIndentation = INDENTATION_CACHE.get(INDENTATION_CACHE.size() - 1); - for(int i = INDENTATION_CACHE.size(); i <= depth; ++i) { - largestIndentation += INDENTATION; - INDENTATION_CACHE.add(largestIndentation); - } - return INDENTATION_CACHE.get(depth); - } - - public static final String join(Object[] elements, String glue) { - ArrayList temp = new ArrayList(elements.length); - for(Object s : elements) { - temp.add(s); - } - return StringHelper.join(temp, glue); - } - - public static final String join(Collection elements, String glue) { - if(elements.isEmpty()) { - return ""; - } + for (int i = 0; i < input1.size(); i++) { + concatenatedString.append(input1.get(i)); + concatenatedString.append("='"); + if (i < input2.size()) { + concatenatedString.append(input2.get(i)); + } + concatenatedString.append("'"); + concatenatedString.append(delimiter); + } + return concatenatedString.toString(); + } - StringBuilder sb = new StringBuilder(); - Iterator itr = elements.iterator(); - sb.append(itr.next().toString()); - - while(itr.hasNext()) { - sb.append(glue); - sb.append(itr.next().toString()); - } - return sb.toString(); - } - - public static String getConcatenatedStringFromList(List input, String delimiter) { - StringBuffer concatenatedString = new StringBuffer(); - for(String data: input) { - concatenatedString.append(data); - concatenatedString.append(delimiter); - } - return concatenatedString.toString(); - } - - public static String getZipAndConcatenated(List input1, List input2, String delimiter) { - StringBuffer concatenatedString = new StringBuffer(); + public static List ArrayToList(String[] input) { + if (input == null) { + return null; + } - for(int i = 0; i < input1.size(); i++) { - concatenatedString.append(input1.get(i)); - concatenatedString.append("='"); - if (i < input2.size()) { - concatenatedString.append(input2.get(i)); - } - concatenatedString.append("'"); - concatenatedString.append(delimiter); - } - return concatenatedString.toString(); - } - - public static List ArrayToList(String[] input) { - if (input == null) { - return null; - } - - List output = new ArrayList(); - for(int i = 0; i < input.length; i++) { - output.add(input[i]); - } - return output; - } + List output = new ArrayList(); + for (int i = 0; i < input.length; i++) { + output.add(input[i]); + } + return output; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/utilities/logging/Message.java b/src/main/java/org/finra/jtaf/core/utilities/logging/Message.java index 1cfd26b..66240bb 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/logging/Message.java +++ b/src/main/java/org/finra/jtaf/core/utilities/logging/Message.java @@ -23,29 +23,28 @@ * Message w/ associated logging level. Used to print logging * messages in a hierarchical fashion (useful for printing messages * from parsers, etc) - * */ public class Message { - private final Level level; - private final String text; + private final Level level; + private final String text; + + public Message(Level level, String text) { + this.level = level; + this.text = text; + } - public Message(Level level, String text) { - this.level = level; - this.text = text; - } - - /** - * @return Log level associated w/ this message - */ - public final Level getLevel() { - return this.level; - } + /** + * @return Log level associated w/ this message + */ + public final Level getLevel() { + return this.level; + } - /** - * @return The text of the message - */ - public final String getText() { - return this.text; - } + /** + * @return The text of the message + */ + public final String getText() { + return this.text; + } } diff --git a/src/main/java/org/finra/jtaf/core/utilities/logging/MessageCollector.java b/src/main/java/org/finra/jtaf/core/utilities/logging/MessageCollector.java index cc4ecb3..7c3f819 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/logging/MessageCollector.java +++ b/src/main/java/org/finra/jtaf/core/utilities/logging/MessageCollector.java @@ -23,100 +23,97 @@ import org.finra.jtaf.core.utilities.StringHelper; - /** * This is used to collect and log error messages in a hierarchical fashion */ public class MessageCollector { - private Section root; - private Stack
history; - - public MessageCollector() { - this("ErrorCollector Root"); - } - - public MessageCollector(String rootName) { - this.root = new Section(rootName); - this.history = new Stack
(); - this.history.push(this.root); - } - - public final void reset(String rootName) { - this.root = new Section(rootName); - this.history.clear(); - this.history.push(this.root); - } - - public final Section getRootSection() { - return this.root; - } - - public final Section getCurrentSection() { - return this.history.peek(); - } - - - public final Section push(String sectionName) { - return this.history.push(this.getCurrentSection().newSection(sectionName)); - } - - public final void pop() { - Section retval = this.history.pop(); - - // If the section we just exited didn't contain anything, - // then delete it. - if(retval.isEmpty()) { - // TODO: This could be optimized, but whatever - this.history.peek().getSections().remove(retval); - } - } - - - - public final void log(Level level, String message) { - this.getCurrentSection().addMessage(new Message(level, message)); - } - - public final void debug(String message) { - this.log(Level.DEBUG, message); - } - - public final void info(String message) { - this.log(Level.INFO, message); - } - - public final void warn(String message) { - this.log(Level.WARN, message); - } - - public final void error(String message) { - this.log(Level.ERROR, message); - } - - public final void fatal(String message) { - this.log(Level.FATAL, message); - } - - public final void dump(Logger log) { - this.recursiveDump(log, this.getRootSection(), 0); - } - - private final void recursiveDump(Logger log, Section section, int depth) { - if(!Level.ALL.isGreaterOrEqual(section.getLevel())) { - log.log(section.getLevel(), StringHelper.indent(depth) + section.getName()); - - ++depth; - - for(Message m : section.getMessages()) { - log.log(m.getLevel(), StringHelper.indent(depth) + m.getText()); - } - - for(Section s : section.getSections()) { - this.recursiveDump(log, s, depth); - } - } - } - - - + private Section root; + private Stack
history; + + public MessageCollector() { + this("ErrorCollector Root"); + } + + public MessageCollector(String rootName) { + this.root = new Section(rootName); + this.history = new Stack
(); + this.history.push(this.root); + } + + public final void reset(String rootName) { + this.root = new Section(rootName); + this.history.clear(); + this.history.push(this.root); + } + + public final Section getRootSection() { + return this.root; + } + + public final Section getCurrentSection() { + return this.history.peek(); + } + + + public final Section push(String sectionName) { + return this.history.push(this.getCurrentSection().newSection(sectionName)); + } + + public final void pop() { + Section retval = this.history.pop(); + + // If the section we just exited didn't contain anything, + // then delete it. + if (retval.isEmpty()) { + // TODO: This could be optimized, but whatever + this.history.peek().getSections().remove(retval); + } + } + + + public final void log(Level level, String message) { + this.getCurrentSection().addMessage(new Message(level, message)); + } + + public final void debug(String message) { + this.log(Level.DEBUG, message); + } + + public final void info(String message) { + this.log(Level.INFO, message); + } + + public final void warn(String message) { + this.log(Level.WARN, message); + } + + public final void error(String message) { + this.log(Level.ERROR, message); + } + + public final void fatal(String message) { + this.log(Level.FATAL, message); + } + + public final void dump(Logger log) { + this.recursiveDump(log, this.getRootSection(), 0); + } + + private final void recursiveDump(Logger log, Section section, int depth) { + if (!Level.ALL.isGreaterOrEqual(section.getLevel())) { + log.log(section.getLevel(), StringHelper.indent(depth) + section.getName()); + + ++depth; + + for (Message m : section.getMessages()) { + log.log(m.getLevel(), StringHelper.indent(depth) + m.getText()); + } + + for (Section s : section.getSections()) { + this.recursiveDump(log, s, depth); + } + } + } + + } diff --git a/src/main/java/org/finra/jtaf/core/utilities/logging/Section.java b/src/main/java/org/finra/jtaf/core/utilities/logging/Section.java index 3121aa2..9c1a7cf 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/logging/Section.java +++ b/src/main/java/org/finra/jtaf/core/utilities/logging/Section.java @@ -25,126 +25,131 @@ /** * Serves as a container for messages and other message sections. - * + *

* TODO: Sections and Messages should have the same base class, but - * I can't think of a good word for it. - * + * I can't think of a good word for it. */ public class Section { - private final String text; - private final Section parent; - - private List

subsections; - private List messages; - private Level level; - - - /** - * External classes are only allowed to instantiate root - * message sections. Subsections are created automatically - * upon request. - * @param name - */ - public Section(String name) { - this(name, null); - } - - /** - * Private constructor used to create subsections - * @param text - * @param parent - */ - private Section(String text, Section parent) { - this.text = text; - this.parent = parent; - this.subsections = new ArrayList
(); - this.messages = new LinkedList(); - this.level = Level.ALL; - } - - /** - * A text label for the section. Something like "In file XYZ" - * @return - */ - public final String getName() { - return this.text; - } - - /** - * Does this Section contain anything useful? - * @return - */ - public final boolean isEmpty() { - return (this.subsections.isEmpty() && this.messages.isEmpty()); - } - - /** - * Retrieves the section w/ the given name, or creates a new - * section if none w/ the given name exists - * @param name - * @return - */ - public Section newSection(String name) { - Section retval = new Section(name, this); - this.subsections.add(retval); - return retval; - } - - - /** - * @return A list of subsections - */ - public List
getSections() { - return this.subsections; - } - - - /** - * Inserts the message into this section. If the message's level - * is greater than this section's level, the section set its level - * equal to the message's level and inform its parent. - * @param message - */ - public final void addMessage(Message message) { - this.messages.add(message); - this.tryRaiseLevel(message.getLevel()); - } - - - /** - * - * @param level - */ - private final void tryRaiseLevel(Level level) { - if(!this.getLevel().isGreaterOrEqual(level)) { - this.level = level; - if(this.getParent() != null) { - this.getParent().tryRaiseLevel(level); - } - } - } - - /** - * @return A list of the messages within this section - */ - public final List getMessages() { - return new ArrayList(this.messages); - } - - /** - * A section's level is Max(max level of subsection, max level of message). - * In other words, the level is the greatest level of a child element. - * @return - */ - public final Level getLevel() { - return this.level; - } - - - /** - * @return The parent of this section, or null if this section is the root - */ - public final Section getParent() { - return this.parent; - } + private final String text; + private final Section parent; + + private List
subsections; + private List messages; + private Level level; + + + /** + * External classes are only allowed to instantiate root + * message sections. Subsections are created automatically + * upon request. + * + * @param name + */ + public Section(String name) { + this(name, null); + } + + /** + * Private constructor used to create subsections + * + * @param text + * @param parent + */ + private Section(String text, Section parent) { + this.text = text; + this.parent = parent; + this.subsections = new ArrayList
(); + this.messages = new LinkedList(); + this.level = Level.ALL; + } + + /** + * A text label for the section. Something like "In file XYZ" + * + * @return + */ + public final String getName() { + return this.text; + } + + /** + * Does this Section contain anything useful? + * + * @return + */ + public final boolean isEmpty() { + return (this.subsections.isEmpty() && this.messages.isEmpty()); + } + + /** + * Retrieves the section w/ the given name, or creates a new + * section if none w/ the given name exists + * + * @param name + * @return + */ + public Section newSection(String name) { + Section retval = new Section(name, this); + this.subsections.add(retval); + return retval; + } + + + /** + * @return A list of subsections + */ + public List
getSections() { + return this.subsections; + } + + + /** + * Inserts the message into this section. If the message's level + * is greater than this section's level, the section set its level + * equal to the message's level and inform its parent. + * + * @param message + */ + public final void addMessage(Message message) { + this.messages.add(message); + this.tryRaiseLevel(message.getLevel()); + } + + + /** + * @param level + */ + private final void tryRaiseLevel(Level level) { + if (!this.getLevel().isGreaterOrEqual(level)) { + this.level = level; + if (this.getParent() != null) { + this.getParent().tryRaiseLevel(level); + } + } + } + + /** + * @return A list of the messages within this section + */ + public final List getMessages() { + return new ArrayList(this.messages); + } + + /** + * A section's level is Max(max level of subsection, max level of message). + * In other words, the level is the greatest level of a child element. + * + * @return + */ + public final Level getLevel() { + return this.level; + } + + + /** + * @return The parent of this section, or null if this section is the root + */ + public final Section getParent() { + return this.parent; + } } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java b/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java index e2aa3d8..9a9d084 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java @@ -7,29 +7,29 @@ public class AssertionFailedErrorTest { - - public void testAssertionFailedErrorMessage1() { - AssertionFailedError e = new AssertionFailedError(null); - Assert.assertEquals("", e.getMessage()); - } - - public void testAssertionFailedErrorMessage2() { - AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); - Assert.assertEquals("This is an assertion failed", e.getMessage()); - } - - @Test(expected=AssertionFailedError.class) - public void testAssertionFailedError1() { - AssertionFailedError e = new AssertionFailedError(null); - Assert.assertEquals("", e.getMessage()); - throw e; - } - - @Test(expected=AssertionFailedError.class) - public void testAssertionFailedError2() { - AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); - Assert.assertEquals("This is an assertion failed", e.getMessage()); - throw e; - } + + public void testAssertionFailedErrorMessage1() { + AssertionFailedError e = new AssertionFailedError(null); + Assert.assertEquals("", e.getMessage()); + } + + public void testAssertionFailedErrorMessage2() { + AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); + Assert.assertEquals("This is an assertion failed", e.getMessage()); + } + + @Test(expected = AssertionFailedError.class) + public void testAssertionFailedError1() { + AssertionFailedError e = new AssertionFailedError(null); + Assert.assertEquals("", e.getMessage()); + throw e; + } + + @Test(expected = AssertionFailedError.class) + public void testAssertionFailedError2() { + AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); + Assert.assertEquals("This is an assertion failed", e.getMessage()); + throw e; + } } diff --git a/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java b/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java index 8077a87..583063f 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java @@ -8,106 +8,105 @@ import org.junit.Test; public class ErrorAccumulatorTest { - - @Test - public void testErrorAccumulatorConstructAndGetName() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("test", ea.getName()); - } - - @Test - public void testErrorAccumulatorSetAndGetName() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("test", ea.getName()); - } - - @Test - public void testErrorAccumulatorAddErrorsAndGetNumErrors() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertTrue(ea.isEmpty()); - ea.addError(new Throwable()); - Assert.assertEquals(ea.getNumErrors(), 1); - ea.addError(new Exception()); - Assert.assertEquals(ea.getNumErrors(), 2); - ea.addError(new RuntimeException()); - Assert.assertEquals(ea.getNumErrors(), 3); - } - - @Test - public void testErrorAccumulatorGetErrorMessages() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - ea.addError(new Exception("This is a test message")); - ea.addError(new RuntimeException("This is another test message")); - ea.addError(new Exception()); - String errorMessagesExpected = "\n This is a test message\n This is another test message\n null"; - Assert.assertEquals(errorMessagesExpected, ea.getErrorMessages()); - } - - @Test - public void testErrorAccumulatorGetErrorStackTraces() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - - StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); - StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements = {ste1, ste2}; - Throwable t = new Throwable(); - t.setStackTrace(elements); - ea.addError(t); - - StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); - StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements2 = {ste3, ste4}; - Throwable t2 = new Throwable(); - t2.setStackTrace(elements2); - ea.addError(t2); - - - - String errorStackTracesExpected = "\n java.lang.Throwable\n\tat Banana.unpeel(helloworld.txt:47)\n\t" + - "at Orange.unpeel(helloworld.txt:49)\n\n java.lang.Throwable\n\tat Apple.unpeel(helloworld.txt:47)" + - "\n\tat Pear.unpeel(helloworld.txt:49)"; - Assert.assertEquals(errorStackTracesExpected.replaceAll("[\t\n\r]", ""), - ea.getErrorStackTraces().replaceAll("[\t\n\r]", "")); - } - - @Test - public void testErrorAccumulatorGetErrorStackTraceElements() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - - StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); - StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements = {ste1, ste2}; - Throwable t = new Throwable(); - t.setStackTrace(elements); - ea.addError(t); - - StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); - StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements2 = {ste3, ste4}; - Throwable t2 = new Throwable(); - t2.setStackTrace(elements2); - ea.addError(t2); - - - List expected = new ArrayList(); - expected.add(elements); - expected.add(elements2); - - Assert.assertArrayEquals(expected.get(0), ea.getErrorStackTraceElementsList().get(0)); - Assert.assertArrayEquals(expected.get(1), ea.getErrorStackTraceElementsList().get(1)); - } - - @Test - public void testThrowErrorsWhenNone() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - ea.throwErrors(); - // shouldn't throw any exceptions - } - - @Test - public void testWrappedErrorsWhenNone() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("Get wrapped errors wasn't null", null, ea.getWrappedErrors()); - } - + + @Test + public void testErrorAccumulatorConstructAndGetName() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("test", ea.getName()); + } + + @Test + public void testErrorAccumulatorSetAndGetName() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("test", ea.getName()); + } + + @Test + public void testErrorAccumulatorAddErrorsAndGetNumErrors() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertTrue(ea.isEmpty()); + ea.addError(new Throwable()); + Assert.assertEquals(ea.getNumErrors(), 1); + ea.addError(new Exception()); + Assert.assertEquals(ea.getNumErrors(), 2); + ea.addError(new RuntimeException()); + Assert.assertEquals(ea.getNumErrors(), 3); + } + + @Test + public void testErrorAccumulatorGetErrorMessages() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + ea.addError(new Exception("This is a test message")); + ea.addError(new RuntimeException("This is another test message")); + ea.addError(new Exception()); + String errorMessagesExpected = "\n This is a test message\n This is another test message\n null"; + Assert.assertEquals(errorMessagesExpected, ea.getErrorMessages()); + } + + @Test + public void testErrorAccumulatorGetErrorStackTraces() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + + StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); + StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements = {ste1, ste2}; + Throwable t = new Throwable(); + t.setStackTrace(elements); + ea.addError(t); + + StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); + StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements2 = {ste3, ste4}; + Throwable t2 = new Throwable(); + t2.setStackTrace(elements2); + ea.addError(t2); + + + String errorStackTracesExpected = "\n java.lang.Throwable\n\tat Banana.unpeel(helloworld.txt:47)\n\t" + + "at Orange.unpeel(helloworld.txt:49)\n\n java.lang.Throwable\n\tat Apple.unpeel(helloworld.txt:47)" + + "\n\tat Pear.unpeel(helloworld.txt:49)"; + Assert.assertEquals(errorStackTracesExpected.replaceAll("[\t\n\r]", ""), + ea.getErrorStackTraces().replaceAll("[\t\n\r]", "")); + } + + @Test + public void testErrorAccumulatorGetErrorStackTraceElements() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + + StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); + StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements = {ste1, ste2}; + Throwable t = new Throwable(); + t.setStackTrace(elements); + ea.addError(t); + + StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); + StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements2 = {ste3, ste4}; + Throwable t2 = new Throwable(); + t2.setStackTrace(elements2); + ea.addError(t2); + + + List expected = new ArrayList(); + expected.add(elements); + expected.add(elements2); + + Assert.assertArrayEquals(expected.get(0), ea.getErrorStackTraceElementsList().get(0)); + Assert.assertArrayEquals(expected.get(1), ea.getErrorStackTraceElementsList().get(1)); + } + + @Test + public void testThrowErrorsWhenNone() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + ea.throwErrors(); + // shouldn't throw any exceptions + } + + @Test + public void testWrappedErrorsWhenNone() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("Get wrapped errors wasn't null", null, ea.getWrappedErrors()); + } + } diff --git a/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java b/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java index 4de5e12..523c474 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java @@ -5,596 +5,596 @@ public class IgnoreErrorsAssertTest { - @Test - public void testAssertTrueWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue("This was a failure", false); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertTrueWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue("Hopefully there's no failure here", true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertTrueWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue(false); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertTrueWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue(true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse("Hopefully there's no failure here", false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse("This was a failure", true); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertFalseWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse(false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse(true); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testFailWithMessage() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.fail("Failure"); - Assert.assertEquals("\n Failure", iea.checkErrors()); - } - - @Test - public void testFail() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.fail(); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenNull() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object)null, (Object)null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (Object)"", (Object)""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (Object)"", (Object)" "); - Assert.assertEquals("\n This was a failure expected:<> but was:< >", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object)"", (Object)""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object)"", (Object)" "); - Assert.assertEquals("\n expected:<> but was:< >", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", "", " "); - Assert.assertEquals("\n This was a failure expected:<[]> but was:<[ ]>", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", "", ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("", " "); - Assert.assertEquals("\n expected:<[]> but was:<[ ]>", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("", ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenEqual() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .05, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", .05, .08, .02); - Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", .05, .06, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .08, .02); - Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .06, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenEqual() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .05f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", .05f, .08f, .02f); - Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", .05f, .06f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .08f, .02f); - Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .06f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (long)100, (long)101); - Assert.assertEquals("\n This was a failure expected:<100> but was:<101>", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (long)100, (long)100); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((long)100, (long)101); - Assert.assertEquals("\n expected:<100> but was:<101>", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((long)100, (long)100); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenFalse1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", true, false); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenFalse2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", false, true); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenTrue1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", true, true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenTrue2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", false, false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenFalse1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(true, false); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenFalse2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(false, true); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenTrue1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(true, true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenTrue2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(false, false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (byte) 14, (byte) 15); - Assert.assertEquals("\n This was a failure expected:<14> but was:<15>", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (byte) 4, (byte) 4); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((byte) 14, (byte) 15); - Assert.assertEquals("\n expected:<14> but was:<15>", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((byte) 4, (byte) 4); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", 'a', 'b'); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", 'a', 'a'); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals('a', 'b'); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals('a', 'a'); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (short)1, (short)2); - Assert.assertEquals("\n This was a failure expected:<1> but was:<2>", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (short)1, (short)1); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((short)1, (short)2); - Assert.assertEquals("\n expected:<1> but was:<2>", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((short)1, (short)1); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", 5, 8); - Assert.assertEquals("\n This was a failure expected:<5> but was:<8>", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", 5, 5); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(5, 8); - Assert.assertEquals("\n expected:<5> but was:<8>", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(5, 5); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull("This was a failure", null); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull("Hopefully there's no failure here", new Object()); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull(null); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull(new Object()); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNullWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull("This was a failure", new Object()); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertNullWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull("Hopefully there's no failure here", null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNullWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String superman = "superman"; - iea.assertNull(superman); - Assert.assertEquals("\n Expected: but was: superman", iea.checkErrors()); - } - - @Test - public void testAssertNullWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull(null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertSameWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.assertSame("This was a failure", a, b); - Assert.assertEquals("\n This was a failure expected same: was not:", iea.checkErrors()); - } - - @Test - public void testAssertSameWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertSame("Hopefully there's no failure here", a, a); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertSameWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.assertSame(a, b); - Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); - } - - @Test - public void testAssertSameWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertSame(a, a); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertNotSame("This was a failure", a, a); - Assert.assertEquals("\n This was a failure expected not same", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - Object b = new Object(); - iea.assertNotSame("Hopefully there's no failure here", a, b); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.assertNotSame(a, a); - Assert.assertEquals("\n expected not same", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - Object b = new Object(); - iea.assertNotSame(a, b); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testFailSame1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.failSame("This is an error message"); - Assert.assertEquals("\n This is an error message expected not same", iea.checkErrors()); - } - - @Test - public void testFailSame2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.failSame(null); - Assert.assertEquals("\n expected not same", iea.checkErrors()); - } - - @Test - public void testFailNotSame1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.failNotSame("This is an error message", a, a); - Assert.assertEquals("\n This is an error message expected same: was not:", iea.checkErrors()); - } - - @Test - public void testFailNotSame2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.failNotSame(null, a, a); - Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); - } - - @Test - public void testFailNotEquals1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals("This is an error message", a, b); - Assert.assertEquals("\n This is an error message expected: but was:", iea.checkErrors()); - } - - @Test - public void testFailNotEquals2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals(null, a, b); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testFormat1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Assert.assertEquals("This is an error message expected: but was:", iea.format("This is an error message", "Superman", "Batman")); - } - - @Test - public void testFormat2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Assert.assertEquals("expected: but was:", iea.format(null, "Superman", "Batman")); - } - - @Test(expected=AssertionFailedError.class) - public void testEndOfCommand() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals(null, a, b); - iea.endOfCommand(); - } + @Test + public void testAssertTrueWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue("This was a failure", false); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertTrueWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue("Hopefully there's no failure here", true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertTrueWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue(false); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertTrueWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue(true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse("Hopefully there's no failure here", false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse("This was a failure", true); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertFalseWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse(false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse(true); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testFailWithMessage() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.fail("Failure"); + Assert.assertEquals("\n Failure", iea.checkErrors()); + } + + @Test + public void testFail() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.fail(); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenNull() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) null, (Object) null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (Object) "", (Object) ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (Object) "", (Object) " "); + Assert.assertEquals("\n This was a failure expected:<> but was:< >", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) "", (Object) ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) "", (Object) " "); + Assert.assertEquals("\n expected:<> but was:< >", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", "", " "); + Assert.assertEquals("\n This was a failure expected:<[]> but was:<[ ]>", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", "", ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("", " "); + Assert.assertEquals("\n expected:<[]> but was:<[ ]>", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("", ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenEqual() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .05, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", .05, .08, .02); + Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", .05, .06, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .08, .02); + Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .06, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenEqual() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .05f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", .05f, .08f, .02f); + Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", .05f, .06f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .08f, .02f); + Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .06f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (long) 100, (long) 101); + Assert.assertEquals("\n This was a failure expected:<100> but was:<101>", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (long) 100, (long) 100); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((long) 100, (long) 101); + Assert.assertEquals("\n expected:<100> but was:<101>", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((long) 100, (long) 100); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenFalse1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", true, false); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenFalse2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", false, true); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenTrue1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", true, true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenTrue2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", false, false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenFalse1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(true, false); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenFalse2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(false, true); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenTrue1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(true, true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenTrue2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(false, false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (byte) 14, (byte) 15); + Assert.assertEquals("\n This was a failure expected:<14> but was:<15>", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (byte) 4, (byte) 4); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((byte) 14, (byte) 15); + Assert.assertEquals("\n expected:<14> but was:<15>", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((byte) 4, (byte) 4); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", 'a', 'b'); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", 'a', 'a'); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals('a', 'b'); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals('a', 'a'); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (short) 1, (short) 2); + Assert.assertEquals("\n This was a failure expected:<1> but was:<2>", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (short) 1, (short) 1); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((short) 1, (short) 2); + Assert.assertEquals("\n expected:<1> but was:<2>", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((short) 1, (short) 1); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", 5, 8); + Assert.assertEquals("\n This was a failure expected:<5> but was:<8>", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", 5, 5); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(5, 8); + Assert.assertEquals("\n expected:<5> but was:<8>", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(5, 5); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull("This was a failure", null); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull("Hopefully there's no failure here", new Object()); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull(null); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull(new Object()); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNullWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull("This was a failure", new Object()); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertNullWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull("Hopefully there's no failure here", null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNullWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String superman = "superman"; + iea.assertNull(superman); + Assert.assertEquals("\n Expected: but was: superman", iea.checkErrors()); + } + + @Test + public void testAssertNullWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull(null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertSameWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.assertSame("This was a failure", a, b); + Assert.assertEquals("\n This was a failure expected same: was not:", iea.checkErrors()); + } + + @Test + public void testAssertSameWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertSame("Hopefully there's no failure here", a, a); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertSameWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.assertSame(a, b); + Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); + } + + @Test + public void testAssertSameWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertSame(a, a); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertNotSame("This was a failure", a, a); + Assert.assertEquals("\n This was a failure expected not same", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + Object b = new Object(); + iea.assertNotSame("Hopefully there's no failure here", a, b); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.assertNotSame(a, a); + Assert.assertEquals("\n expected not same", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + Object b = new Object(); + iea.assertNotSame(a, b); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testFailSame1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.failSame("This is an error message"); + Assert.assertEquals("\n This is an error message expected not same", iea.checkErrors()); + } + + @Test + public void testFailSame2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.failSame(null); + Assert.assertEquals("\n expected not same", iea.checkErrors()); + } + + @Test + public void testFailNotSame1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.failNotSame("This is an error message", a, a); + Assert.assertEquals("\n This is an error message expected same: was not:", iea.checkErrors()); + } + + @Test + public void testFailNotSame2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.failNotSame(null, a, a); + Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); + } + + @Test + public void testFailNotEquals1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals("This is an error message", a, b); + Assert.assertEquals("\n This is an error message expected: but was:", iea.checkErrors()); + } + + @Test + public void testFailNotEquals2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals(null, a, b); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testFormat1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Assert.assertEquals("This is an error message expected: but was:", iea.format("This is an error message", "Superman", "Batman")); + } + + @Test + public void testFormat2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Assert.assertEquals("expected: but was:", iea.format(null, "Superman", "Batman")); + } + + @Test(expected = AssertionFailedError.class) + public void testEndOfCommand() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals(null, a, b); + iea.endOfCommand(); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java index d17d287..41d8223 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java @@ -4,16 +4,16 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class ByeCommand extends Command{ +public class ByeCommand extends Command { - public ByeCommand(String name) throws NameFormatException { - super(name); - } + public ByeCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data", "Bye !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Bye !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java index c016a40..afb5da1 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java @@ -3,16 +3,16 @@ import org.finra.jtaf.core.model.exceptions.NameFormatException; import org.finra.jtaf.core.model.execution.IInvocationContext; -public class ExtendedByeCommand extends ByeCommand{ +public class ExtendedByeCommand extends ByeCommand { - public ExtendedByeCommand(String name) throws NameFormatException { - super(name); - } + public ExtendedByeCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data","Bye Bye "+getContext().getObject("data")); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Bye Bye " + getContext().getObject("data")); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java index 35cfac2..95de466 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java @@ -3,17 +3,17 @@ import org.finra.jtaf.core.model.exceptions.NameFormatException; import org.finra.jtaf.core.model.execution.IInvocationContext; -public class ExtendedHelloCommand extends HelloCommand{ +public class ExtendedHelloCommand extends HelloCommand { - public ExtendedHelloCommand(String name) throws NameFormatException { - super(name); - } + public ExtendedHelloCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - super.execute(ctx); - String data = (String )getContext().getObject("data"); - data = "Hello Hello" + data ; - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + super.execute(ctx); + String data = (String) getContext().getObject("data"); + data = "Hello Hello" + data; + } } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java index 6110191..27d9498 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java @@ -6,16 +6,16 @@ import org.finra.jtaf.core.model.invocationtarget.Command; import org.junit.Assert; -public class ExtendedVerifyByeCommand extends Command{ +public class ExtendedVerifyByeCommand extends Command { - public ExtendedVerifyByeCommand(String name) throws NameFormatException { - super(name); - } + public ExtendedVerifyByeCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data",""); - Assert.assertEquals(data, "Bye Bye Bye !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Bye Bye Bye !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java index 5ee6f99..d2e17de 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java @@ -6,16 +6,16 @@ import org.finra.jtaf.core.model.invocationtarget.Command; import org.junit.Assert; -public class ExtendedVerifyHelloCommand extends Command{ +public class ExtendedVerifyHelloCommand extends Command { - public ExtendedVerifyHelloCommand(String name) throws NameFormatException { - super(name); - } + public ExtendedVerifyHelloCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data",""); - Assert.assertEquals(data, "Hello Hello Hello World !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Hello Hello Hello World !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java index ce28a6f..94479f8 100644 --- a/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java @@ -4,16 +4,16 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class HelloCommand extends Command{ +public class HelloCommand extends Command { - public HelloCommand(String name) throws NameFormatException { - super(name); - } + public HelloCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data", "Hello World !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Hello World !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java b/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java index 74a125f..004a7ed 100644 --- a/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java @@ -18,8 +18,8 @@ public class RandomGeneratorTest { - private static AutomationEngine engine=null; - private static TestAgenda testAgenda =null; + private static AutomationEngine engine = null; + private static TestAgenda testAgenda = null; private static boolean setup = false; private static TestScript generateRegexp = null; private static TestScript generateRegexp2 = null; @@ -35,19 +35,19 @@ public class RandomGeneratorTest { private static TestScript generateString3 = null; private static TestScript generateString4 = null; private static TestScript generateString5 = null; - + final static public List abbrevUSState = new ArrayList(Arrays.asList("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", - "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); - + "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); + final static public List USState = new ArrayList(Arrays.asList("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", - "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", - "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", - "Wisconsin", "Wyoming")); - public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; + "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", + "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", + "Wisconsin", "Wyoming")); + public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; @Before public void setup() { - + engine = AutomationEngine.getInstance(); if (engine.getTestAgenda() == null) { @@ -55,10 +55,10 @@ public void setup() { // engine.setDependenciesOn(false); testAgenda = engine.getTestAgenda(); - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); } - - + + if (!setup) { testAgenda = engine.getTestAgenda(); @@ -66,33 +66,33 @@ public void setup() { String temp = testScript.getName(); temp = temp.replace(testScript.getFileName(), ""); if (temp.equals("GenerateRegexp")) - generateRegexp = testScript; + generateRegexp = testScript; if (temp.equals("GenerateRegexp2")) - generateRegexp2 = testScript; + generateRegexp2 = testScript; if (temp.equals("GeneratePhone")) - generatePhone = testScript; + generatePhone = testScript; if (temp.equals("GenerateAbbrevUSState")) - generateAbbrevUSState = testScript; + generateAbbrevUSState = testScript; if (temp.equals("GenerateUSState")) - generateUSState = testScript; + generateUSState = testScript; if (temp.equals("GenerateNumber")) - generateNumber = testScript; + generateNumber = testScript; if (temp.equals("GenerateNumber2")) - generateNumber2 = testScript; + generateNumber2 = testScript; if (temp.equals("GenerateNumber3")) - generateNumber3 = testScript; + generateNumber3 = testScript; if (temp.equals("GenerateNumber4")) - generateNumber4 = testScript; + generateNumber4 = testScript; if (temp.equals("GenerateString")) - generateString = testScript; + generateString = testScript; if (temp.equals("GenerateString2")) - generateString2 = testScript; + generateString2 = testScript; if (temp.equals("GenerateString3")) - generateString3 = testScript; + generateString3 = testScript; if (temp.equals("GenerateString4")) - generateString4 = testScript; + generateString4 = testScript; if (temp.equals("GenerateString5")) - generateString5 = testScript; + generateString5 = testScript; } } setup = true; @@ -102,8 +102,8 @@ public void setup() { public void testGenerateRegexp() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateRegexp); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); } @@ -112,8 +112,8 @@ public void testGenerateRegexp() throws Throwable { public void testGenerateRegexp2() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateRegexp2); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); } @@ -122,8 +122,8 @@ public void testGenerateRegexp2() throws Throwable { public void testGeneratePhone() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generatePhone); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Phone regex failed", str.matches("[0-9]{10}")); } @@ -132,147 +132,156 @@ public void testGeneratePhone() throws Throwable { public void testGenerateAbbrevUSState() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateAbbrevUSState); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("String generated was not an abbreviated US state", abbrevUSState.contains(str)); } - + @Test public void testGenerateUSState() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateUSState); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("String generated was not an abbreviated US state", USState.contains(str)); } /*** * Tests Number Generated with default length (5) + * * @throws Throwable */ @Test public void testGenerateNumber() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateNumber); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); } - + /*** * Tests Number Generated with length = 7 + * * @throws Throwable */ @Test public void testGenerateNumber2() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateNumber2); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Number generation failed", str.matches("[0-9]{7}")); } - + /*** * Tests Number Generated between 10 and 100 + * * @throws Throwable */ @Test public void testGenerateNumber3() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateNumber3); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); int num = Integer.parseInt(str); Assert.assertTrue("Number generation failed", 10 <= num && num <= 100); } - + /*** - * Test number generated with min specified but no max, so use default length (5) + * Test number generated with min specified but no max, so use default length (5) + * * @throws Throwable */ @Test public void testGenerateNumber4() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateNumber4); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); } /*** * Tests String generated with default length (5) + * * @throws Throwable */ @Test public void testGenerateString() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateString); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("["+ charsForRandomString + "]{5}")); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); } /*** * Tests String generated with length = 7 + * * @throws Throwable */ @Test public void testGenerateString2() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateString2); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("["+ charsForRandomString + "]{7}")); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); } - + /** * Tests String with length in range from 5-10 characters + * * @throws Throwable */ @Test public void testGenerateString3() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateString3); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("["+ charsForRandomString + "]{5,10}")); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5,10}")); } /** * Tests String with length = 7 when min length is specified without a max + * * @throws Throwable */ @Test public void testGenerateString4() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateString4); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("["+ charsForRandomString + "]{7}")); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); } - + /** * Tests String with default length (5) when min length is specified without a max + * * @throws Throwable */ @Test public void testGenerateString5() throws Throwable { Interpreter iv = AutomationEngine.getInstance().getInterpreter(); TestResult tr = iv.interpret(generateString5); - if(!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("["+ charsForRandomString + "]{5}")); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); } } diff --git a/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java b/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java index 0cabcd4..62a397f 100644 --- a/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java @@ -14,8 +14,8 @@ public class RepeatTest { - private static AutomationEngine engine=null; - private static TestAgenda testAgenda =null; + private static AutomationEngine engine = null; + private static TestAgenda testAgenda = null; private static boolean setup = false; private static TestScript complex = null; private static TestScript repeat = null; @@ -23,17 +23,17 @@ public class RepeatTest { @Before public void setup() { - + engine = AutomationEngine.getInstance(); if (engine.getTestAgenda() == null) { engine.buildModel(new File("testlibrary"), new File("testscripts")); testAgenda = engine.getTestAgenda(); - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); } - - + + if (!setup) { testAgenda = engine.getTestAgenda(); @@ -50,7 +50,7 @@ public void setup() { repeat = testScript; } } - + } setup = true; diff --git a/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java index 9ad803c..912f8f8 100644 --- a/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java @@ -6,16 +6,16 @@ import org.finra.jtaf.core.model.invocationtarget.Command; import org.junit.Assert; -public class VerifyByeCommand extends Command{ +public class VerifyByeCommand extends Command { - public VerifyByeCommand(String name) throws NameFormatException { - super(name); - } + public VerifyByeCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data",""); - Assert.assertEquals(data, "Bye !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Bye !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java index 2860486..df4c0ce 100644 --- a/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java @@ -6,16 +6,16 @@ import org.finra.jtaf.core.model.invocationtarget.Command; import org.junit.Assert; -public class VerifyHelloCommand extends Command{ +public class VerifyHelloCommand extends Command { - public VerifyHelloCommand(String name) throws NameFormatException { - super(name); - } + public VerifyHelloCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data",""); - Assert.assertEquals(data, "Hello World !"); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Hello World !"); + } } diff --git a/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java b/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java index 8d961a8..36331e7 100644 --- a/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java @@ -334,10 +334,10 @@ public void testGetOptionalObject() throws Throwable { helper.setValueOut("test", "$contextKey(test2)"); Assert.assertEquals("testString", (String) helper.getOptionalObject("test")); - + helper.setValueOut("testStartIndex", "$contextKeyy(startIndex)"); Assert.assertEquals("startIndexString", (String) helper.getOptionalObject("testStartIndex")); - + helper.setValueOut("testEndIndex", "$contextKeyy(endIndex"); Assert.assertEquals("", (String) helper.getOptionalObject("testEndIndex")); RuntimeException exception = null; @@ -386,7 +386,7 @@ protected Node buildTestRoot(String scriptFileName, String testOfInterestName) t Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { + .equals(testOfInterestName)) { testRoot = suiteNodeChildNode; break; } diff --git a/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java b/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java index f28b0b1..7197890 100644 --- a/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java +++ b/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java @@ -4,9 +4,7 @@ import org.junit.runner.RunWith; - - -@RunWith(JTAFMasterSuite.class) +@RunWith(JTAFMasterSuite.class) public class XMLTestParrelDriver { } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java b/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java index ab083a3..4f5c272 100644 --- a/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java +++ b/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java @@ -4,19 +4,15 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class DebugPrintCommand extends Command -{ - public DebugPrintCommand(String name) throws NameFormatException - { - super(name); - } +public class DebugPrintCommand extends Command { + public DebugPrintCommand(String name) throws NameFormatException { + super(name); + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable - { - synchronized(DebugPrintCommand.class) - { - System.err.println(getRequiredString("message")); - } - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + synchronized (DebugPrintCommand.class) { + System.err.println(getRequiredString("message")); + } + } } diff --git a/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java b/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java index 886f396..77f58ac 100644 --- a/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java +++ b/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java @@ -6,17 +6,17 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class IThrowExceptionCmd extends Command{ +public class IThrowExceptionCmd extends Command { - public IThrowExceptionCmd(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } + public IThrowExceptionCmd(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - throw new SQLException("This is just a test"); - - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + throw new SQLException("This is just a test"); + + } } diff --git a/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java b/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java index 634da58..76511cf 100644 --- a/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java +++ b/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java @@ -4,18 +4,18 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class MockCommand1 extends Command{ +public class MockCommand1 extends Command { - public MockCommand1(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } + public MockCommand1(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getRequiredBoolean("param1"); - - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getRequiredBoolean("param1"); + + } } diff --git a/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java b/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java index 04f75f5..b1435a1 100644 --- a/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java +++ b/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java @@ -4,19 +4,19 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class MockCommand2 extends Command{ - public static boolean testEnd; - - public MockCommand2(String name) throws NameFormatException { - super(name); - testEnd = false; - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - testEnd = true; - } +public class MockCommand2 extends Command { + public static boolean testEnd; + + public MockCommand2(String name) throws NameFormatException { + super(name); + testEnd = false; + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + testEnd = true; + } } diff --git a/src/test/java/org/finra/jtaf/core/mock/Repeat.java b/src/test/java/org/finra/jtaf/core/mock/Repeat.java index 62033ef..6007895 100644 --- a/src/test/java/org/finra/jtaf/core/mock/Repeat.java +++ b/src/test/java/org/finra/jtaf/core/mock/Repeat.java @@ -4,17 +4,17 @@ import org.finra.jtaf.core.model.execution.IInvocationContext; import org.finra.jtaf.core.model.invocationtarget.Command; -public class Repeat extends Command{ +public class Repeat extends Command { - public Repeat(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } + public Repeat(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - //do nothing - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + //do nothing + } } diff --git a/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java b/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java index d598d28..2a91616 100644 --- a/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java +++ b/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java @@ -7,85 +7,85 @@ public class TestParamFetchingCmd extends Command { - public TestParamFetchingCmd(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } + public TestParamFetchingCmd(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - if (getName().equalsIgnoreCase("testoptionalParameters")) - testOptionalParameters(); - else if (getName().equalsIgnoreCase("testRequiredParameters")) - testRequiredParameters(); - else if (getName().equalsIgnoreCase("testParameters")) - testParameters(); - } + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + if (getName().equalsIgnoreCase("testoptionalParameters")) + testOptionalParameters(); + else if (getName().equalsIgnoreCase("testRequiredParameters")) + testRequiredParameters(); + else if (getName().equalsIgnoreCase("testParameters")) + testParameters(); + } - private void testParameters() { - try{ - getRequiredString("testStringRequired"); - }catch(Exception e){ - Assert.assertEquals("testParameters: missing required String attribute 'testStringRequired'", e.getMessage()); - - } - try{ - getRequiredInteger("testIntegerRequired"); - }catch(Exception e){ - Assert.assertEquals("testParameters: missing required integer attribute 'testIntegerRequired'", e.getMessage()); - - } - try{ - getRequiredBoolean("testBooleanRequired"); - }catch(Exception e){ - Assert.assertEquals("testParameters: missing required boolean attribute 'testBooleanRequired'", e.getMessage()); - - } - try{ - getRequiredFloat("testFloatRequired"); - }catch(Exception e){ - Assert.assertEquals("testParameters: missing required float attribute 'testFloatRequired'", e.getMessage()); - - } - try{ - getRequiredObject("testObjectRequired"); - }catch(Exception e){ - Assert.assertEquals("testParameters : The parameter with key [testObjectRequired] is not set.", e.getMessage()); - - } - getOptionalObject("testObjectOptional"); - Assert.assertTrue(getGlobalContext().get("OptString")!=null); - - - } + private void testParameters() { + try { + getRequiredString("testStringRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required String attribute 'testStringRequired'", e.getMessage()); - private void testOptionalParameters(){ - Assert.assertEquals("test string",getRequiredString("testStringRequired")); - Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); - Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"),0.2); - Assert.assertEquals(false, getRequiredBoolean("testBooleanRequired")); - Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); - Assert.assertEquals("test string optional", getOptionalString("testStringOptional")); - Assert.assertEquals("{cat, dog}",getOptionalObject("testObjectOptional")); - Assert.assertEquals(false, getBooleanOrDefault("testBooleanDefault", true)); - Assert.assertEquals("not the default string",getStringOrDefault("testStringDefault", "testString")); - Assert.assertEquals(2,getIntegerOrDefault("testIntegerDefault", 1)); - Assert.assertEquals(2.2f,getFloatOrDefault("testFloatDefault", 1.1f), 0.2); - } + } + try { + getRequiredInteger("testIntegerRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required integer attribute 'testIntegerRequired'", e.getMessage()); - private void testRequiredParameters() { - Assert.assertEquals("test string required",getRequiredString("testStringRequired")); - Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); - Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"),0.2); - Assert.assertEquals(true, getRequiredBoolean("testBooleanRequired")); - Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); - Assert.assertTrue(getOptionalString("testStringOptional") == null); - getOptionalObject("testObjectOptional"); - Assert.assertTrue(getGlobalContext().get("OptObj")!=null); - Assert.assertEquals(true, getBooleanOrDefault("testBooleanDefault", true)); - Assert.assertEquals("default string",getStringOrDefault("testStringDefault", "default string")); - Assert.assertEquals(1,getIntegerOrDefault("testIntegerDefault", 1)); - Assert.assertEquals(1.1f,getFloatOrDefault("testFloatDefault", 1.1f), 0.2); - } + } + try { + getRequiredBoolean("testBooleanRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required boolean attribute 'testBooleanRequired'", e.getMessage()); + + } + try { + getRequiredFloat("testFloatRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required float attribute 'testFloatRequired'", e.getMessage()); + + } + try { + getRequiredObject("testObjectRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters : The parameter with key [testObjectRequired] is not set.", e.getMessage()); + + } + getOptionalObject("testObjectOptional"); + Assert.assertTrue(getGlobalContext().get("OptString") != null); + + + } + + private void testOptionalParameters() { + Assert.assertEquals("test string", getRequiredString("testStringRequired")); + Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); + Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); + Assert.assertEquals(false, getRequiredBoolean("testBooleanRequired")); + Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); + Assert.assertEquals("test string optional", getOptionalString("testStringOptional")); + Assert.assertEquals("{cat, dog}", getOptionalObject("testObjectOptional")); + Assert.assertEquals(false, getBooleanOrDefault("testBooleanDefault", true)); + Assert.assertEquals("not the default string", getStringOrDefault("testStringDefault", "testString")); + Assert.assertEquals(2, getIntegerOrDefault("testIntegerDefault", 1)); + Assert.assertEquals(2.2f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); + } + + private void testRequiredParameters() { + Assert.assertEquals("test string required", getRequiredString("testStringRequired")); + Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); + Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); + Assert.assertEquals(true, getRequiredBoolean("testBooleanRequired")); + Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); + Assert.assertTrue(getOptionalString("testStringOptional") == null); + getOptionalObject("testObjectOptional"); + Assert.assertTrue(getGlobalContext().get("OptObj") != null); + Assert.assertEquals(true, getBooleanOrDefault("testBooleanDefault", true)); + Assert.assertEquals("default string", getStringOrDefault("testStringDefault", "default string")); + Assert.assertEquals(1, getIntegerOrDefault("testIntegerDefault", 1)); + Assert.assertEquals(1.1f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); + } } diff --git a/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java b/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java index 00e3e7f..4e1eae9 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java @@ -18,25 +18,23 @@ public class ConcurrentSchedulerTest { - @Test public void testCheckTestsStatus() throws Exception { - - if ( AutomationEngine.getInstance().getTestAgenda() == null) { + + if (AutomationEngine.getInstance().getTestAgenda() == null) { AutomationEngine.getInstance().buildModel(new File("testlibrary"), new File("testscripts")); - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); } - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB","FAILED"); + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "FAILED"); AutomationEngine.getInstance().getTestAgenda().setThreadCount("-1"); ConcurrentScheduler scheduler = new ConcurrentScheduler(); - + //scheduler.registerTestName("Test"); scheduler.finished(); - - - - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB","READY"); - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestA","FAILED"); + + + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "READY"); + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestA", "FAILED"); scheduler.finished(); @@ -52,7 +50,7 @@ protected Node buildTestRoot(String scriptFileName, String testOfInterestName) t Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { + .equals(testOfInterestName)) { testRoot = suiteNodeChildNode; break; } diff --git a/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java b/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java index 4c83a62..27848d3 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java @@ -7,9 +7,9 @@ public class MasterSuiteRunnersBuilderTest { @Test - public void testRunnerForClass() throws Throwable{ + public void testRunnerForClass() throws Throwable { MasterSuiteRunnersBuilder builder = new MasterSuiteRunnersBuilder(); Assert.assertEquals(null, builder.runnerForClass(null)); } - + } diff --git a/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java b/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java index 14d2bb1..c55de6e 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java @@ -82,7 +82,7 @@ public void testRunJtafTestScript() throws Throwable { AutomationEngine.getInstance().getTestDigraph().addVertex(node); } - + runner = new ParallelScriptRunner(testScript); Throwable error = null; @@ -93,8 +93,8 @@ public void testRunJtafTestScript() throws Throwable { } Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionError")); Assert.assertTrue(error.getMessage().equals("One or more Dependent tests failed")); - - + + AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(), "SUCCESS"); try { @@ -116,7 +116,7 @@ protected Node buildTestRoot(String scriptFileName, String testOfInterestName) t Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { + .equals(testOfInterestName)) { testRoot = suiteNodeChildNode; break; } @@ -135,10 +135,10 @@ protected TestSuite buildTestSuite(Node testRoot) throws Exception { private class MyNode extends DiNode { private String testName = ""; // This shouldnt change after being set - // initially + // initially private String testStatus = ""; private TestScript testScript = null; // This shouldnt change after - // being set initially + // being set initially public MyNode(TestScript ts) { super(ts); diff --git a/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java index 3470894..50cc2ec 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java @@ -11,132 +11,122 @@ import org.junit.Test; -public class AutomationValueFilterPluginTest -{ - private static final String AUTOMATION_VALUE_A = "A"; - private static final String AUTOMATION_VALUE_B = "B"; - private static final String AUTOMATION_VALUE_C = "C"; - private static final String AUTOMATION_VALUE_D = "D"; - - private TestAgenda testAgenda; - private TestScript dummyScriptA; - private TestScript dummyScriptB1; - private TestScript dummyScriptB2; - private TestScript dummyScriptC; - private PostAllParserPluginContext postAllParserPluginContext; - - @Before - public void setup() throws NameFormatException - { - testAgenda = new TestAgenda(); - - dummyScriptA = buildDummyScript(testAgenda, "DummyScriptA", AUTOMATION_VALUE_A); - dummyScriptB1 = buildDummyScript(testAgenda, "DummyScriptB1", AUTOMATION_VALUE_B); - dummyScriptB2 = buildDummyScript(testAgenda, "DummyScriptB2", AUTOMATION_VALUE_B); - dummyScriptC = buildDummyScript(testAgenda, "DummyScriptC", AUTOMATION_VALUE_C); - - postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); - } - - private TestScript buildDummyScript(TestAgenda testAgenda, String name, String automationValueA) throws NameFormatException - { - TestScript result = new TestScript(name, false); - result.setAutomationValue(automationValueA); - result.setFileName("DummyFileName.xml"); - testAgenda.getTestScripts().add(result); - return result; - } - - @Test - public void testExecuteNoAutomationValues() throws NameFormatException, ParserPluginException - { - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueNoIncludedTests() throws NameFormatException, ParserPluginException - { - testAgenda.addAutomationValue(AUTOMATION_VALUE_D); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueOneIncludedTest() throws NameFormatException, ParserPluginException - { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueTwoIncludedTests() throws NameFormatException, ParserPluginException - { - testAgenda.addAutomationValue(AUTOMATION_VALUE_B); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteTwoAutomationValuesThreeIncludedTests() throws NameFormatException, ParserPluginException - { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - testAgenda.addAutomationValue(AUTOMATION_VALUE_B); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteTwoAutomationValuesNoAutomationValueInTestOrStrategy() throws NameFormatException, ParserPluginException - { - dummyScriptA.setAutomationValue(null); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - } - - @Test - public void testExecuteTwoAutomationValuesNoAutomationValueInTestOneInStrategy() throws NameFormatException, ParserPluginException - { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - - dummyScriptA.setAutomationValue(null); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - } +public class AutomationValueFilterPluginTest { + private static final String AUTOMATION_VALUE_A = "A"; + private static final String AUTOMATION_VALUE_B = "B"; + private static final String AUTOMATION_VALUE_C = "C"; + private static final String AUTOMATION_VALUE_D = "D"; + + private TestAgenda testAgenda; + private TestScript dummyScriptA; + private TestScript dummyScriptB1; + private TestScript dummyScriptB2; + private TestScript dummyScriptC; + private PostAllParserPluginContext postAllParserPluginContext; + + @Before + public void setup() throws NameFormatException { + testAgenda = new TestAgenda(); + + dummyScriptA = buildDummyScript(testAgenda, "DummyScriptA", AUTOMATION_VALUE_A); + dummyScriptB1 = buildDummyScript(testAgenda, "DummyScriptB1", AUTOMATION_VALUE_B); + dummyScriptB2 = buildDummyScript(testAgenda, "DummyScriptB2", AUTOMATION_VALUE_B); + dummyScriptC = buildDummyScript(testAgenda, "DummyScriptC", AUTOMATION_VALUE_C); + + postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); + } + + private TestScript buildDummyScript(TestAgenda testAgenda, String name, String automationValueA) throws NameFormatException { + TestScript result = new TestScript(name, false); + result.setAutomationValue(automationValueA); + result.setFileName("DummyFileName.xml"); + testAgenda.getTestScripts().add(result); + return result; + } + + @Test + public void testExecuteNoAutomationValues() throws NameFormatException, ParserPluginException { + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueNoIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_D); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueOneIncludedTest() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueTwoIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_B); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteTwoAutomationValuesThreeIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + testAgenda.addAutomationValue(AUTOMATION_VALUE_B); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteTwoAutomationValuesNoAutomationValueInTestOrStrategy() throws NameFormatException, ParserPluginException { + dummyScriptA.setAutomationValue(null); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + } + + @Test + public void testExecuteTwoAutomationValuesNoAutomationValueInTestOneInStrategy() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + + dummyScriptA.setAutomationValue(null); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java index 061586a..9c0785d 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java @@ -13,40 +13,35 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -public class AutomationValuePluginTest -{ - private static final String AUTOMATION_VALUE_NAME = "automationValue"; - private static final String AUTOMATION_VALUE_TEST_STRATEGY_FILE = "AutomationValueTestStrategy.strategy.xml"; - private static final String FILE_AUTOMATION_VALUE = "DummyAutomationValue"; - - @Test - public void testExecute() throws Exception - { - TestAgenda testAgenda = new TestAgenda(); - Assert.assertTrue("Test agenda automation values set is NOT empty", testAgenda.isAutomationValuesEmpty()); - AutomationValuePlugin automationValuePlugin = new AutomationValuePlugin(); - Element element = buildElement(); - PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); - automationValuePlugin.execute(postStrategyParserPluginContext); - Assert.assertFalse("Test agenda automation values set IS empty", testAgenda.isAutomationValuesEmpty()); - Assert.assertEquals("Test agenda has incorrect automation values size", 1, testAgenda.getAutomationValues().size()); - Assert.assertTrue("Automation Value: " + FILE_AUTOMATION_VALUE + " was NOT found", testAgenda.containsAutomationValue(FILE_AUTOMATION_VALUE)); - } +public class AutomationValuePluginTest { + private static final String AUTOMATION_VALUE_NAME = "automationValue"; + private static final String AUTOMATION_VALUE_TEST_STRATEGY_FILE = "AutomationValueTestStrategy.strategy.xml"; + private static final String FILE_AUTOMATION_VALUE = "DummyAutomationValue"; - private Element buildElement() throws Exception - { - InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(AUTOMATION_VALUE_TEST_STRATEGY_FILE); - Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList nodeList = executeRoot.getChildNodes(); - Element element = null; - for(int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) - { - Node node = nodeList.item(nodeIndex); - if(node.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) - { - element = (Element) node; - } - } - return element; - } + @Test + public void testExecute() throws Exception { + TestAgenda testAgenda = new TestAgenda(); + Assert.assertTrue("Test agenda automation values set is NOT empty", testAgenda.isAutomationValuesEmpty()); + AutomationValuePlugin automationValuePlugin = new AutomationValuePlugin(); + Element element = buildElement(); + PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); + automationValuePlugin.execute(postStrategyParserPluginContext); + Assert.assertFalse("Test agenda automation values set IS empty", testAgenda.isAutomationValuesEmpty()); + Assert.assertEquals("Test agenda has incorrect automation values size", 1, testAgenda.getAutomationValues().size()); + Assert.assertTrue("Automation Value: " + FILE_AUTOMATION_VALUE + " was NOT found", testAgenda.containsAutomationValue(FILE_AUTOMATION_VALUE)); + } + + private Element buildElement() throws Exception { + InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(AUTOMATION_VALUE_TEST_STRATEGY_FILE); + Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList nodeList = executeRoot.getChildNodes(); + Element element = null; + for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { + Node node = nodeList.item(nodeIndex); + if (node.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { + element = (Element) node; + } + } + return element; + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java index 94b798c..f9d00bd 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java @@ -8,35 +8,31 @@ import org.junit.Assert; import org.junit.Test; -public class DigraphPluginTest -{ - private static final String DEPENDENT_TEST = "Dependent Test with AutomationValue not Specified in Strategy"; - private static final String AUTOMATION_VALUE = "AutomationValueTest"; - - private TestAgenda testAgenda; - - @Test - public void testAutomationValueChangedWhenDependent() - { - AutomationEngine automationEngine = AutomationEngine.getInstance(); - if(automationEngine.getTestAgenda() == null) - automationEngine.buildModel(new File("testlibrary"), new File("testscripts")); - testAgenda = automationEngine.getTestAgenda(); - - Assert.assertTrue(testAgendaIncludesTest(DEPENDENT_TEST)); - Assert.assertEquals(AUTOMATION_VALUE, getScriptByName(DEPENDENT_TEST).getAutomationValue()); - } - - private boolean testAgendaIncludesTest(String dependentTest) - { - return getScriptByName(DEPENDENT_TEST) != null; - } - - private TestScript getScriptByName(String dependentTest) - { - for (TestScript testScript : testAgenda.getTestScripts()) - if(testScript.getName().equals(dependentTest)) - return testScript; - return null; - } +public class DigraphPluginTest { + private static final String DEPENDENT_TEST = "Dependent Test with AutomationValue not Specified in Strategy"; + private static final String AUTOMATION_VALUE = "AutomationValueTest"; + + private TestAgenda testAgenda; + + @Test + public void testAutomationValueChangedWhenDependent() { + AutomationEngine automationEngine = AutomationEngine.getInstance(); + if (automationEngine.getTestAgenda() == null) + automationEngine.buildModel(new File("testlibrary"), new File("testscripts")); + testAgenda = automationEngine.getTestAgenda(); + + Assert.assertTrue(testAgendaIncludesTest(DEPENDENT_TEST)); + Assert.assertEquals(AUTOMATION_VALUE, getScriptByName(DEPENDENT_TEST).getAutomationValue()); + } + + private boolean testAgendaIncludesTest(String dependentTest) { + return getScriptByName(DEPENDENT_TEST) != null; + } + + private TestScript getScriptByName(String dependentTest) { + for (TestScript testScript : testAgenda.getTestScripts()) + if (testScript.getName().equals(dependentTest)) + return testScript; + return null; + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java index 831e28b..5527d9b 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java @@ -13,32 +13,29 @@ import org.w3c.dom.Node; -public class LoopPluginTest extends ParserPluginTest -{ - private static final String SCRIPT_FILE_NAME = "testscripts/LoopDebug.xml"; - private static final String TEST_OF_INTEREST_NAME = "Loop Debug Test"; - private static final int ITERATION_COUNT = 4; - - @Test - public void testExecute() throws Exception - { - LoopPlugin loopPlugin = new LoopPlugin(AutomationEngine.getInstance()); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - Assert.assertEquals(1, testSuite.getComponentList().size()); +public class LoopPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/LoopDebug.xml"; + private static final String TEST_OF_INTEREST_NAME = "Loop Debug Test"; + private static final int ITERATION_COUNT = 4; - List componentList = testSuite.getComponentList(); - String originalTestName = componentList.get(componentList.size() - 1).getName(); - Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); - - loopPlugin.execute(postTestParserPluginContext); - Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); - for(int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) - { - TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); - Assert.assertEquals(TEST_OF_INTEREST_NAME + " [iteration " + iterationNumber +" of " + ITERATION_COUNT + "]", iterationTestScript.getName()); - System.out.println(iterationTestScript.getName()); - } - } + @Test + public void testExecute() throws Exception { + LoopPlugin loopPlugin = new LoopPlugin(AutomationEngine.getInstance()); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + Assert.assertEquals(1, testSuite.getComponentList().size()); + + List componentList = testSuite.getComponentList(); + String originalTestName = componentList.get(componentList.size() - 1).getName(); + Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); + + loopPlugin.execute(postTestParserPluginContext); + Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); + for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { + TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); + Assert.assertEquals(TEST_OF_INTEREST_NAME + " [iteration " + iterationNumber + " of " + ITERATION_COUNT + "]", iterationTestScript.getName()); + System.out.println(iterationTestScript.getName()); + } + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java index 664fab5..cf6394c 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java @@ -14,39 +14,34 @@ import org.w3c.dom.NodeList; -public class MaxThreadsPluginTest -{ - private static final String MAX_THREADS_NAME = "maxThreads"; - private static final String MAX_THREADS_TEST_STRATEGY_FILE = "MaxThreadsTestStrategy.strategy.xml"; - private static final int DEFAULT_THREAD_COUNT = 1; - private static final int FILE_THREAD_COUNT = 3; - - @Test - public void testExecute() throws Exception - { - TestAgenda testAgenda = new TestAgenda(); - Assert.assertEquals(DEFAULT_THREAD_COUNT, testAgenda.getThreadCount()); - MaxThreadsPlugin maxThreadsPlugin = new MaxThreadsPlugin(); - Element element = buildElement(); - PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); - maxThreadsPlugin.execute(postStrategyParserPluginContext); - Assert.assertEquals(FILE_THREAD_COUNT, testAgenda.getThreadCount()); - } +public class MaxThreadsPluginTest { + private static final String MAX_THREADS_NAME = "maxThreads"; + private static final String MAX_THREADS_TEST_STRATEGY_FILE = "MaxThreadsTestStrategy.strategy.xml"; + private static final int DEFAULT_THREAD_COUNT = 1; + private static final int FILE_THREAD_COUNT = 3; - private Element buildElement() throws Exception - { - InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(MAX_THREADS_TEST_STRATEGY_FILE); - Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList nodeList = executeRoot.getChildNodes(); - Element element = null; - for(int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) - { - Node node = nodeList.item(nodeIndex); - if(node.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) - { - element = (Element) node; - } - } - return element; - } + @Test + public void testExecute() throws Exception { + TestAgenda testAgenda = new TestAgenda(); + Assert.assertEquals(DEFAULT_THREAD_COUNT, testAgenda.getThreadCount()); + MaxThreadsPlugin maxThreadsPlugin = new MaxThreadsPlugin(); + Element element = buildElement(); + PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); + maxThreadsPlugin.execute(postStrategyParserPluginContext); + Assert.assertEquals(FILE_THREAD_COUNT, testAgenda.getThreadCount()); + } + + private Element buildElement() throws Exception { + InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(MAX_THREADS_TEST_STRATEGY_FILE); + Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList nodeList = executeRoot.getChildNodes(); + Element element = null; + for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { + Node node = nodeList.item(nodeIndex); + if (node.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { + element = (Element) node; + } + } + return element; + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java index 5dd851b..8781655 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java @@ -14,31 +14,26 @@ import org.w3c.dom.NodeList; -public abstract class ParserPluginTest -{ - protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception - { - Node testRoot = null; - InputStream inputStream = new FileInputStream(scriptFileName); - Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); - for(int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) - { - Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); - if(suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent().equals(testOfInterestName)) - { - testRoot = suiteNodeChildNode; - break; - } - } - return testRoot; - } +public abstract class ParserPluginTest { + protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { + Node testRoot = null; + InputStream inputStream = new FileInputStream(scriptFileName); + Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); + for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { + Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); + if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent().equals(testOfInterestName)) { + testRoot = suiteNodeChildNode; + break; + } + } + return testRoot; + } - protected TestSuite buildTestSuite(Node testRoot) throws Exception - { - TestSuite testSuite = new TestSuite("dummy test suite"); - TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript((Element) testRoot, new MessageCollector()); - testSuite.add(testScript); - return testSuite; - } + protected TestSuite buildTestSuite(Node testRoot) throws Exception { + TestSuite testSuite = new TestSuite("dummy test suite"); + TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript((Element) testRoot, new MessageCollector()); + testSuite.add(testScript); + return testSuite; + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java b/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java index 37af95b..3a10d56 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java +++ b/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java @@ -14,43 +14,39 @@ import org.junit.Assert; import org.junit.Test; -public class ScriptParserTests -{ - private static final String SCRIPT_FILE_NAME = "EveryTagSuite.xml"; - - - private static final String MISSING_FILE_NAME = "ThisFileDoesNotExist.xml"; - private static final String DUPLICATE_TEST_FILE_NAME = "parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml"; - - @Test - public void testHandleTestSource() throws Exception - { - DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/every_tag/" + SCRIPT_FILE_NAME).getDocumentElement(); +public class ScriptParserTests { + private static final String SCRIPT_FILE_NAME = "EveryTagSuite.xml"; + + + private static final String MISSING_FILE_NAME = "ThisFileDoesNotExist.xml"; + private static final String DUPLICATE_TEST_FILE_NAME = "parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml"; + + @Test + public void testHandleTestSource() throws Exception { + DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/every_tag/" + SCRIPT_FILE_NAME).getDocumentElement(); // TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - TestNamespace fileNameSpace = AutomationEngine.getInstance().getScriptParser().handleTestSource(new File("parser_testing/every_tag"), new MessageCollector()); - TestSuite testSuite = (TestSuite) fileNameSpace.getComponentList().get(0); - TestScript testScript = (TestScript) testSuite.getComponentList().get(0); - - Assert.assertEquals("Test with Every Tag", testScript.getName()); - Assert.assertEquals("Some issue", testScript.getIssue()); - Assert.assertEquals(1, testScript.getCRs().size()); - Assert.assertEquals("cr123", testScript.getCRs().get(0)); - Assert.assertEquals("Some coverage", testScript.getCoverage()); - - InvocationList invocationList = testScript.getBody(); - Assert.assertEquals(1, invocationList.size()); - Assert.assertEquals("TryRecoverCleanup", invocationList.get(0).getTargetName()); - } - - @Test(expected = FileNotFoundException.class) - public void testHandleTestSourceNoFile() throws Exception - { - (new ScriptParser()).handleTestSource(new File(MISSING_FILE_NAME), new MessageCollector()); - } - - @Test - public void testhandleTestSourceDuplicateTestName() throws Exception - { - (new ScriptParser()).handleTestSource(new File(DUPLICATE_TEST_FILE_NAME), new MessageCollector()); - } + TestNamespace fileNameSpace = AutomationEngine.getInstance().getScriptParser().handleTestSource(new File("parser_testing/every_tag"), new MessageCollector()); + TestSuite testSuite = (TestSuite) fileNameSpace.getComponentList().get(0); + TestScript testScript = (TestScript) testSuite.getComponentList().get(0); + + Assert.assertEquals("Test with Every Tag", testScript.getName()); + Assert.assertEquals("Some issue", testScript.getIssue()); + Assert.assertEquals(1, testScript.getCRs().size()); + Assert.assertEquals("cr123", testScript.getCRs().get(0)); + Assert.assertEquals("Some coverage", testScript.getCoverage()); + + InvocationList invocationList = testScript.getBody(); + Assert.assertEquals(1, invocationList.size()); + Assert.assertEquals("TryRecoverCleanup", invocationList.get(0).getTargetName()); + } + + @Test(expected = FileNotFoundException.class) + public void testHandleTestSourceNoFile() throws Exception { + (new ScriptParser()).handleTestSource(new File(MISSING_FILE_NAME), new MessageCollector()); + } + + @Test + public void testhandleTestSourceDuplicateTestName() throws Exception { + (new ScriptParser()).handleTestSource(new File(DUPLICATE_TEST_FILE_NAME), new MessageCollector()); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java b/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java index 3f1cf91..318eb1c 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java @@ -20,145 +20,125 @@ import org.w3c.dom.NodeList; // Only handles cases not covered by other tests -public class StatementParserTest -{ - private static final String TEST_ELEMENT = "test"; - private static final String TEST_STEPS_ELEMENT = "teststeps"; - private static final String TRY_RECOVER_CLEANUP_NAME = "TryRecoverCleanup"; - private static final String NAME_ATTRIBUTE = "name"; - private static final String FILE_NAME = "parser_testing/StatementParserTesting.xml"; - - private static final String NO_TEST_STEPS_SCRIPT_NAME = "No test steps"; - private static final String ONE_TEST_STEP_SCRIPT_NAME = "One test step"; - private static final String TRY_RECOVER_BLOCKS_SCRIPT_NAME = "Only try and recover at top level"; - private static final String RECOVER_FIRST_BLOCK_SCRIPT_NAME = "Only recover at top level"; - private static final String CLEANUP_FIRST_BLOCK_SCRIPT_NAME = "Only cleanup at top level"; - private static final String EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME = "Empty TryRecoverCleanup"; - private static final String BLOCK_PARAM_EXCEPTION_SCRIPT_NAME = "Block parameter has parsing exception"; - private static final String LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME = "List parameter has no parsing exception"; - private static final String LIST_PARAM_EXCEPTION_SCRIPT_NAME = "List parameter has parsing exception"; - - private static DocumentBuilder documentBuilder = null; - - private StatementParser statementParser = null; - - @BeforeClass - public static void beforeClass() throws Exception - { - documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } - - @Before - public void before() - { - statementParser = new StatementParser(); - } - - @Test - public void testProcessStatementListNoTestSteps() throws Exception - { - Element testElement = getTestStepsElement(NO_TEST_STEPS_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(0, invocationList.size()); - } - - @Test - public void testProcessStatementListOneTestStep() throws Exception - { - Element testElement = getTestStepsElement(ONE_TEST_STEP_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - } - - @Test - public void testProcessStatementListTryRecoverFirstBlocks() throws Exception - { - Element testElement = getTestStepsElement(TRY_RECOVER_BLOCKS_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - } - - @Test(expected = UnexpectedElementException.class) - public void testProcessStatementListRecoverFirstBlock() throws Exception - { - Element testElement = getTestStepsElement(RECOVER_FIRST_BLOCK_SCRIPT_NAME); - statementParser.processStatementList(testElement, new MessageCollector()); - } - - @Test(expected = UnexpectedElementException.class) - public void testProcessStatementListCleanupFirstBlock() throws Exception - { - Element testElement = getTestStepsElement(CLEANUP_FIRST_BLOCK_SCRIPT_NAME); - statementParser.processStatementList(testElement, new MessageCollector()); - } - - @Test - public void testProcessStatementListEmptyTryRecoverCleanup() throws Exception - { - Element testElement = getTestStepsElement(EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - Assert.assertEquals(TRY_RECOVER_CLEANUP_NAME, invocationList.get(0).getTargetName()); - } - - // this also covers the case of a map parameter having a parsing exception - @Test - public void testProcessStatementListInvocationBlockParameterHasException() throws Exception - { - Element testElement = getTestStepsElement(BLOCK_PARAM_EXCEPTION_SCRIPT_NAME); - try - { - statementParser.processStatementList(testElement, new MessageCollector()); - } - catch(ParsingException parsingException) - { - ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; - ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); - String message = "The element 'string' is missing the required attribute 'name'"; - Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); - } - } - - @Test - public void testProcessStatementListInvocationListParameterHasNoException() throws Exception - { - Element testElement = getTestStepsElement(LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Object listParameter = invocationList.get(0).getParameters().get("listParameter"); - Assert.assertNotNull(listParameter); - Assert.assertTrue(listParameter instanceof List); - } - - @Test - public void testProcessStatementListInvocationListParameterHasException() throws Exception - { - Element testElement = getTestStepsElement(LIST_PARAM_EXCEPTION_SCRIPT_NAME); - try - { - statementParser.processStatementList(testElement, new MessageCollector()); - } - catch(ParsingException parsingException) - { - ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; - ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); - String message = "The element 'string' is missing the required attribute 'name'"; - Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); - } - } - - protected Element getTestStepsElement(String testName) throws Exception - { - Element documentElement = documentBuilder.parse(FILE_NAME).getDocumentElement(); - NodeList childNodes = documentElement.getChildNodes(); - for(int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) - { - Node testNode = childNodes.item(childNodeIndex); - if(!testNode.getNodeName().equalsIgnoreCase(TEST_ELEMENT)) - continue; - if(!testNode.getAttributes().getNamedItem(NAME_ATTRIBUTE).getTextContent().equals(testName)) - continue; - return ParserHelper.getFirstChildElementCaseInsensitive((Element) testNode, TEST_STEPS_ELEMENT); - } - return null; - } +public class StatementParserTest { + private static final String TEST_ELEMENT = "test"; + private static final String TEST_STEPS_ELEMENT = "teststeps"; + private static final String TRY_RECOVER_CLEANUP_NAME = "TryRecoverCleanup"; + private static final String NAME_ATTRIBUTE = "name"; + private static final String FILE_NAME = "parser_testing/StatementParserTesting.xml"; + + private static final String NO_TEST_STEPS_SCRIPT_NAME = "No test steps"; + private static final String ONE_TEST_STEP_SCRIPT_NAME = "One test step"; + private static final String TRY_RECOVER_BLOCKS_SCRIPT_NAME = "Only try and recover at top level"; + private static final String RECOVER_FIRST_BLOCK_SCRIPT_NAME = "Only recover at top level"; + private static final String CLEANUP_FIRST_BLOCK_SCRIPT_NAME = "Only cleanup at top level"; + private static final String EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME = "Empty TryRecoverCleanup"; + private static final String BLOCK_PARAM_EXCEPTION_SCRIPT_NAME = "Block parameter has parsing exception"; + private static final String LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME = "List parameter has no parsing exception"; + private static final String LIST_PARAM_EXCEPTION_SCRIPT_NAME = "List parameter has parsing exception"; + + private static DocumentBuilder documentBuilder = null; + + private StatementParser statementParser = null; + + @BeforeClass + public static void beforeClass() throws Exception { + documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } + + @Before + public void before() { + statementParser = new StatementParser(); + } + + @Test + public void testProcessStatementListNoTestSteps() throws Exception { + Element testElement = getTestStepsElement(NO_TEST_STEPS_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(0, invocationList.size()); + } + + @Test + public void testProcessStatementListOneTestStep() throws Exception { + Element testElement = getTestStepsElement(ONE_TEST_STEP_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + } + + @Test + public void testProcessStatementListTryRecoverFirstBlocks() throws Exception { + Element testElement = getTestStepsElement(TRY_RECOVER_BLOCKS_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + } + + @Test(expected = UnexpectedElementException.class) + public void testProcessStatementListRecoverFirstBlock() throws Exception { + Element testElement = getTestStepsElement(RECOVER_FIRST_BLOCK_SCRIPT_NAME); + statementParser.processStatementList(testElement, new MessageCollector()); + } + + @Test(expected = UnexpectedElementException.class) + public void testProcessStatementListCleanupFirstBlock() throws Exception { + Element testElement = getTestStepsElement(CLEANUP_FIRST_BLOCK_SCRIPT_NAME); + statementParser.processStatementList(testElement, new MessageCollector()); + } + + @Test + public void testProcessStatementListEmptyTryRecoverCleanup() throws Exception { + Element testElement = getTestStepsElement(EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + Assert.assertEquals(TRY_RECOVER_CLEANUP_NAME, invocationList.get(0).getTargetName()); + } + + // this also covers the case of a map parameter having a parsing exception + @Test + public void testProcessStatementListInvocationBlockParameterHasException() throws Exception { + Element testElement = getTestStepsElement(BLOCK_PARAM_EXCEPTION_SCRIPT_NAME); + try { + statementParser.processStatementList(testElement, new MessageCollector()); + } catch (ParsingException parsingException) { + ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; + ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); + String message = "The element 'string' is missing the required attribute 'name'"; + Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); + } + } + + @Test + public void testProcessStatementListInvocationListParameterHasNoException() throws Exception { + Element testElement = getTestStepsElement(LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Object listParameter = invocationList.get(0).getParameters().get("listParameter"); + Assert.assertNotNull(listParameter); + Assert.assertTrue(listParameter instanceof List); + } + + @Test + public void testProcessStatementListInvocationListParameterHasException() throws Exception { + Element testElement = getTestStepsElement(LIST_PARAM_EXCEPTION_SCRIPT_NAME); + try { + statementParser.processStatementList(testElement, new MessageCollector()); + } catch (ParsingException parsingException) { + ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; + ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); + String message = "The element 'string' is missing the required attribute 'name'"; + Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); + } + } + + protected Element getTestStepsElement(String testName) throws Exception { + Element documentElement = documentBuilder.parse(FILE_NAME).getDocumentElement(); + NodeList childNodes = documentElement.getChildNodes(); + for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { + Node testNode = childNodes.item(childNodeIndex); + if (!testNode.getNodeName().equalsIgnoreCase(TEST_ELEMENT)) + continue; + if (!testNode.getAttributes().getNamedItem(NAME_ATTRIBUTE).getTextContent().equals(testName)) + continue; + return ParserHelper.getFirstChildElementCaseInsensitive((Element) testNode, TEST_STEPS_ELEMENT); + } + return null; + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java index 3c8979e..9e465e8 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java @@ -12,43 +12,39 @@ import org.w3c.dom.Element; -public class SuiteDependenciesPluginTest extends ParserPluginTest -{ - private static final String TAG_NAME = "dependencies"; - private static final String SCRIPT_FILE_NAME = "SuiteDependencyParserTest.xml"; - private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteDependency.xml"; - private static final String DEPENDENT_SUITE_NAME = "JTAF CORE"; - private static final String DEPENDENT_TEST_NAME = "Block Testing"; - - @Test() - public void testExecute() throws Exception - { - SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteDependenciesPlugin.execute(postSuiteParserPluginContext); - - Assert.assertEquals(1, testSuite.getDependencies().getDependenciesSuites().size()); - Assert.assertTrue(testSuite.getDependencies().getDependenciesSuites().contains(DEPENDENT_SUITE_NAME)); - - Assert.assertEquals(1, testSuite.getDependencies().getDependenciesTests().size()); - Assert.assertTrue(testSuite.getDependencies().getDependenciesTests().contains(DEPENDENT_TEST_NAME)); - } - - @Test(expected = ParserPluginException.class) - public void testExecuteUnexpectedElement() throws Exception - { - SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteDependenciesPlugin.execute(postSuiteParserPluginContext); - } - - @Test - public void testGetTagName() - { - Assert.assertEquals(TAG_NAME, new SuiteDependenciesPlugin().getTagName()); - } +public class SuiteDependenciesPluginTest extends ParserPluginTest { + private static final String TAG_NAME = "dependencies"; + private static final String SCRIPT_FILE_NAME = "SuiteDependencyParserTest.xml"; + private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteDependency.xml"; + private static final String DEPENDENT_SUITE_NAME = "JTAF CORE"; + private static final String DEPENDENT_TEST_NAME = "Block Testing"; + + @Test() + public void testExecute() throws Exception { + SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteDependenciesPlugin.execute(postSuiteParserPluginContext); + + Assert.assertEquals(1, testSuite.getDependencies().getDependenciesSuites().size()); + Assert.assertTrue(testSuite.getDependencies().getDependenciesSuites().contains(DEPENDENT_SUITE_NAME)); + + Assert.assertEquals(1, testSuite.getDependencies().getDependenciesTests().size()); + Assert.assertTrue(testSuite.getDependencies().getDependenciesTests().contains(DEPENDENT_TEST_NAME)); + } + + @Test(expected = ParserPluginException.class) + public void testExecuteUnexpectedElement() throws Exception { + SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteDependenciesPlugin.execute(postSuiteParserPluginContext); + } + + @Test + public void testGetTagName() { + Assert.assertEquals(TAG_NAME, new SuiteDependenciesPlugin().getTagName()); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java index b631967..d63257a 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java @@ -12,43 +12,39 @@ import org.w3c.dom.Element; -public class SuiteExclusionsPluginTest extends ParserPluginTest -{ - private static final String TAG_NAME = "exclusions"; - private static final String SCRIPT_FILE_NAME = "SuiteExclusionParserTest.xml"; - private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteExclusion.xml"; - private static final String EXCLUSION_SUITE_NAME = "JTAF CORE"; - private static final String EXCLUSION_TEST_NAME = "Block Testing"; - - @Test() - public void testExecute() throws Exception - { - SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteExclusionsPlugin.execute(postSuiteParserPluginContext); - - Assert.assertEquals(1, testSuite.getExclusions().getDependenciesSuites().size()); - Assert.assertTrue(testSuite.getExclusions().getDependenciesSuites().contains(EXCLUSION_SUITE_NAME)); - - Assert.assertEquals(1, testSuite.getExclusions().getDependenciesTests().size()); - Assert.assertTrue(testSuite.getExclusions().getDependenciesTests().contains(EXCLUSION_TEST_NAME)); - } - - @Test(expected = ParserPluginException.class) - public void testExecuteUnexpectedElement() throws Exception - { - SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteExclusionsPlugin.execute(postSuiteParserPluginContext); - } - - @Test - public void testGetTagName() - { - Assert.assertEquals(TAG_NAME, new SuiteExclusionsPlugin().getTagName()); - } +public class SuiteExclusionsPluginTest extends ParserPluginTest { + private static final String TAG_NAME = "exclusions"; + private static final String SCRIPT_FILE_NAME = "SuiteExclusionParserTest.xml"; + private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteExclusion.xml"; + private static final String EXCLUSION_SUITE_NAME = "JTAF CORE"; + private static final String EXCLUSION_TEST_NAME = "Block Testing"; + + @Test() + public void testExecute() throws Exception { + SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteExclusionsPlugin.execute(postSuiteParserPluginContext); + + Assert.assertEquals(1, testSuite.getExclusions().getDependenciesSuites().size()); + Assert.assertTrue(testSuite.getExclusions().getDependenciesSuites().contains(EXCLUSION_SUITE_NAME)); + + Assert.assertEquals(1, testSuite.getExclusions().getDependenciesTests().size()); + Assert.assertTrue(testSuite.getExclusions().getDependenciesTests().contains(EXCLUSION_TEST_NAME)); + } + + @Test(expected = ParserPluginException.class) + public void testExecuteUnexpectedElement() throws Exception { + SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteExclusionsPlugin.execute(postSuiteParserPluginContext); + } + + @Test + public void testGetTagName() { + Assert.assertEquals(TAG_NAME, new SuiteExclusionsPlugin().getTagName()); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java index 5f2e07a..f8b47dd 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java @@ -13,35 +13,32 @@ import org.w3c.dom.Node; -public class TestDataPluginTest extends ParserPluginTest -{ - private static final String SCRIPT_FILE_NAME = "testscripts/TestDataDebug.xml"; - private static final String TEST_OF_INTEREST_NAME = "TestData Debug Test"; - private static final int ITERATION_COUNT = 4; - private static final String[] TEST_NAMES_FROM_DATA_FILE = new String[] {"Print XYZ", "Print ABC", "Print 123", "Print 456"}; - - @Test - public void testExecute() throws Exception - { +public class TestDataPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/TestDataDebug.xml"; + private static final String TEST_OF_INTEREST_NAME = "TestData Debug Test"; + private static final int ITERATION_COUNT = 4; + private static final String[] TEST_NAMES_FROM_DATA_FILE = new String[]{"Print XYZ", "Print ABC", "Print 123", "Print 456"}; + + @Test + public void testExecute() throws Exception { // LoopPlugin loopPlugin = new LoopPlugin(); - TestDataPlugin testDataPlugin = new TestDataPlugin(AutomationEngine.getInstance()); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - Assert.assertEquals(1, testSuite.getComponentList().size()); + TestDataPlugin testDataPlugin = new TestDataPlugin(AutomationEngine.getInstance()); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + Assert.assertEquals(1, testSuite.getComponentList().size()); + + List componentList = testSuite.getComponentList(); + String originalTestName = componentList.get(componentList.size() - 1).getName(); + Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); - List componentList = testSuite.getComponentList(); - String originalTestName = componentList.get(componentList.size() - 1).getName(); - Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); - - testDataPlugin.execute(postTestParserPluginContext); - Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); - for(int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) - { - TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); - String testNameFromDataFile = TEST_NAMES_FROM_DATA_FILE[iterationNumber - 1]; - Assert.assertEquals(TEST_OF_INTEREST_NAME + " [data file row #" + iterationNumber +"] ; testNameFromDataFile-" + testNameFromDataFile, iterationTestScript.getName()); - System.out.println(iterationTestScript.getName()); - } - } + testDataPlugin.execute(postTestParserPluginContext); + Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); + for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { + TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); + String testNameFromDataFile = TEST_NAMES_FROM_DATA_FILE[iterationNumber - 1]; + Assert.assertEquals(TEST_OF_INTEREST_NAME + " [data file row #" + iterationNumber + "] ; testNameFromDataFile-" + testNameFromDataFile, iterationTestScript.getName()); + System.out.println(iterationTestScript.getName()); + } + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java index 20c067f..eeb97e2 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java @@ -13,27 +13,25 @@ import org.w3c.dom.Node; -public class TestDependenciesPluginTest extends ParserPluginTest -{ - private static final String SCRIPT_FILE_NAME = "testscripts/DependencyTest.xml"; - private static final String TEST_OF_INTEREST_NAME = "Dependency Plugin Debug Test F"; - private static final String TEST_DEPENDENCY_1 = "Dependency Plugin Debug Test C"; - private static final String TEST_DEPENDENCY_2 = "Dependency Plugin Debug Test D"; - - @Test - public void testExecute() throws Exception - { - TestDependenciesPlugin testDependenciesPlugin = new TestDependenciesPlugin(); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - testDependenciesPlugin.execute(postTestParserPluginContext); - - List componentList = testSuite.getComponentList(); - TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); - Dependencies dependencies = latestTestScript.getDependencies(); - Assert.assertEquals(2, dependencies.getDependenciesTests().size()); - Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_1)); - Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_2)); - } +public class TestDependenciesPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/DependencyTest.xml"; + private static final String TEST_OF_INTEREST_NAME = "Dependency Plugin Debug Test F"; + private static final String TEST_DEPENDENCY_1 = "Dependency Plugin Debug Test C"; + private static final String TEST_DEPENDENCY_2 = "Dependency Plugin Debug Test D"; + + @Test + public void testExecute() throws Exception { + TestDependenciesPlugin testDependenciesPlugin = new TestDependenciesPlugin(); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + testDependenciesPlugin.execute(postTestParserPluginContext); + + List componentList = testSuite.getComponentList(); + TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); + Dependencies dependencies = latestTestScript.getDependencies(); + Assert.assertEquals(2, dependencies.getDependenciesTests().size()); + Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_1)); + Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_2)); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java index fb05e16..04ce67b 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java @@ -13,27 +13,25 @@ import org.w3c.dom.Node; -public class TestExclusionsPluginTest extends ParserPluginTest -{ - private static final String SCRIPT_FILE_NAME = "testscripts/ExclusionTest.xml"; - private static final String TEST_OF_INTEREST_NAME = "Exclusion Plugin Debug Test F"; - private static final String TEST_EXCLUSION_1 = "Exclusion Plugin Debug Test C"; - private static final String TEST_EXCLUSION_2 = "Exclusion Plugin Debug Test D"; - - @Test - public void testExecute() throws Exception - { - TestExclusionsPlugin testExclusionsPlugin = new TestExclusionsPlugin(); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - testExclusionsPlugin.execute(postTestParserPluginContext); - - List componentList = testSuite.getComponentList(); - TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); - Dependencies exclusions = latestTestScript.getExclusions(); - Assert.assertEquals(2, exclusions.getDependenciesTests().size()); - Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_1)); - Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_2)); - } +public class TestExclusionsPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/ExclusionTest.xml"; + private static final String TEST_OF_INTEREST_NAME = "Exclusion Plugin Debug Test F"; + private static final String TEST_EXCLUSION_1 = "Exclusion Plugin Debug Test C"; + private static final String TEST_EXCLUSION_2 = "Exclusion Plugin Debug Test D"; + + @Test + public void testExecute() throws Exception { + TestExclusionsPlugin testExclusionsPlugin = new TestExclusionsPlugin(); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + testExclusionsPlugin.execute(postTestParserPluginContext); + + List componentList = testSuite.getComponentList(); + TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); + Dependencies exclusions = latestTestScript.getExclusions(); + Assert.assertEquals(2, exclusions.getDependenciesTests().size()); + Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_1)); + Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_2)); + } } diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java index 2e9d0be..f5540b3 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java @@ -8,29 +8,25 @@ import org.junit.Before; import org.junit.Test; -public class TestStrategyParserTest -{ - private static final String INVALID_ROOT_STRATEGY_FILE_NAME = "parser_testing/InvalidRoot.strategy.xml"; - private static final String MISSING_TARGET_NAME_STRATEGY_FILE_NAME = "parser_testing/MissingTargetNameAttribute.strategy.xml"; - - private TestStrategyParser testStrategyParser; - - @Before - public void before() throws Exception - { - testStrategyParser = new TestStrategyParser(); - testStrategyParser.setPostParseStrategyElementPlugins(new ArrayList()); - } - - @Test(expected = UnexpectedElementException.class) - public void testParseInvalidRoot() throws Exception - { - testStrategyParser.parse(new File(INVALID_ROOT_STRATEGY_FILE_NAME)); - } - - @Test - public void testParseMissingTargetName() throws Exception - { - testStrategyParser.parse(new File(MISSING_TARGET_NAME_STRATEGY_FILE_NAME)); - } +public class TestStrategyParserTest { + private static final String INVALID_ROOT_STRATEGY_FILE_NAME = "parser_testing/InvalidRoot.strategy.xml"; + private static final String MISSING_TARGET_NAME_STRATEGY_FILE_NAME = "parser_testing/MissingTargetNameAttribute.strategy.xml"; + + private TestStrategyParser testStrategyParser; + + @Before + public void before() throws Exception { + testStrategyParser = new TestStrategyParser(); + testStrategyParser.setPostParseStrategyElementPlugins(new ArrayList()); + } + + @Test(expected = UnexpectedElementException.class) + public void testParseInvalidRoot() throws Exception { + testStrategyParser.parse(new File(INVALID_ROOT_STRATEGY_FILE_NAME)); + } + + @Test + public void testParseMissingTargetName() throws Exception { + testStrategyParser.parse(new File(MISSING_TARGET_NAME_STRATEGY_FILE_NAME)); + } } diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java index 0ffc23e..8077cbe 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java @@ -9,30 +9,30 @@ public class DummyCommandRunnerPlugin implements ICommandRunnerPlugin { - CommandRunnerPluginContext before; - CommandRunnerPluginContext after; - - @Override - public void handleCommandBefore(CommandRunnerPluginContext args) - throws RunnerPluginException { - - before=args; - if(before.getTestStepsDetails().getName().equals("mockstep2")) - Assert.assertEquals(false,MockCommand2.testEnd); - - } - - @Override - public void handleCommandAfter(CommandRunnerPluginContext args) - throws RunnerPluginException { - after=args; - if(before.getTestStepsDetails().getName().equals("mockstep2")){ - Assert.assertEquals(true,MockCommand2.testEnd); - - } - - if(after.getTestStepsDetails().getName().equals("mockstep1")) - Assert.assertEquals(true, after.getTestStepsDetails().getActualResult()); - } + CommandRunnerPluginContext before; + CommandRunnerPluginContext after; + + @Override + public void handleCommandBefore(CommandRunnerPluginContext args) + throws RunnerPluginException { + + before = args; + if (before.getTestStepsDetails().getName().equals("mockstep2")) + Assert.assertEquals(false, MockCommand2.testEnd); + + } + + @Override + public void handleCommandAfter(CommandRunnerPluginContext args) + throws RunnerPluginException { + after = args; + if (before.getTestStepsDetails().getName().equals("mockstep2")) { + Assert.assertEquals(true, MockCommand2.testEnd); + + } + + if (after.getTestStepsDetails().getName().equals("mockstep1")) + Assert.assertEquals(true, after.getTestStepsDetails().getActualResult()); + } } diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java index 769eae9..fa9f17e 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java @@ -10,33 +10,33 @@ */ public class DummyTestRunnerPlugin implements ITestRunnerPlugin { - TestRunnerPluginContext argsBefore; - TestRunnerPluginContext argsAfter; - - @Override - public void handleTestStart(TestRunnerPluginContext args) - throws RunnerPluginException { - argsBefore = new TestRunnerPluginContext(null, null, null); - argsBefore = args; - - } - - @Override - public void handleTestFinish(TestRunnerPluginContext args) - throws RunnerPluginException { - argsAfter = new TestRunnerPluginContext(null, null, null); - argsAfter = args; - try{ - if(argsAfter.getTestResult().getTestStepsDetails().size()>0){ - if(argsAfter.getTestResult().getTestStepsDetails().get(0).getName().equalsIgnoreCase("mockstep2")) - throw new RunnerPluginException("Testing Plugin Exceptions"); - } - - }catch(RunnerPluginException e){ - throw new RunnerPluginException("Plugin Exception", e); - } - - - } + TestRunnerPluginContext argsBefore; + TestRunnerPluginContext argsAfter; + + @Override + public void handleTestStart(TestRunnerPluginContext args) + throws RunnerPluginException { + argsBefore = new TestRunnerPluginContext(null, null, null); + argsBefore = args; + + } + + @Override + public void handleTestFinish(TestRunnerPluginContext args) + throws RunnerPluginException { + argsAfter = new TestRunnerPluginContext(null, null, null); + argsAfter = args; + try { + if (argsAfter.getTestResult().getTestStepsDetails().size() > 0) { + if (argsAfter.getTestResult().getTestStepsDetails().get(0).getName().equalsIgnoreCase("mockstep2")) + throw new RunnerPluginException("Testing Plugin Exceptions"); + } + + } catch (RunnerPluginException e) { + throw new RunnerPluginException("Plugin Exception", e); + } + + + } } diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java b/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java index b9308cf..a186d77 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java @@ -19,161 +19,161 @@ public class ExecutionPluginsTest { - private Command c1; - private Command c2; - private CommandRegistry cmdReg; - private Interpreter iv; - - private DummyTestRunnerPlugin dummyTestPlugin; - private DummyCommandRunnerPlugin dummyCommandPlugin; - private Invocation stmt; - private InvocationList statements; - private TestResult tr; - private IAutomationClassLoader automationClassLoader = new DefaultAutomationClassLoader(); - - private void setUpCommands() throws Throwable { - Class targetClass1 = automationClassLoader - .loadClass("org.finra.jtaf.core.mock.MockCommand1"); - Constructor constructor = targetClass1.getConstructor(String.class); - c1 = (Command) constructor.newInstance("mockstep1"); - - Class targetClass2 = automationClassLoader - .loadClass("org.finra.jtaf.core.mock.MockCommand2"); - Constructor constructor2 = targetClass2.getConstructor(String.class); - c2 = (Command) constructor2.newInstance("mockstep2"); - - } - - public void setUpRegistry() throws Throwable { - cmdReg = new CommandRegistry(); - cmdReg.registerInvocationTarget("mockstep1", c1); - cmdReg.registerInvocationTarget("mockstep2", c2); - } - - private void setupInterpreter(CommandRegistry cr) - throws NameFormatException { - dummyTestPlugin = new DummyTestRunnerPlugin(); - dummyCommandPlugin = new DummyCommandRunnerPlugin(); - List testRunnerPlugins = new ArrayList(); - testRunnerPlugins.add(dummyTestPlugin); - - List commandRunnerPlugins = new ArrayList(); - commandRunnerPlugins.add(dummyCommandPlugin); - - iv = new Interpreter(); - iv.setCommandRegistry(cr); - iv.setTestRunnerPlugins(testRunnerPlugins); - iv.setCommandRunnerPlugins(commandRunnerPlugins); - - } - - @Test - /* Test Success and Command Success */ - public void pluginCallbacksForTestSuccess() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts1 = new TestScript("DummyScript1", false); - stmt = new Invocation(c2.getName()); - statements = new InvocationList(); - statements.add(stmt); - - ts1.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts1); - } catch (Throwable e) { - e.printStackTrace(); - } - - Assert.assertEquals("DummyScript1", dummyTestPlugin.argsBefore - .getTestScript().getName()); - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep2", dummyCommandPlugin.before - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.before - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Passed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsAfter.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep2", dummyCommandPlugin.after - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.after - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Passed", tr.getTestStatus().toString()); - } - - @Test + private Command c1; + private Command c2; + private CommandRegistry cmdReg; + private Interpreter iv; + + private DummyTestRunnerPlugin dummyTestPlugin; + private DummyCommandRunnerPlugin dummyCommandPlugin; + private Invocation stmt; + private InvocationList statements; + private TestResult tr; + private IAutomationClassLoader automationClassLoader = new DefaultAutomationClassLoader(); + + private void setUpCommands() throws Throwable { + Class targetClass1 = automationClassLoader + .loadClass("org.finra.jtaf.core.mock.MockCommand1"); + Constructor constructor = targetClass1.getConstructor(String.class); + c1 = (Command) constructor.newInstance("mockstep1"); + + Class targetClass2 = automationClassLoader + .loadClass("org.finra.jtaf.core.mock.MockCommand2"); + Constructor constructor2 = targetClass2.getConstructor(String.class); + c2 = (Command) constructor2.newInstance("mockstep2"); + + } + + public void setUpRegistry() throws Throwable { + cmdReg = new CommandRegistry(); + cmdReg.registerInvocationTarget("mockstep1", c1); + cmdReg.registerInvocationTarget("mockstep2", c2); + } + + private void setupInterpreter(CommandRegistry cr) + throws NameFormatException { + dummyTestPlugin = new DummyTestRunnerPlugin(); + dummyCommandPlugin = new DummyCommandRunnerPlugin(); + List testRunnerPlugins = new ArrayList(); + testRunnerPlugins.add(dummyTestPlugin); + + List commandRunnerPlugins = new ArrayList(); + commandRunnerPlugins.add(dummyCommandPlugin); + + iv = new Interpreter(); + iv.setCommandRegistry(cr); + iv.setTestRunnerPlugins(testRunnerPlugins); + iv.setCommandRunnerPlugins(commandRunnerPlugins); + + } + + @Test + /* Test Success and Command Success */ + public void pluginCallbacksForTestSuccess() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts1 = new TestScript("DummyScript1", false); + stmt = new Invocation(c2.getName()); + statements = new InvocationList(); + statements.add(stmt); + + ts1.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts1); + } catch (Throwable e) { + e.printStackTrace(); + } + + Assert.assertEquals("DummyScript1", dummyTestPlugin.argsBefore + .getTestScript().getName()); + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep2", dummyCommandPlugin.before + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.before + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Passed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsAfter.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep2", dummyCommandPlugin.after + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.after + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Passed", tr.getTestStatus().toString()); + } + + @Test /* Test Failure */ - public void pluginCallbacksForTestFailure1() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts2 = new TestScript("DummyScript2", false); - stmt = new Invocation("CommandDoesNotExist"); - statements = new InvocationList(); - statements.add(stmt); - ts2.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts2); - } catch (Throwable e) { - e.printStackTrace(); - } - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - - Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - - Assert.assertEquals("Failed", tr.getTestStatus().toString()); - } - - @Test + public void pluginCallbacksForTestFailure1() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts2 = new TestScript("DummyScript2", false); + stmt = new Invocation("CommandDoesNotExist"); + statements = new InvocationList(); + statements.add(stmt); + ts2.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts2); + } catch (Throwable e) { + e.printStackTrace(); + } + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + + Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + + Assert.assertEquals("Failed", tr.getTestStatus().toString()); + } + + @Test /* Test failure and Command failure */ - public void pluginCallbacksForTestFailure2() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts3 = new TestScript("DummyScript3", false); - stmt = new Invocation(c1.getName()); - statements = new InvocationList(); - statements.add(stmt); - ts3.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts3); - } catch (Throwable e) { - e.printStackTrace(); - } - - dummyTestPlugin.argsBefore.getIInvocationContext(); - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep1", dummyCommandPlugin.before - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.before - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep1", dummyCommandPlugin.after - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.after - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Failed", tr.getTestStatus().toString()); - } + public void pluginCallbacksForTestFailure2() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts3 = new TestScript("DummyScript3", false); + stmt = new Invocation(c1.getName()); + statements = new InvocationList(); + statements.add(stmt); + ts3.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts3); + } catch (Throwable e) { + e.printStackTrace(); + } + + dummyTestPlugin.argsBefore.getIInvocationContext(); + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep1", dummyCommandPlugin.before + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.before + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep1", dummyCommandPlugin.after + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.after + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Failed", tr.getTestStatus().toString()); + } } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java index 09d77d9..5225521 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java @@ -1,10 +1,8 @@ package org.finra.jtaf.core.plugins.execution; -public class TearDownTestPlugin implements ITearDownPlugin -{ - @Override - public void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException - { - tearDownPluginContext.getInvocationContext().getAllObjects().put("tearDownTestActualValue".toLowerCase(), "Test successful"); - } +public class TearDownTestPlugin implements ITearDownPlugin { + @Override + public void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException { + tearDownPluginContext.getInvocationContext().getAllObjects().put("tearDownTestActualValue".toLowerCase(), "Test successful"); + } } diff --git a/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java b/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java index 3d33823..52aa7ee 100644 --- a/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java @@ -13,51 +13,46 @@ import org.junit.Test; -public class TraceabilityMatrixPluginTest -{ - private File file; - - @Before - public void setup() - { - file = new File(TraceabilityMatrix.OUTPUT_FILE); - if(file.exists()) - file.delete(); - } - - @After - public void teardown() - { - file.delete(); - } - - // Only verify that the file was created. Content validation will be part of the TraceabilityMatrix unit test - @Test - public void testExecute() throws ParserPluginException - { - TestAgenda testAgenda = new TestAgenda(); - PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); - TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); - traceabilityMatrixPlugin.execute(postAllParserPluginContext); - Assert.assertTrue(file.exists()); - } - - @Test - public void testNoAutomationValue() throws ParserPluginException - { - try{ - TestStrategyParser tsp= new TestStrategyParser(); - TestAgenda ta = new TestAgenda(); - tsp.parse(new File(System.getProperty("user.dir") + "/profiles/strategies/test.strategy.xml")); - tsp.setDigraph(AutomationEngine.getInstance().getTestDigraph()); - ta = tsp.getTestPlan(); - PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(ta, null); - TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); - traceabilityMatrixPlugin.execute(postAllParserPluginContext); - Assert.assertTrue(file.exists()); - }catch (Exception e) { +public class TraceabilityMatrixPluginTest { + private File file; + + @Before + public void setup() { + file = new File(TraceabilityMatrix.OUTPUT_FILE); + if (file.exists()) + file.delete(); + } + + @After + public void teardown() { + file.delete(); + } + + // Only verify that the file was created. Content validation will be part of the TraceabilityMatrix unit test + @Test + public void testExecute() throws ParserPluginException { + TestAgenda testAgenda = new TestAgenda(); + PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); + TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); + traceabilityMatrixPlugin.execute(postAllParserPluginContext); + Assert.assertTrue(file.exists()); + } + + @Test + public void testNoAutomationValue() throws ParserPluginException { + try { + TestStrategyParser tsp = new TestStrategyParser(); + TestAgenda ta = new TestAgenda(); + tsp.parse(new File(System.getProperty("user.dir") + "/profiles/strategies/test.strategy.xml")); + tsp.setDigraph(AutomationEngine.getInstance().getTestDigraph()); + ta = tsp.getTestPlan(); + PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(ta, null); + TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); + traceabilityMatrixPlugin.execute(postAllParserPluginContext); + Assert.assertTrue(file.exists()); + } catch (Exception e) { throw new RuntimeException(e); } - - } + + } } diff --git a/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java b/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java index 453960c..bfaefef 100644 --- a/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java +++ b/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java @@ -3,39 +3,35 @@ import org.junit.Assert; import org.junit.Test; -public class JTAFPropertyManagerTests -{ - private static final String PRESET_SYSTEM_PROPERTY = "test.property.system"; - private static final String PRESET_SYSTEM_PROPERTY_VALUE = "preset system property value"; +public class JTAFPropertyManagerTests { + private static final String PRESET_SYSTEM_PROPERTY = "test.property.system"; + private static final String PRESET_SYSTEM_PROPERTY_VALUE = "preset system property value"; - private static final String FILE_PROPERTY = "test.property.file"; - private static final String FILE_PROPERTY_VALUE = "file property value"; // make sure to set in jtaf.properties also - - private static final String BOTH_PROPERTY = "test.property.both"; - private static final String BOTH_PROPERTY_VALUE_SYSTEM = "set in both (system)"; - private static final String BOTH_PROPERTY_VALUE_FILE = "set in both (file)"; - - @Test - public void testPresetSystemProperty() - { - System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + PRESET_SYSTEM_PROPERTY, PRESET_SYSTEM_PROPERTY_VALUE); - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(PRESET_SYSTEM_PROPERTY); - Assert.assertEquals(PRESET_SYSTEM_PROPERTY_VALUE, fetchedValue); - } - - @Test - public void testFileProperty() - { - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(FILE_PROPERTY); - Assert.assertEquals(FILE_PROPERTY_VALUE, fetchedValue); - } - - @Test - public void testPresetSystemPropertyAndFileProperty() - { - System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + BOTH_PROPERTY, BOTH_PROPERTY_VALUE_SYSTEM); - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(BOTH_PROPERTY); - Assert.assertFalse(BOTH_PROPERTY_VALUE_FILE.equals(fetchedValue)); - Assert.assertEquals(BOTH_PROPERTY_VALUE_SYSTEM, fetchedValue); - } + private static final String FILE_PROPERTY = "test.property.file"; + private static final String FILE_PROPERTY_VALUE = "file property value"; // make sure to set in jtaf.properties also + + private static final String BOTH_PROPERTY = "test.property.both"; + private static final String BOTH_PROPERTY_VALUE_SYSTEM = "set in both (system)"; + private static final String BOTH_PROPERTY_VALUE_FILE = "set in both (file)"; + + @Test + public void testPresetSystemProperty() { + System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + PRESET_SYSTEM_PROPERTY, PRESET_SYSTEM_PROPERTY_VALUE); + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(PRESET_SYSTEM_PROPERTY); + Assert.assertEquals(PRESET_SYSTEM_PROPERTY_VALUE, fetchedValue); + } + + @Test + public void testFileProperty() { + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(FILE_PROPERTY); + Assert.assertEquals(FILE_PROPERTY_VALUE, fetchedValue); + } + + @Test + public void testPresetSystemPropertyAndFileProperty() { + System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + BOTH_PROPERTY, BOTH_PROPERTY_VALUE_SYSTEM); + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(BOTH_PROPERTY); + Assert.assertFalse(BOTH_PROPERTY_VALUE_FILE.equals(fetchedValue)); + Assert.assertEquals(BOTH_PROPERTY_VALUE_SYSTEM, fetchedValue); + } } diff --git a/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java b/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java index b51fa50..30d4f91 100644 --- a/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java +++ b/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java @@ -7,23 +7,22 @@ import org.junit.Test; public class DuplicateRepeatTest { - private static AutomationEngine engine=null; - - - @Test - public void testBuildmodel() { - engine = AutomationEngine.getInstance(); - - try{ - engine.buildModel(new File("mocktestlibrary/dupe.commands.xml"), new File("mocktestscripts")); - Assert.assertEquals("Oops! We have more then one command with same name ('repeat') (case insensitive)! Fix your test commands, please.", engine.mc.getCurrentSection().getName()); - - }catch(Exception e){ - e.printStackTrace(); - } - - - - } - + private static AutomationEngine engine = null; + + + @Test + public void testBuildmodel() { + engine = AutomationEngine.getInstance(); + + try { + engine.buildModel(new File("mocktestlibrary/dupe.commands.xml"), new File("mocktestscripts")); + Assert.assertEquals("Oops! We have more then one command with same name ('repeat') (case insensitive)! Fix your test commands, please.", engine.mc.getCurrentSection().getName()); + + } catch (Exception e) { + e.printStackTrace(); + } + + + } + } From ca10e92897bb39b1a0d59eecaf70f6bf82f52d18 Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Tue, 15 Dec 2015 20:18:31 -0500 Subject: [PATCH 2/7] Add hashCode --- .../java/org/finra/jtaf/core/model/test/TestScript.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestScript.java b/src/main/java/org/finra/jtaf/core/model/test/TestScript.java index c99c5cc..06751cd 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestScript.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestScript.java @@ -197,6 +197,14 @@ public String getException() { return exception; } + @Override + public int hashCode() { + return this.getName().hashCode() + + this.getBody().hashCode() + + this.getFileName().hashCode() + + this.getFullName().hashCode(); + } + @Override public boolean equals(Object o) { if (!(o instanceof TestScript)) { From 7a440d65e6fca6045170497fa6eb813b3400732f Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Tue, 15 Dec 2015 20:20:10 -0500 Subject: [PATCH 3/7] Add hashCode --- .../java/org/finra/jtaf/core/model/test/digraph/DiNode.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java index d8e3057..5b00623 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java @@ -47,6 +47,12 @@ public TestScript getTestScript() { return testScript; } + @Override + public int hashCode() { + return this.getTestName().hashCode() + + this.getTestScript().hashCode(); + } + @Override public boolean equals(Object o) { if (o instanceof DiNode) { From 39921b4d84fbf4b6d1453eabc61f973bf4d715d3 Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Tue, 15 Dec 2015 20:21:19 -0500 Subject: [PATCH 4/7] Make the variables that should never change after set, final --- .../java/org/finra/jtaf/core/model/test/digraph/DiNode.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java index 5b00623..c00dcac 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java @@ -22,9 +22,9 @@ * This class represents a vertex in the digraph */ public class DiNode { - private String testName = ""; //This shouldnt change after being set initially + private final String testName; //This shouldnt change after being set initially private String testStatus = ""; - private TestScript testScript = null; //This shouldnt change after being set initially + private final TestScript testScript; //This shouldnt change after being set initially public DiNode(TestScript ts) { this.testName = ts.getName(); From dd21de4013c22651f6832c759865d375965b0cf3 Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Tue, 15 Dec 2015 20:49:29 -0500 Subject: [PATCH 5/7] Comment out hashCode - seems to break the build --- .../java/org/finra/jtaf/core/model/test/digraph/DiNode.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java index c00dcac..a30d278 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java @@ -47,11 +47,12 @@ public TestScript getTestScript() { return testScript; } + /* @Override public int hashCode() { - return this.getTestName().hashCode() + return this.getTestName().toLowerCase().hashCode() + this.getTestScript().hashCode(); - } + }*/ @Override public boolean equals(Object o) { From ac26780b1418e5c69e94dbb2bea03fa5d1ceea57 Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Wed, 13 Jan 2016 16:14:28 -0500 Subject: [PATCH 6/7] Move to 1.7 --- pom.xml | 8 ++++++++ .../core/exceptions/GetInvocationTargetException.java | 7 +++++++ 2 files changed, 15 insertions(+) create mode 100644 src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java diff --git a/pom.xml b/pom.xml index 6ee6bc0..88e6527 100644 --- a/pom.xml +++ b/pom.xml @@ -214,6 +214,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + diff --git a/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java b/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java new file mode 100644 index 0000000..a6cf1d5 --- /dev/null +++ b/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java @@ -0,0 +1,7 @@ +package org.finra.jtaf.core.exceptions; + +/** + * Created by mibrahim on 1/13/16. + */ +public class GetInvocationTargetException { +} From e57531958bbf1603b206d616694e9d923becb2c2 Mon Sep 17 00:00:00 2001 From: Mohamed Ibrahim Date: Wed, 13 Jan 2016 16:17:27 -0500 Subject: [PATCH 7/7] Convert all dos 2 unix --- mocktestlibrary/dupe.commands.xml | 18 +- mocktestscripts/DoNothing.xml | 32 +- .../DuplicateTestName.xml | 28 +- parser_testing/EmptySuite.xml | 2 +- parser_testing/InvalidRoot.strategy.xml | 12 +- .../InvalidScriptSourceTag.strategy.xml | 8 +- .../MissingTargetNameAttribute.strategy.xml | 10 +- parser_testing/StatementParserTesting.xml | 170 +- parser_testing/SuiteDependencyParserTest.xml | 18 +- parser_testing/SuiteExclusionParserTest.xml | 18 +- .../UnexpectedElementSuiteDependency.xml | 8 +- .../UnexpectedElementSuiteExclusion.xml | 8 +- parser_testing/every_tag/EveryTagSuite.xml | 50 +- pom.xml | 636 ++++---- profiles/strategies/Default.strategy.xml | 68 +- profiles/strategies/test.strategy.xml | 8 +- profiles/strategies/test_merge.xsl | 72 +- seedProject/.classpath | 64 +- seedProject/pom.xml | 146 +- .../commands/helloworld/ExampleCommand.java | 70 +- seedProject/src/main/resources/framework.xml | 20 +- .../src/main/resources/jtaf.properties | 6 +- .../org/finra/jtaf/core/CommandRegistry.java | 134 +- .../core/asserts/AssertionFailedError.java | 70 +- .../jtaf/core/asserts/ErrorAccumulator.java | 328 ++-- .../jtaf/core/asserts/IgnoreErrorsAssert.java | 1356 +++++++-------- .../jtaf/core/commands/IgnoreErrors.java | 168 +- .../commands/context/AbstractContextCmd.java | 92 +- .../commands/context/AddListToListCmd.java | 114 +- .../commands/context/AddObjectToListCmd.java | 114 +- .../context/ManipulateContextHelper.java | 876 +++++----- .../commands/context/PutObjectInMapCmd.java | 100 +- .../context/RemoveObjectFromContextCmd.java | 72 +- .../context/StoreDefaultObjectCmd.java | 88 +- .../context/StoreObjectAsStringCmd.java | 86 +- .../context/StoreObjectFromListCmd.java | 92 +- .../context/StoreObjectFromMapCmd.java | 82 +- .../context/StoreObjectInContextCmd.java | 82 +- .../context/VerifyObjectInContextCmd.java | 114 +- .../core/exceptions/DependencyException.java | 82 +- .../GetInvocationTargetException.java | 9 +- .../core/model/execution/Interpreter.java | 832 +++++----- .../invocationtarget/ContextKeyHandler.java | 242 +-- .../ContextKeyNotFoundException.java | 138 +- .../model/statement/IInvocationVisitor.java | 64 +- .../jtaf/core/model/test/TestStatus.java | 52 +- .../finra/jtaf/core/model/test/TestSuite.java | 154 +- .../core/model/test/digraph/Dependencies.java | 88 +- .../jtaf/core/model/test/digraph/DiEdge.java | 90 +- .../jtaf/core/model/test/digraph/DiNode.java | 138 +- .../model/test/digraph/DigraphFactory.java | 318 ++-- .../core/model/test/digraph/TestDigraph.java | 178 +- .../core/parallel/ConcurrentScheduler.java | 364 ++--- .../jtaf/core/parallel/JTAFMasterSuite.java | 102 +- .../parallel/MasterSuiteRunnersBuilder.java | 140 +- .../core/parallel/ParallelScriptRunner.java | 202 +-- .../jtaf/core/parallel/ResultUpdate.java | 82 +- .../jtaf/core/parallel/TestCaseRunner.java | 120 +- .../parsing/AutomationValueFilterPlugin.java | 98 +- .../core/parsing/AutomationValuePlugin.java | 74 +- .../core/parsing/CommandLibraryParser.java | 784 ++++----- .../jtaf/core/parsing/DigraphPlugin.java | 134 +- .../jtaf/core/parsing/ExceptionPlugin.java | 102 +- .../finra/jtaf/core/parsing/LoopPlugin.java | 254 +-- .../jtaf/core/parsing/MaxThreadsPlugin.java | 76 +- .../finra/jtaf/core/parsing/ScriptParser.java | 1450 ++++++++--------- .../jtaf/core/parsing/StatementParser.java | 602 +++---- .../core/parsing/SuiteDependenciesPlugin.java | 140 +- .../core/parsing/SuiteExclusionsPlugin.java | 140 +- .../jtaf/core/parsing/TestDataPlugin.java | 440 ++--- .../core/parsing/TestDependenciesPlugin.java | 166 +- .../core/parsing/TestExclusionsPlugin.java | 166 +- .../jtaf/core/plugins/PluginManager.java | 206 +-- .../execution/CommandRunnerPluginContext.java | 100 +- .../execution/ICommandRunnerPlugin.java | 80 +- .../plugins/execution/ITearDownPlugin.java | 60 +- .../plugins/execution/ITestRunnerPlugin.java | 82 +- .../execution/RunnerPluginException.java | 68 +- .../execution/TearDownPluginContext.java | 94 +- .../execution/TestRunnerPluginContext.java | 116 +- .../plugins/parsing/IPostParseAllPlugin.java | 64 +- .../IPostParseStrategyElementPlugin.java | 66 +- .../parsing/IPostParseSuitePlugin.java | 76 +- .../plugins/parsing/IPostParseTestPlugin.java | 76 +- .../parsing/ParserPluginException.java | 86 +- .../parsing/PostAllParserPluginContext.java | 110 +- ...ostStrategyElementParserPluginContext.java | 104 +- .../parsing/PostSuiteParserPluginContext.java | 140 +- .../parsing/PostTestParserPluginContext.java | 136 +- .../TraceabilityMatrixPlugin.java | 76 +- .../core/utilities/Base64EncoderDecoder.java | 186 +-- .../utilities/CompositeDataComparator.java | 454 +++--- .../core/utilities/JTAFPropertyManager.java | 78 +- .../jtaf/core/utilities/PropertyManager.java | 154 +- src/main/resources/framework.xml | 68 +- .../testlibrary/context.commands.xml | 298 ++-- .../asserts/AssertionFailedErrorTest.java | 70 +- .../core/asserts/ErrorAccumulatorTest.java | 224 +-- .../core/asserts/IgnoreErrorsAssertTest.java | 1200 +++++++------- .../finra/jtaf/core/commands/ByeCommand.java | 38 +- .../core/commands/ExtendedByeCommand.java | 36 +- .../core/commands/ExtendedHelloCommand.java | 36 +- .../commands/ExtendedVerifyByeCommand.java | 42 +- .../commands/ExtendedVerifyHelloCommand.java | 42 +- .../jtaf/core/commands/HelloCommand.java | 38 +- .../core/commands/RandomGeneratorTest.java | 574 +++---- .../finra/jtaf/core/commands/RepeatTest.java | 168 +- .../jtaf/core/commands/VerifyByeCommand.java | 42 +- .../core/commands/VerifyHelloCommand.java | 42 +- .../context/ManipulateContextHelperTest.java | 810 ++++----- .../jtaf/core/driver/XMLTestParrelDriver.java | 18 +- .../jtaf/core/mock/DebugPrintCommand.java | 36 +- .../jtaf/core/mock/IThrowExceptionCmd.java | 44 +- .../finra/jtaf/core/mock/MockCommand1.java | 42 +- .../finra/jtaf/core/mock/MockCommand2.java | 44 +- .../java/org/finra/jtaf/core/mock/Repeat.java | 40 +- .../jtaf/core/mock/TestParamFetchingCmd.java | 182 +-- .../parallel/ConcurrentSchedulerTest.java | 138 +- .../MasterSuiteRunnersBuilderTest.java | 30 +- .../parallel/ParallelScriptRunnerTest.java | 332 ++-- .../AutomationValueFilterPluginTest.java | 264 +-- .../parsing/AutomationValuePluginTest.java | 94 +- .../jtaf/core/parsing/DigraphPluginTest.java | 76 +- .../jtaf/core/parsing/LoopPluginTest.java | 82 +- .../core/parsing/MaxThreadsPluginTest.java | 94 +- .../jtaf/core/parsing/ParserPluginTest.java | 78 +- .../jtaf/core/parsing/ScriptParserTests.java | 104 +- .../core/parsing/StatementParserTest.java | 288 ++-- .../parsing/SuiteDependenciesPluginTest.java | 100 +- .../parsing/SuiteExclusionsPluginTest.java | 100 +- .../jtaf/core/parsing/TestDataPluginTest.java | 88 +- .../parsing/TestDependenciesPluginTest.java | 74 +- .../parsing/TestExclusionsPluginTest.java | 74 +- .../core/parsing/TestStrategyParserTest.java | 64 +- .../execution/DummyCommandRunnerPlugin.java | 76 +- .../execution/DummyTestRunnerPlugin.java | 84 +- .../execution/ExecutionPluginsTest.java | 356 ++-- .../plugins/execution/TearDownTestPlugin.java | 16 +- .../TraceabilityMatrixPluginTest.java | 116 +- .../utilities/JTAFPropertyManagerTests.java | 74 +- .../jtaf/core/ztest/DuplicateRepeatTest.java | 56 +- .../AutomationValueTestStrategy.strategy.xml | 12 +- .../MaxThreadsTestStrategy.strategy.xml | 12 +- src/test/resources/jtaf.properties | 4 +- src/test/resources/log4j.properties | 10 +- .../testlibrary/anyfolder/verify.commands.xml | 32 +- .../testlibrary/context.test.commands.xml | 84 +- .../resources/testlibrary/hello.commands.xml | 30 +- .../resources/testlibrary/mock.commands.xml | 66 +- testdata/debug/testdataDebug.csv | 8 +- testscripts/AddListToListCmdTest.xml | 424 ++--- testscripts/AddObjectToListCmdTest.xml | 682 ++++---- testscripts/AutomationValue.xml | 124 +- testscripts/Block.xml | 84 +- testscripts/CommandTest.xml | 92 +- testscripts/CommandThrowingExceptionTest.xml | 38 +- testscripts/ConcurrentScheduler.xml | 82 +- testscripts/Coverage.xml | 22 +- testscripts/DependencyTest.xml | 174 +- testscripts/DoNotAddToStrategy.xml | 18 +- testscripts/ExclusionTest.xml | 54 +- testscripts/ExpectFailure.xml | 122 +- testscripts/Function.xml | 52 +- testscripts/IgnoreErrors.xml | 86 +- testscripts/Invoke.xml | 34 +- testscripts/LoopDebug.xml | 24 +- testscripts/ManipulateContextHelper.xml | 32 +- testscripts/MockTestScript.xml | 32 +- testscripts/Multipath.xml | 68 +- testscripts/ParallelScriptRunner.xml | 26 +- testscripts/PutObjectInMapCmdTest.xml | 64 +- testscripts/RandomGenerator.xml | 202 +-- .../RemoveObjectFromContextCmdTest.xml | 38 +- testscripts/Repeat.xml | 98 +- testscripts/ReplaceContext.xml | 112 +- testscripts/StoreObjectAsStringCmdTest.xml | 82 +- testscripts/StoreObjectFromListCmdTest.xml | 126 +- testscripts/StoreObjectFromMapCmdTest.xml | 74 +- testscripts/StoreObjectInContextCmdTest.xml | 48 +- testscripts/TearDownPluginsTests.xml | 48 +- testscripts/TestCommandLibraryDiscovery.xml | 86 +- testscripts/TestDataDebug.xml | 30 +- testscripts/TryRecoverCleanup.xml | 348 ++-- testscripts/VerifyObjectInContextTest.xml | 140 +- testscripts/mock/TraceabilityTest.xml | 34 +- 185 files changed, 13568 insertions(+), 13555 deletions(-) diff --git a/mocktestlibrary/dupe.commands.xml b/mocktestlibrary/dupe.commands.xml index f38a491..54f634e 100644 --- a/mocktestlibrary/dupe.commands.xml +++ b/mocktestlibrary/dupe.commands.xml @@ -1,9 +1,9 @@ - - - - - duplicate command - - - + + + + + duplicate command + + + diff --git a/mocktestscripts/DoNothing.xml b/mocktestscripts/DoNothing.xml index 09c834f..7fb260e 100644 --- a/mocktestscripts/DoNothing.xml +++ b/mocktestscripts/DoNothing.xml @@ -1,17 +1,17 @@ - - - - - - - High - - - - - - - - - + + + + + + + High + + + + + + + + + \ No newline at end of file diff --git a/parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml b/parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml index 5eaa32f..19f1a1d 100644 --- a/parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml +++ b/parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml @@ -1,15 +1,15 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/parser_testing/EmptySuite.xml b/parser_testing/EmptySuite.xml index 2a8e281..bf9435f 100644 --- a/parser_testing/EmptySuite.xml +++ b/parser_testing/EmptySuite.xml @@ -1,2 +1,2 @@ - + \ No newline at end of file diff --git a/parser_testing/InvalidRoot.strategy.xml b/parser_testing/InvalidRoot.strategy.xml index f57b130..3e599a1 100644 --- a/parser_testing/InvalidRoot.strategy.xml +++ b/parser_testing/InvalidRoot.strategy.xml @@ -1,7 +1,7 @@ - - - - ValidAutomationValue - - + + + + ValidAutomationValue + + \ No newline at end of file diff --git a/parser_testing/InvalidScriptSourceTag.strategy.xml b/parser_testing/InvalidScriptSourceTag.strategy.xml index 0e5fa7d..e36dfe5 100644 --- a/parser_testing/InvalidScriptSourceTag.strategy.xml +++ b/parser_testing/InvalidScriptSourceTag.strategy.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/parser_testing/MissingTargetNameAttribute.strategy.xml b/parser_testing/MissingTargetNameAttribute.strategy.xml index 01b65f5..7490d6b 100644 --- a/parser_testing/MissingTargetNameAttribute.strategy.xml +++ b/parser_testing/MissingTargetNameAttribute.strategy.xml @@ -1,6 +1,6 @@ - - - ValidAutomationValue - - + + + ValidAutomationValue + + \ No newline at end of file diff --git a/parser_testing/StatementParserTesting.xml b/parser_testing/StatementParserTesting.xml index 04e1f84..1e903b6 100644 --- a/parser_testing/StatementParserTesting.xml +++ b/parser_testing/StatementParserTesting.xml @@ -1,86 +1,86 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - map entry with no key - - - - - - - - - - - listParameter - - - - - - - - - - - - - - map entry with no key - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + map entry with no key + + + + + + + + + + + listParameter + + + + + + + + + + + + + + map entry with no key + + + + + + \ No newline at end of file diff --git a/parser_testing/SuiteDependencyParserTest.xml b/parser_testing/SuiteDependencyParserTest.xml index 69b0f7a..fec6d6f 100644 --- a/parser_testing/SuiteDependencyParserTest.xml +++ b/parser_testing/SuiteDependencyParserTest.xml @@ -1,10 +1,10 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/parser_testing/SuiteExclusionParserTest.xml b/parser_testing/SuiteExclusionParserTest.xml index 4852a34..a1d1493 100644 --- a/parser_testing/SuiteExclusionParserTest.xml +++ b/parser_testing/SuiteExclusionParserTest.xml @@ -1,10 +1,10 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/parser_testing/UnexpectedElementSuiteDependency.xml b/parser_testing/UnexpectedElementSuiteDependency.xml index b628847..829e578 100644 --- a/parser_testing/UnexpectedElementSuiteDependency.xml +++ b/parser_testing/UnexpectedElementSuiteDependency.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/parser_testing/UnexpectedElementSuiteExclusion.xml b/parser_testing/UnexpectedElementSuiteExclusion.xml index 5e29b51..34350c6 100644 --- a/parser_testing/UnexpectedElementSuiteExclusion.xml +++ b/parser_testing/UnexpectedElementSuiteExclusion.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/parser_testing/every_tag/EveryTagSuite.xml b/parser_testing/every_tag/EveryTagSuite.xml index d1b813e..29153f9 100644 --- a/parser_testing/every_tag/EveryTagSuite.xml +++ b/parser_testing/every_tag/EveryTagSuite.xml @@ -1,26 +1,26 @@ - - - - EveryTagSuiteAutomationValue - - - - - - - - - - Some issue - - - Some coverage - - - - - - - - + + + + EveryTagSuiteAutomationValue + + + + + + + + + + Some issue + + + Some coverage + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 88e6527..2403177 100644 --- a/pom.xml +++ b/pom.xml @@ -1,318 +1,318 @@ - - 4.0.0 - org.finra.jtaf - jtaf-xcore - 1.1-SNAPSHOT - jar - JTAF XCore - The core functionality provided by JTAF. Includes script parsing, test execution, and JUnit support. - http://finraos.github.io/JTAF-XCore/ - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - scm:git:https://github.com/FINRAOS/JTAF-XCore.git - scm:git:https://github.com/FINRAOS/JTAF-XCore.git - https://github.com/FINRAOS/JTAF-XCore.git - HEAD - - - - kood1 - Daniel Koo - danieljamin.koo@gmail.com - http://github.com/kood1 - - - bryantrobbins - Bryan Robbins - bryantrobbins@gmail.com - https://github.com/bryantrobbins - - - lathanagaraj - Latha Nagaraj - latha.nagaraj@gmail.com - https://github.com/lathanagaraj - - - JacobSheppard - Jacob Sheppard - jshep409@gmail.com - http://github.com/JacobSheppard - - - dpulitano - Daniel Pulitano - danielpulitano@gmail.com - https://github.com/dpulitano - - - SonOfFlyingPig - Michael Linford - mike.linford@gmail.com - http://github.com/sonofflyingpig - - - koshya - Anju Koshy - anjuthomas.be@gmail.com - http://github.com/koshya - - - na-na - Nishtha Agarwal - nnishtha.agarwal@gmail.com - https://github.com/na-na - - - - - org.sonatype.oss - oss-parent - 7 - - - - UTF-8 - - - - - - maven-compiler-plugin - - 1.6 - 1.6 - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.17 - - - ${project.build.directory}/test-classes/SampleAutomationJar-1.0.jar - - ${jaCoCoArgLine} - - - **/*Test*.java - - alphabetical - - - - org.apache.maven.surefire - surefire-junit47 - 2.17 - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.17 - - - integration-test - - integration-test - - - - ${project.build.directory}/test-classes/SampleAutomationJar-1.0.jar - - - - profiles/targets/default.properties - profiles/strategies/Default.strategy.xml - - - **/XMLParallelDriver* - - - - - - - false - ${jaCoCoArgLine} - - - - - - - - org.jacoco - jacoco-maven-plugin - 0.6.3.201306030806 - - - - initialize - initialize - - prepare-agent - - - - ${project.build.directory}/coverage-reports/jacoco.exec - - jaCoCoArgLine - - - - - post-all-tests - test - - report - - - - ${project.build.directory}/coverage-reports/jacoco.exec - - ${project.reporting.outputDirectory}/jacoco - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - - - - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - - - commons-lang - commons-lang - 2.6 - - - net.sf.opencsv - opencsv - 2.3 - - - org.springframework - spring-context-support - 4.1.1.RELEASE - - - commons-codec - commons-codec - 1.9 - - - junit - junit - 4.11 - - - org.apache.poi - poi-ooxml - 3.10.1 - - - org.jgrapht - jgrapht-core - 0.9.1 - - - log4j - log4j - 1.2.17 - - - com.github.mifmif - generex - 0.0.3 - - - - - - sonatype-nexus-staging - Sonatype Nexus release repository - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - - sonatype-nexus-snapshots - Sonatype Snapshot Repository - https://oss.sonatype.org/content/repositories/snapshots - - - + + 4.0.0 + org.finra.jtaf + jtaf-xcore + 1.1-SNAPSHOT + jar + JTAF XCore + The core functionality provided by JTAF. Includes script parsing, test execution, and JUnit support. + http://finraos.github.io/JTAF-XCore/ + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + scm:git:https://github.com/FINRAOS/JTAF-XCore.git + scm:git:https://github.com/FINRAOS/JTAF-XCore.git + https://github.com/FINRAOS/JTAF-XCore.git + HEAD + + + + kood1 + Daniel Koo + danieljamin.koo@gmail.com + http://github.com/kood1 + + + bryantrobbins + Bryan Robbins + bryantrobbins@gmail.com + https://github.com/bryantrobbins + + + lathanagaraj + Latha Nagaraj + latha.nagaraj@gmail.com + https://github.com/lathanagaraj + + + JacobSheppard + Jacob Sheppard + jshep409@gmail.com + http://github.com/JacobSheppard + + + dpulitano + Daniel Pulitano + danielpulitano@gmail.com + https://github.com/dpulitano + + + SonOfFlyingPig + Michael Linford + mike.linford@gmail.com + http://github.com/sonofflyingpig + + + koshya + Anju Koshy + anjuthomas.be@gmail.com + http://github.com/koshya + + + na-na + Nishtha Agarwal + nnishtha.agarwal@gmail.com + https://github.com/na-na + + + + + org.sonatype.oss + oss-parent + 7 + + + + UTF-8 + + + + + + maven-compiler-plugin + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.17 + + + ${project.build.directory}/test-classes/SampleAutomationJar-1.0.jar + + ${jaCoCoArgLine} + + + **/*Test*.java + + alphabetical + + + + org.apache.maven.surefire + surefire-junit47 + 2.17 + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.17 + + + integration-test + + integration-test + + + + ${project.build.directory}/test-classes/SampleAutomationJar-1.0.jar + + + + profiles/targets/default.properties + profiles/strategies/Default.strategy.xml + + + **/XMLParallelDriver* + + + + + + + false + ${jaCoCoArgLine} + + + + + + + + org.jacoco + jacoco-maven-plugin + 0.6.3.201306030806 + + + + initialize + initialize + + prepare-agent + + + + ${project.build.directory}/coverage-reports/jacoco.exec + + jaCoCoArgLine + + + + + post-all-tests + test + + report + + + + ${project.build.directory}/coverage-reports/jacoco.exec + + ${project.reporting.outputDirectory}/jacoco + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.4 + + + sign-artifacts + verify + + sign + + + + + + + + + + + commons-lang + commons-lang + 2.6 + + + net.sf.opencsv + opencsv + 2.3 + + + org.springframework + spring-context-support + 4.1.1.RELEASE + + + commons-codec + commons-codec + 1.9 + + + junit + junit + 4.11 + + + org.apache.poi + poi-ooxml + 3.10.1 + + + org.jgrapht + jgrapht-core + 0.9.1 + + + log4j + log4j + 1.2.17 + + + com.github.mifmif + generex + 0.0.3 + + + + + + sonatype-nexus-staging + Sonatype Nexus release repository + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + + sonatype-nexus-snapshots + Sonatype Snapshot Repository + https://oss.sonatype.org/content/repositories/snapshots + + + diff --git a/profiles/strategies/Default.strategy.xml b/profiles/strategies/Default.strategy.xml index 7bb5c71..68109ce 100644 --- a/profiles/strategies/Default.strategy.xml +++ b/profiles/strategies/Default.strategy.xml @@ -1,35 +1,35 @@ - - - - - High - AutomationValueTest - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + High + AutomationValueTest + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/profiles/strategies/test.strategy.xml b/profiles/strategies/test.strategy.xml index 0dd3a62..3d993d0 100644 --- a/profiles/strategies/test.strategy.xml +++ b/profiles/strategies/test.strategy.xml @@ -1,5 +1,5 @@ - - - - + + + + \ No newline at end of file diff --git a/profiles/strategies/test_merge.xsl b/profiles/strategies/test_merge.xsl index 0fea2a8..b2878f9 100644 --- a/profiles/strategies/test_merge.xsl +++ b/profiles/strategies/test_merge.xsl @@ -1,36 +1,36 @@ - - - - - - - - - -

- - - -
- - -

Test Script:

- - -
- - -

Test Suite:

- -
- - -

:

- -
- - -
-
- -
+ + + + + + + + + +

+ + + +
+ + +

Test Script:

+ + +
+ + +

Test Suite:

+ +
+ + +

:

+ +
+ + +
+
+ +
diff --git a/seedProject/.classpath b/seedProject/.classpath index f1fb698..f9b0575 100644 --- a/seedProject/.classpath +++ b/seedProject/.classpath @@ -1,32 +1,32 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/seedProject/pom.xml b/seedProject/pom.xml index ba51699..11d610c 100644 --- a/seedProject/pom.xml +++ b/seedProject/pom.xml @@ -1,73 +1,73 @@ - - 4.0.0 - org.myorg.example - xcore-testproject - 0.1 - XCore Test Project - - src/main/java - - - src/main/resources - - **/*.java - - - - config - - **/*.java - - - - - - maven-compiler-plugin - 3.2 - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.17 - - - perform-it - integration-test - - integration-test - - - - verify-it - verify - - verify - - - - profiles/strategies/${jtaf.strategy}.strategy.xml - - - - - - - **/XMLTestDriver* - - true - - - - - - - org.finra.jtaf - jtaf-core - 1.0-SNAPSHOT - - - + + 4.0.0 + org.myorg.example + xcore-testproject + 0.1 + XCore Test Project + + src/main/java + + + src/main/resources + + **/*.java + + + + config + + **/*.java + + + + + + maven-compiler-plugin + 3.2 + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.17 + + + perform-it + integration-test + + integration-test + + + + verify-it + verify + + verify + + + + profiles/strategies/${jtaf.strategy}.strategy.xml + + + + + + + **/XMLTestDriver* + + true + + + + + + + org.finra.jtaf + jtaf-core + 1.0-SNAPSHOT + + + diff --git a/seedProject/src/main/java/org/myorg/example/commands/helloworld/ExampleCommand.java b/seedProject/src/main/java/org/myorg/example/commands/helloworld/ExampleCommand.java index 68e7c10..c0cb077 100644 --- a/seedProject/src/main/java/org/myorg/example/commands/helloworld/ExampleCommand.java +++ b/seedProject/src/main/java/org/myorg/example/commands/helloworld/ExampleCommand.java @@ -1,36 +1,36 @@ -package org.myorg.example.commands.helloworld; - -import java.util.Map; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class ExampleCommand extends Command { - - public ExampleCommand(String name) throws NameFormatException { - super(name); - } - - protected void execute(IInvocationContext ctx) throws Throwable { - String expectedText="Hello world"; - String actualText=getRequiredString("assertableText"); - - Assert.assertEquals("Your text doesn't match " + expectedText, expectedText, actualText); - - @SuppressWarnings("unchecked") - Map map = (Map) getOptionalObject("mapToPrint"); - - if(map != null) { - for(String k : map.keySet()) { - System.out.println(k + ": " + map.get(k)); - } - } - - boolean printHello = getBooleanOrDefault("printHello", false); - if(printHello) { - System.out.println("Hello."); - } - } +package org.myorg.example.commands.helloworld; + +import java.util.Map; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class ExampleCommand extends Command { + + public ExampleCommand(String name) throws NameFormatException { + super(name); + } + + protected void execute(IInvocationContext ctx) throws Throwable { + String expectedText="Hello world"; + String actualText=getRequiredString("assertableText"); + + Assert.assertEquals("Your text doesn't match " + expectedText, expectedText, actualText); + + @SuppressWarnings("unchecked") + Map map = (Map) getOptionalObject("mapToPrint"); + + if(map != null) { + for(String k : map.keySet()) { + System.out.println(k + ": " + map.get(k)); + } + } + + boolean printHello = getBooleanOrDefault("printHello", false); + if(printHello) { + System.out.println("Hello."); + } + } } \ No newline at end of file diff --git a/seedProject/src/main/resources/framework.xml b/seedProject/src/main/resources/framework.xml index b2036fc..eba6046 100644 --- a/seedProject/src/main/resources/framework.xml +++ b/seedProject/src/main/resources/framework.xml @@ -1,11 +1,11 @@ - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/seedProject/src/main/resources/jtaf.properties b/seedProject/src/main/resources/jtaf.properties index 94f4333..a47bda6 100644 --- a/seedProject/src/main/resources/jtaf.properties +++ b/seedProject/src/main/resources/jtaf.properties @@ -1,3 +1,3 @@ -strategy=profiles/strategies/helloworld.strategy.xml - - +strategy=profiles/strategies/helloworld.strategy.xml + + diff --git a/src/main/java/org/finra/jtaf/core/CommandRegistry.java b/src/main/java/org/finra/jtaf/core/CommandRegistry.java index 2ae3a25..91a8d59 100644 --- a/src/main/java/org/finra/jtaf/core/CommandRegistry.java +++ b/src/main/java/org/finra/jtaf/core/CommandRegistry.java @@ -1,67 +1,67 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core; - -import java.util.HashMap; -import java.util.Map; - -import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; - -/** - * This class is for the commands registered in the *.commands.xml files in - * testlibrary folder. It is a property of the Automation Engine. It saves - * pair for each command. - */ -public class CommandRegistry { - private final Map invocationTargetMap; - - public CommandRegistry() { - this.invocationTargetMap = new HashMap(); - } - - - /** - * Registers the specified command/invocation target. - * - * @param name - * @param invocationTarget - */ - public void registerInvocationTarget(String name, InvocationTarget invocationTarget) { - this.invocationTargetMap.put(name, invocationTarget); - } - - /** - * Returns true if the invocation target is present - * - * @param name - * @return - */ - public final boolean containsInvocationTarget(String name) { - return invocationTargetMap.containsKey(name.toLowerCase()); - } - - /** - * Gets the specified invocation target - * - * @param name - * @return - */ - public final InvocationTarget getInvocationTarget(String name) { - return invocationTargetMap.get(name.toLowerCase()); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core; + +import java.util.HashMap; +import java.util.Map; + +import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; + +/** + * This class is for the commands registered in the *.commands.xml files in + * testlibrary folder. It is a property of the Automation Engine. It saves + * pair for each command. + */ +public class CommandRegistry { + private final Map invocationTargetMap; + + public CommandRegistry() { + this.invocationTargetMap = new HashMap(); + } + + + /** + * Registers the specified command/invocation target. + * + * @param name + * @param invocationTarget + */ + public void registerInvocationTarget(String name, InvocationTarget invocationTarget) { + this.invocationTargetMap.put(name, invocationTarget); + } + + /** + * Returns true if the invocation target is present + * + * @param name + * @return + */ + public final boolean containsInvocationTarget(String name) { + return invocationTargetMap.containsKey(name.toLowerCase()); + } + + /** + * Gets the specified invocation target + * + * @param name + * @return + */ + public final InvocationTarget getInvocationTarget(String name) { + return invocationTargetMap.get(name.toLowerCase()); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java b/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java index 2ce54e0..4754d6b 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java +++ b/src/main/java/org/finra/jtaf/core/asserts/AssertionFailedError.java @@ -1,36 +1,36 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.asserts; - -/** - * Thrown when an assertion failed. - */ -public class AssertionFailedError extends AssertionError { - - private static final long serialVersionUID = 1L; - - public AssertionFailedError() { - } - - public AssertionFailedError(String message) { - super(defaultString(message)); - } - - private static String defaultString(String message) { - return message == null ? "" : message; - } +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.asserts; + +/** + * Thrown when an assertion failed. + */ +public class AssertionFailedError extends AssertionError { + + private static final long serialVersionUID = 1L; + + public AssertionFailedError() { + } + + public AssertionFailedError(String message) { + super(defaultString(message)); + } + + private static String defaultString(String message) { + return message == null ? "" : message; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java b/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java index 61cd8b4..8d5cd7a 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java +++ b/src/main/java/org/finra/jtaf/core/asserts/ErrorAccumulator.java @@ -1,164 +1,164 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.asserts; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.exception.ExceptionUtils; - -/** - * This class can be used to collect errors. - */ -public class ErrorAccumulator { - - private String name; - private ArrayList errors; - - // needed for ignore errors at script level: - boolean errorsThrown = false; - - /** - * Create a named error accumulator - * - * @param name - */ - public ErrorAccumulator(String name) { - this.name = name; - errors = new ArrayList(); - } - - - /** - * Gets the name of the accumulator - * - * @return - */ - public String getName() { - return name; - } - - /** - * Gets the number of errors. - * - * @return - */ - public int getNumErrors() { - return errors.size(); - } - - /** - * Adds and Error to accumulate - * - * @param th - * @return - */ - public boolean addError(Throwable th) { - return errors.add(th); - } - - /** - * returns true if no errors - * - * @return - */ - public boolean isEmpty() { - return errors.isEmpty(); - } - - /** - * Returns error messages - * - * @return - */ - public String getErrorMessages() { - String errorInfo = ""; - - for (int i = 0; i < errors.size(); i++) { - errorInfo = errorInfo + "\n " + errors.get(i).getLocalizedMessage(); - } - - return errorInfo; - } - - /** - * Returns error stack traces - * - * @return - */ - public String getErrorStackTraces() { - String errorInfo = ""; - // TODO: use static access - // TODO: determine if this dependency is really necessary, do we need to - // depend on commons-lang to make stack trace printing easier? - for (int i = 0; i < errors.size(); i++) { - errorInfo = errorInfo + "\n " + ExceptionUtils.getStackTrace(errors.get(i)); - } - - return errorInfo; - } - - /** - * Returns list of stack trace elements - * - * @return - */ - public List getErrorStackTraceElementsList() { - List list = new ArrayList(); - ArrayList errors = getErrors(); - for (Throwable th : errors) { - list.add(th.getStackTrace()); - } - - return list; - } - - /** - * Throws accumulated errors - */ - public void throwErrors() { - AssertionFailedError e = getWrappedErrors(); - if (e != null) { - errorsThrown = true; - throw e; - } - } - - public boolean hasThrown() { - return errorsThrown; - } - - public ArrayList getErrors() { - return errors; - } - - public AssertionFailedError getWrappedErrors() { - - if (isEmpty()) - return null; - - String message = getErrorStackTraces(); - - if (message.equals("")) - return null; - - return new AssertionFailedError( - "Error accumulator found and ignored the following errors in " - + getName() + ":" + message); - - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.asserts; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.exception.ExceptionUtils; + +/** + * This class can be used to collect errors. + */ +public class ErrorAccumulator { + + private String name; + private ArrayList errors; + + // needed for ignore errors at script level: + boolean errorsThrown = false; + + /** + * Create a named error accumulator + * + * @param name + */ + public ErrorAccumulator(String name) { + this.name = name; + errors = new ArrayList(); + } + + + /** + * Gets the name of the accumulator + * + * @return + */ + public String getName() { + return name; + } + + /** + * Gets the number of errors. + * + * @return + */ + public int getNumErrors() { + return errors.size(); + } + + /** + * Adds and Error to accumulate + * + * @param th + * @return + */ + public boolean addError(Throwable th) { + return errors.add(th); + } + + /** + * returns true if no errors + * + * @return + */ + public boolean isEmpty() { + return errors.isEmpty(); + } + + /** + * Returns error messages + * + * @return + */ + public String getErrorMessages() { + String errorInfo = ""; + + for (int i = 0; i < errors.size(); i++) { + errorInfo = errorInfo + "\n " + errors.get(i).getLocalizedMessage(); + } + + return errorInfo; + } + + /** + * Returns error stack traces + * + * @return + */ + public String getErrorStackTraces() { + String errorInfo = ""; + // TODO: use static access + // TODO: determine if this dependency is really necessary, do we need to + // depend on commons-lang to make stack trace printing easier? + for (int i = 0; i < errors.size(); i++) { + errorInfo = errorInfo + "\n " + ExceptionUtils.getStackTrace(errors.get(i)); + } + + return errorInfo; + } + + /** + * Returns list of stack trace elements + * + * @return + */ + public List getErrorStackTraceElementsList() { + List list = new ArrayList(); + ArrayList errors = getErrors(); + for (Throwable th : errors) { + list.add(th.getStackTrace()); + } + + return list; + } + + /** + * Throws accumulated errors + */ + public void throwErrors() { + AssertionFailedError e = getWrappedErrors(); + if (e != null) { + errorsThrown = true; + throw e; + } + } + + public boolean hasThrown() { + return errorsThrown; + } + + public ArrayList getErrors() { + return errors; + } + + public AssertionFailedError getWrappedErrors() { + + if (isEmpty()) + return null; + + String message = getErrorStackTraces(); + + if (message.equals("")) + return null; + + return new AssertionFailedError( + "Error accumulator found and ignored the following errors in " + + getName() + ":" + message); + + } +} diff --git a/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java b/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java index 7e48b75..dc26cd4 100644 --- a/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java +++ b/src/main/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssert.java @@ -1,678 +1,678 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.asserts; - -import junit.framework.Assert; - -/** - * This class is mainly a wrapper for Junits Assert class. Instead of - * immediately throwing an error, the error is stored in an ErrorAccumulator to - * be thrown when needed. - */ -public class IgnoreErrorsAssert { - - public ErrorAccumulator ea; - - /** - * Called to instantiate this class - * - * @param ea the ErrorAccumulator to be used to collect all exceptions - */ - public IgnoreErrorsAssert(ErrorAccumulator ea) { - this.ea = ea; - } - - /** - * Asserts that a condition is true. If it isn't, it stores a Throwable in - * the accumulator with the given message. - * - * @param message message to be thrown if condition is false - * @param condition the condition to be evaluated - */ - @SuppressWarnings("deprecation") - public void assertTrue(String message, boolean condition) { - try { - Assert.assertTrue(message, condition); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that a condition is true. If it isn't, it stores a Throwable in - * the accumulator. - * - * @param condition the condition to be evaluated - */ - @SuppressWarnings("deprecation") - public void assertTrue(boolean condition) { - try { - Assert.assertTrue(condition); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that a condition is false. If it isn't, it stores a Throwable in - * the accumulator with the given message. - * - * @param message message to be thrown if condition is true - * @param condition the condition to be evaluated - */ - @SuppressWarnings("deprecation") - public void assertFalse(String message, boolean condition) { - try { - Assert.assertFalse(message, condition); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that a condition is false. If it isn't, it stores a Throwable in - * the accumulator. - * - * @param condition the condition to be evaluated - */ - @SuppressWarnings("deprecation") - public void assertFalse(boolean condition) { - try { - Assert.assertFalse(condition); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Fails a test with a Throwable being stored in the accumulator with the - * given message. - * - * @param message message to be thrown - */ - @SuppressWarnings("deprecation") - public void fail(String message) { - try { - Assert.fail(message); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Fails a test with a Throwable being stored in the accumulator with no - * message. - */ - @SuppressWarnings("deprecation") - public void fail() { - try { - Assert.fail(); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects are equal. If they are not, a Throwable is - * stored in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - - @SuppressWarnings("deprecation") - public void assertEquals(String message, Object expected, Object actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects are equal. If they are not an Throwable is - * stored in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(Object expected, Object actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two Strings are equal. If they are not, a Throwable is - * stored in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, String expected, String actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two Strings are equal. If they are not, a Throwable is - * stored in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String expected, String actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two doubles are equal concerning a delta. If they are not, a - * Throwable is stored in the accumulator with the given message. If the - * expected value is infinity then the delta value is ignored. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - * @param delta the difference allowed between the two values - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, double expected, double actual, double delta) { - try { - Assert.assertEquals(message, expected, actual, delta); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two doubles are equal concerning a delta. If the expected - * value is infinity then the delta value is ignored. If they are not, a - * Throwable is stored in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - * @param delta the difference allowed between the two values - */ - @SuppressWarnings("deprecation") - public void assertEquals(double expected, double actual, double delta) { - try { - Assert.assertEquals(expected, actual, delta); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two floats are equal concerning a positive delta. If they - * are not, a Throwable is stored in the accumulator with the given message. - * If the expected value is infinity then the delta value is ignored. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - * @param delta the difference allowed between the two values - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, float expected, float actual, float delta) { - try { - Assert.assertEquals(message, expected, actual, delta); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two floats are equal concerning a delta. If the expected - * value is infinity then the delta value is ignored. If they are not, a - * Throwable is stored in the accumulator - * - * @param expected expected value - * @param actual actual value that is being checked - * @param delta the difference allowed between the two values - */ - @SuppressWarnings("deprecation") - public void assertEquals(float expected, float actual, float delta) { - try { - Assert.assertEquals(expected, actual, delta); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two longs are equal. If they are not, a Throwable is stored - * in the accumulator with the given message. If they are not, a Throwable - * is stored in the accumulator - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, long expected, long actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two longs are equal. If they are not, a Throwable is stored - * in the accumulator. If they are not, a Throwable is stored in the - * accumulator - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(long expected, long actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two booleans are equal. If they are not, a Throwable is - * stored in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, boolean expected, boolean actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two booleans are equal. If they are not, a Throwable is - * stored in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(boolean expected, boolean actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two bytes are equal. If they are not an Throwable is thrown - * with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, byte expected, byte actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two bytes are equal. If they are not, a Throwable is stored - * in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(byte expected, byte actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two chars are equal. If they are not, a Throwable is stored - * in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, char expected, char actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two chars are equal. If they are not, a Throwable is stored - * in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(char expected, char actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two shorts are equal. If they are not, a Throwable is stored - * in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - **/ - @SuppressWarnings("deprecation") - public void assertEquals(String message, short expected, short actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two shorts are equal. If they are not, a Throwable is stored - * in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(short expected, short actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two ints are equal. If they are not, a Throwable is stored - * in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(String message, int expected, int actual) { - try { - Assert.assertEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two ints are equal. If they are not, a Throwable is stored - * in the accumulator. - * - * @param expected expected value - * @param actual actual value that is being checked - */ - @SuppressWarnings("deprecation") - public void assertEquals(int expected, int actual) { - try { - Assert.assertEquals(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that an object isn't null. If they are not, a Throwable is stored - * in the accumulator. - * - * @param object object to be checked to see if it is null or not - */ - @SuppressWarnings("deprecation") - public void assertNotNull(Object object) { - try { - Assert.assertNotNull(object); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that an object isn't null. If they are not, a Throwable is stored - * in the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param object object to be checked to see if it is null or not - */ - @SuppressWarnings("deprecation") - public void assertNotNull(String message, Object object) { - try { - Assert.assertNotNull(message, object); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that an object is null. If they are not, a Throwable is stored in - * the accumulator. - * - * @param object Object to check to see if it is null - */ - @SuppressWarnings("deprecation") - public void assertNull(Object object) { - try { - Assert.assertNull(object); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that an object is null. If they are not, a Throwable is stored in - * the accumulator with the given message. - * - * @param message message to be thrown if not equal - * @param object object to be checked to see if it is null or not - */ - @SuppressWarnings("deprecation") - public void assertNull(String message, Object object) { - try { - Assert.assertNull(message, object); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects refer to the same object. If they are not, a - * Throwable is stored in the accumulator with the given message. - * - * @param message message to be thrown if not the same - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void assertSame(String message, Object expected, Object actual) { - try { - Assert.assertSame(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects refer to the same object. If they are not, a - * Throwable is stored in the accumulator. - * - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void assertSame(Object expected, Object actual) { - try { - Assert.assertSame(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects do not refer to the same object. If they are - * not, a Throwable is stored in the accumulator with the given message. - * - * @param message message to be thrown if they are the same - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void assertNotSame(String message, Object expected, Object actual) { - try { - Assert.assertNotSame(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - - } - - /** - * Asserts that two objects do not refer to the same object. If they are - * not, a Throwable is stored in the accumulator. - * - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void assertNotSame(Object expected, Object actual) { - try { - Assert.assertNotSame(expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Asserts that two objects do refer to the same object. If they are not, a - * Throwable is stored in the accumulator with the given message. - * - * @param message message to be thrown if they are the same - */ - @SuppressWarnings("deprecation") - public void failSame(String message) { - try { - Assert.failSame(message); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Calls the Assert classes failNotSame method which creates an exception - * using the given message and object - * - * @param message message to be thrown if they are the same - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void failNotSame(String message, Object expected, Object actual) { - - try { - Assert.failNotSame(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Calls the Assert classes failNotEquals method which creates an exception - * using the given message and objects - * - * @param message message to be thrown if they are the same - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public void failNotEquals(String message, Object expected, Object actual) { - try { - Assert.failNotEquals(message, expected, actual); - } catch (Throwable e) { - ea.addError(e); - } - } - - /** - * Calls the Assert classes format method which creates a formatted string - * using the given message and objects to be used for an exception - * - * @param message message to be thrown if they are the same - * @param expected expected object - * @param actual actual object that is being checked - */ - @SuppressWarnings("deprecation") - public String format(String message, Object expected, Object actual) { - return Assert.format(message, expected, actual); - } - - /** - * Throws all of the accumulated errors. - */ - public void endOfCommand() { - ea.throwErrors(); - - } - - /** - * Used to check if there are any recorded errors. - * - * @return returns the errors that have been recorded. - */ - public String checkErrors() { - return ea.getErrorMessages(); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.asserts; + +import junit.framework.Assert; + +/** + * This class is mainly a wrapper for Junits Assert class. Instead of + * immediately throwing an error, the error is stored in an ErrorAccumulator to + * be thrown when needed. + */ +public class IgnoreErrorsAssert { + + public ErrorAccumulator ea; + + /** + * Called to instantiate this class + * + * @param ea the ErrorAccumulator to be used to collect all exceptions + */ + public IgnoreErrorsAssert(ErrorAccumulator ea) { + this.ea = ea; + } + + /** + * Asserts that a condition is true. If it isn't, it stores a Throwable in + * the accumulator with the given message. + * + * @param message message to be thrown if condition is false + * @param condition the condition to be evaluated + */ + @SuppressWarnings("deprecation") + public void assertTrue(String message, boolean condition) { + try { + Assert.assertTrue(message, condition); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that a condition is true. If it isn't, it stores a Throwable in + * the accumulator. + * + * @param condition the condition to be evaluated + */ + @SuppressWarnings("deprecation") + public void assertTrue(boolean condition) { + try { + Assert.assertTrue(condition); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that a condition is false. If it isn't, it stores a Throwable in + * the accumulator with the given message. + * + * @param message message to be thrown if condition is true + * @param condition the condition to be evaluated + */ + @SuppressWarnings("deprecation") + public void assertFalse(String message, boolean condition) { + try { + Assert.assertFalse(message, condition); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that a condition is false. If it isn't, it stores a Throwable in + * the accumulator. + * + * @param condition the condition to be evaluated + */ + @SuppressWarnings("deprecation") + public void assertFalse(boolean condition) { + try { + Assert.assertFalse(condition); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Fails a test with a Throwable being stored in the accumulator with the + * given message. + * + * @param message message to be thrown + */ + @SuppressWarnings("deprecation") + public void fail(String message) { + try { + Assert.fail(message); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Fails a test with a Throwable being stored in the accumulator with no + * message. + */ + @SuppressWarnings("deprecation") + public void fail() { + try { + Assert.fail(); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects are equal. If they are not, a Throwable is + * stored in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + + @SuppressWarnings("deprecation") + public void assertEquals(String message, Object expected, Object actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects are equal. If they are not an Throwable is + * stored in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(Object expected, Object actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two Strings are equal. If they are not, a Throwable is + * stored in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, String expected, String actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two Strings are equal. If they are not, a Throwable is + * stored in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String expected, String actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two doubles are equal concerning a delta. If they are not, a + * Throwable is stored in the accumulator with the given message. If the + * expected value is infinity then the delta value is ignored. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, double expected, double actual, double delta) { + try { + Assert.assertEquals(message, expected, actual, delta); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two doubles are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. If they are not, a + * Throwable is stored in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values + */ + @SuppressWarnings("deprecation") + public void assertEquals(double expected, double actual, double delta) { + try { + Assert.assertEquals(expected, actual, delta); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two floats are equal concerning a positive delta. If they + * are not, a Throwable is stored in the accumulator with the given message. + * If the expected value is infinity then the delta value is ignored. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, float expected, float actual, float delta) { + try { + Assert.assertEquals(message, expected, actual, delta); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two floats are equal concerning a delta. If the expected + * value is infinity then the delta value is ignored. If they are not, a + * Throwable is stored in the accumulator + * + * @param expected expected value + * @param actual actual value that is being checked + * @param delta the difference allowed between the two values + */ + @SuppressWarnings("deprecation") + public void assertEquals(float expected, float actual, float delta) { + try { + Assert.assertEquals(expected, actual, delta); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two longs are equal. If they are not, a Throwable is stored + * in the accumulator with the given message. If they are not, a Throwable + * is stored in the accumulator + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, long expected, long actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two longs are equal. If they are not, a Throwable is stored + * in the accumulator. If they are not, a Throwable is stored in the + * accumulator + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(long expected, long actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two booleans are equal. If they are not, a Throwable is + * stored in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, boolean expected, boolean actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two booleans are equal. If they are not, a Throwable is + * stored in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(boolean expected, boolean actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two bytes are equal. If they are not an Throwable is thrown + * with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, byte expected, byte actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two bytes are equal. If they are not, a Throwable is stored + * in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(byte expected, byte actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two chars are equal. If they are not, a Throwable is stored + * in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, char expected, char actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two chars are equal. If they are not, a Throwable is stored + * in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(char expected, char actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two shorts are equal. If they are not, a Throwable is stored + * in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + **/ + @SuppressWarnings("deprecation") + public void assertEquals(String message, short expected, short actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two shorts are equal. If they are not, a Throwable is stored + * in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(short expected, short actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two ints are equal. If they are not, a Throwable is stored + * in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(String message, int expected, int actual) { + try { + Assert.assertEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two ints are equal. If they are not, a Throwable is stored + * in the accumulator. + * + * @param expected expected value + * @param actual actual value that is being checked + */ + @SuppressWarnings("deprecation") + public void assertEquals(int expected, int actual) { + try { + Assert.assertEquals(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that an object isn't null. If they are not, a Throwable is stored + * in the accumulator. + * + * @param object object to be checked to see if it is null or not + */ + @SuppressWarnings("deprecation") + public void assertNotNull(Object object) { + try { + Assert.assertNotNull(object); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that an object isn't null. If they are not, a Throwable is stored + * in the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param object object to be checked to see if it is null or not + */ + @SuppressWarnings("deprecation") + public void assertNotNull(String message, Object object) { + try { + Assert.assertNotNull(message, object); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that an object is null. If they are not, a Throwable is stored in + * the accumulator. + * + * @param object Object to check to see if it is null + */ + @SuppressWarnings("deprecation") + public void assertNull(Object object) { + try { + Assert.assertNull(object); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that an object is null. If they are not, a Throwable is stored in + * the accumulator with the given message. + * + * @param message message to be thrown if not equal + * @param object object to be checked to see if it is null or not + */ + @SuppressWarnings("deprecation") + public void assertNull(String message, Object object) { + try { + Assert.assertNull(message, object); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects refer to the same object. If they are not, a + * Throwable is stored in the accumulator with the given message. + * + * @param message message to be thrown if not the same + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void assertSame(String message, Object expected, Object actual) { + try { + Assert.assertSame(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects refer to the same object. If they are not, a + * Throwable is stored in the accumulator. + * + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void assertSame(Object expected, Object actual) { + try { + Assert.assertSame(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects do not refer to the same object. If they are + * not, a Throwable is stored in the accumulator with the given message. + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void assertNotSame(String message, Object expected, Object actual) { + try { + Assert.assertNotSame(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + + } + + /** + * Asserts that two objects do not refer to the same object. If they are + * not, a Throwable is stored in the accumulator. + * + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void assertNotSame(Object expected, Object actual) { + try { + Assert.assertNotSame(expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Asserts that two objects do refer to the same object. If they are not, a + * Throwable is stored in the accumulator with the given message. + * + * @param message message to be thrown if they are the same + */ + @SuppressWarnings("deprecation") + public void failSame(String message) { + try { + Assert.failSame(message); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Calls the Assert classes failNotSame method which creates an exception + * using the given message and object + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void failNotSame(String message, Object expected, Object actual) { + + try { + Assert.failNotSame(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Calls the Assert classes failNotEquals method which creates an exception + * using the given message and objects + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public void failNotEquals(String message, Object expected, Object actual) { + try { + Assert.failNotEquals(message, expected, actual); + } catch (Throwable e) { + ea.addError(e); + } + } + + /** + * Calls the Assert classes format method which creates a formatted string + * using the given message and objects to be used for an exception + * + * @param message message to be thrown if they are the same + * @param expected expected object + * @param actual actual object that is being checked + */ + @SuppressWarnings("deprecation") + public String format(String message, Object expected, Object actual) { + return Assert.format(message, expected, actual); + } + + /** + * Throws all of the accumulated errors. + */ + public void endOfCommand() { + ea.throwErrors(); + + } + + /** + * Used to check if there are any recorded errors. + * + * @return returns the errors that have been recorded. + */ + public String checkErrors() { + return ea.getErrorMessages(); + } +} diff --git a/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java b/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java index dedd6a2..6b9dfce 100644 --- a/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java +++ b/src/main/java/org/finra/jtaf/core/commands/IgnoreErrors.java @@ -1,84 +1,84 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands; - -import java.util.ArrayList; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.model.statement.Invocation; - -/** - * This command surrounds a block of commands to be executed. If one of them - * throws an exception, it is stored to be reported at the end of the test and - * any commands after this block are then executed. - */ -public class IgnoreErrors extends Command { - - /** - * This called when instantiating the command before it is executed by the - * interpreter. The recordResult variable is set to false because details - * about the IgnoreErrors step aren't needed, unlike the commands within the - * IgnoreErrors block. - * - * @param name - The name of the command - * @throws NameFormatException - */ - public IgnoreErrors(String name) throws NameFormatException { - super(name); - recordResult = false; - - } - - /** - * This method goes through all of the commands within the IgnoreErrors - * block and executes them until they have all been executed or an exception - * has been thrown. If an exception is thrown, it is stored in the - * ErrorAccumulator to be reported at the end of the test. - * - * @param ctx - The current context when this method is executed. - */ - @SuppressWarnings("unchecked") - @Override - protected void execute(IInvocationContext ctx) { - ArrayList params = (ArrayList) this.getOptionalObject("blockParam"); - if (params != null) { - for (Object child : params) { - ctx.putObject("ignoreErrorsBlockFlag", true); - - try { - executeInvocation((Invocation) child); - - } catch (Throwable e) { - - interpreter.addError(e); - // logger.info("Error encountered with IgnoreErrors block for statement: " - // + child.toString()); - System.err.println("Error encountered with IgnoreErrors."); - - ctx.putObject("ignoreErrorsBlockFlag", false); - return; - } - - } - ctx.putObject("ignoreErrorsBlockFlag", false); - - } - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands; + +import java.util.ArrayList; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.model.statement.Invocation; + +/** + * This command surrounds a block of commands to be executed. If one of them + * throws an exception, it is stored to be reported at the end of the test and + * any commands after this block are then executed. + */ +public class IgnoreErrors extends Command { + + /** + * This called when instantiating the command before it is executed by the + * interpreter. The recordResult variable is set to false because details + * about the IgnoreErrors step aren't needed, unlike the commands within the + * IgnoreErrors block. + * + * @param name - The name of the command + * @throws NameFormatException + */ + public IgnoreErrors(String name) throws NameFormatException { + super(name); + recordResult = false; + + } + + /** + * This method goes through all of the commands within the IgnoreErrors + * block and executes them until they have all been executed or an exception + * has been thrown. If an exception is thrown, it is stored in the + * ErrorAccumulator to be reported at the end of the test. + * + * @param ctx - The current context when this method is executed. + */ + @SuppressWarnings("unchecked") + @Override + protected void execute(IInvocationContext ctx) { + ArrayList params = (ArrayList) this.getOptionalObject("blockParam"); + if (params != null) { + for (Object child : params) { + ctx.putObject("ignoreErrorsBlockFlag", true); + + try { + executeInvocation((Invocation) child); + + } catch (Throwable e) { + + interpreter.addError(e); + // logger.info("Error encountered with IgnoreErrors block for statement: " + // + child.toString()); + System.err.println("Error encountered with IgnoreErrors."); + + ctx.putObject("ignoreErrorsBlockFlag", false); + return; + } + + } + ctx.putObject("ignoreErrorsBlockFlag", false); + + } + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java index f7eae99..dfe11b2 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AbstractContextCmd.java @@ -1,46 +1,46 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -/** - * Base class for context-manipulating commands - */ -public abstract class AbstractContextCmd extends Command { - protected final ManipulateContextHelper mch = new ManipulateContextHelper(this, Command.getGlobalContext()); - protected IInvocationContext ctx = null; - - public AbstractContextCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected final void execute(IInvocationContext ctx) throws Throwable { - this.ctx = ctx; - execute(); - } - - protected abstract void execute() throws Throwable; - - IInvocationContext ctx() { - return this.getContext(); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +/** + * Base class for context-manipulating commands + */ +public abstract class AbstractContextCmd extends Command { + protected final ManipulateContextHelper mch = new ManipulateContextHelper(this, Command.getGlobalContext()); + protected IInvocationContext ctx = null; + + public AbstractContextCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected final void execute(IInvocationContext ctx) throws Throwable { + this.ctx = ctx; + execute(); + } + + protected abstract void execute() throws Throwable; + + IInvocationContext ctx() { + return this.getContext(); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java index 91663f1..a247a81 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AddListToListCmd.java @@ -1,57 +1,57 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets a list from context and adds all elements to another list stored in context - */ -public class AddListToListCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "addlist"; - public static final String INDEX_ATTRIBUTE = "index"; - public static final String VALUE_OUT_ATTRIBUTE = "tolist"; - - public AddListToListCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - @SuppressWarnings("unchecked") - List valueIn = (List) getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - List valueOut = (List) getOptionalObject(valueOutAttribute); - if (valueOut == null) { - List suppression = new ArrayList(); - valueOut = suppression; - } - Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); - if (index == null || index < 0) { - index = valueOut.size(); - } else if (index > 0) { // for one-based - index -= 1; - } - valueOut.addAll(index, valueIn); - mch.setValueOut(valueOutAttribute, valueOut); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets a list from context and adds all elements to another list stored in context + */ +public class AddListToListCmd extends AbstractContextCmd { + public static final String VALUE_IN_ATTRIBUTE = "addlist"; + public static final String INDEX_ATTRIBUTE = "index"; + public static final String VALUE_OUT_ATTRIBUTE = "tolist"; + + public AddListToListCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + @SuppressWarnings("unchecked") + List valueIn = (List) getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + List valueOut = (List) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + List suppression = new ArrayList(); + valueOut = suppression; + } + Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); + if (index == null || index < 0) { + index = valueOut.size(); + } else if (index > 0) { // for one-based + index -= 1; + } + valueOut.addAll(index, valueIn); + mch.setValueOut(valueOutAttribute, valueOut); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java index bd168c1..8c68eb6 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/AddObjectToListCmd.java @@ -1,57 +1,57 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets an object from context and stores that object into a list in context - */ -public class AddObjectToListCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "object"; - public static final String INDEX_ATTRIBUTE = "index"; - public static final String VALUE_OUT_ATTRIBUTE = "list"; - - public AddObjectToListCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - List valueOut = (List) getOptionalObject(valueOutAttribute); - if (valueOut == null) { - List suppression = new ArrayList(); - valueOut = suppression; - } - Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); - if (index == null || index < 0 || index > valueOut.size()) { - mch.setValueOut(valueOutAttribute, valueOut, valueIn); - } else { - if (index > 0) { // for one-based - index -= 1; - } - mch.setValueOut(valueOutAttribute, valueOut, valueIn, index); - } - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets an object from context and stores that object into a list in context + */ +public class AddObjectToListCmd extends AbstractContextCmd { + public static final String VALUE_IN_ATTRIBUTE = "object"; + public static final String INDEX_ATTRIBUTE = "index"; + public static final String VALUE_OUT_ATTRIBUTE = "list"; + + public AddObjectToListCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + List valueOut = (List) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + List suppression = new ArrayList(); + valueOut = suppression; + } + Integer index = mch.getOptionalInteger(INDEX_ATTRIBUTE); + if (index == null || index < 0 || index > valueOut.size()) { + mch.setValueOut(valueOutAttribute, valueOut, valueIn); + } else { + if (index > 0) { // for one-based + index -= 1; + } + mch.setValueOut(valueOutAttribute, valueOut, valueIn, index); + } + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java b/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java index d5ae8f2..fed01fd 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/ManipulateContextHelper.java @@ -1,438 +1,438 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import java.util.List; -import java.util.Map; - -import org.finra.jtaf.core.model.execution.IInvocationContext; - - -/** - * Helper class used for context commands - *

- * plan for context manipulation: - *

- * action = {replace out with in|prepend in to out|append in to out} - *

- * valuein - * indexin|keyin|null - * foreach = {value in list|key in map|value in map|int|null} - * change = {expand to singleton list|collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list} - *

- * valueout - * indexout|keyout|null - * foreach = {value in list|key in map|value in map|int|null} - * change = {collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list - */ -public class ManipulateContextHelper { - public static final String ACTION_ATTRIBUTE = "action"; - public static final String REPLACE_ACTION = "replace"; - public static final String PREPEND_ACTION = "prepend"; - public static final String APPEND_ACTION = "append"; - public static final String VALUE_IN_ATTRIBUTE = "valuein"; - public static final String INDEX_IN_ATTRIBUTE = "indexin"; - public static final String KEY_IN_ATTRIBUTE = "keyin"; - public static final String CHANGE_IN_ATTRIBUTE = "changein"; - public static final String SINGLETON_CHANGE = "singleton"; - public static final String VALUE_OUT_ATTRIBUTE = "valueout"; - public static final String INDEX_OUT_ATTRIBUTE = "indexout"; - public static final String KEY_OUT_ATTRIBUTE = "keyout"; - public static final String NONE_CHANGE = "none"; - private AbstractContextCmd cmd; - private IInvocationContext ctx; - private Map globalCtx; - - public ManipulateContextHelper(AbstractContextCmd cmd, Map globalCtx) { - this.cmd = cmd; - this.ctx = null; - this.globalCtx = globalCtx; - } - - private String name() { - return cmd.getName(); - } - - private IInvocationContext ctx() { - if (ctx != null) { - return ctx; - } - return cmd.ctx(); - } - - /** - * Sets a context to use instead of the global context provided in the constructor - * - * @param ctx The context to use - */ - public void setContext(IInvocationContext ctx) { - this.ctx = ctx; - } - - /** - * Checks to make sure the current "action" in context is an acceptable value - * - * @return - */ - public String getVerifiedAction() { - String action = getStringOrDefault(ACTION_ATTRIBUTE, REPLACE_ACTION); - if (!(action.equalsIgnoreCase(REPLACE_ACTION) || action.equalsIgnoreCase(APPEND_ACTION) || action.equalsIgnoreCase(PREPEND_ACTION))) { - throw new IllegalArgumentException(this.name() + ": attribute '" + ACTION_ATTRIBUTE + "' must be '" + REPLACE_ACTION + "' or '" + APPEND_ACTION + "' or '" + PREPEND_ACTION + "' (or left unspecified)"); - } - return action; - } - - /** - * Returns the values stored in an object in the context - * - * @param valueInAttribute The location of the object in the context - * @param index The index, if valueInAttribute refers to a list - * @param key The key if valueInAttribute refers to a map - * @return - */ - public Object getValueIn(String valueInAttribute, Integer index, Object key) { - if (index != null) { - return getValueIn(valueInAttribute, index); - } else if (key != null) { - return getValueIn(valueInAttribute, key); - } else { - return getOptionalObject(valueInAttribute); - } - - } - - /** - * Returns the value stored in a map in the context - * - * @param valueInAttribute The location of the map in the context - * @param key the key in the map stored in the context where to retrieve the value - * @return - */ - public Object getValueIn(String valueInAttribute, Object key) { - return ((Map) getOptionalObject(valueInAttribute)).get(key); - } - - /** - * Returns the value stored in a list in the context - * - * @param valueInAttribute The location of the list in the context - * @param index The index in the list stored in the context from where to retrieve the value - * @return - */ - public Object getValueIn(String valueInAttribute, Integer index) { - List list = (List) getOptionalObject(valueInAttribute); - if (index < 0) { - index += list.size(); - } - return list.get(index); - } - - /** - * Stores a value in a list in the context - * - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the value - * @param value The value to store in the list - * @param index The index in the list in which to store the value - */ - public void setValueOut(String valueOutAttribute, List list, Object value, int index) { - list.add(index, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Appends an object to a list stored in the context - * - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the value - * @param value The value to store in the list - */ - public void setValueOut(String valueOutAttribute, List list, Object value) { - list.add(value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Appends all the values of a list into another list that is stored in the context - * - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the values - * @param value The list of values being stored - */ - public void setValueOut(String valueOutAttribute, List list, List value) { - list.addAll(value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stores all the values of a list into another list that is stored in the context - * - * @param valueOutAttribute Where to store the resulting list in the context - * @param list The list in which to store the values - * @param value The list of values being stored - * @param index The index in the list in which to store the value - */ - public void setValueOut(String valueOutAttribute, List list, List value, int index) { - list.addAll(index, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stores a value in a map stored in the context - * - * @param valueOutAttribute Where to store the resulting map in the context - * @param list The map in which to store the values - * @param value The value being stored in the map - * @param key The key at which to store the value in the map - */ - public void setValueOut(String valueOutAttribute, Map list, T value, K key) { - list.put(key, value); - ctx().putObject(valueOutAttribute, list); - } - - /** - * Stored an object in the context - * - * @param valueOutAttribute Where to store the object in the context - * @param value The object to store in the context - */ - public void setValueOut(String valueOutAttribute, Object value) { - ctx().putObject(valueOutAttribute, value); - } - - - /** - * Grabs an Object from the Context. - * - * @param key - * @return - */ - public Object getOptionalObject(String key) { - // We cannot assume that a parameter is optional just because getOptionalObject was - // called. Most commands failed to distinguish between optional and required parameters. - - Object result = ctx().getObject(key); - - // process 'contextKey' parameter - if ((result != null) && (result.getClass().equals(String.class))) { - String[] resultSplitted = ((String) result).split("\\$contextKey"); - StringBuffer resultString = new StringBuffer(resultSplitted[0]); - - int i = 1; - while (resultSplitted.length > i) { - int beginIndex = resultSplitted[i].indexOf("("); - if (beginIndex >= 0) { - int endIndex = resultSplitted[i].indexOf(")", beginIndex); - if (endIndex > 0) { - String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, endIndex); - runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); - - if (globalCtx.get(runTimeKeyName) != null) { - resultString.append(globalCtx.get(runTimeKeyName) + resultSplitted[i].substring(endIndex + 1)); - } else { - throw new RuntimeException("Oops! Processing '" + key + "'='" + result + "' key fails! Can't find run time parameter '" + runTimeKeyName - + "'! You have put it to global content before..."); - } - } - } - i++; - } - return resultString.toString(); - } - return result; - } - - - /** - * Grabs an object from the Context, or throws an exception - * if the Object does not exist. - * - * @param key - * @return - */ - public Object getRequiredObject(String key) { - Object param = this.getOptionalObject(key); - if (param == null) { - throw new IllegalArgumentException(this.name() + " : The parameter with key [" + key + "] is not set."); - } - return param; - } - - - /** - * Returns an integer value, or throws a NullPointerException if the value is not present - * - * @param attributeName - * @param ctx - * @return - */ - public int getRequiredInteger(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - throw new NullPointerException(this.name() + ": missing required integer attribute '" + attributeName + "'"); - } - return Integer.parseInt(value); - } - - - /** - * Like the above, except it returns a default value if the attribute is not set - * - * @param attributeName - * @param ctx - * @param defaultValue - * @return - */ - public int getIntegerOrDefault(String attributeName, int defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - return defaultValue; - } - return Integer.parseInt(value); - } - - /** - * Returns a float stored in the context or throws a NullPointerException is one isn't - * - * @param attributeName Where in the context the float is stored - * @return The float stored in attributeName - */ - public float getRequiredFloat(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - throw new NullPointerException(this.name() + ": missing required float attribute '" + attributeName + "'"); - } - return Float.parseFloat(value); - } - - /** - * Like the above, except it returns a default value if the attribute is not set - * - * @param attributeName Where in the context the float is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The float stored in attributeName or defaultValue if one wasn't present - */ - public float getFloatOrDefault(String attributeName, float defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - return defaultValue; - } - return Float.parseFloat(value); - } - - - /** - * Returns a String stored in the context or throws a NullPointerException is one isn't - * - * @param attributeName Where in the context the String is stored - * @return The String stored in attributeName - */ - public String getRequiredString(String attributeName) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - throw new NullPointerException(this.name() + ": missing required String attribute '" + attributeName + "'"); - } - return value; - } - - - /** - * Like the above, except it returns a default value if the attribute is not set - * - * @param attributeName attributeName Where in the context the String is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The String stored in attributeName or defaultValue if one wasn't present - */ - public String getStringOrDefault(String attributeName, String defaultValue) { - String value = (String) this.getOptionalObject(attributeName); - if (value == null) { - return defaultValue; - } - return value; - } - - /** - * Returns a String stored in the context or null if there isn't one - * - * @param attributeName Where in the context the String is stored - * @return The string stored in attributeName or null if there isn't one - */ - public String getOptionalString(String attributeName) { - return (String) this.getOptionalObject(attributeName); - } - - /** - * Returns a float stored in the context or throws a NullPointerException is one isn't - * - * @param attributeName Where in the context the boolean is stored - * @return The boolean stored in attributeName - */ - public boolean getRequiredBoolean(String attributeName) { - String temp = (String) this.getOptionalObject(attributeName); - if (temp == null) { - throw new NullPointerException(this.name() + ": missing required boolean attribute '" + attributeName + "'"); - } - - temp = temp.trim(); - if (temp.equalsIgnoreCase("true")) { - return true; - } else if (temp.equalsIgnoreCase("false")) { - return false; - } else { - throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false'"); - } - } - - /** - * Like the above, except it returns a default value if the attribute is not set - * - * @param attributeName Where in the context the boolean is stored - * @param defaultValue The value to return if the context does not contain a value at attributeName - * @return The boolean stored in attributeName or defaultValue if one wasn't present - */ - public boolean getBooleanOrDefault(String attributeName, boolean defaultValue) { - String temp = (String) this.getOptionalObject(attributeName); - if (temp == null) { - return defaultValue; - } - - temp = temp.trim(); - if (temp.equalsIgnoreCase("true")) { - return true; - } else if (temp.equalsIgnoreCase("false")) { - return false; - } else { - throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false' (or left unspecified)"); - } - } - - /** - * Returns an Integer stored in the context or null if there isn't one - * - * @param key Where in the context the Integer is stored - * @return The string stored in key or null if there isn't one - */ - public Integer getOptionalInteger(String key) { - String integerAsString = (String) getOptionalObject(key); - if (integerAsString == null) { - return null; - } else { - return Integer.parseInt(integerAsString); - } - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import java.util.List; +import java.util.Map; + +import org.finra.jtaf.core.model.execution.IInvocationContext; + + +/** + * Helper class used for context commands + *

+ * plan for context manipulation: + *

+ * action = {replace out with in|prepend in to out|append in to out} + *

+ * valuein + * indexin|keyin|null + * foreach = {value in list|key in map|value in map|int|null} + * change = {expand to singleton list|collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list} + *

+ * valueout + * indexout|keyout|null + * foreach = {value in list|key in map|value in map|int|null} + * change = {collapse list to set|expand set to map keys|convert map keys to set|convert set to list|convert map values to list + */ +public class ManipulateContextHelper { + public static final String ACTION_ATTRIBUTE = "action"; + public static final String REPLACE_ACTION = "replace"; + public static final String PREPEND_ACTION = "prepend"; + public static final String APPEND_ACTION = "append"; + public static final String VALUE_IN_ATTRIBUTE = "valuein"; + public static final String INDEX_IN_ATTRIBUTE = "indexin"; + public static final String KEY_IN_ATTRIBUTE = "keyin"; + public static final String CHANGE_IN_ATTRIBUTE = "changein"; + public static final String SINGLETON_CHANGE = "singleton"; + public static final String VALUE_OUT_ATTRIBUTE = "valueout"; + public static final String INDEX_OUT_ATTRIBUTE = "indexout"; + public static final String KEY_OUT_ATTRIBUTE = "keyout"; + public static final String NONE_CHANGE = "none"; + private AbstractContextCmd cmd; + private IInvocationContext ctx; + private Map globalCtx; + + public ManipulateContextHelper(AbstractContextCmd cmd, Map globalCtx) { + this.cmd = cmd; + this.ctx = null; + this.globalCtx = globalCtx; + } + + private String name() { + return cmd.getName(); + } + + private IInvocationContext ctx() { + if (ctx != null) { + return ctx; + } + return cmd.ctx(); + } + + /** + * Sets a context to use instead of the global context provided in the constructor + * + * @param ctx The context to use + */ + public void setContext(IInvocationContext ctx) { + this.ctx = ctx; + } + + /** + * Checks to make sure the current "action" in context is an acceptable value + * + * @return + */ + public String getVerifiedAction() { + String action = getStringOrDefault(ACTION_ATTRIBUTE, REPLACE_ACTION); + if (!(action.equalsIgnoreCase(REPLACE_ACTION) || action.equalsIgnoreCase(APPEND_ACTION) || action.equalsIgnoreCase(PREPEND_ACTION))) { + throw new IllegalArgumentException(this.name() + ": attribute '" + ACTION_ATTRIBUTE + "' must be '" + REPLACE_ACTION + "' or '" + APPEND_ACTION + "' or '" + PREPEND_ACTION + "' (or left unspecified)"); + } + return action; + } + + /** + * Returns the values stored in an object in the context + * + * @param valueInAttribute The location of the object in the context + * @param index The index, if valueInAttribute refers to a list + * @param key The key if valueInAttribute refers to a map + * @return + */ + public Object getValueIn(String valueInAttribute, Integer index, Object key) { + if (index != null) { + return getValueIn(valueInAttribute, index); + } else if (key != null) { + return getValueIn(valueInAttribute, key); + } else { + return getOptionalObject(valueInAttribute); + } + + } + + /** + * Returns the value stored in a map in the context + * + * @param valueInAttribute The location of the map in the context + * @param key the key in the map stored in the context where to retrieve the value + * @return + */ + public Object getValueIn(String valueInAttribute, Object key) { + return ((Map) getOptionalObject(valueInAttribute)).get(key); + } + + /** + * Returns the value stored in a list in the context + * + * @param valueInAttribute The location of the list in the context + * @param index The index in the list stored in the context from where to retrieve the value + * @return + */ + public Object getValueIn(String valueInAttribute, Integer index) { + List list = (List) getOptionalObject(valueInAttribute); + if (index < 0) { + index += list.size(); + } + return list.get(index); + } + + /** + * Stores a value in a list in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the value + * @param value The value to store in the list + * @param index The index in the list in which to store the value + */ + public void setValueOut(String valueOutAttribute, List list, Object value, int index) { + list.add(index, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Appends an object to a list stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the value + * @param value The value to store in the list + */ + public void setValueOut(String valueOutAttribute, List list, Object value) { + list.add(value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Appends all the values of a list into another list that is stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the values + * @param value The list of values being stored + */ + public void setValueOut(String valueOutAttribute, List list, List value) { + list.addAll(value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stores all the values of a list into another list that is stored in the context + * + * @param valueOutAttribute Where to store the resulting list in the context + * @param list The list in which to store the values + * @param value The list of values being stored + * @param index The index in the list in which to store the value + */ + public void setValueOut(String valueOutAttribute, List list, List value, int index) { + list.addAll(index, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stores a value in a map stored in the context + * + * @param valueOutAttribute Where to store the resulting map in the context + * @param list The map in which to store the values + * @param value The value being stored in the map + * @param key The key at which to store the value in the map + */ + public void setValueOut(String valueOutAttribute, Map list, T value, K key) { + list.put(key, value); + ctx().putObject(valueOutAttribute, list); + } + + /** + * Stored an object in the context + * + * @param valueOutAttribute Where to store the object in the context + * @param value The object to store in the context + */ + public void setValueOut(String valueOutAttribute, Object value) { + ctx().putObject(valueOutAttribute, value); + } + + + /** + * Grabs an Object from the Context. + * + * @param key + * @return + */ + public Object getOptionalObject(String key) { + // We cannot assume that a parameter is optional just because getOptionalObject was + // called. Most commands failed to distinguish between optional and required parameters. + + Object result = ctx().getObject(key); + + // process 'contextKey' parameter + if ((result != null) && (result.getClass().equals(String.class))) { + String[] resultSplitted = ((String) result).split("\\$contextKey"); + StringBuffer resultString = new StringBuffer(resultSplitted[0]); + + int i = 1; + while (resultSplitted.length > i) { + int beginIndex = resultSplitted[i].indexOf("("); + if (beginIndex >= 0) { + int endIndex = resultSplitted[i].indexOf(")", beginIndex); + if (endIndex > 0) { + String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, endIndex); + runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); + + if (globalCtx.get(runTimeKeyName) != null) { + resultString.append(globalCtx.get(runTimeKeyName) + resultSplitted[i].substring(endIndex + 1)); + } else { + throw new RuntimeException("Oops! Processing '" + key + "'='" + result + "' key fails! Can't find run time parameter '" + runTimeKeyName + + "'! You have put it to global content before..."); + } + } + } + i++; + } + return resultString.toString(); + } + return result; + } + + + /** + * Grabs an object from the Context, or throws an exception + * if the Object does not exist. + * + * @param key + * @return + */ + public Object getRequiredObject(String key) { + Object param = this.getOptionalObject(key); + if (param == null) { + throw new IllegalArgumentException(this.name() + " : The parameter with key [" + key + "] is not set."); + } + return param; + } + + + /** + * Returns an integer value, or throws a NullPointerException if the value is not present + * + * @param attributeName + * @param ctx + * @return + */ + public int getRequiredInteger(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required integer attribute '" + attributeName + "'"); + } + return Integer.parseInt(value); + } + + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName + * @param ctx + * @param defaultValue + * @return + */ + public int getIntegerOrDefault(String attributeName, int defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return Integer.parseInt(value); + } + + /** + * Returns a float stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the float is stored + * @return The float stored in attributeName + */ + public float getRequiredFloat(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required float attribute '" + attributeName + "'"); + } + return Float.parseFloat(value); + } + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName Where in the context the float is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The float stored in attributeName or defaultValue if one wasn't present + */ + public float getFloatOrDefault(String attributeName, float defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return Float.parseFloat(value); + } + + + /** + * Returns a String stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the String is stored + * @return The String stored in attributeName + */ + public String getRequiredString(String attributeName) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + throw new NullPointerException(this.name() + ": missing required String attribute '" + attributeName + "'"); + } + return value; + } + + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName attributeName Where in the context the String is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The String stored in attributeName or defaultValue if one wasn't present + */ + public String getStringOrDefault(String attributeName, String defaultValue) { + String value = (String) this.getOptionalObject(attributeName); + if (value == null) { + return defaultValue; + } + return value; + } + + /** + * Returns a String stored in the context or null if there isn't one + * + * @param attributeName Where in the context the String is stored + * @return The string stored in attributeName or null if there isn't one + */ + public String getOptionalString(String attributeName) { + return (String) this.getOptionalObject(attributeName); + } + + /** + * Returns a float stored in the context or throws a NullPointerException is one isn't + * + * @param attributeName Where in the context the boolean is stored + * @return The boolean stored in attributeName + */ + public boolean getRequiredBoolean(String attributeName) { + String temp = (String) this.getOptionalObject(attributeName); + if (temp == null) { + throw new NullPointerException(this.name() + ": missing required boolean attribute '" + attributeName + "'"); + } + + temp = temp.trim(); + if (temp.equalsIgnoreCase("true")) { + return true; + } else if (temp.equalsIgnoreCase("false")) { + return false; + } else { + throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false'"); + } + } + + /** + * Like the above, except it returns a default value if the attribute is not set + * + * @param attributeName Where in the context the boolean is stored + * @param defaultValue The value to return if the context does not contain a value at attributeName + * @return The boolean stored in attributeName or defaultValue if one wasn't present + */ + public boolean getBooleanOrDefault(String attributeName, boolean defaultValue) { + String temp = (String) this.getOptionalObject(attributeName); + if (temp == null) { + return defaultValue; + } + + temp = temp.trim(); + if (temp.equalsIgnoreCase("true")) { + return true; + } else if (temp.equalsIgnoreCase("false")) { + return false; + } else { + throw new IllegalArgumentException(this.name() + ": attribute '" + attributeName + "' must be either 'true' or 'false' (or left unspecified)"); + } + } + + /** + * Returns an Integer stored in the context or null if there isn't one + * + * @param key Where in the context the Integer is stored + * @return The string stored in key or null if there isn't one + */ + public Integer getOptionalInteger(String key) { + String integerAsString = (String) getOptionalObject(key); + if (integerAsString == null) { + return null; + } else { + return Integer.parseInt(integerAsString); + } + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java index e07cdbf..c08722b 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/PutObjectInMapCmd.java @@ -1,50 +1,50 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import java.util.HashMap; -import java.util.Map; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets an object from context and stores that object into a map in context - */ -public class PutObjectInMapCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "object"; - public static final String KEY_ATTRIBUTE = "key"; - public static final String VALUE_OUT_ATTRIBUTE = "map"; - - public PutObjectInMapCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - @SuppressWarnings("unchecked") - Map valueOut = (Map) getOptionalObject(valueOutAttribute); - if (valueOut == null) { - Map suppression = new HashMap(); - valueOut = suppression; - } - Object key = mch.getRequiredObject(KEY_ATTRIBUTE); - mch.setValueOut(valueOutAttribute, valueOut, valueIn, key); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import java.util.HashMap; +import java.util.Map; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets an object from context and stores that object into a map in context + */ +public class PutObjectInMapCmd extends AbstractContextCmd { + public static final String VALUE_IN_ATTRIBUTE = "object"; + public static final String KEY_ATTRIBUTE = "key"; + public static final String VALUE_OUT_ATTRIBUTE = "map"; + + public PutObjectInMapCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + Object valueIn = getRequiredObject(getRequiredString(VALUE_IN_ATTRIBUTE)); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + @SuppressWarnings("unchecked") + Map valueOut = (Map) getOptionalObject(valueOutAttribute); + if (valueOut == null) { + Map suppression = new HashMap(); + valueOut = suppression; + } + Object key = mch.getRequiredObject(KEY_ATTRIBUTE); + mch.setValueOut(valueOutAttribute, valueOut, valueIn, key); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java index e34bb19..cdceca1 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/RemoveObjectFromContextCmd.java @@ -1,36 +1,36 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Removes an object from context by replacing it with null - */ -public class RemoveObjectFromContextCmd extends AbstractContextCmd { - public static final String VALUE_ATTRIBUTE = "object"; - - public RemoveObjectFromContextCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - mch.setValueOut(getRequiredString(VALUE_ATTRIBUTE), (Object) null); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Removes an object from context by replacing it with null + */ +public class RemoveObjectFromContextCmd extends AbstractContextCmd { + public static final String VALUE_ATTRIBUTE = "object"; + + public RemoveObjectFromContextCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + mch.setValueOut(getRequiredString(VALUE_ATTRIBUTE), (Object) null); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java index 8712bcb..804ef4c 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreDefaultObjectCmd.java @@ -1,44 +1,44 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Stores a default value into context unless the object already exists in context - */ -public class StoreDefaultObjectCmd extends AbstractContextCmd { - public static final String DEFAULT_ATTRIBUTE = "defaultKey"; - public static final String DEFAULT = "default"; - public static final String VALUE_OUT_ATTRIBUTE = "contextKey"; - - public StoreDefaultObjectCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() { - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - Object valueOut = getOptionalObject(valueOutAttribute); - if (valueOut == null) { - String defaultAttribute = getStringOrDefault(DEFAULT_ATTRIBUTE, DEFAULT); - valueOut = getRequiredObject(defaultAttribute); - } - mch.setValueOut(valueOutAttribute, valueOut); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Stores a default value into context unless the object already exists in context + */ +public class StoreDefaultObjectCmd extends AbstractContextCmd { + public static final String DEFAULT_ATTRIBUTE = "defaultKey"; + public static final String DEFAULT = "default"; + public static final String VALUE_OUT_ATTRIBUTE = "contextKey"; + + public StoreDefaultObjectCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() { + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + Object valueOut = getOptionalObject(valueOutAttribute); + if (valueOut == null) { + String defaultAttribute = getStringOrDefault(DEFAULT_ATTRIBUTE, DEFAULT); + valueOut = getRequiredObject(defaultAttribute); + } + mch.setValueOut(valueOutAttribute, valueOut); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java index 5824601..7e425a6 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectAsStringCmd.java @@ -1,43 +1,43 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets an object from context and stores that object into context as its .toString() value - */ -public class StoreObjectAsStringCmd extends AbstractContextCmd { - public static final String VALUE_ATTRIBUTE = "key"; - - public StoreObjectAsStringCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - String valueName = getRequiredString(VALUE_ATTRIBUTE); - Object value = getOptionalObject(valueName); - if (value == null) { - value = "null"; - } else { - value = value.toString(); - } - getContext().putObject(valueName, value); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets an object from context and stores that object into context as its .toString() value + */ +public class StoreObjectAsStringCmd extends AbstractContextCmd { + public static final String VALUE_ATTRIBUTE = "key"; + + public StoreObjectAsStringCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + String valueName = getRequiredString(VALUE_ATTRIBUTE); + Object value = getOptionalObject(valueName); + if (value == null) { + value = "null"; + } else { + value = value.toString(); + } + getContext().putObject(valueName, value); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java index cef36b2..eb15d63 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromListCmd.java @@ -1,46 +1,46 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets an object from a list in context and stores that object into context - */ -public class StoreObjectFromListCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "list"; - public static final String INDEX_ATTRIBUTE = "index"; - public static final String VALUE_OUT_ATTRIBUTE = "object"; - - public StoreObjectFromListCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - Integer index = mch.getRequiredInteger(INDEX_ATTRIBUTE); - if (index <= 0) { - throw new Exception("Index is " + index - + ". Please provide a valid index. (Index starts at 1)"); - } - index = index - 1; // for one-based - Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), index); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - mch.setValueOut(valueOutAttribute, valueIn); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets an object from a list in context and stores that object into context + */ +public class StoreObjectFromListCmd extends AbstractContextCmd { + public static final String VALUE_IN_ATTRIBUTE = "list"; + public static final String INDEX_ATTRIBUTE = "index"; + public static final String VALUE_OUT_ATTRIBUTE = "object"; + + public StoreObjectFromListCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + Integer index = mch.getRequiredInteger(INDEX_ATTRIBUTE); + if (index <= 0) { + throw new Exception("Index is " + index + + ". Please provide a valid index. (Index starts at 1)"); + } + index = index - 1; // for one-based + Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), index); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + mch.setValueOut(valueOutAttribute, valueIn); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java index d04c307..a4fb750 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectFromMapCmd.java @@ -1,41 +1,41 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; - -/** - * Gets an object from a map in context and stores that object into context - */ -public class StoreObjectFromMapCmd extends AbstractContextCmd { - public static final String VALUE_IN_ATTRIBUTE = "map"; - public static final String INDEX_ATTRIBUTE = "mapKey"; - public static final String VALUE_OUT_ATTRIBUTE = "objectKey"; - - public StoreObjectFromMapCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute() throws Throwable { - Object key = mch.getRequiredObject(INDEX_ATTRIBUTE); - Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), key); - String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); - mch.setValueOut(valueOutAttribute, valueIn); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; + +/** + * Gets an object from a map in context and stores that object into context + */ +public class StoreObjectFromMapCmd extends AbstractContextCmd { + public static final String VALUE_IN_ATTRIBUTE = "map"; + public static final String INDEX_ATTRIBUTE = "mapKey"; + public static final String VALUE_OUT_ATTRIBUTE = "objectKey"; + + public StoreObjectFromMapCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute() throws Throwable { + Object key = mch.getRequiredObject(INDEX_ATTRIBUTE); + Object valueIn = mch.getValueIn(getRequiredString(VALUE_IN_ATTRIBUTE), key); + String valueOutAttribute = getRequiredString(VALUE_OUT_ATTRIBUTE); + mch.setValueOut(valueOutAttribute, valueIn); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java index edc58f0..f470c95 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/StoreObjectInContextCmd.java @@ -1,41 +1,41 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.commands.context; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -/** - * Gets an object from context and stores that object into another attribute - */ -public class StoreObjectInContextCmd extends Command { - - public StoreObjectInContextCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext arg0) throws Throwable { - String newKey = getRequiredString("storeKey"); - String key = getRequiredString("loadKey"); - - Object o = getRequiredObject(key); - arg0.putObject(newKey, o); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.commands.context; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +/** + * Gets an object from context and stores that object into another attribute + */ +public class StoreObjectInContextCmd extends Command { + + public StoreObjectInContextCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext arg0) throws Throwable { + String newKey = getRequiredString("storeKey"); + String key = getRequiredString("loadKey"); + + Object o = getRequiredObject(key); + arg0.putObject(newKey, o); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java b/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java index a801d70..a141c7a 100644 --- a/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java +++ b/src/main/java/org/finra/jtaf/core/commands/context/VerifyObjectInContextCmd.java @@ -1,57 +1,57 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.commands.context; - -import java.util.List; - -import org.apache.commons.lang.StringUtils; -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.utilities.CompositeDataComparator; - -/** - * Compares two objects from context - */ -public class VerifyObjectInContextCmd extends Command { - - public VerifyObjectInContextCmd(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext arg0) throws Throwable { - String actualKey = getRequiredString("actualKey"); - String expectedKey = getRequiredString("expectedKey"); - String title = getOptionalString("title"); - boolean failOnNotEqual = getBooleanOrDefault("failOnNotEqual", true); - Object actual = getRequiredObject(actualKey); - Object expected = getRequiredObject(expectedKey); - CompositeDataComparator cdc = new CompositeDataComparator(); - cdc.setAccumulateErrors(true); - cdc.compareObject(title, null, expected, actual); - List errorList = cdc.getErrorList(); - if (failOnNotEqual && errorList != null && !errorList.isEmpty()) { - if (title != null) { - throw new AssertionError("Expected " + title + " did not match actual:\n" + StringUtils.join(errorList, "\n")); - } - throw new AssertionError("Expected did not match actual:\n" + StringUtils.join(errorList, "\n")); - } - arg0.putObject("errorList", errorList); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.commands.context; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.utilities.CompositeDataComparator; + +/** + * Compares two objects from context + */ +public class VerifyObjectInContextCmd extends Command { + + public VerifyObjectInContextCmd(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext arg0) throws Throwable { + String actualKey = getRequiredString("actualKey"); + String expectedKey = getRequiredString("expectedKey"); + String title = getOptionalString("title"); + boolean failOnNotEqual = getBooleanOrDefault("failOnNotEqual", true); + Object actual = getRequiredObject(actualKey); + Object expected = getRequiredObject(expectedKey); + CompositeDataComparator cdc = new CompositeDataComparator(); + cdc.setAccumulateErrors(true); + cdc.compareObject(title, null, expected, actual); + List errorList = cdc.getErrorList(); + if (failOnNotEqual && errorList != null && !errorList.isEmpty()) { + if (title != null) { + throw new AssertionError("Expected " + title + " did not match actual:\n" + StringUtils.join(errorList, "\n")); + } + throw new AssertionError("Expected did not match actual:\n" + StringUtils.join(errorList, "\n")); + } + arg0.putObject("errorList", errorList); + } +} diff --git a/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java b/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java index 95072bc..5f50169 100644 --- a/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java +++ b/src/main/java/org/finra/jtaf/core/exceptions/DependencyException.java @@ -1,41 +1,41 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.exceptions; - -public class DependencyException extends RuntimeException { - - /** - * Auto-generated - */ - private static final long serialVersionUID = 4864467896129227737L; - - public DependencyException() { - super(); - } - - public DependencyException(String message) { - super(message); - } - - public DependencyException(String message, Throwable th) { - super(message, th); - } - - public DependencyException(Throwable th) { - super(th); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.exceptions; + +public class DependencyException extends RuntimeException { + + /** + * Auto-generated + */ + private static final long serialVersionUID = 4864467896129227737L; + + public DependencyException() { + super(); + } + + public DependencyException(String message) { + super(message); + } + + public DependencyException(String message, Throwable th) { + super(message, th); + } + + public DependencyException(Throwable th) { + super(th); + } +} diff --git a/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java b/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java index a6cf1d5..6cfe051 100644 --- a/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java +++ b/src/main/java/org/finra/jtaf/core/exceptions/GetInvocationTargetException.java @@ -3,5 +3,12 @@ /** * Created by mibrahim on 1/13/16. */ -public class GetInvocationTargetException { +public class GetInvocationTargetException extends Exception { + public GetInvocationTargetException(String message) { + super(message); + } + + public GetInvocationTargetException(String message, Exception e) { + super(message, e); + } } diff --git a/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java b/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java index 70f1549..e6b3976 100644 --- a/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java +++ b/src/main/java/org/finra/jtaf/core/model/execution/Interpreter.java @@ -1,413 +1,419 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.execution; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.DefaultAutomationClassLoader; -import org.finra.jtaf.core.IAutomationClassLoader; -import org.finra.jtaf.core.asserts.ErrorAccumulator; -import org.finra.jtaf.core.model.exceptions.MissingInvocationTargetException; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.model.invocationtarget.Function; -import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.statement.InvocationList; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestStatus; -import org.finra.jtaf.core.model.test.TestStepsDetails; -import org.finra.jtaf.core.plugins.execution.CommandRunnerPluginContext; -import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; -import org.finra.jtaf.core.plugins.execution.ITearDownPlugin; -import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; -import org.finra.jtaf.core.plugins.execution.TearDownPluginContext; -import org.finra.jtaf.core.plugins.execution.TestRunnerPluginContext; - -/** - * This class is invoked by the Automation Engine to begin execution - */ -public class Interpreter { - private static final Logger logger = Logger.getLogger(Interpreter.class); - private CommandRegistry commandRegistry; - private static IInterpreterContext context; - private TestStatus testStatus; - public ErrorAccumulator ea; - - private List testRunnerPlugins; - private List commandRunnerPlugins; - private List tearDownPlugins; - private IAutomationClassLoader automationClassLoader; - private List testStepDetails; - - /** - * Add plugins that should run before or after a test - * - * @param testRunnerPlugins => the list of test level plugins - */ - public void setTestRunnerPlugins(List testRunnerPlugins) { - this.testRunnerPlugins = testRunnerPlugins; - } - - /** - * Add plugins that should run before or after a command - * - * @param commandRunnerPlugins => the list of command level plugins - */ - public void setCommandRunnerPlugins( - List commandRunnerPlugins) { - this.commandRunnerPlugins = commandRunnerPlugins; - } - - public void setTearDownPlugins(List tearDownPlugins) { - this.tearDownPlugins = tearDownPlugins; - } - - /** - * Set the command registry - * - * @param commandRegistry - */ - public void setCommandRegistry(CommandRegistry commandRegistry) { - this.commandRegistry = commandRegistry; - } - - /** - * Execute the commands in the testscript passed to the Interpreter. Execute - * custom plugins that are supposed to run before and after each test or - * each command. The test passes if this method executes without throwing an - * exception. - * - * @param test =>testscript object passed by the Automation Engine - * @throws Throwable - */ - public final TestResult interpret(TestScript test) throws Throwable { - logger.info(test.getFullName()); - Throwable failure = null; - context = new CorrectiveContext(); - context.setTestScript(test); - - ea = new ErrorAccumulator("Accumulator"); - // Multithreaded use - automationClassLoader = new DefaultAutomationClassLoader(); - testStatus = TestStatus.Running; - testStepDetails = new ArrayList(); - executeTestStartPlugins(test); - try { - visitInvocationList(test.getBody()); - failure = ea.getWrappedErrors(); - } catch (Throwable t) { - failure = t; - this.testStatus = TestStatus.Failed; - } finally { - if (failure == null) - this.testStatus = TestStatus.Passed; - else { - this.testStatus = TestStatus.Failed; - } - - executeTestFinishPlugins(); - - } - if (failure != null - && failure.getClass().getSimpleName() - .equalsIgnoreCase(test.getException())) { - failure = null; - this.testStatus = TestStatus.Passed; - } - return new TestResult(this.getTestStepDetails(), testStatus, failure); - } - - /** - * Return the list of test steps in the current test - * - * @return - */ - public List getTestStepDetails() { - return testStepDetails; - } - - /** - * Execute the list of commands in the test - * - * @param invocationtList - * @throws Throwable - */ - public void visitInvocationList(InvocationList invocationtList) - throws Throwable { - - try { - - for (Invocation invocation : invocationtList) { - try { - - visitInvocation((Invocation) invocation); - } catch (Throwable th) { - if (!ea.isEmpty() && !ea.hasThrown()) { - ea.addError((Throwable) th); - - ea.throwErrors(); - } else { - throw th; - } - } - } - } catch (Throwable th) { - this.testStatus = TestStatus.Failed; - throw th; - } - } - - /** - * Invoke the command's launch API. Responsible of actual execution of the - * command - * - * @param command => current command object to be executed - * @throws Throwable - */ - public void visitCommand(Command command) throws Throwable { - executeCommandStartPlugins(command); - try { - command.launch(context, this); - } catch (Throwable t) { - throw t; - } finally { - executeCommandFinishPlugins(command); - } - - } - - /** - * Execute the function, if any, present in the test - * - * @param function - * @throws Throwable - */ - public void visitFunction(Function function) throws Throwable { - this.visitInvocationList(function.getBody()); - - } - - /** - * Execute the commands in the testscript passed to the Interpreter. - * - * @param invocation =>testscript object passed by the Automation Engine - * @throws Throwable - */ - public final void visitInvocation(Invocation invocation) throws Throwable { - if (invocation.getTargetName().equals("TryRecoverCleanup")) { - // Ignore logging TryRecoverCleanup statement - } else { - logger.info(invocation.toString()); - } - if (this.commandRegistry.containsInvocationTarget(invocation - .getTargetName())) { - final InvocationTarget target = this.commandRegistry - .getInvocationTarget(invocation.getTargetName()); - context.pushInvocation(invocation, target); - } else { - throw new MissingInvocationTargetException(invocation); - } - - try { - InvocationTarget target = getInvocationTarget(invocation); - - target.acceptInvocationTargetVisitor(this); - - } finally { - - context.popFrame(); - } - } - - /** - * Get the invocation target instance if it exists in the Command Registry - * else throw exception 'Invocation not found' - * - * @param invocation - * @return - * @throws Throwable - */ - public InvocationTarget getInvocationTarget(Invocation invocation) - throws Throwable { - // Check if it exists in the local map already - InvocationTarget target = null; - // Get the InvocationTarget from the previously mapped ones. - InvocationTarget mappedInvocationTarget = this.commandRegistry - .getInvocationTarget(invocation.getTargetName()); - - if (mappedInvocationTarget == null) { - throw new IllegalArgumentException("Invocation " - + invocation.getTargetName() + " not found"); - } - - if (mappedInvocationTarget instanceof Function) { - target = mappedInvocationTarget; - } else { - // Instantiate the InvocationTarget. - Class targetClass = automationClassLoader - .loadClass(mappedInvocationTarget.getClass().getName()); - if (InvocationTarget.class.isAssignableFrom(targetClass)) { - Constructor constructor = targetClass - .getConstructor(String.class); - target = (InvocationTarget) constructor.newInstance(invocation - .getTargetName()); - - // This is to reload the parameters from preparsed Map of - // InvocationTargets (ScriptParser) - for (String s : mappedInvocationTarget.getRequiredParameters()) { - target.addRequiredParameter(s); - } - - for (String s : mappedInvocationTarget.getOptionalParameters()) { - target.addOptionalParameter(s); - } - - for (String s : mappedInvocationTarget.getProductions()) { - target.addProduction(s); - } - } else { - throw new IllegalArgumentException("Invocation not found"); - } - } - return target; - } - - /** - * Add details of the invocation to the list of test steps - */ - public void addDetails(TestStepsDetails details) { - testStepDetails.add(details); - } - - /** - * Add exception to the Error Accumulator and set the Test Status to 'Failed' - * - * @param th - */ - public void addError(Throwable th) { - ea.addError(th); - this.testStatus = TestStatus.Failed; - - } - - /** - * Run TestRunner plugins after a test finishes execution - */ - private void executeTestFinishPlugins() { - - if (testRunnerPlugins != null) { - for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { - try { - testPlugin - .handleTestFinish(new TestRunnerPluginContext( - context.getTestScript(), new TestResult( - this.getTestStepDetails(), - testStatus), context)); - } catch (Throwable e) { - logger.error(e); - - } - - } - } - } - - /** - * Run TestRunner plugins before a test starts execution - * - * @param test => the current testscript in context - */ - private void executeTestStartPlugins(TestScript test) { - // handleTestStart - try { - if (testRunnerPlugins != null) { - for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { - testPlugin.handleTestStart(new TestRunnerPluginContext( - test, new TestResult(this.getTestStepDetails(), - testStatus), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - /** - * Run CommandRunner plugins after a command is executed - * - * @param command - */ - private void executeCommandFinishPlugins(Command command) { - - try { - if (commandRunnerPlugins != null) { - for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { - commandPlugin - .handleCommandAfter(new CommandRunnerPluginContext( - new TestStepsDetails(command.getName(), - command.getUsage()), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - /** - * Run CommandRunner plugins before a command is executed - * - * @param command - */ - private void executeCommandStartPlugins(Command command) { - try { - // handle command start - if (commandRunnerPlugins != null) { - for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { - commandPlugin - .handleCommandBefore(new CommandRunnerPluginContext( - new TestStepsDetails(command.getName(), - command.getUsage()), context)); - } - } - } catch (Throwable th) { - logger.error(th); - } - - } - - public void executeTearDownPlugins(Throwable failureReason, IInvocationContext invocationContext) { - try { - if (tearDownPlugins != null) { - for (ITearDownPlugin tearDownPlugin : tearDownPlugins) { - TestScript testScript = context.getTestScript(); - TearDownPluginContext tearDownPluginContext = new TearDownPluginContext(testScript, failureReason, invocationContext); - tearDownPlugin.handleBeforeTearDown(tearDownPluginContext); - } - } - } catch (Throwable throwable) { - logger.error("Error while executing teardown plugins", throwable); - } - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.execution; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.DefaultAutomationClassLoader; +import org.finra.jtaf.core.IAutomationClassLoader; +import org.finra.jtaf.core.asserts.ErrorAccumulator; +import org.finra.jtaf.core.exceptions.GetInvocationTargetException; +import org.finra.jtaf.core.model.exceptions.MissingInvocationTargetException; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.model.invocationtarget.Function; +import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.statement.InvocationList; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestStatus; +import org.finra.jtaf.core.model.test.TestStepsDetails; +import org.finra.jtaf.core.plugins.execution.CommandRunnerPluginContext; +import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; +import org.finra.jtaf.core.plugins.execution.ITearDownPlugin; +import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; +import org.finra.jtaf.core.plugins.execution.TearDownPluginContext; +import org.finra.jtaf.core.plugins.execution.TestRunnerPluginContext; + +/** + * This class is invoked by the Automation Engine to begin execution + */ +public class Interpreter { + private static final Logger logger = Logger.getLogger(Interpreter.class); + private CommandRegistry commandRegistry; + private static IInterpreterContext context; + private TestStatus testStatus; + public ErrorAccumulator ea; + + private List testRunnerPlugins; + private List commandRunnerPlugins; + private List tearDownPlugins; + private IAutomationClassLoader automationClassLoader; + private List testStepDetails; + + /** + * Add plugins that should run before or after a test + * + * @param testRunnerPlugins => the list of test level plugins + */ + public void setTestRunnerPlugins(List testRunnerPlugins) { + this.testRunnerPlugins = testRunnerPlugins; + } + + /** + * Add plugins that should run before or after a command + * + * @param commandRunnerPlugins => the list of command level plugins + */ + public void setCommandRunnerPlugins( + List commandRunnerPlugins) { + this.commandRunnerPlugins = commandRunnerPlugins; + } + + public void setTearDownPlugins(List tearDownPlugins) { + this.tearDownPlugins = tearDownPlugins; + } + + /** + * Set the command registry + * + * @param commandRegistry + */ + public void setCommandRegistry(CommandRegistry commandRegistry) { + this.commandRegistry = commandRegistry; + } + + /** + * Execute the commands in the testscript passed to the Interpreter. Execute + * custom plugins that are supposed to run before and after each test or + * each command. The test passes if this method executes without throwing an + * exception. + * + * @param test =>testscript object passed by the Automation Engine + * @throws Throwable + */ + public final TestResult interpret(TestScript test) throws Throwable { + logger.info(test.getFullName()); + Throwable failure = null; + context = new CorrectiveContext(); + context.setTestScript(test); + + ea = new ErrorAccumulator("Accumulator"); + // Multithreaded use + automationClassLoader = new DefaultAutomationClassLoader(); + testStatus = TestStatus.Running; + testStepDetails = new ArrayList(); + executeTestStartPlugins(test); + try { + visitInvocationList(test.getBody()); + failure = ea.getWrappedErrors(); + } catch (Throwable t) { + failure = t; + this.testStatus = TestStatus.Failed; + } finally { + if (failure == null) + this.testStatus = TestStatus.Passed; + else { + this.testStatus = TestStatus.Failed; + } + + executeTestFinishPlugins(); + + } + if (failure != null + && failure.getClass().getSimpleName() + .equalsIgnoreCase(test.getException())) { + failure = null; + this.testStatus = TestStatus.Passed; + } + return new TestResult(this.getTestStepDetails(), testStatus, failure); + } + + /** + * Return the list of test steps in the current test + * + * @return + */ + public List getTestStepDetails() { + return testStepDetails; + } + + /** + * Execute the list of commands in the test + * + * @param invocationtList + * @throws Throwable + */ + public void visitInvocationList(InvocationList invocationtList) + throws Throwable { + + try { + + for (Invocation invocation : invocationtList) { + try { + + visitInvocation((Invocation) invocation); + } catch (Throwable th) { + if (!ea.isEmpty() && !ea.hasThrown()) { + ea.addError((Throwable) th); + + ea.throwErrors(); + } else { + throw th; + } + } + } + } catch (Throwable th) { + this.testStatus = TestStatus.Failed; + throw th; + } + } + + /** + * Invoke the command's launch API. Responsible of actual execution of the + * command + * + * @param command => current command object to be executed + * @throws Throwable + */ + public void visitCommand(Command command) throws Throwable { + executeCommandStartPlugins(command); + try { + command.launch(context, this); + } catch (Throwable t) { + throw t; + } finally { + executeCommandFinishPlugins(command); + } + + } + + /** + * Execute the function, if any, present in the test + * + * @param function + * @throws Throwable + */ + public void visitFunction(Function function) throws Throwable { + this.visitInvocationList(function.getBody()); + + } + + /** + * Execute the commands in the testscript passed to the Interpreter. + * + * @param invocation =>testscript object passed by the Automation Engine + * @throws Throwable + */ + public final void visitInvocation(Invocation invocation) throws Throwable { + if (invocation.getTargetName().equals("TryRecoverCleanup")) { + // Ignore logging TryRecoverCleanup statement + } else { + logger.info(invocation.toString()); + } + if (this.commandRegistry.containsInvocationTarget(invocation + .getTargetName())) { + final InvocationTarget target = this.commandRegistry + .getInvocationTarget(invocation.getTargetName()); + context.pushInvocation(invocation, target); + } else { + throw new MissingInvocationTargetException(invocation); + } + + try { + InvocationTarget target = getInvocationTarget(invocation); + + target.acceptInvocationTargetVisitor(this); + + } finally { + + context.popFrame(); + } + } + + /** + * Get the invocation target instance if it exists in the Command Registry + * else throw exception 'Invocation not found' + * + * @param invocation + * @return + * @throws Throwable + */ + public InvocationTarget getInvocationTarget(Invocation invocation) throws GetInvocationTargetException { + // Check if it exists in the local map already + InvocationTarget target = null; + // Get the InvocationTarget from the previously mapped ones. + InvocationTarget mappedInvocationTarget = this.commandRegistry + .getInvocationTarget(invocation.getTargetName()); + + if (mappedInvocationTarget == null) { + throw new IllegalArgumentException("Invocation " + + invocation.getTargetName() + " not found"); + } + + if (mappedInvocationTarget instanceof Function) { + target = mappedInvocationTarget; + } else { + // Instantiate the InvocationTarget. + try { + Class targetClass = automationClassLoader + .loadClass(mappedInvocationTarget.getClass().getName()); + if (InvocationTarget.class.isAssignableFrom(targetClass)) { + Constructor constructor = targetClass + .getConstructor(String.class); + target = (InvocationTarget) constructor.newInstance(invocation + .getTargetName()); + + // This is to reload the parameters from preparsed Map of + // InvocationTargets (ScriptParser) + for (String s : mappedInvocationTarget.getRequiredParameters()) { + target.addRequiredParameter(s); + } + + for (String s : mappedInvocationTarget.getOptionalParameters()) { + target.addOptionalParameter(s); + } + + for (String s : mappedInvocationTarget.getProductions()) { + target.addProduction(s); + } + } else { + throw new GetInvocationTargetException("Invocation not found: " + invocation.toString()); + } + } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException | + InvocationTargetException | InstantiationException e) { + throw new GetInvocationTargetException("Error while ", e); + } + } + return target; + } + + /** + * Add details of the invocation to the list of test steps + */ + public void addDetails(TestStepsDetails details) { + testStepDetails.add(details); + } + + /** + * Add exception to the Error Accumulator and set the Test Status to 'Failed' + * + * @param th + */ + public void addError(Throwable th) { + ea.addError(th); + this.testStatus = TestStatus.Failed; + + } + + /** + * Run TestRunner plugins after a test finishes execution + */ + private void executeTestFinishPlugins() { + + if (testRunnerPlugins != null) { + for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { + try { + testPlugin + .handleTestFinish(new TestRunnerPluginContext( + context.getTestScript(), new TestResult( + this.getTestStepDetails(), + testStatus), context)); + } catch (Throwable e) { + logger.error(e); + + } + + } + } + } + + /** + * Run TestRunner plugins before a test starts execution + * + * @param test => the current testscript in context + */ + private void executeTestStartPlugins(TestScript test) { + // handleTestStart + try { + if (testRunnerPlugins != null) { + for (ITestRunnerPlugin testPlugin : testRunnerPlugins) { + testPlugin.handleTestStart(new TestRunnerPluginContext( + test, new TestResult(this.getTestStepDetails(), + testStatus), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + /** + * Run CommandRunner plugins after a command is executed + * + * @param command + */ + private void executeCommandFinishPlugins(Command command) { + + try { + if (commandRunnerPlugins != null) { + for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { + commandPlugin + .handleCommandAfter(new CommandRunnerPluginContext( + new TestStepsDetails(command.getName(), + command.getUsage()), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + /** + * Run CommandRunner plugins before a command is executed + * + * @param command + */ + private void executeCommandStartPlugins(Command command) { + try { + // handle command start + if (commandRunnerPlugins != null) { + for (ICommandRunnerPlugin commandPlugin : commandRunnerPlugins) { + commandPlugin + .handleCommandBefore(new CommandRunnerPluginContext( + new TestStepsDetails(command.getName(), + command.getUsage()), context)); + } + } + } catch (Throwable th) { + logger.error(th); + } + + } + + public void executeTearDownPlugins(Throwable failureReason, IInvocationContext invocationContext) { + try { + if (tearDownPlugins != null) { + for (ITearDownPlugin tearDownPlugin : tearDownPlugins) { + TestScript testScript = context.getTestScript(); + TearDownPluginContext tearDownPluginContext = new TearDownPluginContext(testScript, failureReason, invocationContext); + tearDownPlugin.handleBeforeTearDown(tearDownPluginContext); + } + } + } catch (Throwable throwable) { + logger.error("Error while executing teardown plugins", throwable); + } + } + +} diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java index 5f46a6d..33a139e 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyHandler.java @@ -1,121 +1,121 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.invocationtarget; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.finra.jtaf.core.model.execution.IInvocationContext; - -/** - * Used to replace keys in the context. - */ -public class ContextKeyHandler { - - private IInvocationContext context; - private final int maxNumberOfResolves = 200; - private int resolveCount = 0; - - /** - * Called when instantiated - * - * @param context - the current context when this is executed. - */ - public ContextKeyHandler(IInvocationContext context) { - this.context = context; - } - - /** - * @param value - the key - * @return - - */ - @SuppressWarnings("unchecked") - public Object replaceContextKey(Object value) { - // This is to avoid replaceContext from getting into an infinite loop of - // recursive calls. - resolveCount++; - if (resolveCount > maxNumberOfResolves) - return value; - - if ((value != null) && (value.getClass().equals(String.class))) { - String[] resultSplitted = ((String) value).split("\\$contextKey"); - StringBuffer resultString = new StringBuffer(resultSplitted[0]); - - int i = 1; - while (resultSplitted.length > i) { - int beginIndex = resultSplitted[i].indexOf("("); - if (beginIndex >= 0) { - int endIndex = resultSplitted[i].indexOf(")", beginIndex); - if (endIndex > 0) { - String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, - endIndex); - runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); - - if (getContext().getObject(runTimeKeyName) != null) { - resultString.append(getContext().getObject(runTimeKeyName) - + resultSplitted[i].substring(endIndex + 1)); - } else if (InvocationTarget.getGlobalContext().get(runTimeKeyName) != null) { - resultString.append(InvocationTarget.getGlobalContext().get( - runTimeKeyName) - + resultSplitted[i].substring(endIndex + 1)); - } else { - throw new ContextKeyNotFoundException("Oops! Processing '" + value - + "' key fails! Can't find run time parameter '" - + runTimeKeyName - + "'! You have put it to global content before..."); - } - } - } - i++; - } - if (resultString.toString().toLowerCase().indexOf("$contextkey") != -1) { - return replaceContextKey(resultString.toString()); - } - return resultString.toString(); - - } else if ((value != null) && (value instanceof List)) { - List list = (List) value; - ArrayList resultList = new ArrayList(); - for (Object o : list) { - resultList.add(replaceContextKey(o)); - } - return resultList; - } else if ((value != null) && (value instanceof Map)) { - Map map = (Map) value; - HashMap resultMap = new HashMap(); - - Set keys = map.keySet(); - for (String key : keys) { - resultMap.put((String) replaceContextKey(key), replaceContextKey(map.get(key))); - } - return resultMap; - } - return value; - } - - /** - * Get the current context. - * - * @return the current context. - */ - public IInvocationContext getContext() { - return context; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.invocationtarget; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.finra.jtaf.core.model.execution.IInvocationContext; + +/** + * Used to replace keys in the context. + */ +public class ContextKeyHandler { + + private IInvocationContext context; + private final int maxNumberOfResolves = 200; + private int resolveCount = 0; + + /** + * Called when instantiated + * + * @param context - the current context when this is executed. + */ + public ContextKeyHandler(IInvocationContext context) { + this.context = context; + } + + /** + * @param value - the key + * @return - + */ + @SuppressWarnings("unchecked") + public Object replaceContextKey(Object value) { + // This is to avoid replaceContext from getting into an infinite loop of + // recursive calls. + resolveCount++; + if (resolveCount > maxNumberOfResolves) + return value; + + if ((value != null) && (value.getClass().equals(String.class))) { + String[] resultSplitted = ((String) value).split("\\$contextKey"); + StringBuffer resultString = new StringBuffer(resultSplitted[0]); + + int i = 1; + while (resultSplitted.length > i) { + int beginIndex = resultSplitted[i].indexOf("("); + if (beginIndex >= 0) { + int endIndex = resultSplitted[i].indexOf(")", beginIndex); + if (endIndex > 0) { + String runTimeKeyName = resultSplitted[i].substring(beginIndex + 1, + endIndex); + runTimeKeyName = runTimeKeyName.replaceAll("'", "").replaceAll("\"", ""); + + if (getContext().getObject(runTimeKeyName) != null) { + resultString.append(getContext().getObject(runTimeKeyName) + + resultSplitted[i].substring(endIndex + 1)); + } else if (InvocationTarget.getGlobalContext().get(runTimeKeyName) != null) { + resultString.append(InvocationTarget.getGlobalContext().get( + runTimeKeyName) + + resultSplitted[i].substring(endIndex + 1)); + } else { + throw new ContextKeyNotFoundException("Oops! Processing '" + value + + "' key fails! Can't find run time parameter '" + + runTimeKeyName + + "'! You have put it to global content before..."); + } + } + } + i++; + } + if (resultString.toString().toLowerCase().indexOf("$contextkey") != -1) { + return replaceContextKey(resultString.toString()); + } + return resultString.toString(); + + } else if ((value != null) && (value instanceof List)) { + List list = (List) value; + ArrayList resultList = new ArrayList(); + for (Object o : list) { + resultList.add(replaceContextKey(o)); + } + return resultList; + } else if ((value != null) && (value instanceof Map)) { + Map map = (Map) value; + HashMap resultMap = new HashMap(); + + Set keys = map.keySet(); + for (String key : keys) { + resultMap.put((String) replaceContextKey(key), replaceContextKey(map.get(key))); + } + return resultMap; + } + return value; + } + + /** + * Get the current context. + * + * @return the current context. + */ + public IInvocationContext getContext() { + return context; + } +} diff --git a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java index eddb173..ca54adc 100644 --- a/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java +++ b/src/main/java/org/finra/jtaf/core/model/invocationtarget/ContextKeyNotFoundException.java @@ -1,69 +1,69 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.invocationtarget; - -/** - * This is an exception thrown when a key, that hasn't been stored in the - * context, is used to get a value from the context. - */ -public class ContextKeyNotFoundException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * A constructor used without specifying the message or throwable. - */ - public ContextKeyNotFoundException() { - super(); - // TODO Auto-generated constructor stub - } - - /** - * A constructor used with specifying the message or throwable. - * - * @param message - The message to be thrown. - * @param cause - The exception encountered that will be thrown. - */ - public ContextKeyNotFoundException(String message, Throwable cause) { - super(message, cause); - // TODO Auto-generated constructor stub - } - - /** - * A constructor used without specifying the message. - * - * @param message - The message to be thrown. - */ - public ContextKeyNotFoundException(String message) { - super(message); - // TODO Auto-generated constructor stub - } - - /** - * A constructor used without specifying the throwable. - * - * @param cause - The exception encountered that will be thrown. - */ - public ContextKeyNotFoundException(Throwable cause) { - super(cause); - // TODO Auto-generated constructor stub - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.invocationtarget; + +/** + * This is an exception thrown when a key, that hasn't been stored in the + * context, is used to get a value from the context. + */ +public class ContextKeyNotFoundException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * A constructor used without specifying the message or throwable. + */ + public ContextKeyNotFoundException() { + super(); + // TODO Auto-generated constructor stub + } + + /** + * A constructor used with specifying the message or throwable. + * + * @param message - The message to be thrown. + * @param cause - The exception encountered that will be thrown. + */ + public ContextKeyNotFoundException(String message, Throwable cause) { + super(message, cause); + // TODO Auto-generated constructor stub + } + + /** + * A constructor used without specifying the message. + * + * @param message - The message to be thrown. + */ + public ContextKeyNotFoundException(String message) { + super(message); + // TODO Auto-generated constructor stub + } + + /** + * A constructor used without specifying the throwable. + * + * @param cause - The exception encountered that will be thrown. + */ + public ContextKeyNotFoundException(Throwable cause) { + super(cause); + // TODO Auto-generated constructor stub + } + +} diff --git a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java index b839de3..a42c7ca 100644 --- a/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java +++ b/src/main/java/org/finra/jtaf/core/model/statement/IInvocationVisitor.java @@ -1,32 +1,32 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.statement; - -/** - * This is an interface to be used for IStatement Vistors - */ -public interface IInvocationVisitor { - - /** - * Visit Invocation - * - * @param Invocation - represent calls to Commands, Functions, etc - * @throws Throwable - */ - void visitInvocation(Invocation invocation) throws Throwable; - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.statement; + +/** + * This is an interface to be used for IStatement Vistors + */ +public interface IInvocationVisitor { + + /** + * Visit Invocation + * + * @param Invocation - represent calls to Commands, Functions, etc + * @throws Throwable + */ + void visitInvocation(Invocation invocation) throws Throwable; + +} diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java b/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java index 0b104bd..90e808a 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestStatus.java @@ -1,26 +1,26 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test; - -/** - * Enum to maintain status of the current test - */ -public enum TestStatus { - Running, // Test failed, but we still need to run plugins - Failed, // Test passed, but we still need to run plugins - Passed -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test; + +/** + * Enum to maintain status of the current test + */ +public enum TestStatus { + Running, // Test failed, but we still need to run plugins + Failed, // Test passed, but we still need to run plugins + Passed +} diff --git a/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java b/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java index ca0f715..63b53a8 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java +++ b/src/main/java/org/finra/jtaf/core/model/test/TestSuite.java @@ -1,77 +1,77 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.test.digraph.Dependencies; - -/** - * This class represents a testsuite object - */ -public class TestSuite extends TestNamespace { - private Dependencies dependencies; - private Dependencies exclusions; - private String testSuiteName; - - public TestSuite(String name) throws NameFormatException { - super(name); - } - - /** - * Return the tests this testsuite depends upon - * - * @return - */ - public Dependencies getDependencies() { - return dependencies; - } - - /** - * Set the dependencies for this testsuite - * - * @param dp - */ - public void setDependencies(Dependencies dp) { - dependencies = dp; - } - - public Dependencies getExclusions() { - return exclusions; - } - - public void setExclusions(Dependencies exc) { - exclusions = exc; - } - - /** - * Return the name of the testsuite - * - * @return - */ - public String getTestSuiteName() { - return testSuiteName; - } - - /** - * Set the name of the testsuite - * - * @param tsn - */ - public void setTestSuiteName(String tsn) { - testSuiteName = tsn; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.test.digraph.Dependencies; + +/** + * This class represents a testsuite object + */ +public class TestSuite extends TestNamespace { + private Dependencies dependencies; + private Dependencies exclusions; + private String testSuiteName; + + public TestSuite(String name) throws NameFormatException { + super(name); + } + + /** + * Return the tests this testsuite depends upon + * + * @return + */ + public Dependencies getDependencies() { + return dependencies; + } + + /** + * Set the dependencies for this testsuite + * + * @param dp + */ + public void setDependencies(Dependencies dp) { + dependencies = dp; + } + + public Dependencies getExclusions() { + return exclusions; + } + + public void setExclusions(Dependencies exc) { + exclusions = exc; + } + + /** + * Return the name of the testsuite + * + * @return + */ + public String getTestSuiteName() { + return testSuiteName; + } + + /** + * Set the name of the testsuite + * + * @param tsn + */ + public void setTestSuiteName(String tsn) { + testSuiteName = tsn; + } +} diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java index 564e6f4..dbd5e89 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/Dependencies.java @@ -1,45 +1,45 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test.digraph; - -import java.util.HashSet; -import java.util.Set; - -/** - * Set of Test Case and Test Suite Dependencies - */ -public class Dependencies { - private Set dependentSuites = new HashSet(); - private Set dependentTests = new HashSet(); - - public Dependencies(Set suite, Set test) { - if (suite != null) { - dependentSuites = suite; - } - if (test != null) { - dependentTests = test; - } - } - - public Set getDependenciesSuites() { - return dependentSuites; - } - - public Set getDependenciesTests() { - return dependentTests; - } +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test.digraph; + +import java.util.HashSet; +import java.util.Set; + +/** + * Set of Test Case and Test Suite Dependencies + */ +public class Dependencies { + private Set dependentSuites = new HashSet(); + private Set dependentTests = new HashSet(); + + public Dependencies(Set suite, Set test) { + if (suite != null) { + dependentSuites = suite; + } + if (test != null) { + dependentTests = test; + } + } + + public Set getDependenciesSuites() { + return dependentSuites; + } + + public Set getDependenciesTests() { + return dependentTests; + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java index 9adcf81..a540921 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiEdge.java @@ -1,45 +1,45 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test.digraph; - -import org.jgrapht.graph.DefaultEdge; - -/** - * This class represents an edge in the digraph - */ -public class DiEdge extends DefaultEdge { - private static final long serialVersionUID = 1L; - - private boolean isExclusionEdge = false; - private boolean isDependencyEdge = false; - - public boolean isDependency() { - return isDependencyEdge; - } - - public boolean isExclusion() { - return isExclusionEdge; - } - - public void setDependencyEdge() { - isDependencyEdge = true; - } - - public void setExclusionEdge() { - isExclusionEdge = true; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test.digraph; + +import org.jgrapht.graph.DefaultEdge; + +/** + * This class represents an edge in the digraph + */ +public class DiEdge extends DefaultEdge { + private static final long serialVersionUID = 1L; + + private boolean isExclusionEdge = false; + private boolean isDependencyEdge = false; + + public boolean isDependency() { + return isDependencyEdge; + } + + public boolean isExclusion() { + return isExclusionEdge; + } + + public void setDependencyEdge() { + isDependencyEdge = true; + } + + public void setExclusionEdge() { + isExclusionEdge = true; + } +} diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java index a30d278..f2983e2 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DiNode.java @@ -1,70 +1,70 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test.digraph; - -import org.finra.jtaf.core.model.test.TestScript; - -/** - * This class represents a vertex in the digraph - */ -public class DiNode { - private final String testName; //This shouldnt change after being set initially - private String testStatus = ""; - private final TestScript testScript; //This shouldnt change after being set initially - - public DiNode(TestScript ts) { - this.testName = ts.getName(); - this.testScript = ts; - } - - public String getTestStatus() { - return testStatus; - } - - protected void setTestStatus(String newTestStatus) { - testStatus = newTestStatus; - } - - public String getTestName() { - return testName; - } - - public TestScript getTestScript() { - return testScript; - } - - /* - @Override - public int hashCode() { - return this.getTestName().toLowerCase().hashCode() - + this.getTestScript().hashCode(); - }*/ - - @Override - public boolean equals(Object o) { - if (o instanceof DiNode) { - if (this.getTestName().equalsIgnoreCase(((DiNode) o).getTestName()) - && this.getTestScript().equals(((DiNode) o).getTestScript())) { - return true; - } else { - return false; - } - } else { - return false; - } - } +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test.digraph; + +import org.finra.jtaf.core.model.test.TestScript; + +/** + * This class represents a vertex in the digraph + */ +public class DiNode { + private final String testName; //This shouldnt change after being set initially + private String testStatus = ""; + private final TestScript testScript; //This shouldnt change after being set initially + + public DiNode(TestScript ts) { + this.testName = ts.getName(); + this.testScript = ts; + } + + public String getTestStatus() { + return testStatus; + } + + protected void setTestStatus(String newTestStatus) { + testStatus = newTestStatus; + } + + public String getTestName() { + return testName; + } + + public TestScript getTestScript() { + return testScript; + } + + /* + @Override + public int hashCode() { + return this.getTestName().toLowerCase().hashCode() + + this.getTestScript().hashCode(); + }*/ + + @Override + public boolean equals(Object o) { + if (o instanceof DiNode) { + if (this.getTestName().equalsIgnoreCase(((DiNode) o).getTestName()) + && this.getTestScript().equals(((DiNode) o).getTestScript())) { + return true; + } else { + return false; + } + } else { + return false; + } + } } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java index c03fca0..31d1767 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/DigraphFactory.java @@ -1,159 +1,159 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test.digraph; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.finra.jtaf.core.exceptions.DependencyException; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestNamespace; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.jgrapht.alg.CycleDetector; -import org.jgrapht.graph.ClassBasedEdgeFactory; - - -/** - * This factory class allows for the addition of nodes and edges into the digraph. - */ -public class DigraphFactory { - private TestDigraph digraph; - private MessageCollector mc; - - public DigraphFactory(TestDigraph digraph2, MessageCollector mc2) { - digraph = digraph2; - mc = mc2; - } - - public void createGraph(TestNamespace testNamespace) { - //First we have to do a replace on all the dependencies that specify a TestSuite name. - Map tsMap = testNamespace.getTestSuiteMapping(); - //Iterate across all the TestSuites and then assign the dependencies to the correct mapping - for (String s : tsMap.keySet()) { - Set tsDependenciesAsTests = new HashSet(); - Set tsExclusionsAsTests = new HashSet(); - //For each TestSuite object in the suitemapping, grab dependencies and convert - - TestSuite currentSuite = tsMap.get(s); - Dependencies dependSuite = currentSuite.getDependencies(); - Dependencies excludeSuite = currentSuite.getExclusions(); - - //Appending all the tests to the list - tsDependenciesAsTests.addAll(dependSuite.getDependenciesTests()); - tsExclusionsAsTests.addAll(excludeSuite.getDependenciesTests()); - - //Grabbing the TestSuite dependencies and converting - for (String dependentSuites : dependSuite.getDependenciesSuites()) { - //Given a supplied dependent suite go into the actual suite and get the test info - if (tsMap.get(dependentSuites) != null) { - for (TestComponent ts : tsMap.get(dependentSuites).getComponentList()) { - tsDependenciesAsTests.add(ts.getName()); - } - } else { - throw new DependencyException("The TestSuite '" + dependentSuites + "' specified for TestSuite '" + s + "' dependencies does not exist!"); - } - } - //Grabbing the TestSuite exclusions and converting - for (String excludedSuites : excludeSuite.getDependenciesSuites()) { - //Given a supplied dependent suite go into the actual suite and get the test info - if (tsMap.get(excludedSuites) != null) { - for (TestComponent ts : tsMap.get(excludedSuites).getComponentList()) { - tsExclusionsAsTests.add(ts.getName()); - } - } else { - throw new DependencyException("The TestSuite '" + excludedSuites + "' specified for TestSuite '" + s + "' exclusions does not exist!"); - } - } - //Now all the TestSuite dependencies have been converted and placed into a list. - //Go down into the Test level and grab its dependencies. - for (TestComponent tc : currentSuite.getComponentList()) { - Dependencies dependTest = ((TestScript) tc).getDependencies(); - Dependencies excludeTest = ((TestScript) tc).getExclusions(); - Set testScriptDependencies = dependTest.getDependenciesTests(); - Set testScriptExclusions = excludeTest.getDependenciesTests(); - - for (String tsDepend : dependTest.getDependenciesSuites()) { - //Given tsDepend as the testSuite - if (tsMap.get(tsDepend) != null) { - for (TestComponent tcTest : tsMap.get(tsDepend).getComponentList()) { - testScriptDependencies.add(tcTest.getName()); - } - } else { - throw new DependencyException("The TestSuite '" + tsDepend + "' specified @ '" + ((TestScript) tc).getFullName() + "' dependencies does not exist!"); - } - } - for (String tsExclude : excludeTest.getDependenciesSuites()) { - //Given tsDepend as the testSuite - if (tsMap.get(tsExclude) != null) { - for (TestComponent tcTest : tsMap.get(tsExclude).getComponentList()) { - testScriptExclusions.add(tcTest.getName()); - } - } else { - throw new DependencyException("The TestSuite '" + tsExclude + "' specified @ '" + ((TestScript) tc).getFullName() + "' exclusions does not exist!"); - } - } - testScriptDependencies.addAll(tsDependenciesAsTests); - testScriptExclusions.addAll(tsExclusionsAsTests); - addEdges(digraph.getVertex(tc.getName()), testScriptDependencies, testScriptExclusions); - } - } - checkDependencyCycles(); - } - - private void checkDependencyCycles() { - TestDigraph forCyclesGraph = new TestDigraph(new ClassBasedEdgeFactory(DiEdge.class)); - for (DiNode d : digraph.vertexSet()) { - forCyclesGraph.addVertex(d); - } - Set tempEdgeSet = new HashSet(); - tempEdgeSet.addAll(digraph.edgeSet()); - for (DiEdge e : tempEdgeSet) { - if (e.isDependency()) { - forCyclesGraph.addEdge(forCyclesGraph.getVertex(digraph.getEdgeSource(e).getTestName()), forCyclesGraph.getVertex(digraph.getEdgeTarget(e).getTestName())); - } - } - CycleDetector cd = new CycleDetector(forCyclesGraph); - Set cycleList = cd.findCycles(); - if (cycleList.size() > 0) { - mc.fatal("Cycle(s) detected"); - for (DiNode d : cycleList) { - mc.fatal("@" + d.getTestScript().getFullName()); - } - throw new DependencyException("Found cycle(s)"); - } - } - - private void addEdges(DiNode edgeFrom, Set dependencies, Set exclusions) { - for (String d : dependencies) { - if (digraph.getVertex(d) != null) { - digraph.addEdge(edgeFrom, digraph.getVertex(d)).setDependencyEdge(); - } else { - throw new DependencyException("The Test dependency: '" + d + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); - } - } - for (String e : exclusions) { - if (digraph.getVertex(e) != null) { - digraph.addEdge(edgeFrom, digraph.getVertex(e)).setExclusionEdge(); - } else { - throw new DependencyException("The Test exclusion: '" + e + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); - } - } - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test.digraph; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.finra.jtaf.core.exceptions.DependencyException; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestNamespace; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.jgrapht.alg.CycleDetector; +import org.jgrapht.graph.ClassBasedEdgeFactory; + + +/** + * This factory class allows for the addition of nodes and edges into the digraph. + */ +public class DigraphFactory { + private TestDigraph digraph; + private MessageCollector mc; + + public DigraphFactory(TestDigraph digraph2, MessageCollector mc2) { + digraph = digraph2; + mc = mc2; + } + + public void createGraph(TestNamespace testNamespace) { + //First we have to do a replace on all the dependencies that specify a TestSuite name. + Map tsMap = testNamespace.getTestSuiteMapping(); + //Iterate across all the TestSuites and then assign the dependencies to the correct mapping + for (String s : tsMap.keySet()) { + Set tsDependenciesAsTests = new HashSet(); + Set tsExclusionsAsTests = new HashSet(); + //For each TestSuite object in the suitemapping, grab dependencies and convert + + TestSuite currentSuite = tsMap.get(s); + Dependencies dependSuite = currentSuite.getDependencies(); + Dependencies excludeSuite = currentSuite.getExclusions(); + + //Appending all the tests to the list + tsDependenciesAsTests.addAll(dependSuite.getDependenciesTests()); + tsExclusionsAsTests.addAll(excludeSuite.getDependenciesTests()); + + //Grabbing the TestSuite dependencies and converting + for (String dependentSuites : dependSuite.getDependenciesSuites()) { + //Given a supplied dependent suite go into the actual suite and get the test info + if (tsMap.get(dependentSuites) != null) { + for (TestComponent ts : tsMap.get(dependentSuites).getComponentList()) { + tsDependenciesAsTests.add(ts.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + dependentSuites + "' specified for TestSuite '" + s + "' dependencies does not exist!"); + } + } + //Grabbing the TestSuite exclusions and converting + for (String excludedSuites : excludeSuite.getDependenciesSuites()) { + //Given a supplied dependent suite go into the actual suite and get the test info + if (tsMap.get(excludedSuites) != null) { + for (TestComponent ts : tsMap.get(excludedSuites).getComponentList()) { + tsExclusionsAsTests.add(ts.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + excludedSuites + "' specified for TestSuite '" + s + "' exclusions does not exist!"); + } + } + //Now all the TestSuite dependencies have been converted and placed into a list. + //Go down into the Test level and grab its dependencies. + for (TestComponent tc : currentSuite.getComponentList()) { + Dependencies dependTest = ((TestScript) tc).getDependencies(); + Dependencies excludeTest = ((TestScript) tc).getExclusions(); + Set testScriptDependencies = dependTest.getDependenciesTests(); + Set testScriptExclusions = excludeTest.getDependenciesTests(); + + for (String tsDepend : dependTest.getDependenciesSuites()) { + //Given tsDepend as the testSuite + if (tsMap.get(tsDepend) != null) { + for (TestComponent tcTest : tsMap.get(tsDepend).getComponentList()) { + testScriptDependencies.add(tcTest.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + tsDepend + "' specified @ '" + ((TestScript) tc).getFullName() + "' dependencies does not exist!"); + } + } + for (String tsExclude : excludeTest.getDependenciesSuites()) { + //Given tsDepend as the testSuite + if (tsMap.get(tsExclude) != null) { + for (TestComponent tcTest : tsMap.get(tsExclude).getComponentList()) { + testScriptExclusions.add(tcTest.getName()); + } + } else { + throw new DependencyException("The TestSuite '" + tsExclude + "' specified @ '" + ((TestScript) tc).getFullName() + "' exclusions does not exist!"); + } + } + testScriptDependencies.addAll(tsDependenciesAsTests); + testScriptExclusions.addAll(tsExclusionsAsTests); + addEdges(digraph.getVertex(tc.getName()), testScriptDependencies, testScriptExclusions); + } + } + checkDependencyCycles(); + } + + private void checkDependencyCycles() { + TestDigraph forCyclesGraph = new TestDigraph(new ClassBasedEdgeFactory(DiEdge.class)); + for (DiNode d : digraph.vertexSet()) { + forCyclesGraph.addVertex(d); + } + Set tempEdgeSet = new HashSet(); + tempEdgeSet.addAll(digraph.edgeSet()); + for (DiEdge e : tempEdgeSet) { + if (e.isDependency()) { + forCyclesGraph.addEdge(forCyclesGraph.getVertex(digraph.getEdgeSource(e).getTestName()), forCyclesGraph.getVertex(digraph.getEdgeTarget(e).getTestName())); + } + } + CycleDetector cd = new CycleDetector(forCyclesGraph); + Set cycleList = cd.findCycles(); + if (cycleList.size() > 0) { + mc.fatal("Cycle(s) detected"); + for (DiNode d : cycleList) { + mc.fatal("@" + d.getTestScript().getFullName()); + } + throw new DependencyException("Found cycle(s)"); + } + } + + private void addEdges(DiNode edgeFrom, Set dependencies, Set exclusions) { + for (String d : dependencies) { + if (digraph.getVertex(d) != null) { + digraph.addEdge(edgeFrom, digraph.getVertex(d)).setDependencyEdge(); + } else { + throw new DependencyException("The Test dependency: '" + d + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); + } + } + for (String e : exclusions) { + if (digraph.getVertex(e) != null) { + digraph.addEdge(edgeFrom, digraph.getVertex(e)).setExclusionEdge(); + } else { + throw new DependencyException("The Test exclusion: '" + e + "' does not exist at '" + edgeFrom.getTestScript().getFullName() + "'"); + } + } + } +} diff --git a/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java b/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java index 64c0808..bef6562 100644 --- a/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java +++ b/src/main/java/org/finra/jtaf/core/model/test/digraph/TestDigraph.java @@ -1,89 +1,89 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.model.test.digraph; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.jgrapht.DirectedGraph; -import org.jgrapht.EdgeFactory; -import org.jgrapht.graph.AbstractBaseGraph; - - -/** - * This is a container class that houses the dependencies and exclusions across the tests. - */ -public class TestDigraph extends AbstractBaseGraph implements DirectedGraph { - private static final long serialVersionUID = 1L; - private Map digraphVertexMapping = new HashMap(); - - public TestDigraph(EdgeFactory arg0) { - super(arg0, true, true); - } - - - public void updateTestStatus(String testName, String status) { - digraphVertexMapping.get(testName).setTestStatus(status); - } - - public DiNode getVertex(String testName) { - return digraphVertexMapping.get(testName); - } - - @Override - public boolean addVertex(DiNode d) { - if (getVertex(d.getTestName()) != null) { - return false; - } - digraphVertexMapping.put(d.getTestName(), d); - return super.addVertex(d); - } - - @Override - public boolean removeVertex(DiNode d) { - if (getVertex(d.getTestName()) != null) { - return false; - } -// digraphVertexMapping.put(d.getTestName(), d); - digraphVertexMapping.remove(d.getTestName()); - return super.removeVertex(d); - } - - public List getAllDependencies(String testName) { - DiNode associatedNode = getVertex(testName); - List dependentNodes = new ArrayList(); - for (DiEdge edge : outgoingEdgesOf(associatedNode)) { - if (edge.isDependency()) { - dependentNodes.add(getEdgeTarget(edge)); - } - } - return dependentNodes; - } - - public List getAllExclusions(String testName) { - DiNode associatedNode = getVertex(testName); - List exclusionNodes = new ArrayList(); - for (DiEdge edge : outgoingEdgesOf(associatedNode)) { - if (edge.isExclusion()) { - exclusionNodes.add(getEdgeTarget(edge)); - } - } - return exclusionNodes; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.model.test.digraph; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.EdgeFactory; +import org.jgrapht.graph.AbstractBaseGraph; + + +/** + * This is a container class that houses the dependencies and exclusions across the tests. + */ +public class TestDigraph extends AbstractBaseGraph implements DirectedGraph { + private static final long serialVersionUID = 1L; + private Map digraphVertexMapping = new HashMap(); + + public TestDigraph(EdgeFactory arg0) { + super(arg0, true, true); + } + + + public void updateTestStatus(String testName, String status) { + digraphVertexMapping.get(testName).setTestStatus(status); + } + + public DiNode getVertex(String testName) { + return digraphVertexMapping.get(testName); + } + + @Override + public boolean addVertex(DiNode d) { + if (getVertex(d.getTestName()) != null) { + return false; + } + digraphVertexMapping.put(d.getTestName(), d); + return super.addVertex(d); + } + + @Override + public boolean removeVertex(DiNode d) { + if (getVertex(d.getTestName()) != null) { + return false; + } +// digraphVertexMapping.put(d.getTestName(), d); + digraphVertexMapping.remove(d.getTestName()); + return super.removeVertex(d); + } + + public List getAllDependencies(String testName) { + DiNode associatedNode = getVertex(testName); + List dependentNodes = new ArrayList(); + for (DiEdge edge : outgoingEdgesOf(associatedNode)) { + if (edge.isDependency()) { + dependentNodes.add(getEdgeTarget(edge)); + } + } + return dependentNodes; + } + + public List getAllExclusions(String testName) { + DiNode associatedNode = getVertex(testName); + List exclusionNodes = new ArrayList(); + for (DiEdge edge : outgoingEdgesOf(associatedNode)) { + if (edge.isExclusion()) { + exclusionNodes.add(getEdgeTarget(edge)); + } + } + return exclusionNodes; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java b/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java index 74d983c..40fb3a4 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ConcurrentScheduler.java @@ -1,182 +1,182 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.model.test.digraph.TestDigraph; -import org.junit.runners.model.RunnerScheduler; - - -/** - * Control the execution of your tests with this Scheduler - */ -public class ConcurrentScheduler implements RunnerScheduler { - - private int NTHREADS = 1; - - // we need a thread pool executor - private ExecutorService execService; - // wrap it in a CompletionService so we have a nicer interface. Our tasks have no return value (void) - private CompletionService completionService; - - // this list contains all of the tests that are ready for execution. - private List> tasks = new LinkedList>(); - - // Before we begin running the tests we store all test threads in a linkedlist - private List theTests = new LinkedList(); - - // We also store the test names alongside the test threads - private static List testNames = new LinkedList(); - - // As threads complete test scripts, they drop their updates in a queue that the main thread uses to - // update test state - private static Queue testUpdates = new ConcurrentLinkedQueue(); - private TestDigraph digraph; - - public ConcurrentScheduler() { - - int threadCount = AutomationEngine.getInstance().getTestAgenda().getThreadCount(); - if (threadCount <= 0) { - NTHREADS = 1; - } else { - NTHREADS = threadCount; - } - execService = Executors.newFixedThreadPool(NTHREADS); - completionService = new ExecutorCompletionService(execService); - digraph = AutomationEngine.getInstance().getTestDigraph(); - - } - - protected static void updateWithStatus(ResultUpdate theUpdate) { - testUpdates.add(theUpdate); - } - - /** - * Tasks are scheduled by submitting them to our threadpool - * and adding the return Future to our tasks collection. - */ - @Override - public void schedule(Runnable test) { - theTests.add(test); - //tasks.add(completionService.submit(test, null)); - } - - /** - * When this method exits, all tasks must be finished. - */ - @Override - public void finished() { - try { - while (!testNames.isEmpty()) { - checkTestsStatus(); - tasks.remove(completionService.take()); - - //update test results - updateTestState(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - for (Future task : tasks) { - task.cancel(true); // if there was an error, attempt to cancel the other tasks - } - execService.shutdown(); // shutdown regardless - } - } - - private void updateTestState() { - while (!testUpdates.isEmpty()) { - ResultUpdate curr = testUpdates.remove(); - theTests.remove(testNames.indexOf(curr.getTestName())); - testNames.remove(curr.getTestName()); - digraph.updateTestStatus(curr.getTestName(), curr.getTestStatus()); - } - } - - private void checkTestsStatus() { - for (String currentTest : testNames) { - String theTestName = currentTest.toString(); - DiNode theTestNode = digraph.getVertex(theTestName); - - //test complete -skip - if (theTestNode.getTestStatus().equalsIgnoreCase("FAILED") || - theTestNode.getTestStatus().equalsIgnoreCase("PASSED") || - theTestNode.getTestStatus().equalsIgnoreCase("READY")) { - continue; - } - - boolean isAllDepFinished = true; - boolean depTestsFailed = false; - //Check Dependencies - for (DiNode dependency : digraph.getAllDependencies(theTestName)) { - if (dependency.getTestStatus().equalsIgnoreCase("FAILED")) { - depTestsFailed = true; - } else if (!dependency.getTestStatus().equalsIgnoreCase("PASSED")) { - isAllDepFinished = false; - break; - } - - } - - //if dependencies aren't done yet. There's no point in checking the Exclusions for - //this test - if (!isAllDepFinished) { - continue; - } - - //Check Exclusions - boolean checkExclusions = true; - for (DiNode exclusion : digraph.getAllExclusions(theTestName)) { - if (exclusion.getTestStatus().equalsIgnoreCase("RUNNING") - || exclusion.getTestStatus().equalsIgnoreCase("READY")) { - checkExclusions = false; - break; - } - } - - if (isAllDepFinished && checkExclusions) { - int corresponding = testNames.indexOf(currentTest); - tasks.add(completionService.submit(theTests.get(corresponding), theTestName)); - if (!depTestsFailed) { - digraph.updateTestStatus(theTestName, "READY"); - } else { - digraph.updateTestStatus(theTestName, "FAILED"); - } - } - - } - - } - - public static void registerTestName(String name) { - testNames.add(name); - } -} - - - +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.CompletionService; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.model.test.digraph.TestDigraph; +import org.junit.runners.model.RunnerScheduler; + + +/** + * Control the execution of your tests with this Scheduler + */ +public class ConcurrentScheduler implements RunnerScheduler { + + private int NTHREADS = 1; + + // we need a thread pool executor + private ExecutorService execService; + // wrap it in a CompletionService so we have a nicer interface. Our tasks have no return value (void) + private CompletionService completionService; + + // this list contains all of the tests that are ready for execution. + private List> tasks = new LinkedList>(); + + // Before we begin running the tests we store all test threads in a linkedlist + private List theTests = new LinkedList(); + + // We also store the test names alongside the test threads + private static List testNames = new LinkedList(); + + // As threads complete test scripts, they drop their updates in a queue that the main thread uses to + // update test state + private static Queue testUpdates = new ConcurrentLinkedQueue(); + private TestDigraph digraph; + + public ConcurrentScheduler() { + + int threadCount = AutomationEngine.getInstance().getTestAgenda().getThreadCount(); + if (threadCount <= 0) { + NTHREADS = 1; + } else { + NTHREADS = threadCount; + } + execService = Executors.newFixedThreadPool(NTHREADS); + completionService = new ExecutorCompletionService(execService); + digraph = AutomationEngine.getInstance().getTestDigraph(); + + } + + protected static void updateWithStatus(ResultUpdate theUpdate) { + testUpdates.add(theUpdate); + } + + /** + * Tasks are scheduled by submitting them to our threadpool + * and adding the return Future to our tasks collection. + */ + @Override + public void schedule(Runnable test) { + theTests.add(test); + //tasks.add(completionService.submit(test, null)); + } + + /** + * When this method exits, all tasks must be finished. + */ + @Override + public void finished() { + try { + while (!testNames.isEmpty()) { + checkTestsStatus(); + tasks.remove(completionService.take()); + + //update test results + updateTestState(); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + for (Future task : tasks) { + task.cancel(true); // if there was an error, attempt to cancel the other tasks + } + execService.shutdown(); // shutdown regardless + } + } + + private void updateTestState() { + while (!testUpdates.isEmpty()) { + ResultUpdate curr = testUpdates.remove(); + theTests.remove(testNames.indexOf(curr.getTestName())); + testNames.remove(curr.getTestName()); + digraph.updateTestStatus(curr.getTestName(), curr.getTestStatus()); + } + } + + private void checkTestsStatus() { + for (String currentTest : testNames) { + String theTestName = currentTest.toString(); + DiNode theTestNode = digraph.getVertex(theTestName); + + //test complete -skip + if (theTestNode.getTestStatus().equalsIgnoreCase("FAILED") || + theTestNode.getTestStatus().equalsIgnoreCase("PASSED") || + theTestNode.getTestStatus().equalsIgnoreCase("READY")) { + continue; + } + + boolean isAllDepFinished = true; + boolean depTestsFailed = false; + //Check Dependencies + for (DiNode dependency : digraph.getAllDependencies(theTestName)) { + if (dependency.getTestStatus().equalsIgnoreCase("FAILED")) { + depTestsFailed = true; + } else if (!dependency.getTestStatus().equalsIgnoreCase("PASSED")) { + isAllDepFinished = false; + break; + } + + } + + //if dependencies aren't done yet. There's no point in checking the Exclusions for + //this test + if (!isAllDepFinished) { + continue; + } + + //Check Exclusions + boolean checkExclusions = true; + for (DiNode exclusion : digraph.getAllExclusions(theTestName)) { + if (exclusion.getTestStatus().equalsIgnoreCase("RUNNING") + || exclusion.getTestStatus().equalsIgnoreCase("READY")) { + checkExclusions = false; + break; + } + } + + if (isAllDepFinished && checkExclusions) { + int corresponding = testNames.indexOf(currentTest); + tasks.add(completionService.submit(theTests.get(corresponding), theTestName)); + if (!depTestsFailed) { + digraph.updateTestStatus(theTestName, "READY"); + } else { + digraph.updateTestStatus(theTestName, "FAILED"); + } + } + + } + + } + + public static void registerTestName(String name) { + testNames.add(name); + } +} + + + diff --git a/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java b/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java index 7ea0bce..5e49147 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java +++ b/src/main/java/org/finra/jtaf/core/parallel/JTAFMasterSuite.java @@ -1,51 +1,51 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runners.Suite; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; -import org.xml.sax.SAXException; - - -/** - * The test suite of the tests that will run together - */ -public class JTAFMasterSuite extends Suite { - - public JTAFMasterSuite(Class klass, RunnerBuilder builder) - throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { - super(klass, (new MasterSuiteRunnersBuilder().runners())); - setScheduler(new ConcurrentScheduler()); - - } - - @Override - public Description getDescription() { - Description description = Description.createSuiteDescription("Automated Tests"); - for (Runner child : getChildren()) - description.addChild(describeChild(child)); - return description; - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; +import org.xml.sax.SAXException; + + +/** + * The test suite of the tests that will run together + */ +public class JTAFMasterSuite extends Suite { + + public JTAFMasterSuite(Class klass, RunnerBuilder builder) + throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { + super(klass, (new MasterSuiteRunnersBuilder().runners())); + setScheduler(new ConcurrentScheduler()); + + } + + @Override + public Description getDescription() { + Description description = Description.createSuiteDescription("Automated Tests"); + for (Runner child : getChildren()) + description.addChild(describeChild(child)); + return description; + } + +} diff --git a/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java b/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java index 441cb3d..040f012 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java +++ b/src/main/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilder.java @@ -1,70 +1,70 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.junit.runner.Runner; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; -import org.xml.sax.SAXException; - - -/** - * Builds the list of runners for the tests in Test Agenda - */ -public class MasterSuiteRunnersBuilder extends RunnerBuilder { - - public MasterSuiteRunnersBuilder() throws IllegalAccessException { - - } - - public List runners() - throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { - - - AutomationEngine engine = AutomationEngine.getInstance(); - ArrayList tests = new ArrayList(); - - engine.buildModel(new File("testlibrary"), new File("testscripts")); - TestAgenda testAgenda = engine.getTestAgenda(); - - for (TestScript testScript : testAgenda.getTestScripts()) { - TestCaseRunner theRunner = new TestCaseRunner(ParallelScriptRunner.class, new ParallelScriptRunner(testScript)); - tests.add(theRunner); - ConcurrentScheduler.registerTestName(testScript.getName()); - } - - return tests; - } - - @Override - public Runner runnerForClass(Class testClass) throws Throwable { - // TODO Auto-generated method stub - return null; - } - - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.junit.runner.Runner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; +import org.xml.sax.SAXException; + + +/** + * Builds the list of runners for the tests in Test Agenda + */ +public class MasterSuiteRunnersBuilder extends RunnerBuilder { + + public MasterSuiteRunnersBuilder() throws IllegalAccessException { + + } + + public List runners() + throws InitializationError, ParsingException, SAXException, IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { + + + AutomationEngine engine = AutomationEngine.getInstance(); + ArrayList tests = new ArrayList(); + + engine.buildModel(new File("testlibrary"), new File("testscripts")); + TestAgenda testAgenda = engine.getTestAgenda(); + + for (TestScript testScript : testAgenda.getTestScripts()) { + TestCaseRunner theRunner = new TestCaseRunner(ParallelScriptRunner.class, new ParallelScriptRunner(testScript)); + tests.add(theRunner); + ConcurrentScheduler.registerTestName(testScript.getName()); + } + + return tests; + } + + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + // TODO Auto-generated method stub + return null; + } + + +} diff --git a/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java b/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java index 1f839b9..6c9bb92 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ParallelScriptRunner.java @@ -1,101 +1,101 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -import org.junit.Assert; -import junit.framework.TestCase; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.execution.Interpreter; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.utilities.StringHelper; -import org.junit.Test; - - -/** - * Allows more than one script to run in parallel - */ -public class ParallelScriptRunner extends TestCase { - - private TestScript theTestScript; - boolean expectedFailureFlag = false; - public static final Logger logger = Logger.getLogger(ParallelScriptRunner.class); - - public ParallelScriptRunner(TestScript theTestScript) { - super(createJUnitName(theTestScript)); - this.theTestScript = theTestScript; - } - - private static final String createJUnitName(TestScript test) { - StringBuilder sb = new StringBuilder(); - sb.append(test.getFullName()); - boolean issuesExist = false; - if (test.getCRs() != null && test.getCRs().size() > 0) { - sb.append(" CR=\""); - sb.append(StringHelper.join(test.getCRs(), ", ")); - - sb.append("\""); - - issuesExist = true; - } - - if (test.getIssue() != null && !test.getIssue().equals("")) { - issuesExist = true; - } - - if (test.getStatus() != null) { - sb.append(" STATUS=\""); - sb.append(test.getStatus()); - sb.append("\""); - } - - if (issuesExist) { - sb.append(" [ISSUE EXISTS]"); - } - - return sb.toString(); - } - - @Test - public void runJtafTestScript() throws Throwable { - - logger.info("Thread " + Thread.currentThread().getId() + " is executing " + this.getName()); - DiNode theTest = AutomationEngine.getInstance().getTestDigraph().getVertex(this.theTestScript.getName()); - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - try { - if (theTest.getTestStatus().equalsIgnoreCase("FAILED")) { - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); - Assert.fail("One or more Dependent tests failed"); - } - TestResult tr = iv.interpret(this.theTestScript); - if (!tr.isTestPassed()) { - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); - throw tr.getFailureReason(); - } - ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "PASSED")); - } catch (Throwable t) { - throw t; - } finally { - - } - - - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +import org.junit.Assert; +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.execution.Interpreter; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.utilities.StringHelper; +import org.junit.Test; + + +/** + * Allows more than one script to run in parallel + */ +public class ParallelScriptRunner extends TestCase { + + private TestScript theTestScript; + boolean expectedFailureFlag = false; + public static final Logger logger = Logger.getLogger(ParallelScriptRunner.class); + + public ParallelScriptRunner(TestScript theTestScript) { + super(createJUnitName(theTestScript)); + this.theTestScript = theTestScript; + } + + private static final String createJUnitName(TestScript test) { + StringBuilder sb = new StringBuilder(); + sb.append(test.getFullName()); + boolean issuesExist = false; + if (test.getCRs() != null && test.getCRs().size() > 0) { + sb.append(" CR=\""); + sb.append(StringHelper.join(test.getCRs(), ", ")); + + sb.append("\""); + + issuesExist = true; + } + + if (test.getIssue() != null && !test.getIssue().equals("")) { + issuesExist = true; + } + + if (test.getStatus() != null) { + sb.append(" STATUS=\""); + sb.append(test.getStatus()); + sb.append("\""); + } + + if (issuesExist) { + sb.append(" [ISSUE EXISTS]"); + } + + return sb.toString(); + } + + @Test + public void runJtafTestScript() throws Throwable { + + logger.info("Thread " + Thread.currentThread().getId() + " is executing " + this.getName()); + DiNode theTest = AutomationEngine.getInstance().getTestDigraph().getVertex(this.theTestScript.getName()); + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + try { + if (theTest.getTestStatus().equalsIgnoreCase("FAILED")) { + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); + Assert.fail("One or more Dependent tests failed"); + } + TestResult tr = iv.interpret(this.theTestScript); + if (!tr.isTestPassed()) { + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "FAILED")); + throw tr.getFailureReason(); + } + ConcurrentScheduler.updateWithStatus(new ResultUpdate(this.theTestScript.getName(), "PASSED")); + } catch (Throwable t) { + throw t; + } finally { + + } + + + } +} diff --git a/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java b/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java index d0a3bc8..b635ad4 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java +++ b/src/main/java/org/finra/jtaf/core/parallel/ResultUpdate.java @@ -1,41 +1,41 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -/** - * This class updates the test status and test result - */ -public class ResultUpdate { - - private String testName; - private String status; - - public ResultUpdate(String testName, String status) { - this.testName = testName; - this.status = status; - } - - public String getTestName() { - return testName; - } - - public String getTestStatus() { - return status; - } -} - - +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +/** + * This class updates the test status and test result + */ +public class ResultUpdate { + + private String testName; + private String status; + + public ResultUpdate(String testName, String status) { + this.testName = testName; + this.status = status; + } + + public String getTestName() { + return testName; + } + + public String getTestStatus() { + return status; + } +} + + diff --git a/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java b/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java index ad59a98..574f199 100644 --- a/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java +++ b/src/main/java/org/finra/jtaf/core/parallel/TestCaseRunner.java @@ -1,60 +1,60 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parallel; - -import java.util.List; - -import org.junit.runner.Description; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; - -/** - * The test case runner class - */ -public class TestCaseRunner extends BlockJUnit4ClassRunner { - - private ParallelScriptRunner scriptWrapper; - - public TestCaseRunner(Class klass, ParallelScriptRunner scriptWrapper) - throws InitializationError { - super(klass); - this.scriptWrapper = scriptWrapper; - } - - protected Object createTest() throws Exception { - return scriptWrapper; - } - - @Override - protected Description describeChild(FrameworkMethod method) { - - return Description.createSuiteDescription(scriptWrapper.getName()); - - } - - - public Description getDescription() { - return Description.createSuiteDescription(scriptWrapper.getName()); - - } - - @Override - protected void collectInitializationErrors(List errors) { - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parallel; + +import java.util.List; + +import org.junit.runner.Description; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; + +/** + * The test case runner class + */ +public class TestCaseRunner extends BlockJUnit4ClassRunner { + + private ParallelScriptRunner scriptWrapper; + + public TestCaseRunner(Class klass, ParallelScriptRunner scriptWrapper) + throws InitializationError { + super(klass); + this.scriptWrapper = scriptWrapper; + } + + protected Object createTest() throws Exception { + return scriptWrapper; + } + + @Override + protected Description describeChild(FrameworkMethod method) { + + return Description.createSuiteDescription(scriptWrapper.getName()); + + } + + + public Description getDescription() { + return Description.createSuiteDescription(scriptWrapper.getName()); + + } + + @Override + protected void collectInitializationErrors(List errors) { + } + +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java index b83268a..6729d68 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/AutomationValueFilterPlugin.java @@ -1,49 +1,49 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; - - -/** - * Core plugin that filters testscripts to run based on the automation value provided in the strategy file - */ -public class AutomationValueFilterPlugin implements IPostParseAllPlugin { - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { - TestAgenda testAgenda = ctx.getTestAgenda(); - if (testAgenda.isAutomationValuesEmpty()) - return; - - List testScripts = ctx.getTestAgenda().getTestScripts(); - List testsToRemove = new ArrayList(); - for (TestScript testScript : testScripts) { - String automationValue = testScript.getAutomationValue(); - if (!testAgenda.containsAutomationValue(automationValue)) - testsToRemove.add(testScript); - } - - testScripts.removeAll(testsToRemove); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; + + +/** + * Core plugin that filters testscripts to run based on the automation value provided in the strategy file + */ +public class AutomationValueFilterPlugin implements IPostParseAllPlugin { + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestAgenda testAgenda = ctx.getTestAgenda(); + if (testAgenda.isAutomationValuesEmpty()) + return; + + List testScripts = ctx.getTestAgenda().getTestScripts(); + List testsToRemove = new ArrayList(); + for (TestScript testScript : testScripts) { + String automationValue = testScript.getAutomationValue(); + if (!testAgenda.containsAutomationValue(automationValue)) + testsToRemove.add(testScript); + } + + testScripts.removeAll(testsToRemove); + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java b/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java index a993a3b..2de47ae 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/AutomationValuePlugin.java @@ -1,37 +1,37 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; -import org.w3c.dom.Element; - -/** - * Plugin that runs post parse of the strategy. Takes care of parsing the automation value in the agenda. - */ -public class AutomationValuePlugin implements IPostParseStrategyElementPlugin { - private static final String AUTOMATION_VALUE_NAME = "automationValue"; - - @Override - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { - Element element = ctx.getElement(); - if (element.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { - ctx.getTestAgenda().addAutomationValue(element.getTextContent()); - } - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; +import org.w3c.dom.Element; + +/** + * Plugin that runs post parse of the strategy. Takes care of parsing the automation value in the agenda. + */ +public class AutomationValuePlugin implements IPostParseStrategyElementPlugin { + private static final String AUTOMATION_VALUE_NAME = "automationValue"; + + @Override + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { + Element element = ctx.getElement(); + if (element.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { + ctx.getTestAgenda().addAutomationValue(element.getTextContent()); + } + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java b/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java index d90cbd2..c0179ee 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/CommandLibraryParser.java @@ -1,392 +1,392 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.IAutomationClassLoader; -import org.finra.jtaf.core.model.exceptions.NameCollisionException; -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.model.invocationtarget.Function; -import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.AttributeHelper; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -/** - * The class is responsible for discovering and parsing commands.xml files from - * the classpath and under the project folder - */ -public class CommandLibraryParser { - private static final String READ_LIBRARY_WARN = "A suspected library %s' was not loaded due to %s"; - private StatementParser stmtParser; - static Logger logger = Logger.getLogger(ScriptParser.class.getPackage() - .getName()); - - private final DocumentBuilder db; - - private IAutomationClassLoader automationClassLoader; - - public CommandLibraryParser() throws ParserConfigurationException { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - stmtParser = new StatementParser(); - } - - public void setAutomationClassLoader( - IAutomationClassLoader automationClassLoader) { - this.automationClassLoader = automationClassLoader; - } - - public CommandRegistry parseCommandLibraries( - CommandRegistry commandRegistry, File additionalLibrarySource, - MessageCollector mc) throws NameFormatException, - NameCollisionException, SAXException, IOException, - ParsingException, URISyntaxException { - - FileWriter fileWriter = null; - try { - fileWriter = new FileWriter("commandNames.txt"); - // process Core commands - for (InvocationTarget t : handleCoreLibrarySource(mc)) { - fileWriter.write(t.getName() - + System.getProperty("line.separator")); - if (commandRegistry.containsInvocationTarget(t.getName() - .toLowerCase())) { - logger.warn("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - mc.push("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - } - commandRegistry.registerInvocationTarget(t.getName() - .toLowerCase(), t); - } - - // process additional library source folder commands which are not - // in the classpath - for (InvocationTarget t : handleLibrarySource( - additionalLibrarySource, mc)) { - fileWriter.write(t.getName() - + System.getProperty("line.separator")); - if (commandRegistry.containsInvocationTarget(t.getName() - .toLowerCase())) { - logger.warn("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - mc.push("Oops! We have more then one command with same name ('" - + t.getName() - + "') (case insensitive)! Fix your test commands, please."); - } - commandRegistry.registerInvocationTarget(t.getName() - .toLowerCase(), t); - } - - return commandRegistry; - } finally { - if (fileWriter != null) { - try { - fileWriter.close(); - } catch (IOException e) { - } - } - } - } - - private List handleCoreLibrarySource(MessageCollector mc) - throws NameFormatException, NameCollisionException, SAXException, - IOException, ParsingException, URISyntaxException { - List retval = new ArrayList(); - - Resource[] resources = getResources(); - - for (Resource resource : resources) { - logger.debug("Parsing library " + resource.getDescription()); - List library = readLibrary(mc, - resource.getInputStream(), resource.getDescription()); - if ((library != null) && (library.size() > 0)) { - // try to read jars (maven or ant setup) - retval.addAll(library); - } else { - logger.debug("Found no commands"); - } - } - return retval; - } - - /** - * for all elements of java.class.path get a Collection of resources under - * testlibrary - * - * @return the resources in the order they are found - */ - - private Resource[] getResources() throws IOException, URISyntaxException { - PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - ArrayList result = new ArrayList(); - - // We want all commands.xml files in testlibrary folder anywhere in the - // hierarchy in the classpath - // There is no single regex to address our requirement. Hence we have - // two regex. - // The first one gets all entries where testLibrary is under root. - // The second gets all - Resource[] firstResultSet = resolver - .getResources("classpath*:/testlibrary/**/*commands.xml"); - if (firstResultSet != null) { - Collections.addAll(result, firstResultSet); - } - // This path does not address testlibrary being directly under the root. - resolver = new PathMatchingResourcePatternResolver(); - Resource[] secondResultSet = resolver - .getResources("classpath*:/**/testlibrary/**/*commands.xml"); - - if (secondResultSet != null) { - if (firstResultSet != null) { - for (Resource secondResource : secondResultSet) { - // check to see if it was already found. - boolean found = false; - for (Resource firstResource : firstResultSet) { - if (firstResource.getDescription().equals( - secondResource.getDescription())) { - found = true; - break; - } - } - if (!found) { - result.add(secondResource); - } - } - } else { - Collections.addAll(result, secondResultSet); - } - } - - return result.toArray(new Resource[]{}); - } - - public final List readLibrary(MessageCollector mc, - InputStream is, String description) { - - List retval = new ArrayList(); - - try { - mc.push("In library '" + description + "'"); - Document d = db.parse(is); - retval.addAll(processLibrary(d.getDocumentElement(), mc)); - - } catch (MalformedURLException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "the url being malformed!"), e); - } catch (IOException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "an io exception while reading it!"), e); - } catch (SAXException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "a SAX exception!"), e); - } catch (ParsingException e) { - logger.warn(String.format(READ_LIBRARY_WARN, description, - "a parsing exception!"), e); - } finally { - mc.pop(); - } - return retval; - } - - private final List handleLibrarySource(File f, - MessageCollector mc) throws NameFormatException, - NameCollisionException, SAXException, IOException, ParsingException { - - List retval = new ArrayList(); - try { - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath()); - } - - if (f.isFile() && f.getName().endsWith(".xml")) { - mc.push("In library " + f.getAbsolutePath()); - - try { - Document d = db.parse(f); - retval.addAll(processLibrary(d.getDocumentElement(), mc)); - } finally { - mc.pop(); - } - } else if (f.isDirectory()) { - ExceptionAccumulator acc = new ExceptionAccumulator(); - for (File child : f.listFiles()) { - try { - retval.addAll(handleLibrarySource(child, mc)); - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - } - } catch (FileNotFoundException e) { - logger.warn("A suspected library file '" + f.getAbsolutePath() - + "' was not found!"); - logger.debug(e); // debug this to slim down the log files - } - return retval; - } - - private final List processLibrary(Element elem, - MessageCollector mc) throws ParsingException { - if (elem.getNodeName().equalsIgnoreCase("library")) { - List invocationTargets = new ArrayList(); - ExceptionAccumulator acc = new ExceptionAccumulator(); - - for (Element child : ParserHelper.getChildren(elem)) { - try { - invocationTargets.add(processInvocationTarget(child, mc)); - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - - return invocationTargets; - } else { - throw new UnexpectedElementException(elem); - } - } - - // This is just called when processing the library. - // It basically just gets what are designated as parameters there and stores - // the names of them - // in the invocation target param list - private final InvocationTarget processInvocationTarget(Element elem, - MessageCollector mc) throws ParsingException { - InvocationTarget retval = null; - final String name = elem.getNodeName().toLowerCase(); - if (name.equals("command")) { - retval = processCommand(elem, mc); - } else if (name.equals("function")) { - retval = processFunction(elem, mc); - } else { - throw new UnexpectedElementException(elem); - } - - final Element usage = ParserHelper.getOptionalElement(elem, "usage"); - if (usage != null) { - retval.setUsage(usage.getTextContent()); - } - - final Element requiredParameters = ParserHelper.getOptionalElement( - elem, "requiredParameters"); - if (requiredParameters != null) { - for (Element child : ParserHelper.getChildren(requiredParameters)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addRequiredParameter(ah.getRequiredString("name")); - } - } - - final Element optionalParameters = ParserHelper.getOptionalElement( - elem, "optionalParameters"); - if (optionalParameters != null) { - for (Element child : ParserHelper.getChildren(optionalParameters)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addOptionalParameter(ah.getRequiredString("name")); - } - } - - final Element produces = ParserHelper.getOptionalElement(elem, - "produces"); - if (produces != null) { - for (Element child : ParserHelper.getChildren(produces)) { - AttributeHelper ah = new AttributeHelper(child); - retval.addProduction(ah.getRequiredString("name")); - } - } - - return retval; - } - - private final Command processCommand(Element elem, MessageCollector mc) - throws ParsingException { - try { - AttributeHelper ah = new AttributeHelper(elem); - final String commandName = ah.getRequiredString("name"); - final String commandClass = ah.getRequiredString("class"); - - Class targetClass = automationClassLoader - .loadClass(commandClass); - if (Command.class.isAssignableFrom(targetClass)) { - Constructor constructor = targetClass - .getConstructor(String.class); - return (Command) constructor.newInstance(commandName); - } else { - throw new IllegalArgumentException( - "All Commands must extend Command"); - } - } catch (Exception e) { - throw new ParsingException(e); - } - } - - private final Function processFunction(Element elem, MessageCollector mc) - throws ParsingException { - try { - - AttributeHelper ah = new AttributeHelper(elem); - Function retval = new Function(ah.getRequiredString("name") - .toLowerCase()); - - retval.setBody(stmtParser.processStatementList( - ParserHelper.getRequireElement(elem, "body"), mc)); - return retval; - } catch (Exception e) { - throw new ParsingException(e); - } - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.IAutomationClassLoader; +import org.finra.jtaf.core.model.exceptions.NameCollisionException; +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.model.invocationtarget.Function; +import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.AttributeHelper; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * The class is responsible for discovering and parsing commands.xml files from + * the classpath and under the project folder + */ +public class CommandLibraryParser { + private static final String READ_LIBRARY_WARN = "A suspected library %s' was not loaded due to %s"; + private StatementParser stmtParser; + static Logger logger = Logger.getLogger(ScriptParser.class.getPackage() + .getName()); + + private final DocumentBuilder db; + + private IAutomationClassLoader automationClassLoader; + + public CommandLibraryParser() throws ParserConfigurationException { + db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + stmtParser = new StatementParser(); + } + + public void setAutomationClassLoader( + IAutomationClassLoader automationClassLoader) { + this.automationClassLoader = automationClassLoader; + } + + public CommandRegistry parseCommandLibraries( + CommandRegistry commandRegistry, File additionalLibrarySource, + MessageCollector mc) throws NameFormatException, + NameCollisionException, SAXException, IOException, + ParsingException, URISyntaxException { + + FileWriter fileWriter = null; + try { + fileWriter = new FileWriter("commandNames.txt"); + // process Core commands + for (InvocationTarget t : handleCoreLibrarySource(mc)) { + fileWriter.write(t.getName() + + System.getProperty("line.separator")); + if (commandRegistry.containsInvocationTarget(t.getName() + .toLowerCase())) { + logger.warn("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + mc.push("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + } + commandRegistry.registerInvocationTarget(t.getName() + .toLowerCase(), t); + } + + // process additional library source folder commands which are not + // in the classpath + for (InvocationTarget t : handleLibrarySource( + additionalLibrarySource, mc)) { + fileWriter.write(t.getName() + + System.getProperty("line.separator")); + if (commandRegistry.containsInvocationTarget(t.getName() + .toLowerCase())) { + logger.warn("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + mc.push("Oops! We have more then one command with same name ('" + + t.getName() + + "') (case insensitive)! Fix your test commands, please."); + } + commandRegistry.registerInvocationTarget(t.getName() + .toLowerCase(), t); + } + + return commandRegistry; + } finally { + if (fileWriter != null) { + try { + fileWriter.close(); + } catch (IOException e) { + } + } + } + } + + private List handleCoreLibrarySource(MessageCollector mc) + throws NameFormatException, NameCollisionException, SAXException, + IOException, ParsingException, URISyntaxException { + List retval = new ArrayList(); + + Resource[] resources = getResources(); + + for (Resource resource : resources) { + logger.debug("Parsing library " + resource.getDescription()); + List library = readLibrary(mc, + resource.getInputStream(), resource.getDescription()); + if ((library != null) && (library.size() > 0)) { + // try to read jars (maven or ant setup) + retval.addAll(library); + } else { + logger.debug("Found no commands"); + } + } + return retval; + } + + /** + * for all elements of java.class.path get a Collection of resources under + * testlibrary + * + * @return the resources in the order they are found + */ + + private Resource[] getResources() throws IOException, URISyntaxException { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + ArrayList result = new ArrayList(); + + // We want all commands.xml files in testlibrary folder anywhere in the + // hierarchy in the classpath + // There is no single regex to address our requirement. Hence we have + // two regex. + // The first one gets all entries where testLibrary is under root. + // The second gets all + Resource[] firstResultSet = resolver + .getResources("classpath*:/testlibrary/**/*commands.xml"); + if (firstResultSet != null) { + Collections.addAll(result, firstResultSet); + } + // This path does not address testlibrary being directly under the root. + resolver = new PathMatchingResourcePatternResolver(); + Resource[] secondResultSet = resolver + .getResources("classpath*:/**/testlibrary/**/*commands.xml"); + + if (secondResultSet != null) { + if (firstResultSet != null) { + for (Resource secondResource : secondResultSet) { + // check to see if it was already found. + boolean found = false; + for (Resource firstResource : firstResultSet) { + if (firstResource.getDescription().equals( + secondResource.getDescription())) { + found = true; + break; + } + } + if (!found) { + result.add(secondResource); + } + } + } else { + Collections.addAll(result, secondResultSet); + } + } + + return result.toArray(new Resource[]{}); + } + + public final List readLibrary(MessageCollector mc, + InputStream is, String description) { + + List retval = new ArrayList(); + + try { + mc.push("In library '" + description + "'"); + Document d = db.parse(is); + retval.addAll(processLibrary(d.getDocumentElement(), mc)); + + } catch (MalformedURLException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "the url being malformed!"), e); + } catch (IOException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "an io exception while reading it!"), e); + } catch (SAXException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "a SAX exception!"), e); + } catch (ParsingException e) { + logger.warn(String.format(READ_LIBRARY_WARN, description, + "a parsing exception!"), e); + } finally { + mc.pop(); + } + return retval; + } + + private final List handleLibrarySource(File f, + MessageCollector mc) throws NameFormatException, + NameCollisionException, SAXException, IOException, ParsingException { + + List retval = new ArrayList(); + try { + if (!f.exists()) { + throw new FileNotFoundException(f.getAbsolutePath()); + } + + if (f.isFile() && f.getName().endsWith(".xml")) { + mc.push("In library " + f.getAbsolutePath()); + + try { + Document d = db.parse(f); + retval.addAll(processLibrary(d.getDocumentElement(), mc)); + } finally { + mc.pop(); + } + } else if (f.isDirectory()) { + ExceptionAccumulator acc = new ExceptionAccumulator(); + for (File child : f.listFiles()) { + try { + retval.addAll(handleLibrarySource(child, mc)); + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + } + } catch (FileNotFoundException e) { + logger.warn("A suspected library file '" + f.getAbsolutePath() + + "' was not found!"); + logger.debug(e); // debug this to slim down the log files + } + return retval; + } + + private final List processLibrary(Element elem, + MessageCollector mc) throws ParsingException { + if (elem.getNodeName().equalsIgnoreCase("library")) { + List invocationTargets = new ArrayList(); + ExceptionAccumulator acc = new ExceptionAccumulator(); + + for (Element child : ParserHelper.getChildren(elem)) { + try { + invocationTargets.add(processInvocationTarget(child, mc)); + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + + return invocationTargets; + } else { + throw new UnexpectedElementException(elem); + } + } + + // This is just called when processing the library. + // It basically just gets what are designated as parameters there and stores + // the names of them + // in the invocation target param list + private final InvocationTarget processInvocationTarget(Element elem, + MessageCollector mc) throws ParsingException { + InvocationTarget retval = null; + final String name = elem.getNodeName().toLowerCase(); + if (name.equals("command")) { + retval = processCommand(elem, mc); + } else if (name.equals("function")) { + retval = processFunction(elem, mc); + } else { + throw new UnexpectedElementException(elem); + } + + final Element usage = ParserHelper.getOptionalElement(elem, "usage"); + if (usage != null) { + retval.setUsage(usage.getTextContent()); + } + + final Element requiredParameters = ParserHelper.getOptionalElement( + elem, "requiredParameters"); + if (requiredParameters != null) { + for (Element child : ParserHelper.getChildren(requiredParameters)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addRequiredParameter(ah.getRequiredString("name")); + } + } + + final Element optionalParameters = ParserHelper.getOptionalElement( + elem, "optionalParameters"); + if (optionalParameters != null) { + for (Element child : ParserHelper.getChildren(optionalParameters)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addOptionalParameter(ah.getRequiredString("name")); + } + } + + final Element produces = ParserHelper.getOptionalElement(elem, + "produces"); + if (produces != null) { + for (Element child : ParserHelper.getChildren(produces)) { + AttributeHelper ah = new AttributeHelper(child); + retval.addProduction(ah.getRequiredString("name")); + } + } + + return retval; + } + + private final Command processCommand(Element elem, MessageCollector mc) + throws ParsingException { + try { + AttributeHelper ah = new AttributeHelper(elem); + final String commandName = ah.getRequiredString("name"); + final String commandClass = ah.getRequiredString("class"); + + Class targetClass = automationClassLoader + .loadClass(commandClass); + if (Command.class.isAssignableFrom(targetClass)) { + Constructor constructor = targetClass + .getConstructor(String.class); + return (Command) constructor.newInstance(commandName); + } else { + throw new IllegalArgumentException( + "All Commands must extend Command"); + } + } catch (Exception e) { + throw new ParsingException(e); + } + } + + private final Function processFunction(Element elem, MessageCollector mc) + throws ParsingException { + try { + + AttributeHelper ah = new AttributeHelper(elem); + Function retval = new Function(ah.getRequiredString("name") + .toLowerCase()); + + retval.setBody(stmtParser.processStatementList( + ParserHelper.getRequireElement(elem, "body"), mc)); + return retval; + } catch (Exception e) { + throw new ParsingException(e); + } + } + +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java index 18f66b9..58bbd3b 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/DigraphPlugin.java @@ -1,67 +1,67 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.LinkedHashSet; -import java.util.Set; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestNamespace; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.model.test.digraph.DigraphFactory; -import org.finra.jtaf.core.model.test.digraph.TestDigraph; -import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; -import org.finra.jtaf.core.utilities.logging.MessageCollector; - -/** - * Parser plugin that runs post all. Scans through the test scripts to create a Digraph as per denpencies. - */ -public class DigraphPlugin implements IPostParseAllPlugin { - protected TestNamespace testNamespace; - - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { - TestDigraph testDigraph = AutomationEngine.getInstance().getTestDigraph(); - TestAgenda testAgenda = ctx.getTestAgenda(); - testNamespace = AutomationEngine.getInstance().getTestRoot(); - DigraphFactory graphFactory = new DigraphFactory(testDigraph, new MessageCollector()); - graphFactory.createGraph(testNamespace); - - Set dependentTests = new LinkedHashSet(); - for (TestScript t : testAgenda.getTestScripts()) - if (testAgenda.containsAutomationValue(t.getAutomationValue())) - dependentTests.addAll(addDependentTests(testDigraph, (TestScript) t)); - - for (TestScript t : dependentTests) - if (!testAgenda.getTestScripts().contains(t)) - testAgenda.getTestScripts().add(t); - } - - private Set addDependentTests(TestDigraph testDigraph, TestScript test) { - Set additionalScript = new LinkedHashSet(); - for (DiNode d : testDigraph.getAllDependencies(test.getName())) { - d.getTestScript().setAutomationValue(test.getAutomationValue()); - additionalScript.add(d.getTestScript()); - additionalScript.addAll(addDependentTests(testDigraph, d.getTestScript())); - } - return additionalScript; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.LinkedHashSet; +import java.util.Set; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestNamespace; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.model.test.digraph.DigraphFactory; +import org.finra.jtaf.core.model.test.digraph.TestDigraph; +import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; +import org.finra.jtaf.core.utilities.logging.MessageCollector; + +/** + * Parser plugin that runs post all. Scans through the test scripts to create a Digraph as per denpencies. + */ +public class DigraphPlugin implements IPostParseAllPlugin { + protected TestNamespace testNamespace; + + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestDigraph testDigraph = AutomationEngine.getInstance().getTestDigraph(); + TestAgenda testAgenda = ctx.getTestAgenda(); + testNamespace = AutomationEngine.getInstance().getTestRoot(); + DigraphFactory graphFactory = new DigraphFactory(testDigraph, new MessageCollector()); + graphFactory.createGraph(testNamespace); + + Set dependentTests = new LinkedHashSet(); + for (TestScript t : testAgenda.getTestScripts()) + if (testAgenda.containsAutomationValue(t.getAutomationValue())) + dependentTests.addAll(addDependentTests(testDigraph, (TestScript) t)); + + for (TestScript t : dependentTests) + if (!testAgenda.getTestScripts().contains(t)) + testAgenda.getTestScripts().add(t); + } + + private Set addDependentTests(TestDigraph testDigraph, TestScript test) { + Set additionalScript = new LinkedHashSet(); + for (DiNode d : testDigraph.getAllDependencies(test.getName())) { + d.getTestScript().setAutomationValue(test.getAutomationValue()); + additionalScript.add(d.getTestScript()); + additionalScript.addAll(addDependentTests(testDigraph, d.getTestScript())); + } + return additionalScript; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java index f690121..1aa4a29 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/ExceptionPlugin.java @@ -1,51 +1,51 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.w3c.dom.NodeList; - - -/** - * This is internal class meant for verification of expected exception in the script - */ -public class ExceptionPlugin implements IPostParseTestPlugin { - public static final String NODE_NAME = "expectedException"; - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { - NodeList childNodes = ctx.getRootNodeTest().getChildNodes(); - for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { - if (childNodes.item(childNodeIndex).getNodeName().equalsIgnoreCase(NODE_NAME)) { - int size = ctx.getTestSuite().getComponentList().size(); - TestScript script = (TestScript) ctx.getTestSuite().getComponentList().get(size - 1); - script.setException(childNodes.item(childNodeIndex).getTextContent()); - //ctx.getTestAgenda().setThreadCount(maxThreads); - } - } - - } - - @Override - public String getTagName() { - - return NODE_NAME; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.w3c.dom.NodeList; + + +/** + * This is internal class meant for verification of expected exception in the script + */ +public class ExceptionPlugin implements IPostParseTestPlugin { + public static final String NODE_NAME = "expectedException"; + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + NodeList childNodes = ctx.getRootNodeTest().getChildNodes(); + for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { + if (childNodes.item(childNodeIndex).getNodeName().equalsIgnoreCase(NODE_NAME)) { + int size = ctx.getTestSuite().getComponentList().size(); + TestScript script = (TestScript) ctx.getTestSuite().getComponentList().get(size - 1); + script.setException(childNodes.item(childNodeIndex).getTextContent()); + //ctx.getTestAgenda().setThreadCount(maxThreads); + } + } + + } + + @Override + public String getTagName() { + + return NODE_NAME; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java index 7728604..ce1bb00 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/LoopPlugin.java @@ -1,127 +1,127 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.exceptions.NameCollisionException; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.model.test.digraph.TestDigraph; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * Parser plugin meant to handle the loop element in the script that determines - * the number of times a test script needs to be run. - */ -public class LoopPlugin implements IPostParseTestPlugin { - protected TestDigraph testDigraph; - - @Override - public String getTagName() { - return "loop"; - } - - public LoopPlugin(AutomationEngine automationEngine) { - this.testDigraph = automationEngine.getTestDigraph(); - } - - @Override - public void execute(PostTestParserPluginContext ctx) - throws ParserPluginException { - int iterationCount = getIterationCount(ctx.getRootNodeTest()); - if (iterationCount != 1) { - TestScript oldTestScript = getOldTestScript(ctx.getTestSuite()); - List iteratedScripts = createIteratedTestScripts(ctx, - oldTestScript, iterationCount); - removeOldTestScript(ctx.getTestSuite()); - addIteratedTestScripts(ctx.getTestSuite(), iteratedScripts); - } - } - - private int getIterationCount(Node rootNodeTest) { - int result = 1; - NodeList children = rootNodeTest.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeName().equalsIgnoreCase("loop")) { - result = Integer.parseInt(children.item(i).getAttributes() - .getNamedItem("iterations").getNodeValue()); - } - } - return result; - } - - private TestScript getOldTestScript(TestSuite testSuite) { - List testComponents = testSuite.getComponentList(); - return (TestScript) testComponents.get(testComponents.size() - 1); - } - - List createIteratedTestScripts(PostTestParserPluginContext ctx, - TestScript oldTestScript, int iterationCount) - throws ParserPluginException { - List result = new ArrayList(); - for (int currentIteration = 1; currentIteration <= iterationCount; currentIteration++) { - TestScript newTestScript; - ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); - try { - newTestScript = sp - .processTestScript((Element) ctx.getRootNodeTest(), - new MessageCollector()); - } catch (ParsingException parsingException) { - throw new ParserPluginException("Problem re-parsing test", - parsingException); - } - newTestScript.setName(newTestScript.getName() + " [iteration " - + currentIteration + " of " + iterationCount + "]"); - result.add(newTestScript); - } - return result; - } - - private void removeOldTestScript(TestSuite testSuite) { - List testComponents = testSuite.getComponentList(); - testComponents.remove(testComponents.size() - 1); - } - - private void addIteratedTestScripts(TestSuite testSuite, - List iteratedScripts) throws ParserPluginException { - try { - for (TestScript iteratedScript : iteratedScripts) { - testSuite.add(iteratedScript); - // DigraphPlugin dependenciesPlugin = - // DigraphPlugin.getInstance(); - // TestDigraph testDigraph = - // dependenciesPlugin.getTestDigraph(); - testDigraph.addVertex(new DiNode(iteratedScript)); - } - } catch (NameCollisionException nameCollisionException) { - throw new ParserPluginException("Duplicate test name: ", - nameCollisionException); - } - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.exceptions.NameCollisionException; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.model.test.digraph.TestDigraph; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Parser plugin meant to handle the loop element in the script that determines + * the number of times a test script needs to be run. + */ +public class LoopPlugin implements IPostParseTestPlugin { + protected TestDigraph testDigraph; + + @Override + public String getTagName() { + return "loop"; + } + + public LoopPlugin(AutomationEngine automationEngine) { + this.testDigraph = automationEngine.getTestDigraph(); + } + + @Override + public void execute(PostTestParserPluginContext ctx) + throws ParserPluginException { + int iterationCount = getIterationCount(ctx.getRootNodeTest()); + if (iterationCount != 1) { + TestScript oldTestScript = getOldTestScript(ctx.getTestSuite()); + List iteratedScripts = createIteratedTestScripts(ctx, + oldTestScript, iterationCount); + removeOldTestScript(ctx.getTestSuite()); + addIteratedTestScripts(ctx.getTestSuite(), iteratedScripts); + } + } + + private int getIterationCount(Node rootNodeTest) { + int result = 1; + NodeList children = rootNodeTest.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase("loop")) { + result = Integer.parseInt(children.item(i).getAttributes() + .getNamedItem("iterations").getNodeValue()); + } + } + return result; + } + + private TestScript getOldTestScript(TestSuite testSuite) { + List testComponents = testSuite.getComponentList(); + return (TestScript) testComponents.get(testComponents.size() - 1); + } + + List createIteratedTestScripts(PostTestParserPluginContext ctx, + TestScript oldTestScript, int iterationCount) + throws ParserPluginException { + List result = new ArrayList(); + for (int currentIteration = 1; currentIteration <= iterationCount; currentIteration++) { + TestScript newTestScript; + ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); + try { + newTestScript = sp + .processTestScript((Element) ctx.getRootNodeTest(), + new MessageCollector()); + } catch (ParsingException parsingException) { + throw new ParserPluginException("Problem re-parsing test", + parsingException); + } + newTestScript.setName(newTestScript.getName() + " [iteration " + + currentIteration + " of " + iterationCount + "]"); + result.add(newTestScript); + } + return result; + } + + private void removeOldTestScript(TestSuite testSuite) { + List testComponents = testSuite.getComponentList(); + testComponents.remove(testComponents.size() - 1); + } + + private void addIteratedTestScripts(TestSuite testSuite, + List iteratedScripts) throws ParserPluginException { + try { + for (TestScript iteratedScript : iteratedScripts) { + testSuite.add(iteratedScript); + // DigraphPlugin dependenciesPlugin = + // DigraphPlugin.getInstance(); + // TestDigraph testDigraph = + // dependenciesPlugin.getTestDigraph(); + testDigraph.addVertex(new DiNode(iteratedScript)); + } + } catch (NameCollisionException nameCollisionException) { + throw new ParserPluginException("Duplicate test name: ", + nameCollisionException); + } + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java index 43ac7a8..1c58b8b 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/MaxThreadsPlugin.java @@ -1,38 +1,38 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; -import org.w3c.dom.Element; - - -/** - * Strategy parser plugin that parses maximum parallel threads in strategy. - */ -public class MaxThreadsPlugin implements IPostParseStrategyElementPlugin { - private static final String MAX_THREADS_NAME = "maxThreads"; - - @Override - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { - Element element = ctx.getElement(); - if (element.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { - ctx.getTestAgenda().setThreadCount(element.getTextContent()); - } - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; +import org.w3c.dom.Element; + + +/** + * Strategy parser plugin that parses maximum parallel threads in strategy. + */ +public class MaxThreadsPlugin implements IPostParseStrategyElementPlugin { + private static final String MAX_THREADS_NAME = "maxThreads"; + + @Override + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException { + Element element = ctx.getElement(); + if (element.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { + ctx.getTestAgenda().setThreadCount(element.getTextContent()); + } + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java b/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java index 10eadcf..d617a65 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/ScriptParser.java @@ -1,726 +1,726 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.exceptions.DependencyException; -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.test.Requirement; -import org.finra.jtaf.core.model.test.TestNamespace; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.model.test.digraph.Dependencies; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.model.test.digraph.TestDigraph; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.MissingAttributeException; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.AttributeHelper; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.finra.jtaf.core.utilities.ExcelFileParser; -import org.finra.jtaf.core.utilities.StringHelper; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import au.com.bytecode.opencsv.CSVReader; - -/** - * FIXME This is a "just get the job done" implementation. I plan to replace - * this class as soon as I get the chance. (I mean... ay ay ay! This is bad!) - */ -public class ScriptParser { - - static Logger logger = Logger.getLogger(ScriptParser.class.getPackage().getName()); - private final DocumentBuilder db; - private TestDigraph digraph; - private StatementParser stmtParser; - private Document d; - private CommandRegistry commandRegistry; - - private List postParseSuitePlugins; - private List postParseTestPlugins; - - - public ScriptParser() throws ParserConfigurationException { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - stmtParser = new StatementParser(); - } - - public void setDigraph(TestDigraph digraph) { - this.digraph = digraph; - } - - public void setPostParseSuitePlugins(List plugins) { - postParseSuitePlugins = plugins; - } - - - public void setPostParseTestPlugins(List plugins) { - postParseTestPlugins = plugins; - } - - public void setCommandRegistry(CommandRegistry commandRegistry) { - this.commandRegistry = commandRegistry; - } - - public final TestNamespace handleTestSource(File f, MessageCollector mc) - throws NameFormatException, SAXException, IOException, ParsingException { - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath()); - } - TestNamespace testNamespace = new TestNamespace(f.getName()); - if (f.isDirectory() && !f.isHidden()) { - ExceptionAccumulator acc = new ExceptionAccumulator(); - - for (File child : f.listFiles()) { - if (child.isDirectory()) { - try { - testNamespace.add(handleTestSource(child, mc)); - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } else { // It's a file - try { - TestSuite ts = handleTestSuite(child, mc); - if (ts != null) { - testNamespace.add(ts); - // run all post suite parse plugins - - Node suiteRootNode = (Node) (d.getDocumentElement()); - // TODO: This needs to check for null, otherwise it - // crashes - - if (postParseSuitePlugins != null) { - for (IPostParseSuitePlugin p : postParseSuitePlugins) { - if (suiteContainsTheTag(suiteRootNode, p.getTagName())) { - p.execute(new PostSuiteParserPluginContext(commandRegistry, ts, suiteRootNode)); - } - } - } - } - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - } - - if (!acc.isEmpty()) { - throw acc; - } - } - return testNamespace; - } - - private boolean suiteContainsTheTag(Node suiteRootNode, String tagName) { - NodeList children = suiteRootNode.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeName().equalsIgnoreCase(tagName)) { - return true; - } - } - return false; - } - - private TestSuite handleTestSuite(File f, MessageCollector mc) throws ParsingException, - NameFormatException, IOException { - if (!f.exists()) { - throw new FileNotFoundException(f.getAbsolutePath()); - } - TestSuite testSuite = null; - if (f.isFile() && f.getName().endsWith(".xml")) { // This should be a - // TestSuite - mc.push("In test file " + f.getAbsolutePath()); - try { - d = db.parse(f); - testSuite = processTestSuite(d.getDocumentElement(), mc, f.getName()); - for (TestScript ts : processTestScripts(d.getDocumentElement(), mc)) { - try { - if (!digraph.addVertex(new DiNode(ts))) { - throw new DependencyException("Duplicate test name '" + ts.getName() - + "' found at: " - + digraph.getVertex(ts.getName()).getTestScript().getFullName()); - } - ts.setFileName(f.getName()); - - testSuite.add(ts); - // run post parse test plugins - Node testRootNode = getTestRootNode(d.getDocumentElement(), ts); - for (IPostParseTestPlugin p : postParseTestPlugins) { - if (testContainsTheTag(testRootNode, p.getTagName())) { - p.execute(new PostTestParserPluginContext(commandRegistry, testSuite, testRootNode)); - } - } - } catch (DependencyException de) { - mc.error(de.getMessage()); - throw de; - } catch (Throwable th) { - mc.error(th.getMessage()); - logger.fatal(th.getMessage()); - } - } - } catch (SAXException e) { - mc.error(e.getMessage()); - // throw e; - } catch (IOException e) { - mc.error(e.getMessage()); - throw e; - } finally { - mc.pop(); - } - } - return testSuite; - } - - private boolean testContainsTheTag(Node testRootNode, String tagName) { - NodeList children = testRootNode.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeName().equalsIgnoreCase(tagName)) { - return true; - } - } - return false; - } - - private Node getTestRootNode(Element documentElement, TestScript ts) { - NodeList list = documentElement.getElementsByTagName("test"); - for (int i = 0; i < list.getLength(); i++) { - Node n = list.item(i); - if (n.getAttributes().getNamedItem("name").getNodeValue().equals(ts.getName())) { - return n; - } - } - return null; - } - - public final TestSuite processTestSuite(Element element, MessageCollector mc, String fileName) - throws ParsingException, NameFormatException { - TestSuite testSuite = new TestSuite(fileName); - if (element.getNodeName().equalsIgnoreCase("testsuite")) { - AttributeHelper testScriptAttributeHelper = new AttributeHelper(element); - - String testSuiteName = null; - try { - testSuiteName = testScriptAttributeHelper.getRequiredString("name"); - testSuite.setTestSuiteName(testSuiteName); - } catch (MissingAttributeException e) { - mc.push(e.getMessage()); - logger.debug("Oops! Test suite has no 'name' attribute! ('" + element.toString() - + "')"); - } - - testSuite.setDependencies(new Dependencies(null, null)); - testSuite.setExclusions(new Dependencies(null, null)); - - return testSuite; - } else { - UnexpectedElementException z = new UnexpectedElementException(element); - mc.error(z.getMessage()); - throw z; - } - } - - private final List processTestScripts(Element element, MessageCollector mc) - throws ParsingException { - if (element.getNodeName().equalsIgnoreCase("testsuite")) { - List testScripts = null; - AttributeHelper testScriptAttributeHelper = new AttributeHelper(element); - - String testSuiteName = null; - try { - testSuiteName = testScriptAttributeHelper.getRequiredString("name"); - } catch (MissingAttributeException e) { - mc.push(e.getMessage()); - logger.debug("Oops! Test suite hasn't 'name' attibite! ('" + element.toString() - + "')"); - } - - // MULTITHREADED 2012.4 Changes START - // ------------------------------------- - // This will seperate out the elements at the testsuite level - ArrayList testSuiteChildren = (ArrayList) ParserHelper - .getChildren(element); - ArrayList tests = new ArrayList(); - - for (Element e : testSuiteChildren) { - if (e.getNodeName().equalsIgnoreCase("test")) { - tests.add(e); - } - } - testScripts = parseTests(tests, mc, testSuiteName); - - // MULTITHREADED 2012.4 Changes END - // ------------------------------------- - return testScripts; - } else { - UnexpectedElementException z = new UnexpectedElementException(element); - mc.error(z.getMessage()); - throw z; - } - } - - private List parseTests(List elementList, MessageCollector mc, - String testSuiteName) throws ExceptionAccumulator { - List testScripts = new ArrayList(); - ExceptionAccumulator acc = new ExceptionAccumulator(); - for (Element child : elementList) { - try { - AttributeHelper testAttributeHelper = new AttributeHelper(child); - String testName = testAttributeHelper.getOptionalString("name"); - int testLoopNumber = getLoopNumber(testAttributeHelper, mc); - - String testDataFile = getTestDataFile(child); - String sheetName = getSheetName(child); - List> testData = null; - int tsNamefromFilePosition = -1; - if (testDataFile != null) { - if (testDataFile.endsWith(".xlsx")) { - testData = getExcelDataFromFile(testDataFile, sheetName, mc, true); - } else if (testDataFile.endsWith(".xls")) { - testData = getExcelDataFromFile(testDataFile, sheetName, mc, false); - } else if (testDataFile.endsWith(".csv")) { - testData = getCSVDataFromFile(testDataFile, mc); - } else { - logger.fatal("Oops! can't parse test data file ('" + testDataFile - + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); - } - tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); - } - - for (int i = 1; i <= testLoopNumber; i++) { - TestScript ts = processTestScript(child, mc); - ts.setTestSuiteName(testSuiteName); - - if (testData != null && testData.size() > 0) { - int rowNumber = 0; - List titleRow = null; - for (List row : testData) { - String tsNamefromFile = ""; - if (tsNamefromFilePosition >= 0) { - tsNamefromFile = "testNameFromDataFile-" - + row.get(tsNamefromFilePosition); - } - if (0 == rowNumber) { - titleRow = row; - } else { - if (testLoopNumber != 1) { - ts.setName(testName + " [data file row #" + rowNumber - + "; iteration #" + i + " of " + testLoopNumber + "]; " - + tsNamefromFile); - } else { - ts.setName(testName + " [data file row #" + rowNumber + "] ; " - + tsNamefromFile); - } - ts.setDescription(ts.getDescription() + " (" - + StringHelper.getZipAndConcatenated(titleRow, row, ", ") - + ")"); - setTestDataToTestScript(titleRow, row, ts); - testScripts.add(ts); - } - rowNumber++; - ts = processTestScript(child, mc); - ts.setTestSuiteName(testSuiteName); - } - } else { - if (testLoopNumber > 1) { - ts.setName(testName + " [iteration " + i + " of " + testLoopNumber - + "]"); - } - testScripts.add(ts); - } - } - } catch (Throwable th) { - logger.fatal(th.getMessage()); - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - - return testScripts; - } - - private final String getTestDataFile(Element test) { - for (Element testChild : ParserHelper.getChildren(test)) { - if (testChild.getTagName().equalsIgnoreCase("testData")) { - String file = testChild.getAttribute("file"); - if (file != null && file.length() > 0) { - return file; - } - } - } - return null; - } - - private final String getSheetName(Element test) { - for (Element testChild : ParserHelper.getChildren(test)) { - if (testChild.getTagName().equalsIgnoreCase("testData")) { - String file = testChild.getAttribute("sheet"); - if (file != null && file.length() > 0) { - return file; - } - } - } - return null; - } - - private final List> getExcelDataFromFile(String testDataFile, String sheetName, - MessageCollector mc, boolean isXlsx) { - if (testDataFile != null && testDataFile.length() > 0) { - ExcelFileParser excelFileParser = null; - try { - if (sheetName != null) { - excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); - } else { - excelFileParser = new ExcelFileParser(testDataFile, isXlsx); - } - return excelFileParser.parseExcelFile(isXlsx); - } catch (Exception e) { - String errorMessage = "Oops! Can't parse excel file '" + testDataFile + "'!"; - logger.fatal(errorMessage); - mc.error(errorMessage); - } - } - return null; - } - - private final List> getCSVDataFromFile(String testDataFile, MessageCollector mc) { - List> result = new ArrayList>(); - CSVReader reader = null; - try { - reader = new CSVReader(new FileReader(testDataFile)); - List nextLine; - - while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { - if ((nextLine != null) && (nextLine.size() > 0) - && (!nextLine.get(0).startsWith("#"))) { - result.add(nextLine); - } - } - } catch (Exception e) { - logger.fatal("Oops! Can't open file '" + testDataFile + "'!"); - return null; - } finally { - if (reader != null) { - try { - reader.close(); - } catch (Exception e) { - //Dont care - logger.fatal("Oops! Can't close file '" + testDataFile + "'!"); - - } - } - } - return result; - } - - private final int getLoopNumber(AttributeHelper testAttributeHelper, MessageCollector mc) { - String testLoop = testAttributeHelper.getOptionalString("loop"); - int testLoopNumber = 1; - if (testLoop != null) { - try { - testLoopNumber = Integer.parseInt(testLoop); - return testLoopNumber; - } catch (java.lang.NumberFormatException e) { - String errorMessage = "Oops! Can't parse test 'loop' property ('" - + testLoop - + "'). It has be number like '3'. This parameter means number of execution for this test. Fix your test case script, please!"; - logger.fatal(errorMessage); - mc.error(errorMessage); - } - } - return 1; - } - - // TODO: Start with here - // This gets passed the row of titles, a row of data, and the testscript - // associated with the file - // It then goes through and adds the - // this gets called for every row of data in the datafile - // once this method executes, the testscript is added to a list of - // testscripts. - // so each row of data is effectively a new test script - private void setTestDataToTestScript(List title, List data, TestScript ts) { - for (Invocation statement : ts.getBody()) { - if (statement instanceof Invocation) { - Map parameters = ((Invocation) statement).getParameters(); - for (int i = 0; i < title.size(); i++) { - if (i < data.size()) { - parameters.put(title.get(i), data.get(i)); - } else { - parameters.put(title.get(i), ""); - } - } - } - /** - * if (statement instanceof TryRecoverCleanup) { TryRecoverCleanup - * trcSt = (TryRecoverCleanup) statement; - * - * // StatementList statementList = trcSt.getTry(); // - * statementList.addAll(trcSt.getRecover()); // - * statementList.addAll(trcSt.getCleanup()); // TODO: Ask author why - * this was placed and when? - * - * for (IStatement currentStatement : statementList) { if - * (currentStatement instanceof Invocation) { Map - * parameters = ((Invocation) currentStatement) .getParameters(); - * for (int i = 0; i < title.size(); i++) { if (i < data.size()) { - * parameters.put(title.get(i), data.get(i)); } else { - * parameters.put(title.get(i), ""); } } } } } - **/ - } - } - - public final TestScript processTestScript(Element elem, MessageCollector mc) - throws ParsingException { - preprocessTestScript(ParserHelper.getRequireElement(elem, "teststeps"), mc); - - AttributeHelper ah = new AttributeHelper(elem); - String name = null; - try { - name = ah.getRequiredString("name"); - } catch (MissingAttributeException e) { - mc.push(e.getMessage()); - throw e; - } - - boolean isCaptureSystemInformation = false; - String isCaptureSystemInformationStr = ah.getOptionalString("isCaptureSystemInformation"); - if (isCaptureSystemInformationStr != null) { - if (isCaptureSystemInformationStr.equalsIgnoreCase("true") - || isCaptureSystemInformationStr.equalsIgnoreCase("1") - || isCaptureSystemInformationStr.equalsIgnoreCase("yes")) { - isCaptureSystemInformation = true; - } else if (!isCaptureSystemInformationStr.equalsIgnoreCase("false") - && !isCaptureSystemInformationStr.equalsIgnoreCase("0") - && !isCaptureSystemInformationStr.equalsIgnoreCase("no")) { - logger.fatal("Oops! Can't parse '" - + isCaptureSystemInformationStr - + "'. It can be only one of 'true'/'false', '1'/'0' or 'yes'/'no'. Fix your test script, please!.."); - } - } - - try { - mc.push("In test " + name); - TestScript testScript = new TestScript(name, isCaptureSystemInformation); - testScript.setBody(stmtParser.processStatementList(ParserHelper.getRequireElement(elem, - "teststeps"), mc)); - - // Multithread 2012.4 CHANGES START------------------------ - // This is to reference the local test case values - Element dependentElement = ParserHelper.getFirstChildElementCaseInsensitive(elem, - "dependencies"); - Set dependentListTests = new HashSet(); - Set dependentListTestSuites = new HashSet(); - - if (dependentElement != null) { - for (Element e : ParserHelper.getChildren(dependentElement)) { - if (e.getNodeName().equalsIgnoreCase("test")) { - dependentListTests.add(new AttributeHelper(e).getRequiredString("name")); - } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { - dependentListTestSuites.add(new AttributeHelper(e) - .getRequiredString("name")); - } - } - } - - Element exclusionElement = ParserHelper.getFirstChildElementCaseInsensitive(elem, - "exclusions"); - Set excludedListTests = new HashSet(); - Set excludedListTestSuites = new HashSet(); - if (exclusionElement != null) { - for (Element e : ParserHelper.getChildren(exclusionElement)) { - if (e.getNodeName().equalsIgnoreCase("test")) { - excludedListTests.add(new AttributeHelper(e).getRequiredString("name")); - } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { - excludedListTestSuites - .add(new AttributeHelper(e).getRequiredString("name")); - } - } - } - testScript.setDependencies(dependentListTestSuites, dependentListTests); - testScript.setExclusions(excludedListTestSuites, excludedListTests); - // Multithread 2012.4 CHANGES END------------------------ - - testScript.setTestCaseID(ah.getOptionalString("testcaseid")); - - Element issuesElem = ParserHelper.getOptionalElement(elem, "issues"); - if (issuesElem != null) { - testScript.setIssue(processIssue(issuesElem)); - testScript.setCRs(processCRs(issuesElem)); - } - - testScript.setStatus(ah.getOptionalString("status")); - - Element avElem = ParserHelper.getFirstChildElementCaseInsensitive(elem, - "automationvalue"); - if (avElem != null) { - // not sure why this doesn't just call avElem.getTextContent() - testScript.setAutomationValue(stmtParser.processString(avElem, mc).toString()); - } - - // TODO: Should we make this into a list? - // retval.getRequirements() = new - Element covElem = ParserHelper.getOptionalElement(elem, "coverage"); - if (covElem != null) { - - // Requirement List - List children = ParserHelper.getChildren(covElem); - ArrayList requirements = new ArrayList(); - StringBuffer coverage = new StringBuffer(); - if (!children.isEmpty()) { - for (Element child : children) { - Requirement requirement = new Requirement(); - String type = child.getAttribute("type"); - String value = child.getTextContent(); - - if (!type.equals("")) { - requirement.setType(child.getAttribute("type")); - requirement.setValue(value.trim()); - requirements.add(requirement); - } - - // to maintain coverage for tracebility matrix - coverage = coverage.append(value.trim() + ","); - } - testScript.setRequirements(requirements); - testScript.setCoverage(coverage.substring(0, coverage.length() - 1)); - } else { - testScript.setCoverage(stmtParser.processString(covElem, mc).toString().trim()); - } - } - - Element descElem = ParserHelper.getOptionalElement(elem, "desc"); - if (descElem != null) { - testScript.setDescription(stmtParser.processString(descElem, mc).toString()); - } - - return testScript; - } catch (NameFormatException e) { - mc.error(e.getMessage()); - throw new ParsingException(e); - } finally { - mc.pop(); - } - } - - private final void preprocessTestScript(Element elem, MessageCollector mc) { - List children = ParserHelper.getChildren(elem); - if (children.isEmpty()) { - return; - } - - // If we detect a Teardown command, then we need to create - // a Try...Cleanup block - final Element last = children.get(children.size() - 1); - if (last.getNodeName().equalsIgnoreCase("teardown")) { - final Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); - final Element tryBlock = elem.getOwnerDocument().createElement("try"); - final Element cleanupBlock = elem.getOwnerDocument().createElement("cleanup"); - - safety.appendChild(tryBlock); - safety.appendChild(cleanupBlock); - - for (int i = 0, max = children.size() - 1; i < max; ++i) { - Element next = children.get(i); - elem.removeChild(next); - tryBlock.appendChild(next); - } - - elem.removeChild(last); - cleanupBlock.setAttribute("isTearDown", "true"); - for (Element e : ParserHelper.getChildren(last)) { - cleanupBlock.appendChild(e); - } - elem.appendChild(safety); - } - } - - private final String processIssue(Element elem) { - String retval = ""; - NodeList nl = elem.getChildNodes(); - for (int i = 0; i < nl.getLength(); ++i) { - Node n = nl.item(i); - if (n.getNodeType() == Node.TEXT_NODE) { - retval += n.getNodeValue(); - } - } - - if (!retval.equals("")) - return retval.trim(); - else - return null; - } - - private final List processCRs(Element elem) { - List retval = new ArrayList(); - for (Element child : ParserHelper.getChildren(elem)) { - if (child.getNodeName().equalsIgnoreCase("cr")) { - String crNumber = child.getAttribute("no"); - retval.add(crNumber); - } - } - return retval; - } - - private int getTSNameFromDataFilePosition(List> testData) { - // try to findout 'JTAF.test.name' column. Value from this column - // necessary to add to ts name. - if (testData != null && testData.size() > 0) { - List firstLine = testData.get(0); - int pos = 0; - for (String firstLineItem : firstLine) { - if (firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) { - return pos; - } else { - pos++; - } - } - } - return -1; - } - +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.exceptions.DependencyException; +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.test.Requirement; +import org.finra.jtaf.core.model.test.TestNamespace; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.model.test.digraph.Dependencies; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.model.test.digraph.TestDigraph; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.MissingAttributeException; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.AttributeHelper; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.finra.jtaf.core.utilities.ExcelFileParser; +import org.finra.jtaf.core.utilities.StringHelper; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import au.com.bytecode.opencsv.CSVReader; + +/** + * FIXME This is a "just get the job done" implementation. I plan to replace + * this class as soon as I get the chance. (I mean... ay ay ay! This is bad!) + */ +public class ScriptParser { + + static Logger logger = Logger.getLogger(ScriptParser.class.getPackage().getName()); + private final DocumentBuilder db; + private TestDigraph digraph; + private StatementParser stmtParser; + private Document d; + private CommandRegistry commandRegistry; + + private List postParseSuitePlugins; + private List postParseTestPlugins; + + + public ScriptParser() throws ParserConfigurationException { + db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + stmtParser = new StatementParser(); + } + + public void setDigraph(TestDigraph digraph) { + this.digraph = digraph; + } + + public void setPostParseSuitePlugins(List plugins) { + postParseSuitePlugins = plugins; + } + + + public void setPostParseTestPlugins(List plugins) { + postParseTestPlugins = plugins; + } + + public void setCommandRegistry(CommandRegistry commandRegistry) { + this.commandRegistry = commandRegistry; + } + + public final TestNamespace handleTestSource(File f, MessageCollector mc) + throws NameFormatException, SAXException, IOException, ParsingException { + if (!f.exists()) { + throw new FileNotFoundException(f.getAbsolutePath()); + } + TestNamespace testNamespace = new TestNamespace(f.getName()); + if (f.isDirectory() && !f.isHidden()) { + ExceptionAccumulator acc = new ExceptionAccumulator(); + + for (File child : f.listFiles()) { + if (child.isDirectory()) { + try { + testNamespace.add(handleTestSource(child, mc)); + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } else { // It's a file + try { + TestSuite ts = handleTestSuite(child, mc); + if (ts != null) { + testNamespace.add(ts); + // run all post suite parse plugins + + Node suiteRootNode = (Node) (d.getDocumentElement()); + // TODO: This needs to check for null, otherwise it + // crashes + + if (postParseSuitePlugins != null) { + for (IPostParseSuitePlugin p : postParseSuitePlugins) { + if (suiteContainsTheTag(suiteRootNode, p.getTagName())) { + p.execute(new PostSuiteParserPluginContext(commandRegistry, ts, suiteRootNode)); + } + } + } + } + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + } + + if (!acc.isEmpty()) { + throw acc; + } + } + return testNamespace; + } + + private boolean suiteContainsTheTag(Node suiteRootNode, String tagName) { + NodeList children = suiteRootNode.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase(tagName)) { + return true; + } + } + return false; + } + + private TestSuite handleTestSuite(File f, MessageCollector mc) throws ParsingException, + NameFormatException, IOException { + if (!f.exists()) { + throw new FileNotFoundException(f.getAbsolutePath()); + } + TestSuite testSuite = null; + if (f.isFile() && f.getName().endsWith(".xml")) { // This should be a + // TestSuite + mc.push("In test file " + f.getAbsolutePath()); + try { + d = db.parse(f); + testSuite = processTestSuite(d.getDocumentElement(), mc, f.getName()); + for (TestScript ts : processTestScripts(d.getDocumentElement(), mc)) { + try { + if (!digraph.addVertex(new DiNode(ts))) { + throw new DependencyException("Duplicate test name '" + ts.getName() + + "' found at: " + + digraph.getVertex(ts.getName()).getTestScript().getFullName()); + } + ts.setFileName(f.getName()); + + testSuite.add(ts); + // run post parse test plugins + Node testRootNode = getTestRootNode(d.getDocumentElement(), ts); + for (IPostParseTestPlugin p : postParseTestPlugins) { + if (testContainsTheTag(testRootNode, p.getTagName())) { + p.execute(new PostTestParserPluginContext(commandRegistry, testSuite, testRootNode)); + } + } + } catch (DependencyException de) { // TODO: Why are we catching a RuntimException here ? + mc.error(de.getMessage()); + throw de; + } catch (Throwable th) { + mc.error(th.getMessage()); + logger.fatal(th.getMessage()); + } + } + } catch (SAXException e) { + mc.error(e.getMessage()); + // throw e; + } catch (IOException e) { + mc.error(e.getMessage()); + throw e; + } finally { + mc.pop(); + } + } + return testSuite; + } + + private boolean testContainsTheTag(Node testRootNode, String tagName) { + NodeList children = testRootNode.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase(tagName)) { + return true; + } + } + return false; + } + + private Node getTestRootNode(Element documentElement, TestScript ts) { + NodeList list = documentElement.getElementsByTagName("test"); + for (int i = 0; i < list.getLength(); i++) { + Node n = list.item(i); + if (n.getAttributes().getNamedItem("name").getNodeValue().equals(ts.getName())) { + return n; + } + } + return null; + } + + public final TestSuite processTestSuite(Element element, MessageCollector mc, String fileName) + throws ParsingException, NameFormatException { + TestSuite testSuite = new TestSuite(fileName); + if (element.getNodeName().equalsIgnoreCase("testsuite")) { + AttributeHelper testScriptAttributeHelper = new AttributeHelper(element); + + String testSuiteName = null; + try { + testSuiteName = testScriptAttributeHelper.getRequiredString("name"); + testSuite.setTestSuiteName(testSuiteName); + } catch (MissingAttributeException e) { + mc.push(e.getMessage()); + logger.debug("Oops! Test suite has no 'name' attribute! ('" + element.toString() + + "')"); + } + + testSuite.setDependencies(new Dependencies(null, null)); + testSuite.setExclusions(new Dependencies(null, null)); + + return testSuite; + } else { + UnexpectedElementException z = new UnexpectedElementException(element); + mc.error(z.getMessage()); + throw z; + } + } + + private final List processTestScripts(Element element, MessageCollector mc) + throws ParsingException { + if (element.getNodeName().equalsIgnoreCase("testsuite")) { + List testScripts = null; + AttributeHelper testScriptAttributeHelper = new AttributeHelper(element); + + String testSuiteName = null; + try { + testSuiteName = testScriptAttributeHelper.getRequiredString("name"); + } catch (MissingAttributeException e) { + mc.push(e.getMessage()); + logger.debug("Oops! Test suite hasn't 'name' attibite! ('" + element.toString() + + "')"); + } + + // MULTITHREADED 2012.4 Changes START + // ------------------------------------- + // This will seperate out the elements at the testsuite level + ArrayList testSuiteChildren = (ArrayList) ParserHelper + .getChildren(element); + ArrayList tests = new ArrayList(); + + for (Element e : testSuiteChildren) { + if (e.getNodeName().equalsIgnoreCase("test")) { + tests.add(e); + } + } + testScripts = parseTests(tests, mc, testSuiteName); + + // MULTITHREADED 2012.4 Changes END + // ------------------------------------- + return testScripts; + } else { + UnexpectedElementException z = new UnexpectedElementException(element); + mc.error(z.getMessage()); + throw z; + } + } + + private List parseTests(List elementList, MessageCollector mc, + String testSuiteName) throws ExceptionAccumulator { + List testScripts = new ArrayList(); + ExceptionAccumulator acc = new ExceptionAccumulator(); + for (Element child : elementList) { + try { + AttributeHelper testAttributeHelper = new AttributeHelper(child); + String testName = testAttributeHelper.getOptionalString("name"); + int testLoopNumber = getLoopNumber(testAttributeHelper, mc); + + String testDataFile = getTestDataFile(child); + String sheetName = getSheetName(child); + List> testData = null; + int tsNamefromFilePosition = -1; + if (testDataFile != null) { + if (testDataFile.endsWith(".xlsx")) { + testData = getExcelDataFromFile(testDataFile, sheetName, mc, true); + } else if (testDataFile.endsWith(".xls")) { + testData = getExcelDataFromFile(testDataFile, sheetName, mc, false); + } else if (testDataFile.endsWith(".csv")) { + testData = getCSVDataFromFile(testDataFile, mc); + } else { + logger.fatal("Oops! can't parse test data file ('" + testDataFile + + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); + } + tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); + } + + for (int i = 1; i <= testLoopNumber; i++) { + TestScript ts = processTestScript(child, mc); + ts.setTestSuiteName(testSuiteName); + + if (testData != null && testData.size() > 0) { + int rowNumber = 0; + List titleRow = null; + for (List row : testData) { + String tsNamefromFile = ""; + if (tsNamefromFilePosition >= 0) { + tsNamefromFile = "testNameFromDataFile-" + + row.get(tsNamefromFilePosition); + } + if (0 == rowNumber) { + titleRow = row; + } else { + if (testLoopNumber != 1) { + ts.setName(testName + " [data file row #" + rowNumber + + "; iteration #" + i + " of " + testLoopNumber + "]; " + + tsNamefromFile); + } else { + ts.setName(testName + " [data file row #" + rowNumber + "] ; " + + tsNamefromFile); + } + ts.setDescription(ts.getDescription() + " (" + + StringHelper.getZipAndConcatenated(titleRow, row, ", ") + + ")"); + setTestDataToTestScript(titleRow, row, ts); + testScripts.add(ts); + } + rowNumber++; + ts = processTestScript(child, mc); + ts.setTestSuiteName(testSuiteName); + } + } else { + if (testLoopNumber > 1) { + ts.setName(testName + " [iteration " + i + " of " + testLoopNumber + + "]"); + } + testScripts.add(ts); + } + } + } catch (Throwable th) { + logger.fatal(th.getMessage()); + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + + return testScripts; + } + + private final String getTestDataFile(Element test) { + for (Element testChild : ParserHelper.getChildren(test)) { + if (testChild.getTagName().equalsIgnoreCase("testData")) { + String file = testChild.getAttribute("file"); + if (file != null && file.length() > 0) { + return file; + } + } + } + return null; + } + + private final String getSheetName(Element test) { + for (Element testChild : ParserHelper.getChildren(test)) { + if (testChild.getTagName().equalsIgnoreCase("testData")) { + String file = testChild.getAttribute("sheet"); + if (file != null && file.length() > 0) { + return file; + } + } + } + return null; + } + + private final List> getExcelDataFromFile(String testDataFile, String sheetName, + MessageCollector mc, boolean isXlsx) { + if (testDataFile != null && testDataFile.length() > 0) { + ExcelFileParser excelFileParser = null; + try { + if (sheetName != null) { + excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); + } else { + excelFileParser = new ExcelFileParser(testDataFile, isXlsx); + } + return excelFileParser.parseExcelFile(isXlsx); + } catch (Exception e) { + String errorMessage = "Oops! Can't parse excel file '" + testDataFile + "'!"; + logger.fatal(errorMessage); + mc.error(errorMessage); + } + } + return null; + } + + private final List> getCSVDataFromFile(String testDataFile, MessageCollector mc) { + List> result = new ArrayList>(); + CSVReader reader = null; + try { + reader = new CSVReader(new FileReader(testDataFile)); + List nextLine; + + while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { + if ((nextLine != null) && (nextLine.size() > 0) + && (!nextLine.get(0).startsWith("#"))) { + result.add(nextLine); + } + } + } catch (Exception e) { + logger.fatal("Oops! Can't open file '" + testDataFile + "'!"); + return null; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (Exception e) { + //Dont care + logger.fatal("Oops! Can't close file '" + testDataFile + "'!"); + + } + } + } + return result; + } + + private final int getLoopNumber(AttributeHelper testAttributeHelper, MessageCollector mc) { + String testLoop = testAttributeHelper.getOptionalString("loop"); + int testLoopNumber = 1; + if (testLoop != null) { + try { + testLoopNumber = Integer.parseInt(testLoop); + return testLoopNumber; + } catch (java.lang.NumberFormatException e) { + String errorMessage = "Oops! Can't parse test 'loop' property ('" + + testLoop + + "'). It has be number like '3'. This parameter means number of execution for this test. Fix your test case script, please!"; + logger.fatal(errorMessage); + mc.error(errorMessage); + } + } + return 1; + } + + // TODO: Start with here + // This gets passed the row of titles, a row of data, and the testscript + // associated with the file + // It then goes through and adds the + // this gets called for every row of data in the datafile + // once this method executes, the testscript is added to a list of + // testscripts. + // so each row of data is effectively a new test script + private void setTestDataToTestScript(List title, List data, TestScript ts) { + for (Invocation statement : ts.getBody()) { + if (statement instanceof Invocation) { + Map parameters = ((Invocation) statement).getParameters(); + for (int i = 0; i < title.size(); i++) { + if (i < data.size()) { + parameters.put(title.get(i), data.get(i)); + } else { + parameters.put(title.get(i), ""); + } + } + } + /** + * if (statement instanceof TryRecoverCleanup) { TryRecoverCleanup + * trcSt = (TryRecoverCleanup) statement; + * + * // StatementList statementList = trcSt.getTry(); // + * statementList.addAll(trcSt.getRecover()); // + * statementList.addAll(trcSt.getCleanup()); // TODO: Ask author why + * this was placed and when? + * + * for (IStatement currentStatement : statementList) { if + * (currentStatement instanceof Invocation) { Map + * parameters = ((Invocation) currentStatement) .getParameters(); + * for (int i = 0; i < title.size(); i++) { if (i < data.size()) { + * parameters.put(title.get(i), data.get(i)); } else { + * parameters.put(title.get(i), ""); } } } } } + **/ + } + } + + public final TestScript processTestScript(Element elem, MessageCollector mc) + throws ParsingException { + preprocessTestScript(ParserHelper.getRequireElement(elem, "teststeps"), mc); + + AttributeHelper ah = new AttributeHelper(elem); + String name = null; + try { + name = ah.getRequiredString("name"); + } catch (MissingAttributeException e) { + mc.push(e.getMessage()); + throw e; + } + + boolean isCaptureSystemInformation = false; + String isCaptureSystemInformationStr = ah.getOptionalString("isCaptureSystemInformation"); + if (isCaptureSystemInformationStr != null) { + if (isCaptureSystemInformationStr.equalsIgnoreCase("true") + || isCaptureSystemInformationStr.equalsIgnoreCase("1") + || isCaptureSystemInformationStr.equalsIgnoreCase("yes")) { + isCaptureSystemInformation = true; + } else if (!isCaptureSystemInformationStr.equalsIgnoreCase("false") + && !isCaptureSystemInformationStr.equalsIgnoreCase("0") + && !isCaptureSystemInformationStr.equalsIgnoreCase("no")) { + logger.fatal("Oops! Can't parse '" + + isCaptureSystemInformationStr + + "'. It can be only one of 'true'/'false', '1'/'0' or 'yes'/'no'. Fix your test script, please!.."); + } + } + + try { + mc.push("In test " + name); + TestScript testScript = new TestScript(name, isCaptureSystemInformation); + testScript.setBody(stmtParser.processStatementList(ParserHelper.getRequireElement(elem, + "teststeps"), mc)); + + // Multithread 2012.4 CHANGES START------------------------ + // This is to reference the local test case values + Element dependentElement = ParserHelper.getFirstChildElementCaseInsensitive(elem, + "dependencies"); + Set dependentListTests = new HashSet(); + Set dependentListTestSuites = new HashSet(); + + if (dependentElement != null) { + for (Element e : ParserHelper.getChildren(dependentElement)) { + if (e.getNodeName().equalsIgnoreCase("test")) { + dependentListTests.add(new AttributeHelper(e).getRequiredString("name")); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + dependentListTestSuites.add(new AttributeHelper(e) + .getRequiredString("name")); + } + } + } + + Element exclusionElement = ParserHelper.getFirstChildElementCaseInsensitive(elem, + "exclusions"); + Set excludedListTests = new HashSet(); + Set excludedListTestSuites = new HashSet(); + if (exclusionElement != null) { + for (Element e : ParserHelper.getChildren(exclusionElement)) { + if (e.getNodeName().equalsIgnoreCase("test")) { + excludedListTests.add(new AttributeHelper(e).getRequiredString("name")); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + excludedListTestSuites + .add(new AttributeHelper(e).getRequiredString("name")); + } + } + } + testScript.setDependencies(dependentListTestSuites, dependentListTests); + testScript.setExclusions(excludedListTestSuites, excludedListTests); + // Multithread 2012.4 CHANGES END------------------------ + + testScript.setTestCaseID(ah.getOptionalString("testcaseid")); + + Element issuesElem = ParserHelper.getOptionalElement(elem, "issues"); + if (issuesElem != null) { + testScript.setIssue(processIssue(issuesElem)); + testScript.setCRs(processCRs(issuesElem)); + } + + testScript.setStatus(ah.getOptionalString("status")); + + Element avElem = ParserHelper.getFirstChildElementCaseInsensitive(elem, + "automationvalue"); + if (avElem != null) { + // not sure why this doesn't just call avElem.getTextContent() + testScript.setAutomationValue(stmtParser.processString(avElem, mc).toString()); + } + + // TODO: Should we make this into a list? + // retval.getRequirements() = new + Element covElem = ParserHelper.getOptionalElement(elem, "coverage"); + if (covElem != null) { + + // Requirement List + List children = ParserHelper.getChildren(covElem); + ArrayList requirements = new ArrayList(); + StringBuffer coverage = new StringBuffer(); + if (!children.isEmpty()) { + for (Element child : children) { + Requirement requirement = new Requirement(); + String type = child.getAttribute("type"); + String value = child.getTextContent(); + + if (!type.equals("")) { + requirement.setType(child.getAttribute("type")); + requirement.setValue(value.trim()); + requirements.add(requirement); + } + + // to maintain coverage for tracebility matrix + coverage = coverage.append(value.trim() + ","); + } + testScript.setRequirements(requirements); + testScript.setCoverage(coverage.substring(0, coverage.length() - 1)); + } else { + testScript.setCoverage(stmtParser.processString(covElem, mc).toString().trim()); + } + } + + Element descElem = ParserHelper.getOptionalElement(elem, "desc"); + if (descElem != null) { + testScript.setDescription(stmtParser.processString(descElem, mc).toString()); + } + + return testScript; + } catch (NameFormatException e) { + mc.error(e.getMessage()); + throw new ParsingException(e); + } finally { + mc.pop(); + } + } + + private final void preprocessTestScript(Element elem, MessageCollector mc) { + List children = ParserHelper.getChildren(elem); + if (children.isEmpty()) { + return; + } + + // If we detect a Teardown command, then we need to create + // a Try...Cleanup block + final Element last = children.get(children.size() - 1); + if (last.getNodeName().equalsIgnoreCase("teardown")) { + final Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); + final Element tryBlock = elem.getOwnerDocument().createElement("try"); + final Element cleanupBlock = elem.getOwnerDocument().createElement("cleanup"); + + safety.appendChild(tryBlock); + safety.appendChild(cleanupBlock); + + for (int i = 0, max = children.size() - 1; i < max; ++i) { + Element next = children.get(i); + elem.removeChild(next); + tryBlock.appendChild(next); + } + + elem.removeChild(last); + cleanupBlock.setAttribute("isTearDown", "true"); + for (Element e : ParserHelper.getChildren(last)) { + cleanupBlock.appendChild(e); + } + elem.appendChild(safety); + } + } + + private final String processIssue(Element elem) { + String retval = ""; + NodeList nl = elem.getChildNodes(); + for (int i = 0; i < nl.getLength(); ++i) { + Node n = nl.item(i); + if (n.getNodeType() == Node.TEXT_NODE) { + retval += n.getNodeValue(); + } + } + + if (!retval.equals("")) + return retval.trim(); + else + return null; + } + + private final List processCRs(Element elem) { + List retval = new ArrayList(); + for (Element child : ParserHelper.getChildren(elem)) { + if (child.getNodeName().equalsIgnoreCase("cr")) { + String crNumber = child.getAttribute("no"); + retval.add(crNumber); + } + } + return retval; + } + + private int getTSNameFromDataFilePosition(List> testData) { + // try to findout 'JTAF.test.name' column. Value from this column + // necessary to add to ts name. + if (testData != null && testData.size() > 0) { + List firstLine = testData.get(0); + int pos = 0; + for (String firstLineItem : firstLine) { + if (firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) { + return pos; + } else { + pos++; + } + } + } + return -1; + } + } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java b/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java index 55f9bf8..87a6d3f 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java +++ b/src/main/java/org/finra/jtaf/core/parsing/StatementParser.java @@ -1,301 +1,301 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.statement.InvocationList; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.AttributeHelper; -import org.finra.jtaf.core.parsing.helpers.ElementScanner; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -/** - * Responsible for parsing statement in test script. - */ -public class StatementParser { - - private static final List NON_BLOCK_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "list", "string", "map", "boolean")); - private static final List STRING_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "string")); - - public final InvocationList processStatementList(Element elem, MessageCollector mc) - throws ParsingException { - // Create formal try...recover...cleanup blocks - preprocessStatementList(elem, mc); - - InvocationList retval = new InvocationList(); - for (Element child : ParserHelper.getChildren(elem)) { - - retval.add(processStatement(child, mc)); - } - return retval; - } - - //TODO: This needs to come across a TryRecoverCleanup and handle that - private final void preprocessStatementList(Element elem, MessageCollector mc) - throws ParsingException { - - ElementScanner es = new ElementScanner(ParserHelper.getChildren(elem)); - Element next = null; - // Element tRC = - // elem.getOwnerDocument().createElement("TryRecoverCleanup"); - if (!elem.getNodeName().equals("TryRecoverCleanup")) { - while (es.hasNext()) { - - if ((next = es.tryMatch("try")) != null) { - Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); - Element tryBlock = elem.getOwnerDocument().createElement("try"); - NodeList childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - tryBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - elem.replaceChild(safety, next); - safety.appendChild(tryBlock); - - if ((next = es.tryMatch("recover")) != null) { - elem.removeChild(next); - Element recoverBlock = elem.getOwnerDocument().createElement("recover"); - childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - recoverBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - safety.appendChild(recoverBlock); - } - - if ((next = es.tryMatch("cleanup")) != null) { - elem.removeChild(next); - Element cleanUpBlock = elem.getOwnerDocument().createElement("cleanup"); - childNodes = next.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - cleanUpBlock.appendChild(childNodes.item(i).cloneNode(true)); - - } - safety.appendChild(cleanUpBlock); - } - - continue; - } else if (((next = es.tryMatch("recover")) != null) - || ((next = es.tryMatch("cleanup")) != null)) { - throw new UnexpectedElementException(next); - } - - // Move on to the next element - es.match(); - } - } - } - - private final Invocation processStatement(Element elem, MessageCollector mc) - throws ParsingException { - try { - mc.push(elem.getNodeName()); - - return processInvocation(elem, mc); - - } catch (ParsingException e) { - mc.error(e.getMessage()); - throw e; - } finally { - mc.pop(); - } - } - - - // TODO Use this in order to put the child nodes of the command as the block - // Calls processMap which calls process object. This method then deals with - // strings, maps, and lists - // This can be changed so that it either does processCommand or processX - // depending no what - // the default value is - private final Invocation processInvocation(Element elem, MessageCollector mc) - throws ParsingException { - Invocation retval = new Invocation(elem.getNodeName()); - Map> invocationAttributesMap = new HashMap>(); - - // get properties from children - // TODO: This will process all children of the command - preprocessStatementList(elem, mc); - invocationAttributesMap.putAll(processInvocationChildNodes(elem, mc)); - - // get properties from attributes - final AttributeHelper attrs = new AttributeHelper(elem); - - // invocationAttributesMap.putAll(temp); - retval.setParameters(invocationAttributesMap); - retval.getParameters().putAll(attrs.getMap()); - retval.getParameters().putAll(processMap(elem, mc)); - - return retval; - } - - // TODO: This needs to send a child node to processInvocation if it is a - // command - private final Map> processInvocationChildNodes(Element elem, - MessageCollector mc) throws ParsingException { - boolean blockCreated = false; - try { - mc.push(elem.getNodeName()); - Map> result = new HashMap>(); - List block = new ArrayList(); - NodeList childNodes = elem.getChildNodes(); - // there used to be a check for null here, but the JavaDoc makes no - // mention that this is possible and I can find no examples online - // of how to cause that - if (childNodes.getLength() > 0) { - for (int i = 0; i < childNodes.getLength(); i++) { - Node currentNode = childNodes.item(i); - if (currentNode.getNodeType() == Node.ELEMENT_NODE - && !isNonBlockParameterType(currentNode.getNodeName())) { - blockCreated = true; - Invocation child = processInvocation((Element) currentNode, mc); - block.add(child); - - /** - * else { Object thing = processObject((Element) - * currentNode, mc); block.add(thing); } - **/ - - // TODO: processInvocation to get a command handled. - // It should then be stored in result - // processInvocation(currentNode, mc); - // String nodeName = currentNode.getNodeName(); - } - - } - if (blockCreated) { - - result.put("blockParam", block); - } - } - return result; - } finally { - mc.pop(); - } - } - - - private boolean isNonBlockParameterType(String nodeName) { - return NON_BLOCK_PARAMETER_TYPES.contains(nodeName.toLowerCase()); - } - - private final Map processMap(Element elem, MessageCollector mc) - throws ParsingException { - ExceptionAccumulator acc = new ExceptionAccumulator(); - HashMap retval = new HashMap(); - - for (Element child : ParserHelper.getChildren(elem)) { - try { - final AttributeHelper attrs = new AttributeHelper(child); - Object value = processObject(child, mc); - if (value != null) { - String key = attrs.getRequiredString("name"); - retval.put(key, value); - } - } catch (Throwable th) { - mc.error(th.getMessage()); - acc.add(th); - } - } - - if (!acc.isEmpty()) { - throw acc; - } - - return retval; - } - - private final List processList(Element elem, MessageCollector mc) - throws ParsingException { - - try { - mc.push(elem.getNodeName()); - ArrayList retval = new ArrayList(); - for (Element child : ParserHelper.getChildren(elem)) { - retval.add(processObject(child, mc)); - } - return retval; - } finally { - mc.pop(); - } - - } - - private final Object processObject(Element elem, MessageCollector mc) throws ParsingException { - try { - - mc.push("In data element " + elem.getNodeName()); - final String name = elem.getNodeName().toLowerCase(); -// if (name.equals("param") || name.equals("string")) { - if (isStringParameterType(name)) { - return processString(elem, mc); - } else if (name.equals("map")) { - return processMap(elem, mc); - } else if (name.equals("list")) { - return processList(elem, mc); - } else { - return null; - } - } finally { - mc.pop(); - } - } - - private boolean isStringParameterType(String parameterType) { - return STRING_PARAMETER_TYPES.contains(parameterType.toLowerCase()); - } - - // something strange is going on here. why can 's have child nodes? why is this public? - public Object processString(Element elem, MessageCollector mc) throws ParsingException { - try { - mc.push(elem.getNodeName()); - Map> childNodeValue = processInvocationChildNodes(elem, mc); - AttributeHelper ah = new AttributeHelper(elem); - if (ah != null && ah.entrySet().size() > 0) { - if (ah.containsKey("name") && (ah.entrySet().size() == 1)) { - // this is map... - } else { - return ah; - } - } else if (!childNodeValue.isEmpty()) { - for (String key : childNodeValue.keySet()) { - return childNodeValue.get(key); - } - } - - return elem.getTextContent(); - } finally { - mc.pop(); - } - } - - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.statement.InvocationList; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.AttributeHelper; +import org.finra.jtaf.core.parsing.helpers.ElementScanner; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +/** + * Responsible for parsing statement in test script. + */ +public class StatementParser { + + private static final List NON_BLOCK_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "list", "string", "map", "boolean")); + private static final List STRING_PARAMETER_TYPES = Collections.unmodifiableList(Arrays.asList("param", "string")); + + public final InvocationList processStatementList(Element elem, MessageCollector mc) + throws ParsingException { + // Create formal try...recover...cleanup blocks + preprocessStatementList(elem, mc); + + InvocationList retval = new InvocationList(); + for (Element child : ParserHelper.getChildren(elem)) { + + retval.add(processStatement(child, mc)); + } + return retval; + } + + //TODO: This needs to come across a TryRecoverCleanup and handle that + private final void preprocessStatementList(Element elem, MessageCollector mc) + throws ParsingException { + + ElementScanner es = new ElementScanner(ParserHelper.getChildren(elem)); + Element next = null; + // Element tRC = + // elem.getOwnerDocument().createElement("TryRecoverCleanup"); + if (!elem.getNodeName().equals("TryRecoverCleanup")) { + while (es.hasNext()) { + + if ((next = es.tryMatch("try")) != null) { + Element safety = elem.getOwnerDocument().createElement("TryRecoverCleanup"); + Element tryBlock = elem.getOwnerDocument().createElement("try"); + NodeList childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + tryBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + elem.replaceChild(safety, next); + safety.appendChild(tryBlock); + + if ((next = es.tryMatch("recover")) != null) { + elem.removeChild(next); + Element recoverBlock = elem.getOwnerDocument().createElement("recover"); + childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + recoverBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + safety.appendChild(recoverBlock); + } + + if ((next = es.tryMatch("cleanup")) != null) { + elem.removeChild(next); + Element cleanUpBlock = elem.getOwnerDocument().createElement("cleanup"); + childNodes = next.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + cleanUpBlock.appendChild(childNodes.item(i).cloneNode(true)); + + } + safety.appendChild(cleanUpBlock); + } + + continue; + } else if (((next = es.tryMatch("recover")) != null) + || ((next = es.tryMatch("cleanup")) != null)) { + throw new UnexpectedElementException(next); + } + + // Move on to the next element + es.match(); + } + } + } + + private final Invocation processStatement(Element elem, MessageCollector mc) + throws ParsingException { + try { + mc.push(elem.getNodeName()); + + return processInvocation(elem, mc); + + } catch (ParsingException e) { + mc.error(e.getMessage()); + throw e; + } finally { + mc.pop(); + } + } + + + // TODO Use this in order to put the child nodes of the command as the block + // Calls processMap which calls process object. This method then deals with + // strings, maps, and lists + // This can be changed so that it either does processCommand or processX + // depending no what + // the default value is + private final Invocation processInvocation(Element elem, MessageCollector mc) + throws ParsingException { + Invocation retval = new Invocation(elem.getNodeName()); + Map> invocationAttributesMap = new HashMap>(); + + // get properties from children + // TODO: This will process all children of the command + preprocessStatementList(elem, mc); + invocationAttributesMap.putAll(processInvocationChildNodes(elem, mc)); + + // get properties from attributes + final AttributeHelper attrs = new AttributeHelper(elem); + + // invocationAttributesMap.putAll(temp); + retval.setParameters(invocationAttributesMap); + retval.getParameters().putAll(attrs.getMap()); + retval.getParameters().putAll(processMap(elem, mc)); + + return retval; + } + + // TODO: This needs to send a child node to processInvocation if it is a + // command + private final Map> processInvocationChildNodes(Element elem, + MessageCollector mc) throws ParsingException { + boolean blockCreated = false; + try { + mc.push(elem.getNodeName()); + Map> result = new HashMap>(); + List block = new ArrayList(); + NodeList childNodes = elem.getChildNodes(); + // there used to be a check for null here, but the JavaDoc makes no + // mention that this is possible and I can find no examples online + // of how to cause that + if (childNodes.getLength() > 0) { + for (int i = 0; i < childNodes.getLength(); i++) { + Node currentNode = childNodes.item(i); + if (currentNode.getNodeType() == Node.ELEMENT_NODE + && !isNonBlockParameterType(currentNode.getNodeName())) { + blockCreated = true; + Invocation child = processInvocation((Element) currentNode, mc); + block.add(child); + + /** + * else { Object thing = processObject((Element) + * currentNode, mc); block.add(thing); } + **/ + + // TODO: processInvocation to get a command handled. + // It should then be stored in result + // processInvocation(currentNode, mc); + // String nodeName = currentNode.getNodeName(); + } + + } + if (blockCreated) { + + result.put("blockParam", block); + } + } + return result; + } finally { + mc.pop(); + } + } + + + private boolean isNonBlockParameterType(String nodeName) { + return NON_BLOCK_PARAMETER_TYPES.contains(nodeName.toLowerCase()); + } + + private final Map processMap(Element elem, MessageCollector mc) + throws ParsingException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + HashMap retval = new HashMap(); + + for (Element child : ParserHelper.getChildren(elem)) { + try { + final AttributeHelper attrs = new AttributeHelper(child); + Object value = processObject(child, mc); + if (value != null) { + String key = attrs.getRequiredString("name"); + retval.put(key, value); + } + } catch (Throwable th) { + mc.error(th.getMessage()); + acc.add(th); + } + } + + if (!acc.isEmpty()) { + throw acc; + } + + return retval; + } + + private final List processList(Element elem, MessageCollector mc) + throws ParsingException { + + try { + mc.push(elem.getNodeName()); + ArrayList retval = new ArrayList(); + for (Element child : ParserHelper.getChildren(elem)) { + retval.add(processObject(child, mc)); + } + return retval; + } finally { + mc.pop(); + } + + } + + private final Object processObject(Element elem, MessageCollector mc) throws ParsingException { + try { + + mc.push("In data element " + elem.getNodeName()); + final String name = elem.getNodeName().toLowerCase(); +// if (name.equals("param") || name.equals("string")) { + if (isStringParameterType(name)) { + return processString(elem, mc); + } else if (name.equals("map")) { + return processMap(elem, mc); + } else if (name.equals("list")) { + return processList(elem, mc); + } else { + return null; + } + } finally { + mc.pop(); + } + } + + private boolean isStringParameterType(String parameterType) { + return STRING_PARAMETER_TYPES.contains(parameterType.toLowerCase()); + } + + // something strange is going on here. why can 's have child nodes? why is this public? + public Object processString(Element elem, MessageCollector mc) throws ParsingException { + try { + mc.push(elem.getNodeName()); + Map> childNodeValue = processInvocationChildNodes(elem, mc); + AttributeHelper ah = new AttributeHelper(elem); + if (ah != null && ah.entrySet().size() > 0) { + if (ah.containsKey("name") && (ah.entrySet().size() == 1)) { + // this is map... + } else { + return ah; + } + } else if (!childNodeValue.isEmpty()) { + for (String key : childNodeValue.keySet()) { + return childNodeValue.get(key); + } + } + + return elem.getTextContent(); + } finally { + mc.pop(); + } + } + + +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java index f22ef91..4a9d3eb 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/SuiteDependenciesPlugin.java @@ -1,70 +1,70 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.Set; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.AttributeHelper; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; -import org.w3c.dom.Element; - -/** - * Parser plugin to parse test suite dependencies - */ -public class SuiteDependenciesPlugin implements IPostParseSuitePlugin { - private static final String DEPENDENCIES_NAME = "dependencies"; - private static Logger logger = Logger.getLogger(SuiteDependenciesPlugin.class.getPackage().getName()); - - @Override - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { - ExceptionAccumulator acc = new ExceptionAccumulator(); - Set dependentTests = ctx.getTestSuite().getDependencies().getDependenciesTests(); - Set dependentTestSuites = ctx.getTestSuite().getDependencies().getDependenciesSuites(); - Element dependenciesElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), DEPENDENCIES_NAME); - for (Element e : ParserHelper.getChildren(dependenciesElement)) { - try { - AttributeHelper depAttributeHelper = new AttributeHelper(e); - String dependentValue = depAttributeHelper.getRequiredString("name"); - if (e.getNodeName().equalsIgnoreCase("test")) { - dependentTests.add(dependentValue); - } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { - dependentTestSuites.add(dependentValue); - } else { - throw new UnexpectedElementException(e); - } - } catch (Throwable th) { - logger.fatal(th.getMessage()); -// mc.error(th.getMessage()); - acc.add(th); - } - } - if (!acc.isEmpty()) { - throw new ParserPluginException(acc); - } - } - - @Override - public String getTagName() { - return DEPENDENCIES_NAME; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.Set; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.AttributeHelper; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; +import org.w3c.dom.Element; + +/** + * Parser plugin to parse test suite dependencies + */ +public class SuiteDependenciesPlugin implements IPostParseSuitePlugin { + private static final String DEPENDENCIES_NAME = "dependencies"; + private static Logger logger = Logger.getLogger(SuiteDependenciesPlugin.class.getPackage().getName()); + + @Override + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + Set dependentTests = ctx.getTestSuite().getDependencies().getDependenciesTests(); + Set dependentTestSuites = ctx.getTestSuite().getDependencies().getDependenciesSuites(); + Element dependenciesElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), DEPENDENCIES_NAME); + for (Element e : ParserHelper.getChildren(dependenciesElement)) { + try { + AttributeHelper depAttributeHelper = new AttributeHelper(e); + String dependentValue = depAttributeHelper.getRequiredString("name"); + if (e.getNodeName().equalsIgnoreCase("test")) { + dependentTests.add(dependentValue); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + dependentTestSuites.add(dependentValue); + } else { + throw new UnexpectedElementException(e); + } + } catch (Throwable th) { + logger.fatal(th.getMessage()); +// mc.error(th.getMessage()); + acc.add(th); + } + } + if (!acc.isEmpty()) { + throw new ParserPluginException(acc); + } + } + + @Override + public String getTagName() { + return DEPENDENCIES_NAME; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java index 23e8432..342fff2 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/SuiteExclusionsPlugin.java @@ -1,70 +1,70 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.Set; - -import org.apache.log4j.Logger; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.AttributeHelper; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; -import org.w3c.dom.Element; - -/** - * Parser plugin to handle exclusions defined in a test suite. - */ -public class SuiteExclusionsPlugin implements IPostParseSuitePlugin { - private static final String EXCLUSIONS_NAME = "exclusions"; - private static Logger logger = Logger.getLogger(SuiteExclusionsPlugin.class.getPackage().getName()); - - @Override - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { - ExceptionAccumulator acc = new ExceptionAccumulator(); - Set exclusionTests = ctx.getTestSuite().getExclusions().getDependenciesTests(); - Set exclusionTestSuites = ctx.getTestSuite().getExclusions().getDependenciesSuites(); - Element exclusionsElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), EXCLUSIONS_NAME); - for (Element e : ParserHelper.getChildren(exclusionsElement)) { - try { - AttributeHelper excAttributeHelper = new AttributeHelper(e); - String exclusionValue = excAttributeHelper.getRequiredString("name"); - if (e.getNodeName().equalsIgnoreCase("test")) { - exclusionTests.add(exclusionValue); - } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { - exclusionTestSuites.add(exclusionValue); - } else { - throw new UnexpectedElementException(e); - } - } catch (Throwable th) { - logger.fatal(th.getMessage()); -// mc.error(th.getMessage()); - acc.add(th); - } - } - if (!acc.isEmpty()) { - throw new ParserPluginException(acc); - } - } - - @Override - public String getTagName() { - return EXCLUSIONS_NAME; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.Set; + +import org.apache.log4j.Logger; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.AttributeHelper; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; +import org.w3c.dom.Element; + +/** + * Parser plugin to handle exclusions defined in a test suite. + */ +public class SuiteExclusionsPlugin implements IPostParseSuitePlugin { + private static final String EXCLUSIONS_NAME = "exclusions"; + private static Logger logger = Logger.getLogger(SuiteExclusionsPlugin.class.getPackage().getName()); + + @Override + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { + ExceptionAccumulator acc = new ExceptionAccumulator(); + Set exclusionTests = ctx.getTestSuite().getExclusions().getDependenciesTests(); + Set exclusionTestSuites = ctx.getTestSuite().getExclusions().getDependenciesSuites(); + Element exclusionsElement = ParserHelper.getFirstChildElementCaseInsensitive((Element) ctx.getRootNodeSuite(), EXCLUSIONS_NAME); + for (Element e : ParserHelper.getChildren(exclusionsElement)) { + try { + AttributeHelper excAttributeHelper = new AttributeHelper(e); + String exclusionValue = excAttributeHelper.getRequiredString("name"); + if (e.getNodeName().equalsIgnoreCase("test")) { + exclusionTests.add(exclusionValue); + } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { + exclusionTestSuites.add(exclusionValue); + } else { + throw new UnexpectedElementException(e); + } + } catch (Throwable th) { + logger.fatal(th.getMessage()); +// mc.error(th.getMessage()); + acc.add(th); + } + } + if (!acc.isEmpty()) { + throw new ParserPluginException(acc); + } + } + + @Override + public String getTagName() { + return EXCLUSIONS_NAME; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java index ed9bfb3..57001b4 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestDataPlugin.java @@ -1,220 +1,220 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.exceptions.NameCollisionException; -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.model.test.digraph.TestDigraph; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.finra.jtaf.core.utilities.ExcelFileParser; -import org.finra.jtaf.core.utilities.StringHelper; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import au.com.bytecode.opencsv.CSVReader; - -/** - * Parser plugin to handle testdata element in a test script. - */ -public class TestDataPlugin implements IPostParseTestPlugin { - protected TestDigraph testDigraph; - - public TestDataPlugin(AutomationEngine automationEngine) { - this.testDigraph = automationEngine.getTestDigraph(); - } - - @Override - public String getTagName() { - return "testdata"; - } - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { - String testDataFile = getTestDataAttribute(ctx, "file"); - String testDataSheet = getTestDataAttribute(ctx, "sheet"); - List> testData = getTestData(testDataFile, testDataSheet); - int tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); - - List testComponents = ctx.getTestSuite().getComponentList(); - testComponents.remove(testComponents.size() - 1); - for (int testDataRow = 1; testDataRow < testData.size(); testDataRow++) { -// TestScript ts = null; - TestScript ts = reparseScript(ctx); - renameScript(ts, tsNamefromFilePosition, testData.get(testDataRow), testDataRow); - - setTestDataToTestScript(testData.get(0), testData.get(testDataRow), ts); - - addToSuite(ctx, ts); - - -// DigraphPlugin dependenciesPlugin = DigraphPlugin.getInstance(); -// TestDigraph testDigraph = dependenciesPlugin.getTestDigraph(); - testDigraph.addVertex(new DiNode(ts)); - } - } - - private String getTestDataAttribute(PostTestParserPluginContext ctx, String attributeName) { - NodeList children = ctx.getRootNodeTest().getChildNodes(); - String result = null; - - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeName().equalsIgnoreCase("testData")) { - Node attribute = children.item(i).getAttributes().getNamedItem(attributeName); - if (attribute == null) - continue; - result = attribute.getNodeValue(); - } - } - - return result; - } - - private List> getTestData(String file, String sheet) throws ParserPluginException { - if (file.endsWith(".xlsx")) { - return getExcelDataFromFile(file, sheet, true); - } - - if (file.endsWith(".xls")) { - return getExcelDataFromFile(file, sheet, false); - } - - if (file.endsWith(".csv")) { - return getCSVDataFromFile(file); - } - - throw new ParserPluginException("Oops! can't parse test data file ('" + file + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); - } - - private int getTSNameFromDataFilePosition(List> testData) { - // try to findout 'JTAF.test.name' column. Value from this column - // necessary to add to ts name. - if (testData != null && testData.size() > 0) { - List firstLine = testData.get(0); - int pos = 0; - for (String firstLineItem : firstLine) { - if (firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) { - return pos; - } else { - pos++; - } - } - } - return -1; - } - - private final List> getExcelDataFromFile(String testDataFile, String sheetName, boolean isXlsx) throws ParserPluginException { - if (testDataFile != null && testDataFile.length() > 0) { - ExcelFileParser excelFileParser = null; - try { - if (sheetName != null) { - excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); - } else { - excelFileParser = new ExcelFileParser(testDataFile, isXlsx); - } - return excelFileParser.parseExcelFile(isXlsx); - } catch (Exception e) { - throw new ParserPluginException("Oops! Can't parse excel file '" + testDataFile + "'!"); - } - } - return null; - } - - private List> getCSVDataFromFile(String file) throws ParserPluginException { - List> result = new ArrayList>(); - CSVReader reader = null; - try { - reader = new CSVReader(new FileReader(file)); - List nextLine; - - while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { - if ((nextLine != null) && (nextLine.size() > 0) && (!nextLine.get(0).startsWith("#"))) { - result.add(nextLine); - } - } - } catch (Exception exception) { - throw new ParserPluginException("Oops! Can't open file '" + file + "'!", exception); - } finally { - try { - if (reader != null) - reader.close(); - } catch (IOException ioException) { - throw new ParserPluginException("Problem closing CSVReader", ioException); - } - } - return result; - } - - private TestScript reparseScript(PostTestParserPluginContext ctx) throws ParserPluginException { - ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); - try { - return sp.processTestScript((Element) ctx.getRootNodeTest(), new MessageCollector()); - } catch (Exception exception) { - throw new ParserPluginException(exception); - } - } - - private void addToSuite(PostTestParserPluginContext ctx, TestScript ts) throws ParserPluginException { - try { - ctx.getTestSuite().add(ts); - } catch (NameCollisionException nameCollisionException) { - throw new ParserPluginException(nameCollisionException); - } - } - - private void setTestDataToTestScript(List title, List data, TestScript ts) { - for (Invocation statement : ts.getBody()) { - if (statement instanceof Invocation) { - Map parameters = ((Invocation) statement).getParameters(); - for (int i = 0; i < title.size(); i++) { - if (i < data.size()) { - parameters.put(title.get(i), data.get(i)); - } else { - parameters.put(title.get(i), ""); - } - } - } - } - } - - private void renameScript(TestScript ts, int tsNamefromFilePosition, List row, int rowNumber) { - // TODO Auto-generated method stub - - String tsNamefromFile = ""; - if (tsNamefromFilePosition >= 0) { - tsNamefromFile = "testNameFromDataFile-" + row.get(tsNamefromFilePosition); - } - - String newName = ts.getName(); - newName += " [data file row #" + rowNumber + "] ; " + tsNamefromFile; - - ts.setName(newName); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.exceptions.NameCollisionException; +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.model.test.digraph.TestDigraph; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.finra.jtaf.core.utilities.ExcelFileParser; +import org.finra.jtaf.core.utilities.StringHelper; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import au.com.bytecode.opencsv.CSVReader; + +/** + * Parser plugin to handle testdata element in a test script. + */ +public class TestDataPlugin implements IPostParseTestPlugin { + protected TestDigraph testDigraph; + + public TestDataPlugin(AutomationEngine automationEngine) { + this.testDigraph = automationEngine.getTestDigraph(); + } + + @Override + public String getTagName() { + return "testdata"; + } + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + String testDataFile = getTestDataAttribute(ctx, "file"); + String testDataSheet = getTestDataAttribute(ctx, "sheet"); + List> testData = getTestData(testDataFile, testDataSheet); + int tsNamefromFilePosition = getTSNameFromDataFilePosition(testData); + + List testComponents = ctx.getTestSuite().getComponentList(); + testComponents.remove(testComponents.size() - 1); + for (int testDataRow = 1; testDataRow < testData.size(); testDataRow++) { +// TestScript ts = null; + TestScript ts = reparseScript(ctx); + renameScript(ts, tsNamefromFilePosition, testData.get(testDataRow), testDataRow); + + setTestDataToTestScript(testData.get(0), testData.get(testDataRow), ts); + + addToSuite(ctx, ts); + + +// DigraphPlugin dependenciesPlugin = DigraphPlugin.getInstance(); +// TestDigraph testDigraph = dependenciesPlugin.getTestDigraph(); + testDigraph.addVertex(new DiNode(ts)); + } + } + + private String getTestDataAttribute(PostTestParserPluginContext ctx, String attributeName) { + NodeList children = ctx.getRootNodeTest().getChildNodes(); + String result = null; + + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeName().equalsIgnoreCase("testData")) { + Node attribute = children.item(i).getAttributes().getNamedItem(attributeName); + if (attribute == null) + continue; + result = attribute.getNodeValue(); + } + } + + return result; + } + + private List> getTestData(String file, String sheet) throws ParserPluginException { + if (file.endsWith(".xlsx")) { + return getExcelDataFromFile(file, sheet, true); + } + + if (file.endsWith(".xls")) { + return getExcelDataFromFile(file, sheet, false); + } + + if (file.endsWith(".csv")) { + return getCSVDataFromFile(file); + } + + throw new ParserPluginException("Oops! can't parse test data file ('" + file + "'). Supported 'xls', 'xlsx' and 'csv' extentions."); + } + + private int getTSNameFromDataFilePosition(List> testData) { + // try to findout 'JTAF.test.name' column. Value from this column + // necessary to add to ts name. + if (testData != null && testData.size() > 0) { + List firstLine = testData.get(0); + int pos = 0; + for (String firstLineItem : firstLine) { + if (firstLineItem != null && firstLineItem.equalsIgnoreCase("JTAF.test.name")) { + return pos; + } else { + pos++; + } + } + } + return -1; + } + + private final List> getExcelDataFromFile(String testDataFile, String sheetName, boolean isXlsx) throws ParserPluginException { + if (testDataFile != null && testDataFile.length() > 0) { + ExcelFileParser excelFileParser = null; + try { + if (sheetName != null) { + excelFileParser = new ExcelFileParser(testDataFile, sheetName, isXlsx); + } else { + excelFileParser = new ExcelFileParser(testDataFile, isXlsx); + } + return excelFileParser.parseExcelFile(isXlsx); + } catch (Exception e) { + throw new ParserPluginException("Oops! Can't parse excel file '" + testDataFile + "'!"); + } + } + return null; + } + + private List> getCSVDataFromFile(String file) throws ParserPluginException { + List> result = new ArrayList>(); + CSVReader reader = null; + try { + reader = new CSVReader(new FileReader(file)); + List nextLine; + + while ((nextLine = StringHelper.ArrayToList(reader.readNext())) != null) { + if ((nextLine != null) && (nextLine.size() > 0) && (!nextLine.get(0).startsWith("#"))) { + result.add(nextLine); + } + } + } catch (Exception exception) { + throw new ParserPluginException("Oops! Can't open file '" + file + "'!", exception); + } finally { + try { + if (reader != null) + reader.close(); + } catch (IOException ioException) { + throw new ParserPluginException("Problem closing CSVReader", ioException); + } + } + return result; + } + + private TestScript reparseScript(PostTestParserPluginContext ctx) throws ParserPluginException { + ScriptParser sp = AutomationEngine.getInstance().getScriptParser(); + try { + return sp.processTestScript((Element) ctx.getRootNodeTest(), new MessageCollector()); + } catch (Exception exception) { + throw new ParserPluginException(exception); + } + } + + private void addToSuite(PostTestParserPluginContext ctx, TestScript ts) throws ParserPluginException { + try { + ctx.getTestSuite().add(ts); + } catch (NameCollisionException nameCollisionException) { + throw new ParserPluginException(nameCollisionException); + } + } + + private void setTestDataToTestScript(List title, List data, TestScript ts) { + for (Invocation statement : ts.getBody()) { + if (statement instanceof Invocation) { + Map parameters = ((Invocation) statement).getParameters(); + for (int i = 0; i < title.size(); i++) { + if (i < data.size()) { + parameters.put(title.get(i), data.get(i)); + } else { + parameters.put(title.get(i), ""); + } + } + } + } + } + + private void renameScript(TestScript ts, int tsNamefromFilePosition, List row, int rowNumber) { + // TODO Auto-generated method stub + + String tsNamefromFile = ""; + if (tsNamefromFilePosition >= 0) { + tsNamefromFile = "testNameFromDataFile-" + row.get(tsNamefromFilePosition); + } + + String newName = ts.getName(); + newName += " [data file row #" + rowNumber + "] ; " + tsNamefromFile; + + ts.setName(newName); + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java index ed84ee6..34e5684 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestDependenciesPlugin.java @@ -1,83 +1,83 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -/** - * parser plugin to parse the dependencies defined in a test script. - */ -public class TestDependenciesPlugin implements IPostParseTestPlugin { - public static final String DEPENDENCIES_NAME = "dependencies"; - public static final String TEST_NAME = "test"; - public static final String TEST_SUITE_NAME = "testsuite"; - - @Override - public String getTagName() { - return DEPENDENCIES_NAME; - } - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { - Set exclusionSuites = new HashSet(); - Set exclusionTests = new HashSet(); - - NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); - for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { - Node testChildNode = testChildNodes.item(testChildNodeIndex); - if (testChildNode.getNodeName().equalsIgnoreCase(DEPENDENCIES_NAME)) { - handleDependencyNode(testChildNode, exclusionSuites, exclusionTests); - } - } - - List componentList = ctx.getTestSuite().getComponentList(); - TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); - lastTestScript.setDependencies(exclusionSuites, exclusionTests); - } - - private void handleDependencyNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { - NodeList dependencyChildNodes = testChildNode.getChildNodes(); - for (int dependencyChildNodeIndex = 0; dependencyChildNodeIndex < dependencyChildNodes.getLength(); dependencyChildNodeIndex++) { - Node dependencyChildNode = dependencyChildNodes.item(dependencyChildNodeIndex); - Set addSet = determineSet(dependencyChildNode.getNodeName(), exclusionSuites, exclusionTests); - if (addSet == null) - continue; - String name = dependencyChildNode.getAttributes().getNamedItem("name").getTextContent(); - addSet.add(name); - } - } - - private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { - if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { - return exclusionSuites; - } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { - return exclusionTests; - } - return null; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +/** + * parser plugin to parse the dependencies defined in a test script. + */ +public class TestDependenciesPlugin implements IPostParseTestPlugin { + public static final String DEPENDENCIES_NAME = "dependencies"; + public static final String TEST_NAME = "test"; + public static final String TEST_SUITE_NAME = "testsuite"; + + @Override + public String getTagName() { + return DEPENDENCIES_NAME; + } + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + Set exclusionSuites = new HashSet(); + Set exclusionTests = new HashSet(); + + NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); + for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { + Node testChildNode = testChildNodes.item(testChildNodeIndex); + if (testChildNode.getNodeName().equalsIgnoreCase(DEPENDENCIES_NAME)) { + handleDependencyNode(testChildNode, exclusionSuites, exclusionTests); + } + } + + List componentList = ctx.getTestSuite().getComponentList(); + TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); + lastTestScript.setDependencies(exclusionSuites, exclusionTests); + } + + private void handleDependencyNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { + NodeList dependencyChildNodes = testChildNode.getChildNodes(); + for (int dependencyChildNodeIndex = 0; dependencyChildNodeIndex < dependencyChildNodes.getLength(); dependencyChildNodeIndex++) { + Node dependencyChildNode = dependencyChildNodes.item(dependencyChildNodeIndex); + Set addSet = determineSet(dependencyChildNode.getNodeName(), exclusionSuites, exclusionTests); + if (addSet == null) + continue; + String name = dependencyChildNode.getAttributes().getNamedItem("name").getTextContent(); + addSet.add(name); + } + } + + private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { + if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { + return exclusionSuites; + } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { + return exclusionTests; + } + return null; + } +} diff --git a/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java b/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java index d4243ba..c397dba 100644 --- a/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java +++ b/src/main/java/org/finra/jtaf/core/parsing/TestExclusionsPlugin.java @@ -1,83 +1,83 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.parsing; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -/** - * Parser plugin responsible for parsing exclusions in test script. - */ -public class TestExclusionsPlugin implements IPostParseTestPlugin { - public static final String EXCLUSIONS_NAME = "exclusions"; - public static final String TEST_NAME = "test"; - public static final String TEST_SUITE_NAME = "testsuite"; - - @Override - public String getTagName() { - return EXCLUSIONS_NAME; - } - - @Override - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { - Set exclusionSuites = new HashSet(); - Set exclusionTests = new HashSet(); - - NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); - for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { - Node testChildNode = testChildNodes.item(testChildNodeIndex); - if (testChildNode.getNodeName().equalsIgnoreCase(EXCLUSIONS_NAME)) { - handleExclusionNode(testChildNode, exclusionSuites, exclusionTests); - } - } - - List componentList = ctx.getTestSuite().getComponentList(); - TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); - lastTestScript.setExclusions(exclusionSuites, exclusionTests); - } - - private void handleExclusionNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { - NodeList exclusionChildNodes = testChildNode.getChildNodes(); - for (int exclusionChildNodeIndex = 0; exclusionChildNodeIndex < exclusionChildNodes.getLength(); exclusionChildNodeIndex++) { - Node exclusionChildNode = exclusionChildNodes.item(exclusionChildNodeIndex); - Set addSet = determineSet(exclusionChildNode.getNodeName(), exclusionSuites, exclusionTests); - if (addSet == null) - continue; - String name = exclusionChildNode.getAttributes().getNamedItem("name").getTextContent(); - addSet.add(name); - } - } - - private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { - if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { - return exclusionSuites; - } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { - return exclusionTests; - } - return null; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.parsing; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +/** + * Parser plugin responsible for parsing exclusions in test script. + */ +public class TestExclusionsPlugin implements IPostParseTestPlugin { + public static final String EXCLUSIONS_NAME = "exclusions"; + public static final String TEST_NAME = "test"; + public static final String TEST_SUITE_NAME = "testsuite"; + + @Override + public String getTagName() { + return EXCLUSIONS_NAME; + } + + @Override + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException { + Set exclusionSuites = new HashSet(); + Set exclusionTests = new HashSet(); + + NodeList testChildNodes = ctx.getRootNodeTest().getChildNodes(); + for (int testChildNodeIndex = 0; testChildNodeIndex < testChildNodes.getLength(); testChildNodeIndex++) { + Node testChildNode = testChildNodes.item(testChildNodeIndex); + if (testChildNode.getNodeName().equalsIgnoreCase(EXCLUSIONS_NAME)) { + handleExclusionNode(testChildNode, exclusionSuites, exclusionTests); + } + } + + List componentList = ctx.getTestSuite().getComponentList(); + TestScript lastTestScript = (TestScript) componentList.get(componentList.size() - 1); + lastTestScript.setExclusions(exclusionSuites, exclusionTests); + } + + private void handleExclusionNode(Node testChildNode, Set exclusionSuites, Set exclusionTests) { + NodeList exclusionChildNodes = testChildNode.getChildNodes(); + for (int exclusionChildNodeIndex = 0; exclusionChildNodeIndex < exclusionChildNodes.getLength(); exclusionChildNodeIndex++) { + Node exclusionChildNode = exclusionChildNodes.item(exclusionChildNodeIndex); + Set addSet = determineSet(exclusionChildNode.getNodeName(), exclusionSuites, exclusionTests); + if (addSet == null) + continue; + String name = exclusionChildNode.getAttributes().getNamedItem("name").getTextContent(); + addSet.add(name); + } + } + + private Set determineSet(String nodeName, Set exclusionSuites, Set exclusionTests) { + if (nodeName.equalsIgnoreCase(TEST_SUITE_NAME)) { + return exclusionSuites; + } else if (nodeName.equalsIgnoreCase(TEST_NAME)) { + return exclusionTests; + } + return null; + } +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java b/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java index b8de85c..b052518 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java +++ b/src/main/java/org/finra/jtaf/core/plugins/PluginManager.java @@ -1,103 +1,103 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins; - -import java.util.List; - -import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; -import org.finra.jtaf.core.plugins.execution.ITearDownPlugin; -import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; -import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; -import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; -import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; -import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; - -/** - * Plugin Manager is a class to register the parsing and the execution level - * plugins. Any number of custom plugins can be registered by addin them as a - * property of the Pluginmanager bean in framework.xml - */ -public class PluginManager { - - private List postParseAllPlugins; - private List postParseSuitePlugins; - private List postParseTestPlugins; - private List postParseStrategyElementPlugins; - private List tearDownPlugins; - - private List testRunnerPlugins; - private List commandRunnerPlugins; - - public void setPostParseAllPlugins(List plugins) { - postParseAllPlugins = plugins; - } - - public List getPostParseAllPlugins() { - return postParseAllPlugins; - } - - public void setPostParseSuitePlugins( - List customPlugins) { - postParseSuitePlugins = customPlugins; - } - - public List getPostParseSuitePlugins() { - return postParseSuitePlugins; - } - - public void setPostParseTestPlugins(List plugins) { - postParseTestPlugins = plugins; - } - - public List getPostParseTestPlugins() { - return postParseTestPlugins; - } - - public void setPostParseStrategyElementPlugins( - List plugins) { - postParseStrategyElementPlugins = plugins; - } - - public List getPostParseStrategyElementPlugins() { - return postParseStrategyElementPlugins; - } - - public void setTestRunnerPlugins(List customPlugins) { - this.testRunnerPlugins = customPlugins; - } - - public List getTestRunnerPlugins() { - return testRunnerPlugins; - } - - public void setCommandRunnerPlugins(List customPlugins) { - this.commandRunnerPlugins = customPlugins; - } - - public List getCommandRunnerPlugins() { - return commandRunnerPlugins; - } - - public void setTearDownPlugins(List tearDownPlugins) { - this.tearDownPlugins = tearDownPlugins; - } - - public List getTearDownPlugins() { - return tearDownPlugins; - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins; + +import java.util.List; + +import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; +import org.finra.jtaf.core.plugins.execution.ITearDownPlugin; +import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; +import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; +import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; +import org.finra.jtaf.core.plugins.parsing.IPostParseSuitePlugin; +import org.finra.jtaf.core.plugins.parsing.IPostParseTestPlugin; + +/** + * Plugin Manager is a class to register the parsing and the execution level + * plugins. Any number of custom plugins can be registered by addin them as a + * property of the Pluginmanager bean in framework.xml + */ +public class PluginManager { + + private List postParseAllPlugins; + private List postParseSuitePlugins; + private List postParseTestPlugins; + private List postParseStrategyElementPlugins; + private List tearDownPlugins; + + private List testRunnerPlugins; + private List commandRunnerPlugins; + + public void setPostParseAllPlugins(List plugins) { + postParseAllPlugins = plugins; + } + + public List getPostParseAllPlugins() { + return postParseAllPlugins; + } + + public void setPostParseSuitePlugins( + List customPlugins) { + postParseSuitePlugins = customPlugins; + } + + public List getPostParseSuitePlugins() { + return postParseSuitePlugins; + } + + public void setPostParseTestPlugins(List plugins) { + postParseTestPlugins = plugins; + } + + public List getPostParseTestPlugins() { + return postParseTestPlugins; + } + + public void setPostParseStrategyElementPlugins( + List plugins) { + postParseStrategyElementPlugins = plugins; + } + + public List getPostParseStrategyElementPlugins() { + return postParseStrategyElementPlugins; + } + + public void setTestRunnerPlugins(List customPlugins) { + this.testRunnerPlugins = customPlugins; + } + + public List getTestRunnerPlugins() { + return testRunnerPlugins; + } + + public void setCommandRunnerPlugins(List customPlugins) { + this.commandRunnerPlugins = customPlugins; + } + + public List getCommandRunnerPlugins() { + return commandRunnerPlugins; + } + + public void setTearDownPlugins(List tearDownPlugins) { + this.tearDownPlugins = tearDownPlugins; + } + + public List getTearDownPlugins() { + return tearDownPlugins; + } + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java index 517c2cf..422fa8e 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/CommandRunnerPluginContext.java @@ -1,50 +1,50 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.test.TestStepsDetails; - -/** - * This is the context visible to Command Runner Plugins - */ -public class CommandRunnerPluginContext { - - private TestStepsDetails testStepsDetails; - private IInvocationContext context; - - public CommandRunnerPluginContext(TestStepsDetails ts, IInvocationContext ctx) { - this.context = ctx; - this.testStepsDetails = ts; - } - - /*** - * @return IInovocationContext - holds a map of values over the life of a Test Script - */ - public IInvocationContext getIInvocationContext() { - return context; - } - - /*** - * @return TestStepsDetails - contains some metadata concerning the command - */ - public TestStepsDetails getTestStepsDetails() { - return testStepsDetails; - } - - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.test.TestStepsDetails; + +/** + * This is the context visible to Command Runner Plugins + */ +public class CommandRunnerPluginContext { + + private TestStepsDetails testStepsDetails; + private IInvocationContext context; + + public CommandRunnerPluginContext(TestStepsDetails ts, IInvocationContext ctx) { + this.context = ctx; + this.testStepsDetails = ts; + } + + /*** + * @return IInovocationContext - holds a map of values over the life of a Test Script + */ + public IInvocationContext getIInvocationContext() { + return context; + } + + /*** + * @return TestStepsDetails - contains some metadata concerning the command + */ + public TestStepsDetails getTestStepsDetails() { + return testStepsDetails; + } + + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java index b808721..617d98f 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ICommandRunnerPlugin.java @@ -1,40 +1,40 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - - -/** - * This is the interface to be used for Command Execution plugins - */ -public interface ICommandRunnerPlugin { - - /** - * Called before every command is run - * - * @param ctx - * @throws RunnerPluginException - */ - void handleCommandBefore(CommandRunnerPluginContext ctx) throws RunnerPluginException; - - /** - * Called after every command is finished running - * - * @param ctx - * @throws RunnerPluginException - */ - void handleCommandAfter(CommandRunnerPluginContext ctx) throws RunnerPluginException; -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + + +/** + * This is the interface to be used for Command Execution plugins + */ +public interface ICommandRunnerPlugin { + + /** + * Called before every command is run + * + * @param ctx + * @throws RunnerPluginException + */ + void handleCommandBefore(CommandRunnerPluginContext ctx) throws RunnerPluginException; + + /** + * Called after every command is finished running + * + * @param ctx + * @throws RunnerPluginException + */ + void handleCommandAfter(CommandRunnerPluginContext ctx) throws RunnerPluginException; +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java index d0784a7..dd4c403 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ITearDownPlugin.java @@ -1,30 +1,30 @@ -/* - * (C) Copyright 2015 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - -/** - * This is the interface for tearDown plugins - */ -public interface ITearDownPlugin { - /** - * This method is called when a script fails and the tearDown is entered - * - * @param tearDownPluginContext - * @throws RunnerPluginException - */ - void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException; -} +/* + * (C) Copyright 2015 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + +/** + * This is the interface for tearDown plugins + */ +public interface ITearDownPlugin { + /** + * This method is called when a script fails and the tearDown is entered + * + * @param tearDownPluginContext + * @throws RunnerPluginException + */ + void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException; +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java index 50cf81c..520e609 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/ITestRunnerPlugin.java @@ -1,41 +1,41 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - - -/** - * This is the interface to be used for Test Execution plugins - */ -public interface ITestRunnerPlugin { - - /** - * Called before every test starts - * - * @param ctx - * @throws RunnerPluginException - */ - void handleTestStart(TestRunnerPluginContext ctx) throws RunnerPluginException; - - /** - * Called after every test finishes - * - * @param ctx - * @throws RunnerPluginException - */ - void handleTestFinish(TestRunnerPluginContext ctx) throws RunnerPluginException; - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + + +/** + * This is the interface to be used for Test Execution plugins + */ +public interface ITestRunnerPlugin { + + /** + * Called before every test starts + * + * @param ctx + * @throws RunnerPluginException + */ + void handleTestStart(TestRunnerPluginContext ctx) throws RunnerPluginException; + + /** + * Called after every test finishes + * + * @param ctx + * @throws RunnerPluginException + */ + void handleTestFinish(TestRunnerPluginContext ctx) throws RunnerPluginException; + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java b/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java index 8815d71..6451074 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/RunnerPluginException.java @@ -1,34 +1,34 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - -/** - * Thrown by Runner Execution Plugins to indicate a general Exception - */ -public class RunnerPluginException extends Exception { - - private static final long serialVersionUID = 1L; - - public RunnerPluginException(String message) { - super(message); - } - - public RunnerPluginException(String message, Throwable th) { - super(message, th); - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + +/** + * Thrown by Runner Execution Plugins to indicate a general Exception + */ +public class RunnerPluginException extends Exception { + + private static final long serialVersionUID = 1L; + + public RunnerPluginException(String message) { + super(message); + } + + public RunnerPluginException(String message, Throwable th) { + super(message, th); + } + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java index 9cf99cf..96b49ea 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/TearDownPluginContext.java @@ -1,47 +1,47 @@ -/* - * (C) Copyright 2015 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.test.TestScript; - -/** - * This is the context visible to tearDown plugins - */ -public class TearDownPluginContext { - private TestScript testScript; - private Throwable failureReason; - private IInvocationContext invocationContext; - - public TearDownPluginContext(TestScript testScript, Throwable failureReason, IInvocationContext invocationContext) { - this.testScript = testScript; - this.failureReason = failureReason; - this.invocationContext = invocationContext; - } - - public TestScript getTestScript() { - return testScript; - } - - public Throwable getFailureReason() { - return failureReason; - } - - public IInvocationContext getInvocationContext() { - return invocationContext; - } -} +/* + * (C) Copyright 2015 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.test.TestScript; + +/** + * This is the context visible to tearDown plugins + */ +public class TearDownPluginContext { + private TestScript testScript; + private Throwable failureReason; + private IInvocationContext invocationContext; + + public TearDownPluginContext(TestScript testScript, Throwable failureReason, IInvocationContext invocationContext) { + this.testScript = testScript; + this.failureReason = failureReason; + this.invocationContext = invocationContext; + } + + public TestScript getTestScript() { + return testScript; + } + + public Throwable getFailureReason() { + return failureReason; + } + + public IInvocationContext getInvocationContext() { + return invocationContext; + } +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java index 44d013b..37fd921 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/execution/TestRunnerPluginContext.java @@ -1,58 +1,58 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.execution; - -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; - -/** - * This is the context visible to Test Runner Plugins - */ -public class TestRunnerPluginContext { - private TestScript testScript; - private TestResult testResult; - private IInvocationContext invocationContext; - - public TestRunnerPluginContext(TestScript ts, TestResult tr, IInvocationContext ctx) { - this.testScript = ts; - this.testResult = tr; - this.invocationContext = ctx; - } - - /*** - * @return TestScript - */ - public TestScript getTestScript() { - return testScript; - } - - /*** - * @return TestResult of the Test Script - */ - public TestResult getTestResult() { - return testResult; - } - - /*** - * @return IInovocationContext - holds a map of values over the life of the Test Script - */ - public IInvocationContext getIInvocationContext() { - return invocationContext; - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.execution; + +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; + +/** + * This is the context visible to Test Runner Plugins + */ +public class TestRunnerPluginContext { + private TestScript testScript; + private TestResult testResult; + private IInvocationContext invocationContext; + + public TestRunnerPluginContext(TestScript ts, TestResult tr, IInvocationContext ctx) { + this.testScript = ts; + this.testResult = tr; + this.invocationContext = ctx; + } + + /*** + * @return TestScript + */ + public TestScript getTestScript() { + return testScript; + } + + /*** + * @return TestResult of the Test Script + */ + public TestResult getTestResult() { + return testResult; + } + + /*** + * @return IInovocationContext - holds a map of values over the life of the Test Script + */ + public IInvocationContext getIInvocationContext() { + return invocationContext; + } + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java index 8c39b44..6131089 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseAllPlugin.java @@ -1,32 +1,32 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -/*** - * Interface for Parser Plugins which get executed after all tests are parsed - */ -public interface IPostParseAllPlugin { - - /*** - * This method executes after all tests are parsed - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException; -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +/*** + * Interface for Parser Plugins which get executed after all tests are parsed + */ +public interface IPostParseAllPlugin { + + /*** + * This method executes after all tests are parsed + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException; +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java index 327b6c3..a6f7b75 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseStrategyElementPlugin.java @@ -1,33 +1,33 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -/*** - * Interface for Parser Plugins which get executed after the test strategy is - * parsed - */ - -public interface IPostParseStrategyElementPlugin { - /*** - * This method executes after all the test strategy is parsed - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException; -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +/*** + * Interface for Parser Plugins which get executed after the test strategy is + * parsed + */ + +public interface IPostParseStrategyElementPlugin { + /*** + * This method executes after all the test strategy is parsed + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostStrategyElementParserPluginContext ctx) throws ParserPluginException; +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java index a4ff050..e2e9851 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseSuitePlugin.java @@ -1,38 +1,38 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -/*** - * Interface for Parser Plugins which get executed after each applicable suite is parsed - */ -public interface IPostParseSuitePlugin { - - /*** - * This method executes after each suite is parsed which has the tag name returned by getTagName() - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException; - - /*** - * This will return the tag name the ScriptParser will be looking for in the suite. If not found, - * the execute method will not be run. - */ - public String getTagName(); -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +/*** + * Interface for Parser Plugins which get executed after each applicable suite is parsed + */ +public interface IPostParseSuitePlugin { + + /*** + * This method executes after each suite is parsed which has the tag name returned by getTagName() + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException; + + /*** + * This will return the tag name the ScriptParser will be looking for in the suite. If not found, + * the execute method will not be run. + */ + public String getTagName(); +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java index 19aebf2..ff01d1e 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/IPostParseTestPlugin.java @@ -1,38 +1,38 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -/*** - * Interface for Parser Plugins which get executed after each applicable test is parsed - */ -public interface IPostParseTestPlugin { - - /*** - * This method executes after each test is parsed which has the tag name returned by getTagName() - * - * @param ctx - * @throws ParserPluginException - */ - public void execute(PostTestParserPluginContext ctx) throws ParserPluginException; - - /*** - * This will return the tag name the ScriptParser will be looking for in the test body. If not found, - * the execute method will not be run. - */ - public String getTagName(); -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +/*** + * Interface for Parser Plugins which get executed after each applicable test is parsed + */ +public interface IPostParseTestPlugin { + + /*** + * This method executes after each test is parsed which has the tag name returned by getTagName() + * + * @param ctx + * @throws ParserPluginException + */ + public void execute(PostTestParserPluginContext ctx) throws ParserPluginException; + + /*** + * This will return the tag name the ScriptParser will be looking for in the test body. If not found, + * the execute method will not be run. + */ + public String getTagName(); +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java index b491e97..c088692 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/ParserPluginException.java @@ -1,43 +1,43 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -/*** - * This exception is thrown by the parser plugins - */ -public class ParserPluginException extends Exception { - - // automatically generated - private static final long serialVersionUID = -195286095131824362L; - - public ParserPluginException() { - super(); - } - - public ParserPluginException(String message) { - super(message); - } - - public ParserPluginException(Throwable throwable) { - super(throwable); - } - - public ParserPluginException(String message, Throwable throwable) { - super(message, throwable); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +/*** + * This exception is thrown by the parser plugins + */ +public class ParserPluginException extends Exception { + + // automatically generated + private static final long serialVersionUID = -195286095131824362L; + + public ParserPluginException() { + super(); + } + + public ParserPluginException(String message) { + super(message); + } + + public ParserPluginException(Throwable throwable) { + super(throwable); + } + + public ParserPluginException(String message, Throwable throwable) { + super(message, throwable); + } +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java index cb030b4..fe01c97 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostAllParserPluginContext.java @@ -1,55 +1,55 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.model.test.TestAgenda; - - -/*** - * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - */ -public class PostAllParserPluginContext { - - private TestAgenda testAgenda; - private CommandRegistry commandRegistry; - - public PostAllParserPluginContext(TestAgenda testAgenda, CommandRegistry commandRegistry) { - this.testAgenda = testAgenda; - this.commandRegistry = commandRegistry; - } - - /*** - * Returns the Test Agenda associated with the test run, so plugins can read and modify the data - * - * @return testAgenda - */ - public TestAgenda getTestAgenda() { - return testAgenda; - } - - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.model.test.TestAgenda; + + +/*** + * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. + */ +public class PostAllParserPluginContext { + + private TestAgenda testAgenda; + private CommandRegistry commandRegistry; + + public PostAllParserPluginContext(TestAgenda testAgenda, CommandRegistry commandRegistry) { + this.testAgenda = testAgenda; + this.commandRegistry = commandRegistry; + } + + /*** + * Returns the Test Agenda associated with the test run, so plugins can read and modify the data + * + * @return testAgenda + */ + public TestAgenda getTestAgenda() { + return testAgenda; + } + + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java index 44fef85..c479875 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostStrategyElementParserPluginContext.java @@ -1,52 +1,52 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.plugins.parsing; - -import org.finra.jtaf.core.model.test.TestAgenda; -import org.w3c.dom.Element; - -/*** - * Exposes the data that can be used and/or modified by a IPostParseStrategyElementPlugin. - */ -public class PostStrategyElementParserPluginContext { - private TestAgenda testAgenda; - private Element element; - - public PostStrategyElementParserPluginContext(TestAgenda testAgenda, Element element) { - this.testAgenda = testAgenda; - this.element = element; - } - - /*** - * Returns the Test Agenda associated with the test run, so plugins can read and modify the data - * - * @return testAgenda - */ - public TestAgenda getTestAgenda() { - return testAgenda; - } - - /*** - * Returns the parsed Element object so that the relevant xml data can be used - * in the plugin - * - * @return element - */ - public Element getElement() { - return element; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.plugins.parsing; + +import org.finra.jtaf.core.model.test.TestAgenda; +import org.w3c.dom.Element; + +/*** + * Exposes the data that can be used and/or modified by a IPostParseStrategyElementPlugin. + */ +public class PostStrategyElementParserPluginContext { + private TestAgenda testAgenda; + private Element element; + + public PostStrategyElementParserPluginContext(TestAgenda testAgenda, Element element) { + this.testAgenda = testAgenda; + this.element = element; + } + + /*** + * Returns the Test Agenda associated with the test run, so plugins can read and modify the data + * + * @return testAgenda + */ + public TestAgenda getTestAgenda() { + return testAgenda; + } + + /*** + * Returns the parsed Element object so that the relevant xml data can be used + * in the plugin + * + * @return element + */ + public Element getElement() { + return element; + } +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java index 97a2737..155c98d 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostSuiteParserPluginContext.java @@ -1,70 +1,70 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.model.test.TestSuite; -import org.w3c.dom.Node; - - -/*** - * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - */ -public class PostSuiteParserPluginContext { - - private CommandRegistry commandRegistry; - private TestSuite testSuite; - private Node suiteRoot; - - public PostSuiteParserPluginContext(CommandRegistry commandRegistry, - TestSuite testSuite, Node suiteRoot) { - this.commandRegistry = commandRegistry; - this.testSuite = testSuite; - this.suiteRoot = suiteRoot; - } - - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - - /*** - * Returns the Test Suite the test is a part of, so plugins can add test scripts to the suite - * if needed - * - * @return testSuite - */ - public TestSuite getTestSuite() { - return testSuite; - } - - /*** - * Returns the root Node object of the current suite so that the relevant xml data can be used - * in the plugin - * - * @return elementRoot - */ - public Node getRootNodeSuite() { - return suiteRoot; - } - -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.model.test.TestSuite; +import org.w3c.dom.Node; + + +/*** + * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. + */ +public class PostSuiteParserPluginContext { + + private CommandRegistry commandRegistry; + private TestSuite testSuite; + private Node suiteRoot; + + public PostSuiteParserPluginContext(CommandRegistry commandRegistry, + TestSuite testSuite, Node suiteRoot) { + this.commandRegistry = commandRegistry; + this.testSuite = testSuite; + this.suiteRoot = suiteRoot; + } + + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + + /*** + * Returns the Test Suite the test is a part of, so plugins can add test scripts to the suite + * if needed + * + * @return testSuite + */ + public TestSuite getTestSuite() { + return testSuite; + } + + /*** + * Returns the root Node object of the current suite so that the relevant xml data can be used + * in the plugin + * + * @return elementRoot + */ + public Node getRootNodeSuite() { + return suiteRoot; + } + +} diff --git a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java index 6cf35db..cd20560 100644 --- a/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java +++ b/src/main/java/org/finra/jtaf/core/plugins/parsing/PostTestParserPluginContext.java @@ -1,68 +1,68 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.plugins.parsing; - -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.model.test.TestSuite; -import org.w3c.dom.Node; - -/*** - * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. - */ -public class PostTestParserPluginContext { - - private CommandRegistry commandRegistry; - private TestSuite testSuite; - private Node testRoot; - - public PostTestParserPluginContext(CommandRegistry commandRegistry, - TestSuite testSuite, Node testRoot) { - this.commandRegistry = commandRegistry; - this.testSuite = testSuite; - this.testRoot = testRoot; - } - - /*** - * Returns the Command Library model, so plugins can use the data - * - * @return commandModel - */ - public CommandRegistry getCommandRegistry() { - return commandRegistry; - } - - /*** - * Returns the Test Suite the test is a part of, so plugins can add test - * scripts to the suite if needed - * - * @return testSuite - */ - public TestSuite getTestSuite() { - return testSuite; - } - - /*** - * Returns the root Node object of the current test so that the relevant xml - * data can be used in the plugin - * - * @return elementRoot - */ - public Node getRootNodeTest() { - return testRoot; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.plugins.parsing; + +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.model.test.TestSuite; +import org.w3c.dom.Node; + +/*** + * Exposes the data that can be used and/or modified by a IPostParseTestPlugin. + */ +public class PostTestParserPluginContext { + + private CommandRegistry commandRegistry; + private TestSuite testSuite; + private Node testRoot; + + public PostTestParserPluginContext(CommandRegistry commandRegistry, + TestSuite testSuite, Node testRoot) { + this.commandRegistry = commandRegistry; + this.testSuite = testSuite; + this.testRoot = testRoot; + } + + /*** + * Returns the Command Library model, so plugins can use the data + * + * @return commandModel + */ + public CommandRegistry getCommandRegistry() { + return commandRegistry; + } + + /*** + * Returns the Test Suite the test is a part of, so plugins can add test + * scripts to the suite if needed + * + * @return testSuite + */ + public TestSuite getTestSuite() { + return testSuite; + } + + /*** + * Returns the root Node object of the current test so that the relevant xml + * data can be used in the plugin + * + * @return elementRoot + */ + public Node getRootNodeTest() { + return testRoot; + } +} diff --git a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java index 8710caf..92bba58 100644 --- a/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java +++ b/src/main/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPlugin.java @@ -1,38 +1,38 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.traceability; - -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; - -/** - * Plugin to produce a traceability matrix - */ -public class TraceabilityMatrixPlugin implements IPostParseAllPlugin { - /** - * Produces a traceability matrix after all parsing has completed - * - * @param ctx PostAllParserPluginContext - */ - @Override - public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { - TestAgenda testAgenda = ctx.getTestAgenda(); - TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.traceability; + +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.plugins.parsing.IPostParseAllPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; + +/** + * Plugin to produce a traceability matrix + */ +public class TraceabilityMatrixPlugin implements IPostParseAllPlugin { + /** + * Produces a traceability matrix after all parsing has completed + * + * @param ctx PostAllParserPluginContext + */ + @Override + public void execute(PostAllParserPluginContext ctx) throws ParserPluginException { + TestAgenda testAgenda = ctx.getTestAgenda(); + TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + } +} diff --git a/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java b/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java index 6951806..57d9b59 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java +++ b/src/main/java/org/finra/jtaf/core/utilities/Base64EncoderDecoder.java @@ -1,94 +1,94 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.finra.jtaf.core.utilities; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileReader; -import java.io.FileWriter; - -import org.apache.commons.codec.binary.Base64; - -//Apache Commons Codec Base64 static Encoder/Decoder - -/** - * Utility class to encode or decode string using base64. - */ -public class Base64EncoderDecoder { - private static String fileLocation = "C:\\TEMP\\base64\\test.properties"; - - /* - * main method is used to decode a property file only. It can take one incoming parameter - the location of - * the file to be encoded. If there is no incoming parameter (or more than one provided), then the default 'propertyFileLocation' value used. - */ - public static void main(String[] args) throws Exception { - if (args.length == 1) { - setPropertyFileLocation(args[0]); - } - - String fileName = fileLocation.split("\\\\")[fileLocation.split("\\\\").length - 1]; - String encodedFileName = fileName.split("\\.")[0] + "_Encoded." + fileName.split("\\.")[1]; - String encodedFileLocation = fileLocation.replace(fileName, encodedFileName); - - BufferedReader in = new BufferedReader(new FileReader(fileLocation)); - BufferedWriter out = new BufferedWriter(new FileWriter(encodedFileLocation)); - - String line; - String key; - String value; - - while ((line = in.readLine()) != null) { - if (!line.startsWith("#")) { - if (line.contains("=")) { - key = line.substring(0, line.indexOf("=")); - value = line.substring(line.indexOf("=") + 1); - if (key.endsWith(".password")) { - value = encodeString(value); - line = key + "=" + value; - } - } - } - - System.out.println(line); - out.write(line + System.getProperty("line.separator")); - } - - in.close(); - out.close(); - } - - - public static String encodeString(String stringToEncode) { - byte[] encodedBytes = Base64.encodeBase64(stringToEncode.getBytes()); - return new String(encodedBytes); - } - - public static String decodeString(String stringToDecode) { - byte[] decodedBytes = Base64.decodeBase64(stringToDecode.getBytes()); - return new String(decodedBytes); - } - - public static String getPropertyFileLocation() { - return fileLocation; - } - - public static void setPropertyFileLocation(String newPropertyFileLocation) { - fileLocation = newPropertyFileLocation; - } - +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.finra.jtaf.core.utilities; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; + +import org.apache.commons.codec.binary.Base64; + +//Apache Commons Codec Base64 static Encoder/Decoder + +/** + * Utility class to encode or decode string using base64. + */ +public class Base64EncoderDecoder { + private static String fileLocation = "C:\\TEMP\\base64\\test.properties"; + + /* + * main method is used to decode a property file only. It can take one incoming parameter - the location of + * the file to be encoded. If there is no incoming parameter (or more than one provided), then the default 'propertyFileLocation' value used. + */ + public static void main(String[] args) throws Exception { + if (args.length == 1) { + setPropertyFileLocation(args[0]); + } + + String fileName = fileLocation.split("\\\\")[fileLocation.split("\\\\").length - 1]; + String encodedFileName = fileName.split("\\.")[0] + "_Encoded." + fileName.split("\\.")[1]; + String encodedFileLocation = fileLocation.replace(fileName, encodedFileName); + + BufferedReader in = new BufferedReader(new FileReader(fileLocation)); + BufferedWriter out = new BufferedWriter(new FileWriter(encodedFileLocation)); + + String line; + String key; + String value; + + while ((line = in.readLine()) != null) { + if (!line.startsWith("#")) { + if (line.contains("=")) { + key = line.substring(0, line.indexOf("=")); + value = line.substring(line.indexOf("=") + 1); + if (key.endsWith(".password")) { + value = encodeString(value); + line = key + "=" + value; + } + } + } + + System.out.println(line); + out.write(line + System.getProperty("line.separator")); + } + + in.close(); + out.close(); + } + + + public static String encodeString(String stringToEncode) { + byte[] encodedBytes = Base64.encodeBase64(stringToEncode.getBytes()); + return new String(encodedBytes); + } + + public static String decodeString(String stringToDecode) { + byte[] decodedBytes = Base64.decodeBase64(stringToDecode.getBytes()); + return new String(decodedBytes); + } + + public static String getPropertyFileLocation() { + return fileLocation; + } + + public static void setPropertyFileLocation(String newPropertyFileLocation) { + fileLocation = newPropertyFileLocation; + } + } \ No newline at end of file diff --git a/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java b/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java index 3715235..207c267 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java +++ b/src/main/java/org/finra/jtaf/core/utilities/CompositeDataComparator.java @@ -1,227 +1,227 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.utilities; - -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.finra.jtaf.core.asserts.AssertionFailedError; - - -/** - * Utility class to perform comparison of lists and maps - */ -public class CompositeDataComparator { - - private List errorList; - private boolean accumulateErrors; - - public CompositeDataComparator() { - accumulateErrors = false; - } - - public CompositeDataComparator(boolean accumulateErrors) { - this.accumulateErrors = accumulateErrors; - errorList = new ArrayList(); - } - - public void compareMap(String title, String element, Map expComp, - Map actualComp) { - String prefix = getPrefix(title, element); - Set keySet = expComp.keySet(); - - for (Iterator iter = keySet.iterator(); iter.hasNext(); ) { - String obj = (String) iter.next(); - - Object eValue = expComp.get(obj); - - if (!actualComp.containsKey(obj)) { - reportError(prefix + " Couldn't find Element [" + obj - + "] in Actual Data"); - - } - Object aValue = actualComp.get(obj); - - assessAndCompare(prefix, obj, eValue, aValue); - } - } - - public void compareList(String title, String element, List expList, - List actualList) { - String prefix = getPrefix(title, element); - - if (compareSize(prefix, expList, actualList)) { - - for (int i = 0; i < expList.size(); i++) { - Object expected = expList.get(i); - Object actual = actualList.get(i); - - assessAndCompare(prefix + "[position : " + (i + 1) + "]", null, - expected, actual); - } - } - } - - /* - * for comparing untyped objects that may be instances of Boolean, String, String[], Timestamp, List, or Map - * lists and maps are internally tested for the same types recursively - * - * any other types on the basic or internal levels are compared as type Object - * - * if basic or internal Objects are both null they are considered equal - */ - public void compareObject(String title, String element, Object expected, Object actual) { - assessAndCompare(title, element, expected, actual); - } - - public List getErrorList() { - return errorList; - } - - /** - * Sets the accumulate errors flag - * - * @param accumulateErrors determines if the comparator will throw - * an exception with errors found, or accumulate them for later reporting - */ - public void setAccumulateErrors(boolean accumulateErrors) { - this.accumulateErrors = accumulateErrors; - if (accumulateErrors && errorList == null) { - errorList = new ArrayList(); - } - } - - /** - * Gets the accumulate errors flag - * - * @return the accumulate errors flag - */ - public boolean getAccumulateErrors() { - return this.accumulateErrors; - } - - private void reportError(String error) { - if (!accumulateErrors) - throw new AssertionFailedError(error); - else - errorList.add(error); - - } - - private String getPrefix(String title, String element) { - return (element == null && !"".equals(element)) ? title : title + "-> " - + element + " : "; - } - - private void assessAndCompare(String title, String element, - Object expected, Object actual) { - String prefix = getPrefix(title, element); - - if (expected == null && actual == null) { - return; - } else if (expected == null || actual == null) { - if ("".equals(expected) || "".equals(actual)) - return; - reportError(prefix + " didn't match. Expected Value[" + expected - + "] and Actual Value [" + actual + "]."); - } else if (expected instanceof Map) { - compareMap(title, element, (Map) expected, (Map) actual); - } else if (expected instanceof List) { - compareList(title, element, (List) expected, (List) actual); - } else if (expected instanceof Timestamp) { - Timestamp expTimestamp = (Timestamp) expected; - if (!(actual instanceof Timestamp)) - reportError(prefix + " Expected value [" + expTimestamp - + "] and Actual Value [" + actual + "]."); - - else - compareObject(prefix, expTimestamp, (Timestamp) actual); - } else if (expected instanceof String[]) { - String e[] = (String[]) expected; - String a[] = (String[]) actual; - - if (e.length != a.length) - reportError(prefix - + " Length of string array didn't match. Expected [" - + e.length + "] and Actual [" + a.length + "]."); - - for (int i = 0; i < e.length; i++) { - try { - Double expD = Double.valueOf((String) e[i]); - Double actD = Double.valueOf((String) a[i]); - - compareObject(prefix, expD, actD); - } catch (NumberFormatException ignore) { - compareObject(prefix, e[i], a[i]); - } - } - } else if (expected instanceof String) { - - try { - Double expD = Double.valueOf((String) expected); - Double actD = Double.valueOf((String) actual); - - compareObject(prefix, expD, actD); - } catch (NumberFormatException ignore) { - compareObject(prefix, expected, actual); - } - } else if (expected instanceof Boolean && actual instanceof String) { - - try { - - String actualString = Boolean.FALSE.toString(); - if ("y".equalsIgnoreCase((String) actual) - || "true".equalsIgnoreCase((String) actual)) { - actualString = Boolean.TRUE.toString(); - } - - compareObject(prefix, expected.toString(), actualString); - } catch (NumberFormatException ignore) { - compareObject(prefix, expected, actual); - } - } else if (expected instanceof Integer && actual instanceof BigDecimal) { - BigDecimal expectedBigDecimal = new BigDecimal((Integer) expected); - compareObject(prefix, expectedBigDecimal, actual); - - } else { - compareObject(prefix, expected, actual); - } - } - - private void compareObject(String prefix, Object expected, Object actual) { - if (!expected.equals(actual)) { - reportError(prefix + " didn't match. Expected Value[" + expected - + "] and Actual Value [" + actual + "]."); - } - } - - private boolean compareSize(String comp, List expSessions, List actualSessions) { - boolean equal = true; - if (expSessions.size() != actualSessions.size()) { - reportError(comp + "didn't match; Expected List size: " - + expSessions.size() + " -- Actual List size: " - + actualSessions.size()); - equal = false; - } - return equal; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.utilities; + +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.finra.jtaf.core.asserts.AssertionFailedError; + + +/** + * Utility class to perform comparison of lists and maps + */ +public class CompositeDataComparator { + + private List errorList; + private boolean accumulateErrors; + + public CompositeDataComparator() { + accumulateErrors = false; + } + + public CompositeDataComparator(boolean accumulateErrors) { + this.accumulateErrors = accumulateErrors; + errorList = new ArrayList(); + } + + public void compareMap(String title, String element, Map expComp, + Map actualComp) { + String prefix = getPrefix(title, element); + Set keySet = expComp.keySet(); + + for (Iterator iter = keySet.iterator(); iter.hasNext(); ) { + String obj = (String) iter.next(); + + Object eValue = expComp.get(obj); + + if (!actualComp.containsKey(obj)) { + reportError(prefix + " Couldn't find Element [" + obj + + "] in Actual Data"); + + } + Object aValue = actualComp.get(obj); + + assessAndCompare(prefix, obj, eValue, aValue); + } + } + + public void compareList(String title, String element, List expList, + List actualList) { + String prefix = getPrefix(title, element); + + if (compareSize(prefix, expList, actualList)) { + + for (int i = 0; i < expList.size(); i++) { + Object expected = expList.get(i); + Object actual = actualList.get(i); + + assessAndCompare(prefix + "[position : " + (i + 1) + "]", null, + expected, actual); + } + } + } + + /* + * for comparing untyped objects that may be instances of Boolean, String, String[], Timestamp, List, or Map + * lists and maps are internally tested for the same types recursively + * + * any other types on the basic or internal levels are compared as type Object + * + * if basic or internal Objects are both null they are considered equal + */ + public void compareObject(String title, String element, Object expected, Object actual) { + assessAndCompare(title, element, expected, actual); + } + + public List getErrorList() { + return errorList; + } + + /** + * Sets the accumulate errors flag + * + * @param accumulateErrors determines if the comparator will throw + * an exception with errors found, or accumulate them for later reporting + */ + public void setAccumulateErrors(boolean accumulateErrors) { + this.accumulateErrors = accumulateErrors; + if (accumulateErrors && errorList == null) { + errorList = new ArrayList(); + } + } + + /** + * Gets the accumulate errors flag + * + * @return the accumulate errors flag + */ + public boolean getAccumulateErrors() { + return this.accumulateErrors; + } + + private void reportError(String error) { + if (!accumulateErrors) + throw new AssertionFailedError(error); + else + errorList.add(error); + + } + + private String getPrefix(String title, String element) { + return (element == null && !"".equals(element)) ? title : title + "-> " + + element + " : "; + } + + private void assessAndCompare(String title, String element, + Object expected, Object actual) { + String prefix = getPrefix(title, element); + + if (expected == null && actual == null) { + return; + } else if (expected == null || actual == null) { + if ("".equals(expected) || "".equals(actual)) + return; + reportError(prefix + " didn't match. Expected Value[" + expected + + "] and Actual Value [" + actual + "]."); + } else if (expected instanceof Map) { + compareMap(title, element, (Map) expected, (Map) actual); + } else if (expected instanceof List) { + compareList(title, element, (List) expected, (List) actual); + } else if (expected instanceof Timestamp) { + Timestamp expTimestamp = (Timestamp) expected; + if (!(actual instanceof Timestamp)) + reportError(prefix + " Expected value [" + expTimestamp + + "] and Actual Value [" + actual + "]."); + + else + compareObject(prefix, expTimestamp, (Timestamp) actual); + } else if (expected instanceof String[]) { + String e[] = (String[]) expected; + String a[] = (String[]) actual; + + if (e.length != a.length) + reportError(prefix + + " Length of string array didn't match. Expected [" + + e.length + "] and Actual [" + a.length + "]."); + + for (int i = 0; i < e.length; i++) { + try { + Double expD = Double.valueOf((String) e[i]); + Double actD = Double.valueOf((String) a[i]); + + compareObject(prefix, expD, actD); + } catch (NumberFormatException ignore) { + compareObject(prefix, e[i], a[i]); + } + } + } else if (expected instanceof String) { + + try { + Double expD = Double.valueOf((String) expected); + Double actD = Double.valueOf((String) actual); + + compareObject(prefix, expD, actD); + } catch (NumberFormatException ignore) { + compareObject(prefix, expected, actual); + } + } else if (expected instanceof Boolean && actual instanceof String) { + + try { + + String actualString = Boolean.FALSE.toString(); + if ("y".equalsIgnoreCase((String) actual) + || "true".equalsIgnoreCase((String) actual)) { + actualString = Boolean.TRUE.toString(); + } + + compareObject(prefix, expected.toString(), actualString); + } catch (NumberFormatException ignore) { + compareObject(prefix, expected, actual); + } + } else if (expected instanceof Integer && actual instanceof BigDecimal) { + BigDecimal expectedBigDecimal = new BigDecimal((Integer) expected); + compareObject(prefix, expectedBigDecimal, actual); + + } else { + compareObject(prefix, expected, actual); + } + } + + private void compareObject(String prefix, Object expected, Object actual) { + if (!expected.equals(actual)) { + reportError(prefix + " didn't match. Expected Value[" + expected + + "] and Actual Value [" + actual + "]."); + } + } + + private boolean compareSize(String comp, List expSessions, List actualSessions) { + boolean equal = true; + if (expSessions.size() != actualSessions.size()) { + reportError(comp + "didn't match; Expected List size: " + + expSessions.size() + " -- Actual List size: " + + actualSessions.size()); + equal = false; + } + return equal; + } +} diff --git a/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java b/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java index 3adcdc3..977441b 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java +++ b/src/main/java/org/finra/jtaf/core/utilities/JTAFPropertyManager.java @@ -1,39 +1,39 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.utilities; - - -/** - * Responsible for reading properties configured in jtaf.properties file. - */ -public class JTAFPropertyManager extends PropertyManager { - private static JTAFPropertyManager instance; - - public static final String JTAF_PROPERTIES_FILE_NAME = "jtaf.properties"; - public static final String PROPERTY_PREFIX = "jtaf"; - - private JTAFPropertyManager() { - super(JTAF_PROPERTIES_FILE_NAME, PROPERTY_PREFIX); - } - - public static JTAFPropertyManager getInstance() { - if (instance == null) { - instance = new JTAFPropertyManager(); - } - return instance; - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.utilities; + + +/** + * Responsible for reading properties configured in jtaf.properties file. + */ +public class JTAFPropertyManager extends PropertyManager { + private static JTAFPropertyManager instance; + + public static final String JTAF_PROPERTIES_FILE_NAME = "jtaf.properties"; + public static final String PROPERTY_PREFIX = "jtaf"; + + private JTAFPropertyManager() { + super(JTAF_PROPERTIES_FILE_NAME, PROPERTY_PREFIX); + } + + public static JTAFPropertyManager getInstance() { + if (instance == null) { + instance = new JTAFPropertyManager(); + } + return instance; + } +} diff --git a/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java b/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java index 0ba9e87..62abe0e 100644 --- a/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java +++ b/src/main/java/org/finra/jtaf/core/utilities/PropertyManager.java @@ -1,77 +1,77 @@ -/* - * (C) Copyright 2014 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.core.utilities; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.PropertyResourceBundle; - -/** - * This class is similar to java Properties reader. It takes care of reading properties from the specified file. - * The difference however is, it allows to override any property by specifying it as a System - * property. - */ -public class PropertyManager { - - protected String fileName; - protected String propertyPrefix; - protected PropertyResourceBundle propertyResourceBundle; - - public PropertyManager(String fileName, String propertyPrefix) { - this.fileName = fileName; - this.propertyPrefix = propertyPrefix; - propertyResourceBundle = getPropertyResourceBundle(); - if (propertyResourceBundle != null) { - loadProperties(); - } - } - - public String getProperty(String propertyName) { - return System.getProperty(propertyPrefix + "." + propertyName); - } - - protected PropertyResourceBundle getPropertyResourceBundle() { - try { - InputStream inputStream = PropertyManager.class.getClassLoader() - .getResourceAsStream(fileName); - if (inputStream == null) { - File propertiesFile = new File(fileName); - inputStream = new FileInputStream(propertiesFile); - } - return new PropertyResourceBundle(inputStream); - } catch (FileNotFoundException fileNotFoundException) { - return null; - } catch (Exception exception) { - throw new RuntimeException("Problem loading properties", exception); - } - } - - protected void loadProperties() { - Enumeration keys = propertyResourceBundle.getKeys(); - while (keys.hasMoreElements()) { - String key = keys.nextElement(); - String newProperty = propertyResourceBundle.getString(key); - String newKey = propertyPrefix + "." + key; - if (System.getProperty(newKey) == null) { - System.setProperty(newKey, newProperty); - } - } - } -} +/* + * (C) Copyright 2014 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.core.utilities; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.PropertyResourceBundle; + +/** + * This class is similar to java Properties reader. It takes care of reading properties from the specified file. + * The difference however is, it allows to override any property by specifying it as a System + * property. + */ +public class PropertyManager { + + protected String fileName; + protected String propertyPrefix; + protected PropertyResourceBundle propertyResourceBundle; + + public PropertyManager(String fileName, String propertyPrefix) { + this.fileName = fileName; + this.propertyPrefix = propertyPrefix; + propertyResourceBundle = getPropertyResourceBundle(); + if (propertyResourceBundle != null) { + loadProperties(); + } + } + + public String getProperty(String propertyName) { + return System.getProperty(propertyPrefix + "." + propertyName); + } + + protected PropertyResourceBundle getPropertyResourceBundle() { + try { + InputStream inputStream = PropertyManager.class.getClassLoader() + .getResourceAsStream(fileName); + if (inputStream == null) { + File propertiesFile = new File(fileName); + inputStream = new FileInputStream(propertiesFile); + } + return new PropertyResourceBundle(inputStream); + } catch (FileNotFoundException fileNotFoundException) { + return null; + } catch (Exception exception) { + throw new RuntimeException("Problem loading properties", exception); + } + } + + protected void loadProperties() { + Enumeration keys = propertyResourceBundle.getKeys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + String newProperty = propertyResourceBundle.getString(key); + String newKey = propertyPrefix + "." + key; + if (System.getProperty(newKey) == null) { + System.setProperty(newKey, newProperty); + } + } + } +} diff --git a/src/main/resources/framework.xml b/src/main/resources/framework.xml index d927180..1d20929 100644 --- a/src/main/resources/framework.xml +++ b/src/main/resources/framework.xml @@ -1,35 +1,35 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/testlibrary/context.commands.xml b/src/main/resources/testlibrary/context.commands.xml index c9ca8f7..257e738 100644 --- a/src/main/resources/testlibrary/context.commands.xml +++ b/src/main/resources/testlibrary/context.commands.xml @@ -1,149 +1,149 @@ - - - - - - Gets a list from context and adds its elements to another list stored in the context - - - Name of the list in the context to which addlist's elements are added - Name of the list in the context whose elements will be added to tolist - - - The index of the tolist at which the elements of the addlist should get added (default: size of tolist) - - - The list with all of the elements in it. The name will be the value of tolist - - - - - Gets an object from context and adds that object into a list in the context - - - Name of list in context to which object will get added - Name of the object in context to add to list - - - The index of the list at which object should get added (default: size of list) - - - The list with the object in it. The name will be the value of list - - - - - Gets an object from context and puts it into a map in context - - - Name of map in context - Name of the object in context to put into map - The key to use for the object's new map entry - - - The map with the object put in it. The name will be the value of map - - - - - Removes an object from context by replacing it with null - - - Name of the object in context to remove - - - Null value stored as the value of object in the context - - - - - Gets an object at a specified index from a list in context and stores that object into context - - - Name of list in context to get object from - Name of context key for which the object will get stored - - - The index of the list to get (default: size of list) - - - The object pulled from the list will get pushed into the context with the name as the value of objectKey - - - - - Gets an object from a map in context and stores that object into context - - - Name of map in context to get object from - Name of context key for which the object will get stored - The key of the object to grab in the map - - - The object pulled from the map is pushed to the context with its name as objectKey - - - - - Gets an object from context and stores that object into another attribute - - - Context key from which to get the object - Context key to which the object should be stored - - - Stores the object into the storeKey specified above - - - - - Gets an object from context and restores that object into context with its .toString() value - - - Name of the key whose object will be restored in the context as a String - - - The String value of the object will be restored for the key - - - - Verifies an object in context against another according to the expected object's type (ie: if map, then compare size and all keys/values) - - Context key of the actual object to compare - Context key of the expected object to compare - - - The display name of the object being verified (for error reporting purposes) - True by default. When the actual object does not equal the expected object, an AssertionFailedError will be thrown - - - A list of error messages received when trying to compare equality of actual and expected - - - - - Stores a default value into context unless the object already exists in context - - - Key to store the default object if not yet stored in the context - - - If specified, the object in the context pulled with this value as its key will become the default value - The default value to use if no defaultKey specified. Note that this can be any sort of variable in the test script with name='default' (string, list, map, integer, etc.) - - - Stores it into the object name specified above - - - - + + + + + + Gets a list from context and adds its elements to another list stored in the context + + + Name of the list in the context to which addlist's elements are added + Name of the list in the context whose elements will be added to tolist + + + The index of the tolist at which the elements of the addlist should get added (default: size of tolist) + + + The list with all of the elements in it. The name will be the value of tolist + + + + + Gets an object from context and adds that object into a list in the context + + + Name of list in context to which object will get added + Name of the object in context to add to list + + + The index of the list at which object should get added (default: size of list) + + + The list with the object in it. The name will be the value of list + + + + + Gets an object from context and puts it into a map in context + + + Name of map in context + Name of the object in context to put into map + The key to use for the object's new map entry + + + The map with the object put in it. The name will be the value of map + + + + + Removes an object from context by replacing it with null + + + Name of the object in context to remove + + + Null value stored as the value of object in the context + + + + + Gets an object at a specified index from a list in context and stores that object into context + + + Name of list in context to get object from + Name of context key for which the object will get stored + + + The index of the list to get (default: size of list) + + + The object pulled from the list will get pushed into the context with the name as the value of objectKey + + + + + Gets an object from a map in context and stores that object into context + + + Name of map in context to get object from + Name of context key for which the object will get stored + The key of the object to grab in the map + + + The object pulled from the map is pushed to the context with its name as objectKey + + + + + Gets an object from context and stores that object into another attribute + + + Context key from which to get the object + Context key to which the object should be stored + + + Stores the object into the storeKey specified above + + + + + Gets an object from context and restores that object into context with its .toString() value + + + Name of the key whose object will be restored in the context as a String + + + The String value of the object will be restored for the key + + + + Verifies an object in context against another according to the expected object's type (ie: if map, then compare size and all keys/values) + + Context key of the actual object to compare + Context key of the expected object to compare + + + The display name of the object being verified (for error reporting purposes) + True by default. When the actual object does not equal the expected object, an AssertionFailedError will be thrown + + + A list of error messages received when trying to compare equality of actual and expected + + + + + Stores a default value into context unless the object already exists in context + + + Key to store the default object if not yet stored in the context + + + If specified, the object in the context pulled with this value as its key will become the default value + The default value to use if no defaultKey specified. Note that this can be any sort of variable in the test script with name='default' (string, list, map, integer, etc.) + + + Stores it into the object name specified above + + + + diff --git a/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java b/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java index 9a9d084..d774e9b 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/AssertionFailedErrorTest.java @@ -1,35 +1,35 @@ -package org.finra.jtaf.core.asserts; - -import org.finra.jtaf.core.asserts.AssertionFailedError; -import org.junit.Assert; - -import org.junit.Test; - - -public class AssertionFailedErrorTest { - - public void testAssertionFailedErrorMessage1() { - AssertionFailedError e = new AssertionFailedError(null); - Assert.assertEquals("", e.getMessage()); - } - - public void testAssertionFailedErrorMessage2() { - AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); - Assert.assertEquals("This is an assertion failed", e.getMessage()); - } - - @Test(expected = AssertionFailedError.class) - public void testAssertionFailedError1() { - AssertionFailedError e = new AssertionFailedError(null); - Assert.assertEquals("", e.getMessage()); - throw e; - } - - @Test(expected = AssertionFailedError.class) - public void testAssertionFailedError2() { - AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); - Assert.assertEquals("This is an assertion failed", e.getMessage()); - throw e; - } - -} +package org.finra.jtaf.core.asserts; + +import org.finra.jtaf.core.asserts.AssertionFailedError; +import org.junit.Assert; + +import org.junit.Test; + + +public class AssertionFailedErrorTest { + + public void testAssertionFailedErrorMessage1() { + AssertionFailedError e = new AssertionFailedError(null); + Assert.assertEquals("", e.getMessage()); + } + + public void testAssertionFailedErrorMessage2() { + AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); + Assert.assertEquals("This is an assertion failed", e.getMessage()); + } + + @Test(expected = AssertionFailedError.class) + public void testAssertionFailedError1() { + AssertionFailedError e = new AssertionFailedError(null); + Assert.assertEquals("", e.getMessage()); + throw e; + } + + @Test(expected = AssertionFailedError.class) + public void testAssertionFailedError2() { + AssertionFailedError e = new AssertionFailedError("This is an assertion failed"); + Assert.assertEquals("This is an assertion failed", e.getMessage()); + throw e; + } + +} diff --git a/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java b/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java index 583063f..8f9f937 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/ErrorAccumulatorTest.java @@ -1,112 +1,112 @@ -package org.finra.jtaf.core.asserts; - -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.asserts.ErrorAccumulator; -import org.junit.Assert; -import org.junit.Test; - -public class ErrorAccumulatorTest { - - @Test - public void testErrorAccumulatorConstructAndGetName() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("test", ea.getName()); - } - - @Test - public void testErrorAccumulatorSetAndGetName() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("test", ea.getName()); - } - - @Test - public void testErrorAccumulatorAddErrorsAndGetNumErrors() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertTrue(ea.isEmpty()); - ea.addError(new Throwable()); - Assert.assertEquals(ea.getNumErrors(), 1); - ea.addError(new Exception()); - Assert.assertEquals(ea.getNumErrors(), 2); - ea.addError(new RuntimeException()); - Assert.assertEquals(ea.getNumErrors(), 3); - } - - @Test - public void testErrorAccumulatorGetErrorMessages() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - ea.addError(new Exception("This is a test message")); - ea.addError(new RuntimeException("This is another test message")); - ea.addError(new Exception()); - String errorMessagesExpected = "\n This is a test message\n This is another test message\n null"; - Assert.assertEquals(errorMessagesExpected, ea.getErrorMessages()); - } - - @Test - public void testErrorAccumulatorGetErrorStackTraces() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - - StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); - StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements = {ste1, ste2}; - Throwable t = new Throwable(); - t.setStackTrace(elements); - ea.addError(t); - - StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); - StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements2 = {ste3, ste4}; - Throwable t2 = new Throwable(); - t2.setStackTrace(elements2); - ea.addError(t2); - - - String errorStackTracesExpected = "\n java.lang.Throwable\n\tat Banana.unpeel(helloworld.txt:47)\n\t" + - "at Orange.unpeel(helloworld.txt:49)\n\n java.lang.Throwable\n\tat Apple.unpeel(helloworld.txt:47)" + - "\n\tat Pear.unpeel(helloworld.txt:49)"; - Assert.assertEquals(errorStackTracesExpected.replaceAll("[\t\n\r]", ""), - ea.getErrorStackTraces().replaceAll("[\t\n\r]", "")); - } - - @Test - public void testErrorAccumulatorGetErrorStackTraceElements() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - - StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); - StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements = {ste1, ste2}; - Throwable t = new Throwable(); - t.setStackTrace(elements); - ea.addError(t); - - StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); - StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); - StackTraceElement[] elements2 = {ste3, ste4}; - Throwable t2 = new Throwable(); - t2.setStackTrace(elements2); - ea.addError(t2); - - - List expected = new ArrayList(); - expected.add(elements); - expected.add(elements2); - - Assert.assertArrayEquals(expected.get(0), ea.getErrorStackTraceElementsList().get(0)); - Assert.assertArrayEquals(expected.get(1), ea.getErrorStackTraceElementsList().get(1)); - } - - @Test - public void testThrowErrorsWhenNone() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - ea.throwErrors(); - // shouldn't throw any exceptions - } - - @Test - public void testWrappedErrorsWhenNone() { - ErrorAccumulator ea = new ErrorAccumulator("test"); - Assert.assertEquals("Get wrapped errors wasn't null", null, ea.getWrappedErrors()); - } - -} +package org.finra.jtaf.core.asserts; + +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.asserts.ErrorAccumulator; +import org.junit.Assert; +import org.junit.Test; + +public class ErrorAccumulatorTest { + + @Test + public void testErrorAccumulatorConstructAndGetName() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("test", ea.getName()); + } + + @Test + public void testErrorAccumulatorSetAndGetName() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("test", ea.getName()); + } + + @Test + public void testErrorAccumulatorAddErrorsAndGetNumErrors() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertTrue(ea.isEmpty()); + ea.addError(new Throwable()); + Assert.assertEquals(ea.getNumErrors(), 1); + ea.addError(new Exception()); + Assert.assertEquals(ea.getNumErrors(), 2); + ea.addError(new RuntimeException()); + Assert.assertEquals(ea.getNumErrors(), 3); + } + + @Test + public void testErrorAccumulatorGetErrorMessages() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + ea.addError(new Exception("This is a test message")); + ea.addError(new RuntimeException("This is another test message")); + ea.addError(new Exception()); + String errorMessagesExpected = "\n This is a test message\n This is another test message\n null"; + Assert.assertEquals(errorMessagesExpected, ea.getErrorMessages()); + } + + @Test + public void testErrorAccumulatorGetErrorStackTraces() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + + StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); + StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements = {ste1, ste2}; + Throwable t = new Throwable(); + t.setStackTrace(elements); + ea.addError(t); + + StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); + StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements2 = {ste3, ste4}; + Throwable t2 = new Throwable(); + t2.setStackTrace(elements2); + ea.addError(t2); + + + String errorStackTracesExpected = "\n java.lang.Throwable\n\tat Banana.unpeel(helloworld.txt:47)\n\t" + + "at Orange.unpeel(helloworld.txt:49)\n\n java.lang.Throwable\n\tat Apple.unpeel(helloworld.txt:47)" + + "\n\tat Pear.unpeel(helloworld.txt:49)"; + Assert.assertEquals(errorStackTracesExpected.replaceAll("[\t\n\r]", ""), + ea.getErrorStackTraces().replaceAll("[\t\n\r]", "")); + } + + @Test + public void testErrorAccumulatorGetErrorStackTraceElements() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + + StackTraceElement ste1 = new StackTraceElement("Banana", "unpeel", "helloworld.txt", 47); + StackTraceElement ste2 = new StackTraceElement("Orange", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements = {ste1, ste2}; + Throwable t = new Throwable(); + t.setStackTrace(elements); + ea.addError(t); + + StackTraceElement ste3 = new StackTraceElement("Apple", "unpeel", "helloworld.txt", 47); + StackTraceElement ste4 = new StackTraceElement("Pear", "unpeel", "helloworld.txt", 49); + StackTraceElement[] elements2 = {ste3, ste4}; + Throwable t2 = new Throwable(); + t2.setStackTrace(elements2); + ea.addError(t2); + + + List expected = new ArrayList(); + expected.add(elements); + expected.add(elements2); + + Assert.assertArrayEquals(expected.get(0), ea.getErrorStackTraceElementsList().get(0)); + Assert.assertArrayEquals(expected.get(1), ea.getErrorStackTraceElementsList().get(1)); + } + + @Test + public void testThrowErrorsWhenNone() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + ea.throwErrors(); + // shouldn't throw any exceptions + } + + @Test + public void testWrappedErrorsWhenNone() { + ErrorAccumulator ea = new ErrorAccumulator("test"); + Assert.assertEquals("Get wrapped errors wasn't null", null, ea.getWrappedErrors()); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java b/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java index 523c474..7469f25 100644 --- a/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java +++ b/src/test/java/org/finra/jtaf/core/asserts/IgnoreErrorsAssertTest.java @@ -1,600 +1,600 @@ -package org.finra.jtaf.core.asserts; - -import org.junit.Assert; -import org.junit.Test; - -public class IgnoreErrorsAssertTest { - - @Test - public void testAssertTrueWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue("This was a failure", false); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertTrueWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue("Hopefully there's no failure here", true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertTrueWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue(false); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertTrueWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertTrue(true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse("Hopefully there's no failure here", false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse("This was a failure", true); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertFalseWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse(false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFalseWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertFalse(true); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testFailWithMessage() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.fail("Failure"); - Assert.assertEquals("\n Failure", iea.checkErrors()); - } - - @Test - public void testFail() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.fail(); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenNull() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object) null, (Object) null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (Object) "", (Object) ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (Object) "", (Object) " "); - Assert.assertEquals("\n This was a failure expected:<> but was:< >", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object) "", (Object) ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertObjectEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((Object) "", (Object) " "); - Assert.assertEquals("\n expected:<> but was:< >", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", "", " "); - Assert.assertEquals("\n This was a failure expected:<[]> but was:<[ ]>", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", "", ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("", " "); - Assert.assertEquals("\n expected:<[]> but was:<[ ]>", iea.checkErrors()); - } - - @Test - public void testAssertStringEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("", ""); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenEqual() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .05, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", .05, .08, .02); - Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", .05, .06, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .08, .02); - Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertDoubleEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05, .06, .02); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenEqual() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .05f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", .05f, .08f, .02f); - Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", .05f, .06f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .08f, .02f); - Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); - } - - @Test - public void testAssertFloatEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(.05f, .06f, .02f); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (long) 100, (long) 101); - Assert.assertEquals("\n This was a failure expected:<100> but was:<101>", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (long) 100, (long) 100); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((long) 100, (long) 101); - Assert.assertEquals("\n expected:<100> but was:<101>", iea.checkErrors()); - } - - @Test - public void testAssertLongEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((long) 100, (long) 100); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenFalse1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", true, false); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenFalse2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", false, true); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenTrue1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", true, true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWithMessageWhenTrue2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", false, false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenFalse1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(true, false); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenFalse2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(false, true); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenTrue1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(true, true); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertBooleanEqualsWhenTrue2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(false, false); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (byte) 14, (byte) 15); - Assert.assertEquals("\n This was a failure expected:<14> but was:<15>", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (byte) 4, (byte) 4); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((byte) 14, (byte) 15); - Assert.assertEquals("\n expected:<14> but was:<15>", iea.checkErrors()); - } - - @Test - public void testAssertByteEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((byte) 4, (byte) 4); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", 'a', 'b'); - Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", 'a', 'a'); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals('a', 'b'); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testAssertCharEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals('a', 'a'); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", (short) 1, (short) 2); - Assert.assertEquals("\n This was a failure expected:<1> but was:<2>", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", (short) 1, (short) 1); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((short) 1, (short) 2); - Assert.assertEquals("\n expected:<1> but was:<2>", iea.checkErrors()); - } - - @Test - public void testAssertShortEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals((short) 1, (short) 1); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("This was a failure", 5, 8); - Assert.assertEquals("\n This was a failure expected:<5> but was:<8>", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals("Hopefully there's no failure here", 5, 5); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(5, 8); - Assert.assertEquals("\n expected:<5> but was:<8>", iea.checkErrors()); - } - - @Test - public void testAssertIntegerEqualsWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertEquals(5, 5); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull("This was a failure", null); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull("Hopefully there's no failure here", new Object()); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull(null); - Assert.assertEquals("\n null", iea.checkErrors()); - } - - @Test - public void testAssertNotNullWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNotNull(new Object()); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNullWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull("This was a failure", new Object()); - Assert.assertEquals("\n This was a failure", iea.checkErrors()); - } - - @Test - public void testAssertNullWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull("Hopefully there's no failure here", null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNullWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String superman = "superman"; - iea.assertNull(superman); - Assert.assertEquals("\n Expected: but was: superman", iea.checkErrors()); - } - - @Test - public void testAssertNullWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.assertNull(null); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertSameWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.assertSame("This was a failure", a, b); - Assert.assertEquals("\n This was a failure expected same: was not:", iea.checkErrors()); - } - - @Test - public void testAssertSameWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertSame("Hopefully there's no failure here", a, a); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertSameWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.assertSame(a, b); - Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); - } - - @Test - public void testAssertSameWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertSame(a, a); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWithMessageWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - iea.assertNotSame("This was a failure", a, a); - Assert.assertEquals("\n This was a failure expected not same", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWithMessageWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - Object b = new Object(); - iea.assertNotSame("Hopefully there's no failure here", a, b); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWhenFalse() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.assertNotSame(a, a); - Assert.assertEquals("\n expected not same", iea.checkErrors()); - } - - @Test - public void testAssertNotSameWhenTrue() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Object a = new Object(); - Object b = new Object(); - iea.assertNotSame(a, b); - Assert.assertEquals("", iea.checkErrors()); - } - - @Test - public void testFailSame1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.failSame("This is an error message"); - Assert.assertEquals("\n This is an error message expected not same", iea.checkErrors()); - } - - @Test - public void testFailSame2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - iea.failSame(null); - Assert.assertEquals("\n expected not same", iea.checkErrors()); - } - - @Test - public void testFailNotSame1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.failNotSame("This is an error message", a, a); - Assert.assertEquals("\n This is an error message expected same: was not:", iea.checkErrors()); - } - - @Test - public void testFailNotSame2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - iea.failNotSame(null, a, a); - Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); - } - - @Test - public void testFailNotEquals1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals("This is an error message", a, b); - Assert.assertEquals("\n This is an error message expected: but was:", iea.checkErrors()); - } - - @Test - public void testFailNotEquals2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals(null, a, b); - Assert.assertEquals("\n expected: but was:", iea.checkErrors()); - } - - @Test - public void testFormat1() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Assert.assertEquals("This is an error message expected: but was:", iea.format("This is an error message", "Superman", "Batman")); - } - - @Test - public void testFormat2() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - Assert.assertEquals("expected: but was:", iea.format(null, "Superman", "Batman")); - } - - @Test(expected = AssertionFailedError.class) - public void testEndOfCommand() { - IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); - String a = "tomato"; - String b = "tomatoh"; - iea.failNotEquals(null, a, b); - iea.endOfCommand(); - } -} +package org.finra.jtaf.core.asserts; + +import org.junit.Assert; +import org.junit.Test; + +public class IgnoreErrorsAssertTest { + + @Test + public void testAssertTrueWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue("This was a failure", false); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertTrueWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue("Hopefully there's no failure here", true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertTrueWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue(false); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertTrueWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertTrue(true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse("Hopefully there's no failure here", false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse("This was a failure", true); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertFalseWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse(false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFalseWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertFalse(true); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testFailWithMessage() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.fail("Failure"); + Assert.assertEquals("\n Failure", iea.checkErrors()); + } + + @Test + public void testFail() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.fail(); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenNull() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) null, (Object) null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (Object) "", (Object) ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (Object) "", (Object) " "); + Assert.assertEquals("\n This was a failure expected:<> but was:< >", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) "", (Object) ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertObjectEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((Object) "", (Object) " "); + Assert.assertEquals("\n expected:<> but was:< >", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", "", " "); + Assert.assertEquals("\n This was a failure expected:<[]> but was:<[ ]>", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", "", ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("", " "); + Assert.assertEquals("\n expected:<[]> but was:<[ ]>", iea.checkErrors()); + } + + @Test + public void testAssertStringEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("", ""); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenEqual() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .05, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", .05, .08, .02); + Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", .05, .06, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .08, .02); + Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertDoubleEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05, .06, .02); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenEqual() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .05f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", .05f, .08f, .02f); + Assert.assertEquals("\n This was a failure expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", .05f, .06f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .08f, .02f); + Assert.assertEquals("\n expected:<0.05> but was:<0.08>", iea.checkErrors()); + } + + @Test + public void testAssertFloatEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(.05f, .06f, .02f); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (long) 100, (long) 101); + Assert.assertEquals("\n This was a failure expected:<100> but was:<101>", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (long) 100, (long) 100); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((long) 100, (long) 101); + Assert.assertEquals("\n expected:<100> but was:<101>", iea.checkErrors()); + } + + @Test + public void testAssertLongEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((long) 100, (long) 100); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenFalse1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", true, false); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenFalse2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", false, true); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenTrue1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", true, true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWithMessageWhenTrue2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", false, false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenFalse1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(true, false); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenFalse2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(false, true); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenTrue1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(true, true); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertBooleanEqualsWhenTrue2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(false, false); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (byte) 14, (byte) 15); + Assert.assertEquals("\n This was a failure expected:<14> but was:<15>", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (byte) 4, (byte) 4); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((byte) 14, (byte) 15); + Assert.assertEquals("\n expected:<14> but was:<15>", iea.checkErrors()); + } + + @Test + public void testAssertByteEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((byte) 4, (byte) 4); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", 'a', 'b'); + Assert.assertEquals("\n This was a failure expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", 'a', 'a'); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals('a', 'b'); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testAssertCharEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals('a', 'a'); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", (short) 1, (short) 2); + Assert.assertEquals("\n This was a failure expected:<1> but was:<2>", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", (short) 1, (short) 1); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((short) 1, (short) 2); + Assert.assertEquals("\n expected:<1> but was:<2>", iea.checkErrors()); + } + + @Test + public void testAssertShortEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals((short) 1, (short) 1); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("This was a failure", 5, 8); + Assert.assertEquals("\n This was a failure expected:<5> but was:<8>", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals("Hopefully there's no failure here", 5, 5); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(5, 8); + Assert.assertEquals("\n expected:<5> but was:<8>", iea.checkErrors()); + } + + @Test + public void testAssertIntegerEqualsWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertEquals(5, 5); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull("This was a failure", null); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull("Hopefully there's no failure here", new Object()); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull(null); + Assert.assertEquals("\n null", iea.checkErrors()); + } + + @Test + public void testAssertNotNullWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNotNull(new Object()); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNullWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull("This was a failure", new Object()); + Assert.assertEquals("\n This was a failure", iea.checkErrors()); + } + + @Test + public void testAssertNullWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull("Hopefully there's no failure here", null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNullWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String superman = "superman"; + iea.assertNull(superman); + Assert.assertEquals("\n Expected: but was: superman", iea.checkErrors()); + } + + @Test + public void testAssertNullWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.assertNull(null); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertSameWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.assertSame("This was a failure", a, b); + Assert.assertEquals("\n This was a failure expected same: was not:", iea.checkErrors()); + } + + @Test + public void testAssertSameWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertSame("Hopefully there's no failure here", a, a); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertSameWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.assertSame(a, b); + Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); + } + + @Test + public void testAssertSameWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertSame(a, a); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWithMessageWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + iea.assertNotSame("This was a failure", a, a); + Assert.assertEquals("\n This was a failure expected not same", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWithMessageWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + Object b = new Object(); + iea.assertNotSame("Hopefully there's no failure here", a, b); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWhenFalse() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.assertNotSame(a, a); + Assert.assertEquals("\n expected not same", iea.checkErrors()); + } + + @Test + public void testAssertNotSameWhenTrue() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Object a = new Object(); + Object b = new Object(); + iea.assertNotSame(a, b); + Assert.assertEquals("", iea.checkErrors()); + } + + @Test + public void testFailSame1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.failSame("This is an error message"); + Assert.assertEquals("\n This is an error message expected not same", iea.checkErrors()); + } + + @Test + public void testFailSame2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + iea.failSame(null); + Assert.assertEquals("\n expected not same", iea.checkErrors()); + } + + @Test + public void testFailNotSame1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.failNotSame("This is an error message", a, a); + Assert.assertEquals("\n This is an error message expected same: was not:", iea.checkErrors()); + } + + @Test + public void testFailNotSame2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + iea.failNotSame(null, a, a); + Assert.assertEquals("\n expected same: was not:", iea.checkErrors()); + } + + @Test + public void testFailNotEquals1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals("This is an error message", a, b); + Assert.assertEquals("\n This is an error message expected: but was:", iea.checkErrors()); + } + + @Test + public void testFailNotEquals2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals(null, a, b); + Assert.assertEquals("\n expected: but was:", iea.checkErrors()); + } + + @Test + public void testFormat1() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Assert.assertEquals("This is an error message expected: but was:", iea.format("This is an error message", "Superman", "Batman")); + } + + @Test + public void testFormat2() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + Assert.assertEquals("expected: but was:", iea.format(null, "Superman", "Batman")); + } + + @Test(expected = AssertionFailedError.class) + public void testEndOfCommand() { + IgnoreErrorsAssert iea = new IgnoreErrorsAssert(new ErrorAccumulator("test")); + String a = "tomato"; + String b = "tomatoh"; + iea.failNotEquals(null, a, b); + iea.endOfCommand(); + } +} diff --git a/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java index 41d8223..a61e799 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ByeCommand.java @@ -1,19 +1,19 @@ -package org.finra.jtaf.core.commands; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class ByeCommand extends Command { - - public ByeCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data", "Bye !"); - } - -} +package org.finra.jtaf.core.commands; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class ByeCommand extends Command { + + public ByeCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Bye !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java index afb5da1..5bb6563 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedByeCommand.java @@ -1,18 +1,18 @@ -package org.finra.jtaf.core.commands; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; - -public class ExtendedByeCommand extends ByeCommand { - - public ExtendedByeCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data", "Bye Bye " + getContext().getObject("data")); - } - -} +package org.finra.jtaf.core.commands; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; + +public class ExtendedByeCommand extends ByeCommand { + + public ExtendedByeCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Bye Bye " + getContext().getObject("data")); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java index 95de466..347a87f 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedHelloCommand.java @@ -1,19 +1,19 @@ -package org.finra.jtaf.core.commands; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; - -public class ExtendedHelloCommand extends HelloCommand { - - public ExtendedHelloCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - super.execute(ctx); - String data = (String) getContext().getObject("data"); - data = "Hello Hello" + data; - } +package org.finra.jtaf.core.commands; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; + +public class ExtendedHelloCommand extends HelloCommand { + + public ExtendedHelloCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + super.execute(ctx); + String data = (String) getContext().getObject("data"); + data = "Hello Hello" + data; + } } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java index 27d9498..89e1548 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyByeCommand.java @@ -1,21 +1,21 @@ -package org.finra.jtaf.core.commands; - - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class ExtendedVerifyByeCommand extends Command { - - public ExtendedVerifyByeCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data", ""); - Assert.assertEquals(data, "Bye Bye Bye !"); - } - -} +package org.finra.jtaf.core.commands; + + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class ExtendedVerifyByeCommand extends Command { + + public ExtendedVerifyByeCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Bye Bye Bye !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java index d2e17de..a4bc970 100644 --- a/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/ExtendedVerifyHelloCommand.java @@ -1,21 +1,21 @@ -package org.finra.jtaf.core.commands; - - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class ExtendedVerifyHelloCommand extends Command { - - public ExtendedVerifyHelloCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data", ""); - Assert.assertEquals(data, "Hello Hello Hello World !"); - } - -} +package org.finra.jtaf.core.commands; + + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class ExtendedVerifyHelloCommand extends Command { + + public ExtendedVerifyHelloCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Hello Hello Hello World !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java index 94479f8..326e96c 100644 --- a/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/HelloCommand.java @@ -1,19 +1,19 @@ -package org.finra.jtaf.core.commands; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class HelloCommand extends Command { - - public HelloCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getContext().putObject("data", "Hello World !"); - } - -} +package org.finra.jtaf.core.commands; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class HelloCommand extends Command { + + public HelloCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getContext().putObject("data", "Hello World !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java b/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java index 004a7ed..4537c36 100644 --- a/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/RandomGeneratorTest.java @@ -1,287 +1,287 @@ -package org.finra.jtaf.core.commands; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.execution.Interpreter; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - -public class RandomGeneratorTest { - - private static AutomationEngine engine = null; - private static TestAgenda testAgenda = null; - private static boolean setup = false; - private static TestScript generateRegexp = null; - private static TestScript generateRegexp2 = null; - private static TestScript generatePhone = null; - private static TestScript generateAbbrevUSState = null; - private static TestScript generateUSState = null; - private static TestScript generateNumber = null; - private static TestScript generateNumber2 = null; - private static TestScript generateNumber3 = null; - private static TestScript generateNumber4 = null; - private static TestScript generateString = null; - private static TestScript generateString2 = null; - private static TestScript generateString3 = null; - private static TestScript generateString4 = null; - private static TestScript generateString5 = null; - - final static public List abbrevUSState = new ArrayList(Arrays.asList("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", - "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); - - final static public List USState = new ArrayList(Arrays.asList("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", - "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", - "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", - "Wisconsin", "Wyoming")); - public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; - - @Before - public void setup() { - - engine = AutomationEngine.getInstance(); - - if (engine.getTestAgenda() == null) { - engine.buildModel(new File("testlibrary"), new File("testscripts")); -// engine.setDependenciesOn(false); - testAgenda = engine.getTestAgenda(); - - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); - } - - - if (!setup) { - testAgenda = engine.getTestAgenda(); - - for (TestScript testScript : testAgenda.getTestScripts()) { - String temp = testScript.getName(); - temp = temp.replace(testScript.getFileName(), ""); - if (temp.equals("GenerateRegexp")) - generateRegexp = testScript; - if (temp.equals("GenerateRegexp2")) - generateRegexp2 = testScript; - if (temp.equals("GeneratePhone")) - generatePhone = testScript; - if (temp.equals("GenerateAbbrevUSState")) - generateAbbrevUSState = testScript; - if (temp.equals("GenerateUSState")) - generateUSState = testScript; - if (temp.equals("GenerateNumber")) - generateNumber = testScript; - if (temp.equals("GenerateNumber2")) - generateNumber2 = testScript; - if (temp.equals("GenerateNumber3")) - generateNumber3 = testScript; - if (temp.equals("GenerateNumber4")) - generateNumber4 = testScript; - if (temp.equals("GenerateString")) - generateString = testScript; - if (temp.equals("GenerateString2")) - generateString2 = testScript; - if (temp.equals("GenerateString3")) - generateString3 = testScript; - if (temp.equals("GenerateString4")) - generateString4 = testScript; - if (temp.equals("GenerateString5")) - generateString5 = testScript; - } - } - setup = true; - } - - @Test - public void testGenerateRegexp() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateRegexp); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); - } - - @Test - public void testGenerateRegexp2() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateRegexp2); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); - } - - @Test - public void testGeneratePhone() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generatePhone); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Phone regex failed", str.matches("[0-9]{10}")); - } - - @Test - public void testGenerateAbbrevUSState() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateAbbrevUSState); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generated was not an abbreviated US state", abbrevUSState.contains(str)); - } - - @Test - public void testGenerateUSState() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateUSState); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generated was not an abbreviated US state", USState.contains(str)); - } - - /*** - * Tests Number Generated with default length (5) - * - * @throws Throwable - */ - @Test - public void testGenerateNumber() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateNumber); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); - } - - /*** - * Tests Number Generated with length = 7 - * - * @throws Throwable - */ - @Test - public void testGenerateNumber2() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateNumber2); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Number generation failed", str.matches("[0-9]{7}")); - } - - /*** - * Tests Number Generated between 10 and 100 - * - * @throws Throwable - */ - @Test - public void testGenerateNumber3() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateNumber3); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - int num = Integer.parseInt(str); - Assert.assertTrue("Number generation failed", 10 <= num && num <= 100); - } - - /*** - * Test number generated with min specified but no max, so use default length (5) - * - * @throws Throwable - */ - @Test - public void testGenerateNumber4() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateNumber4); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); - } - - /*** - * Tests String generated with default length (5) - * - * @throws Throwable - */ - @Test - public void testGenerateString() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateString); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); - } - - /*** - * Tests String generated with length = 7 - * - * @throws Throwable - */ - @Test - public void testGenerateString2() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateString2); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); - } - - /** - * Tests String with length in range from 5-10 characters - * - * @throws Throwable - */ - @Test - public void testGenerateString3() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateString3); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5,10}")); - } - - /** - * Tests String with length = 7 when min length is specified without a max - * - * @throws Throwable - */ - @Test - public void testGenerateString4() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateString4); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); - } - - /** - * Tests String with default length (5) when min length is specified without a max - * - * @throws Throwable - */ - @Test - public void testGenerateString5() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(generateString5); - if (!tr.isTestPassed()) - Assert.fail("JTAF Test failed: " + tr.getFailureReason()); - String str = "" + Command.getFromGlobalContext("it"); - Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); - } - -} +package org.finra.jtaf.core.commands; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.execution.Interpreter; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class RandomGeneratorTest { + + private static AutomationEngine engine = null; + private static TestAgenda testAgenda = null; + private static boolean setup = false; + private static TestScript generateRegexp = null; + private static TestScript generateRegexp2 = null; + private static TestScript generatePhone = null; + private static TestScript generateAbbrevUSState = null; + private static TestScript generateUSState = null; + private static TestScript generateNumber = null; + private static TestScript generateNumber2 = null; + private static TestScript generateNumber3 = null; + private static TestScript generateNumber4 = null; + private static TestScript generateString = null; + private static TestScript generateString2 = null; + private static TestScript generateString3 = null; + private static TestScript generateString4 = null; + private static TestScript generateString5 = null; + + final static public List abbrevUSState = new ArrayList(Arrays.asList("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", + "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY")); + + final static public List USState = new ArrayList(Arrays.asList("Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", + "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Island", "Virginia", "Washington", "West Virginia", + "Wisconsin", "Wyoming")); + public static final String charsForRandomString = "qwertyuioplkjhgfdsazxcvbnm"; + + @Before + public void setup() { + + engine = AutomationEngine.getInstance(); + + if (engine.getTestAgenda() == null) { + engine.buildModel(new File("testlibrary"), new File("testscripts")); +// engine.setDependenciesOn(false); + testAgenda = engine.getTestAgenda(); + + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + } + + + if (!setup) { + testAgenda = engine.getTestAgenda(); + + for (TestScript testScript : testAgenda.getTestScripts()) { + String temp = testScript.getName(); + temp = temp.replace(testScript.getFileName(), ""); + if (temp.equals("GenerateRegexp")) + generateRegexp = testScript; + if (temp.equals("GenerateRegexp2")) + generateRegexp2 = testScript; + if (temp.equals("GeneratePhone")) + generatePhone = testScript; + if (temp.equals("GenerateAbbrevUSState")) + generateAbbrevUSState = testScript; + if (temp.equals("GenerateUSState")) + generateUSState = testScript; + if (temp.equals("GenerateNumber")) + generateNumber = testScript; + if (temp.equals("GenerateNumber2")) + generateNumber2 = testScript; + if (temp.equals("GenerateNumber3")) + generateNumber3 = testScript; + if (temp.equals("GenerateNumber4")) + generateNumber4 = testScript; + if (temp.equals("GenerateString")) + generateString = testScript; + if (temp.equals("GenerateString2")) + generateString2 = testScript; + if (temp.equals("GenerateString3")) + generateString3 = testScript; + if (temp.equals("GenerateString4")) + generateString4 = testScript; + if (temp.equals("GenerateString5")) + generateString5 = testScript; + } + } + setup = true; + } + + @Test + public void testGenerateRegexp() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateRegexp); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); + } + + @Test + public void testGenerateRegexp2() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateRegexp2); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Regexp failed", str.matches("[abc][def]")); + } + + @Test + public void testGeneratePhone() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generatePhone); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Phone regex failed", str.matches("[0-9]{10}")); + } + + @Test + public void testGenerateAbbrevUSState() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateAbbrevUSState); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generated was not an abbreviated US state", abbrevUSState.contains(str)); + } + + @Test + public void testGenerateUSState() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateUSState); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generated was not an abbreviated US state", USState.contains(str)); + } + + /*** + * Tests Number Generated with default length (5) + * + * @throws Throwable + */ + @Test + public void testGenerateNumber() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateNumber); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); + } + + /*** + * Tests Number Generated with length = 7 + * + * @throws Throwable + */ + @Test + public void testGenerateNumber2() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateNumber2); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Number generation failed", str.matches("[0-9]{7}")); + } + + /*** + * Tests Number Generated between 10 and 100 + * + * @throws Throwable + */ + @Test + public void testGenerateNumber3() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateNumber3); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + int num = Integer.parseInt(str); + Assert.assertTrue("Number generation failed", 10 <= num && num <= 100); + } + + /*** + * Test number generated with min specified but no max, so use default length (5) + * + * @throws Throwable + */ + @Test + public void testGenerateNumber4() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateNumber4); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("Number generation failed", str.matches("[0-9]{5}")); + } + + /*** + * Tests String generated with default length (5) + * + * @throws Throwable + */ + @Test + public void testGenerateString() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateString); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); + } + + /*** + * Tests String generated with length = 7 + * + * @throws Throwable + */ + @Test + public void testGenerateString2() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateString2); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); + } + + /** + * Tests String with length in range from 5-10 characters + * + * @throws Throwable + */ + @Test + public void testGenerateString3() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateString3); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5,10}")); + } + + /** + * Tests String with length = 7 when min length is specified without a max + * + * @throws Throwable + */ + @Test + public void testGenerateString4() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateString4); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{7}")); + } + + /** + * Tests String with default length (5) when min length is specified without a max + * + * @throws Throwable + */ + @Test + public void testGenerateString5() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(generateString5); + if (!tr.isTestPassed()) + Assert.fail("JTAF Test failed: " + tr.getFailureReason()); + String str = "" + Command.getFromGlobalContext("it"); + Assert.assertTrue("String generation failed", str.matches("[" + charsForRandomString + "]{5}")); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java b/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java index 62a397f..a78a53f 100644 --- a/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/RepeatTest.java @@ -1,84 +1,84 @@ -package org.finra.jtaf.core.commands; - -import java.io.File; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.execution.Interpreter; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - -public class RepeatTest { - - private static AutomationEngine engine = null; - private static TestAgenda testAgenda = null; - private static boolean setup = false; - private static TestScript complex = null; - private static TestScript repeat = null; - private static TestScript nestedRepeat = null; - - @Before - public void setup() { - - engine = AutomationEngine.getInstance(); - - if (engine.getTestAgenda() == null) { - engine.buildModel(new File("testlibrary"), new File("testscripts")); - testAgenda = engine.getTestAgenda(); - - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); - } - - - if (!setup) { - testAgenda = engine.getTestAgenda(); - - for (TestScript testScript : testAgenda.getTestScripts()) { - String temp = testScript.getName(); - temp = temp.replace(testScript.getFileName(), ""); - if (temp.equals("ComplexRepeat")) { - complex = testScript; - } - if (temp.equals("NestedRepeat")) { - nestedRepeat = testScript; - } - if (temp.equals("Repeat")) { - repeat = testScript; - } - } - - } - setup = true; - - } - - @Test - public void testRepeat() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(repeat); - int size = tr.getTestStepsDetails().size(); - Assert.assertTrue(size == 5); - } - - @Test - public void testNestedRepeat() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(nestedRepeat); - int size = tr.getTestStepsDetails().size(); - Assert.assertTrue(size == 25); - } - - @Test - public void testComplexRepeat() throws Throwable { - Interpreter iv = AutomationEngine.getInstance().getInterpreter(); - TestResult tr = iv.interpret(complex); - int size = tr.getTestStepsDetails().size(); - Assert.assertTrue(size == 30); - - } - -} +package org.finra.jtaf.core.commands; + +import java.io.File; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.execution.Interpreter; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class RepeatTest { + + private static AutomationEngine engine = null; + private static TestAgenda testAgenda = null; + private static boolean setup = false; + private static TestScript complex = null; + private static TestScript repeat = null; + private static TestScript nestedRepeat = null; + + @Before + public void setup() { + + engine = AutomationEngine.getInstance(); + + if (engine.getTestAgenda() == null) { + engine.buildModel(new File("testlibrary"), new File("testscripts")); + testAgenda = engine.getTestAgenda(); + + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + } + + + if (!setup) { + testAgenda = engine.getTestAgenda(); + + for (TestScript testScript : testAgenda.getTestScripts()) { + String temp = testScript.getName(); + temp = temp.replace(testScript.getFileName(), ""); + if (temp.equals("ComplexRepeat")) { + complex = testScript; + } + if (temp.equals("NestedRepeat")) { + nestedRepeat = testScript; + } + if (temp.equals("Repeat")) { + repeat = testScript; + } + } + + } + setup = true; + + } + + @Test + public void testRepeat() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(repeat); + int size = tr.getTestStepsDetails().size(); + Assert.assertTrue(size == 5); + } + + @Test + public void testNestedRepeat() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(nestedRepeat); + int size = tr.getTestStepsDetails().size(); + Assert.assertTrue(size == 25); + } + + @Test + public void testComplexRepeat() throws Throwable { + Interpreter iv = AutomationEngine.getInstance().getInterpreter(); + TestResult tr = iv.interpret(complex); + int size = tr.getTestStepsDetails().size(); + Assert.assertTrue(size == 30); + + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java b/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java index 912f8f8..05acf5a 100644 --- a/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/VerifyByeCommand.java @@ -1,21 +1,21 @@ -package org.finra.jtaf.core.commands; - - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class VerifyByeCommand extends Command { - - public VerifyByeCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data", ""); - Assert.assertEquals(data, "Bye !"); - } - -} +package org.finra.jtaf.core.commands; + + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class VerifyByeCommand extends Command { + + public VerifyByeCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Bye !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java b/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java index df4c0ce..781d7a4 100644 --- a/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java +++ b/src/test/java/org/finra/jtaf/core/commands/VerifyHelloCommand.java @@ -1,21 +1,21 @@ -package org.finra.jtaf.core.commands; - - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class VerifyHelloCommand extends Command { - - public VerifyHelloCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - String data = getStringOrDefault("data", ""); - Assert.assertEquals(data, "Hello World !"); - } - -} +package org.finra.jtaf.core.commands; + + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class VerifyHelloCommand extends Command { + + public VerifyHelloCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + String data = getStringOrDefault("data", ""); + Assert.assertEquals(data, "Hello World !"); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java b/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java index 36331e7..1816d91 100644 --- a/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java +++ b/src/test/java/org/finra/jtaf/core/commands/context/ManipulateContextHelperTest.java @@ -1,405 +1,405 @@ -package org.finra.jtaf.core.commands.context; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.CorrectiveContext; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.execution.Interpreter; -import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class ManipulateContextHelperTest { - - private ManipulateContextHelper helper = null; - private DummyCmd cmd = null; - private Interpreter interpreter = new Interpreter(); - private TestScript testScript = null; - - @Before - public void setup() throws Throwable { - - Node testRoot = buildTestRoot("testscripts/ManipulateContextHelper.xml", "Manipulate"); - TestSuite testSuite = buildTestSuite(testRoot); - Assert.assertEquals(1, testSuite.getComponentList().size()); - - List componentList = testSuite.getComponentList(); - testScript = (TestScript) componentList.get(0); - - cmd = new DummyCmd("Test"); - cmd.addOptionalParameter("String"); - IInvocationContext ctx = new CorrectiveContext(); - Invocation invocation = new Invocation("String"); - ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); - interpreter.interpret(testScript); - cmd.launch(ctx, interpreter); - Map contextGlobal = new HashMap(); - helper = new ManipulateContextHelper(cmd, contextGlobal); - - } - - @Test - public void testNullContext() { - helper.setContext(null); - helper.setValueOut("String", "Test"); - Assert.assertEquals(cmd.ctx().getObject("String"), "Test"); - } - - @Test - public void testNotNullContext() throws Throwable { - IInvocationContext ctx = new CorrectiveContext(); - Invocation invocation = new Invocation("String"); - ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); - interpreter.interpret(testScript); - cmd.launch(ctx, interpreter); - helper.setContext(ctx); - helper.setValueOut("String", "Test"); - - Assert.assertEquals(ctx.getObject("String"), "Test"); - } - - @Test - public void testGetVerifiedAction() throws Throwable { - Assert.assertEquals("replace", helper.getVerifiedAction()); - helper.setValueOut("action", "prepend"); - Assert.assertEquals("prepend", helper.getVerifiedAction()); - helper.setValueOut("action", "append"); - Assert.assertEquals("append", helper.getVerifiedAction()); - - } - - @Test - public void testGetVerifiedActionFailure() throws Throwable { - IInvocationContext ctx = new CorrectiveContext(); - Invocation invocation = new Invocation("String"); - ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); - interpreter.interpret(testScript); - cmd.launch(ctx, interpreter); - helper.setContext(ctx); - helper.setValueOut("action", "Test"); - IllegalArgumentException exception = null; - try { - helper.getVerifiedAction(); - } catch (IllegalArgumentException e) { - exception = e; - } - Assert.assertEquals( - "Test: attribute 'action' must be 'replace' or 'append' or 'prepend' (or left unspecified)", - exception.getMessage()); - - } - - @Test - public void testGetValueIn() { - helper.setValueOut("getValueIn", "Value"); - Assert.assertEquals("Value", helper.getValueIn("getValueIn", null, null)); - // Assert.assertEquals("Value", helper.getValueIn("getValueIn", -1)); - } - - @Test - public void testGetValueInList() { - List list = new ArrayList(); - list.add("IndexOne"); - helper.setValueOut("getValueIn", list); - Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", 0, null)); - Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", -1, null)); - Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", -1)); - } - - @Test - public void testGetValueInMap() { - Map map = new HashMap(); - map.put("key", "valueOne"); - helper.setValueOut("getValueIn", map); - Assert.assertEquals("valueOne", helper.getValueIn("getValueIn", null, "key")); - Assert.assertEquals("valueOne", helper.getValueIn("getValueIn", "key")); - } - - @SuppressWarnings("unchecked") - @Test - public void testSetValueOutObjectToList() { - List list = new ArrayList(); - helper.setValueOut("testList", list, "testString"); - Assert.assertEquals(helper.getValueIn("testList", null, null), list); - Assert.assertEquals("testString", list.get(0)); - - list = ((List) helper.getValueIn("testList", null, null)); - - helper.setValueOut("testList", list, "testString2", 0); - list = ((List) helper.getValueIn("testList", null, null)); - Assert.assertEquals(helper.getValueIn("testList", null, null), list); - Assert.assertEquals("testString2", list.get(0)); - Assert.assertEquals("testString", list.get(1)); - - } - - @Test - public void testSetValueOutListToList() { - List list = new ArrayList(); - list.add("StringOne"); - - List list2 = new ArrayList(); - list2.add("StringTwo"); - - helper.setValueOut("testList", list, list2); - Assert.assertEquals("StringOne", list.get(0)); - Assert.assertEquals("StringTwo", list.get(1)); - - helper.setValueOut("testList", list, list2, 0); - Assert.assertEquals("StringOne", list.get(1)); - Assert.assertEquals("StringTwo", list.get(0)); - - } - - @Test - public void testSetValueOutObjectToMap() { - Map map = new HashMap(); - - helper.setValueOut("testMap", map, "value", "key"); - Assert.assertEquals("value", helper.getValueIn("testMap", null, "key")); - - } - - @Test - public void testGetRequiredObject() { - try { - helper.getRequiredObject("key"); - } catch (Throwable e) { - Assert.assertEquals("Test : The parameter with key [key] is not set.", e.getMessage()); - - } - - helper.setValueOut("test", "string"); - Assert.assertEquals("string", helper.getRequiredObject("test")); - - } - - @Test - public void testGetRequiredString() { - try { - helper.getRequiredString("key"); - } catch (Throwable e) { - Assert.assertEquals("Test: missing required String attribute 'key'", e.getMessage()); - - } - - helper.setValueOut("test", "string"); - Assert.assertEquals("string", helper.getRequiredString("test")); - - } - - @Test - public void testGetStringOrDefault() { - - helper.setValueOut("test", "string"); - Assert.assertEquals("string", helper.getStringOrDefault("test", "test2")); - - } - - @Test - public void testOptionalString() { - - helper.setValueOut("test", "string"); - Assert.assertEquals("string", helper.getOptionalString("test")); - - } - - @Test - public void testGetRequiredInteger() { - try { - helper.getRequiredInteger("key"); - } catch (Throwable e) { - Assert.assertEquals("Test: missing required integer attribute 'key'", e.getMessage()); - - } - - helper.setValueOut("test", "1"); - Assert.assertEquals(1, helper.getRequiredInteger("test")); - - } - - @Test - public void testGetOptionalInteger() { - - Assert.assertEquals(null, helper.getOptionalInteger("key")); - - helper.setValueOut("test", "1"); - Assert.assertEquals(1, (int) helper.getOptionalInteger("test")); - - } - - @Test - public void testGetRequiredIntegerOrDefault() { - Assert.assertEquals(5, helper.getIntegerOrDefault("test", 5)); - helper.setValueOut("test", "1"); - Assert.assertEquals(1, helper.getIntegerOrDefault("test", 5)); - - } - - @Test - public void testGetRequiredFloat() { - try { - helper.getRequiredFloat("key"); - } catch (Throwable e) { - Assert.assertEquals("Test: missing required float attribute 'key'", e.getMessage()); - - } - - helper.setValueOut("test", "1"); - Assert.assertEquals(1f, helper.getRequiredFloat("test"), 0); - } - - @Test - public void testGetRequiredFloatOrDefault() { - Assert.assertEquals(5f, helper.getFloatOrDefault("test", 5f), 0); - helper.setValueOut("test", "1"); - Assert.assertEquals(1f, helper.getFloatOrDefault("test", 5f), 0); - - } - - @Test - public void testGetRequiredBoolean() { - try { - helper.getRequiredBoolean("key"); - } catch (Throwable e) { - Assert.assertEquals("Test: missing required boolean attribute 'key'", e.getMessage()); - - } - - helper.setValueOut("test", "true"); - Assert.assertEquals(true, helper.getRequiredBoolean("test")); - helper.setValueOut("test", "false"); - Assert.assertEquals(false, helper.getRequiredBoolean("test")); - helper.setValueOut("test", "neither"); - - try { - helper.getRequiredBoolean("test"); - } catch (Throwable e) { - Assert.assertEquals("Test: attribute 'test' must be either 'true' or 'false'", e - .getMessage()); - - } - - } - - @Test - public void testGetRequiredBooleanOrDefault() { - - Assert.assertEquals(true, helper.getBooleanOrDefault("key", true)); - - helper.setValueOut("test", "true"); - Assert.assertEquals(true, helper.getBooleanOrDefault("test", false)); - helper.setValueOut("test", "false"); - Assert.assertEquals(false, helper.getBooleanOrDefault("test", true)); - helper.setValueOut("test", "neither"); - - try { - helper.getBooleanOrDefault("test", true); - } catch (Throwable e) { - Assert.assertEquals( - "Test: attribute 'test' must be either 'true' or 'false' (or left unspecified)", - e.getMessage()); - - } - - } - - @Test - public void testGetOptionalObject() throws Throwable { - - Map contextGlobal = new HashMap(); - contextGlobal.put("test2", "testString"); - contextGlobal.put("startIndex", "startIndexString"); - contextGlobal.put("endIndex", "endIndexString"); - - helper = new ManipulateContextHelper(cmd, contextGlobal); - - helper.setValueOut("test", "$contextKey(test2)"); - Assert.assertEquals("testString", (String) helper.getOptionalObject("test")); - - helper.setValueOut("testStartIndex", "$contextKeyy(startIndex)"); - Assert.assertEquals("startIndexString", (String) helper.getOptionalObject("testStartIndex")); - - helper.setValueOut("testEndIndex", "$contextKeyy(endIndex"); - Assert.assertEquals("", (String) helper.getOptionalObject("testEndIndex")); - RuntimeException exception = null; - try { - - helper.setValueOut("failureTest", "$contextKey(test3)"); - helper.getOptionalObject("failureTest"); - } catch (RuntimeException e) { - exception = e; - } - - Assert.assertEquals( - exception.getMessage(), - "Oops! Processing 'failureTest'='$contextKey(test3)' key fails! Can't find run time parameter 'test3'! You have put it to global content before..."); - - } - - private class DummyCmd extends AbstractContextCmd { - - public DummyCmd(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } - - /* - * (non-Javadoc) - * - * @see - * org.finra.jtaf.core.model.invocationtarget.Command#execute(org.finra - * .jtaf.core.model.execution.IInvocationContext) - */ - @Override - protected void execute() throws Throwable { - - } - - } - - protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { - Node testRoot = null; - InputStream inputStream = new FileInputStream(scriptFileName); - Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( - inputStream).getDocumentElement(); - NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); - for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { - Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); - if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") - && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { - testRoot = suiteNodeChildNode; - break; - } - } - return testRoot; - } - - protected TestSuite buildTestSuite(Node testRoot) throws Exception { - TestSuite testSuite = new TestSuite("dummy test suite"); - TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( - (Element) testRoot, new MessageCollector()); - testSuite.add(testScript); - return testSuite; - } - -} +package org.finra.jtaf.core.commands.context; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.CorrectiveContext; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.execution.Interpreter; +import org.finra.jtaf.core.model.invocationtarget.InvocationTarget; +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class ManipulateContextHelperTest { + + private ManipulateContextHelper helper = null; + private DummyCmd cmd = null; + private Interpreter interpreter = new Interpreter(); + private TestScript testScript = null; + + @Before + public void setup() throws Throwable { + + Node testRoot = buildTestRoot("testscripts/ManipulateContextHelper.xml", "Manipulate"); + TestSuite testSuite = buildTestSuite(testRoot); + Assert.assertEquals(1, testSuite.getComponentList().size()); + + List componentList = testSuite.getComponentList(); + testScript = (TestScript) componentList.get(0); + + cmd = new DummyCmd("Test"); + cmd.addOptionalParameter("String"); + IInvocationContext ctx = new CorrectiveContext(); + Invocation invocation = new Invocation("String"); + ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); + interpreter.interpret(testScript); + cmd.launch(ctx, interpreter); + Map contextGlobal = new HashMap(); + helper = new ManipulateContextHelper(cmd, contextGlobal); + + } + + @Test + public void testNullContext() { + helper.setContext(null); + helper.setValueOut("String", "Test"); + Assert.assertEquals(cmd.ctx().getObject("String"), "Test"); + } + + @Test + public void testNotNullContext() throws Throwable { + IInvocationContext ctx = new CorrectiveContext(); + Invocation invocation = new Invocation("String"); + ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); + interpreter.interpret(testScript); + cmd.launch(ctx, interpreter); + helper.setContext(ctx); + helper.setValueOut("String", "Test"); + + Assert.assertEquals(ctx.getObject("String"), "Test"); + } + + @Test + public void testGetVerifiedAction() throws Throwable { + Assert.assertEquals("replace", helper.getVerifiedAction()); + helper.setValueOut("action", "prepend"); + Assert.assertEquals("prepend", helper.getVerifiedAction()); + helper.setValueOut("action", "append"); + Assert.assertEquals("append", helper.getVerifiedAction()); + + } + + @Test + public void testGetVerifiedActionFailure() throws Throwable { + IInvocationContext ctx = new CorrectiveContext(); + Invocation invocation = new Invocation("String"); + ((CorrectiveContext) ctx).pushInvocation(invocation, (InvocationTarget) cmd); + interpreter.interpret(testScript); + cmd.launch(ctx, interpreter); + helper.setContext(ctx); + helper.setValueOut("action", "Test"); + IllegalArgumentException exception = null; + try { + helper.getVerifiedAction(); + } catch (IllegalArgumentException e) { + exception = e; + } + Assert.assertEquals( + "Test: attribute 'action' must be 'replace' or 'append' or 'prepend' (or left unspecified)", + exception.getMessage()); + + } + + @Test + public void testGetValueIn() { + helper.setValueOut("getValueIn", "Value"); + Assert.assertEquals("Value", helper.getValueIn("getValueIn", null, null)); + // Assert.assertEquals("Value", helper.getValueIn("getValueIn", -1)); + } + + @Test + public void testGetValueInList() { + List list = new ArrayList(); + list.add("IndexOne"); + helper.setValueOut("getValueIn", list); + Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", 0, null)); + Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", -1, null)); + Assert.assertEquals("IndexOne", helper.getValueIn("getValueIn", -1)); + } + + @Test + public void testGetValueInMap() { + Map map = new HashMap(); + map.put("key", "valueOne"); + helper.setValueOut("getValueIn", map); + Assert.assertEquals("valueOne", helper.getValueIn("getValueIn", null, "key")); + Assert.assertEquals("valueOne", helper.getValueIn("getValueIn", "key")); + } + + @SuppressWarnings("unchecked") + @Test + public void testSetValueOutObjectToList() { + List list = new ArrayList(); + helper.setValueOut("testList", list, "testString"); + Assert.assertEquals(helper.getValueIn("testList", null, null), list); + Assert.assertEquals("testString", list.get(0)); + + list = ((List) helper.getValueIn("testList", null, null)); + + helper.setValueOut("testList", list, "testString2", 0); + list = ((List) helper.getValueIn("testList", null, null)); + Assert.assertEquals(helper.getValueIn("testList", null, null), list); + Assert.assertEquals("testString2", list.get(0)); + Assert.assertEquals("testString", list.get(1)); + + } + + @Test + public void testSetValueOutListToList() { + List list = new ArrayList(); + list.add("StringOne"); + + List list2 = new ArrayList(); + list2.add("StringTwo"); + + helper.setValueOut("testList", list, list2); + Assert.assertEquals("StringOne", list.get(0)); + Assert.assertEquals("StringTwo", list.get(1)); + + helper.setValueOut("testList", list, list2, 0); + Assert.assertEquals("StringOne", list.get(1)); + Assert.assertEquals("StringTwo", list.get(0)); + + } + + @Test + public void testSetValueOutObjectToMap() { + Map map = new HashMap(); + + helper.setValueOut("testMap", map, "value", "key"); + Assert.assertEquals("value", helper.getValueIn("testMap", null, "key")); + + } + + @Test + public void testGetRequiredObject() { + try { + helper.getRequiredObject("key"); + } catch (Throwable e) { + Assert.assertEquals("Test : The parameter with key [key] is not set.", e.getMessage()); + + } + + helper.setValueOut("test", "string"); + Assert.assertEquals("string", helper.getRequiredObject("test")); + + } + + @Test + public void testGetRequiredString() { + try { + helper.getRequiredString("key"); + } catch (Throwable e) { + Assert.assertEquals("Test: missing required String attribute 'key'", e.getMessage()); + + } + + helper.setValueOut("test", "string"); + Assert.assertEquals("string", helper.getRequiredString("test")); + + } + + @Test + public void testGetStringOrDefault() { + + helper.setValueOut("test", "string"); + Assert.assertEquals("string", helper.getStringOrDefault("test", "test2")); + + } + + @Test + public void testOptionalString() { + + helper.setValueOut("test", "string"); + Assert.assertEquals("string", helper.getOptionalString("test")); + + } + + @Test + public void testGetRequiredInteger() { + try { + helper.getRequiredInteger("key"); + } catch (Throwable e) { + Assert.assertEquals("Test: missing required integer attribute 'key'", e.getMessage()); + + } + + helper.setValueOut("test", "1"); + Assert.assertEquals(1, helper.getRequiredInteger("test")); + + } + + @Test + public void testGetOptionalInteger() { + + Assert.assertEquals(null, helper.getOptionalInteger("key")); + + helper.setValueOut("test", "1"); + Assert.assertEquals(1, (int) helper.getOptionalInteger("test")); + + } + + @Test + public void testGetRequiredIntegerOrDefault() { + Assert.assertEquals(5, helper.getIntegerOrDefault("test", 5)); + helper.setValueOut("test", "1"); + Assert.assertEquals(1, helper.getIntegerOrDefault("test", 5)); + + } + + @Test + public void testGetRequiredFloat() { + try { + helper.getRequiredFloat("key"); + } catch (Throwable e) { + Assert.assertEquals("Test: missing required float attribute 'key'", e.getMessage()); + + } + + helper.setValueOut("test", "1"); + Assert.assertEquals(1f, helper.getRequiredFloat("test"), 0); + } + + @Test + public void testGetRequiredFloatOrDefault() { + Assert.assertEquals(5f, helper.getFloatOrDefault("test", 5f), 0); + helper.setValueOut("test", "1"); + Assert.assertEquals(1f, helper.getFloatOrDefault("test", 5f), 0); + + } + + @Test + public void testGetRequiredBoolean() { + try { + helper.getRequiredBoolean("key"); + } catch (Throwable e) { + Assert.assertEquals("Test: missing required boolean attribute 'key'", e.getMessage()); + + } + + helper.setValueOut("test", "true"); + Assert.assertEquals(true, helper.getRequiredBoolean("test")); + helper.setValueOut("test", "false"); + Assert.assertEquals(false, helper.getRequiredBoolean("test")); + helper.setValueOut("test", "neither"); + + try { + helper.getRequiredBoolean("test"); + } catch (Throwable e) { + Assert.assertEquals("Test: attribute 'test' must be either 'true' or 'false'", e + .getMessage()); + + } + + } + + @Test + public void testGetRequiredBooleanOrDefault() { + + Assert.assertEquals(true, helper.getBooleanOrDefault("key", true)); + + helper.setValueOut("test", "true"); + Assert.assertEquals(true, helper.getBooleanOrDefault("test", false)); + helper.setValueOut("test", "false"); + Assert.assertEquals(false, helper.getBooleanOrDefault("test", true)); + helper.setValueOut("test", "neither"); + + try { + helper.getBooleanOrDefault("test", true); + } catch (Throwable e) { + Assert.assertEquals( + "Test: attribute 'test' must be either 'true' or 'false' (or left unspecified)", + e.getMessage()); + + } + + } + + @Test + public void testGetOptionalObject() throws Throwable { + + Map contextGlobal = new HashMap(); + contextGlobal.put("test2", "testString"); + contextGlobal.put("startIndex", "startIndexString"); + contextGlobal.put("endIndex", "endIndexString"); + + helper = new ManipulateContextHelper(cmd, contextGlobal); + + helper.setValueOut("test", "$contextKey(test2)"); + Assert.assertEquals("testString", (String) helper.getOptionalObject("test")); + + helper.setValueOut("testStartIndex", "$contextKeyy(startIndex)"); + Assert.assertEquals("startIndexString", (String) helper.getOptionalObject("testStartIndex")); + + helper.setValueOut("testEndIndex", "$contextKeyy(endIndex"); + Assert.assertEquals("", (String) helper.getOptionalObject("testEndIndex")); + RuntimeException exception = null; + try { + + helper.setValueOut("failureTest", "$contextKey(test3)"); + helper.getOptionalObject("failureTest"); + } catch (RuntimeException e) { + exception = e; + } + + Assert.assertEquals( + exception.getMessage(), + "Oops! Processing 'failureTest'='$contextKey(test3)' key fails! Can't find run time parameter 'test3'! You have put it to global content before..."); + + } + + private class DummyCmd extends AbstractContextCmd { + + public DummyCmd(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } + + /* + * (non-Javadoc) + * + * @see + * org.finra.jtaf.core.model.invocationtarget.Command#execute(org.finra + * .jtaf.core.model.execution.IInvocationContext) + */ + @Override + protected void execute() throws Throwable { + + } + + } + + protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { + Node testRoot = null; + InputStream inputStream = new FileInputStream(scriptFileName); + Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( + inputStream).getDocumentElement(); + NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); + for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { + Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); + if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") + && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() + .equals(testOfInterestName)) { + testRoot = suiteNodeChildNode; + break; + } + } + return testRoot; + } + + protected TestSuite buildTestSuite(Node testRoot) throws Exception { + TestSuite testSuite = new TestSuite("dummy test suite"); + TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( + (Element) testRoot, new MessageCollector()); + testSuite.add(testScript); + return testSuite; + } + +} diff --git a/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java b/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java index 7197890..fab64ae 100644 --- a/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java +++ b/src/test/java/org/finra/jtaf/core/driver/XMLTestParrelDriver.java @@ -1,10 +1,10 @@ -package org.finra.jtaf.core.driver; - -import org.finra.jtaf.core.parallel.JTAFMasterSuite; -import org.junit.runner.RunWith; - - -@RunWith(JTAFMasterSuite.class) -public class XMLTestParrelDriver { - +package org.finra.jtaf.core.driver; + +import org.finra.jtaf.core.parallel.JTAFMasterSuite; +import org.junit.runner.RunWith; + + +@RunWith(JTAFMasterSuite.class) +public class XMLTestParrelDriver { + } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java b/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java index 4f5c272..dbff94d 100644 --- a/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java +++ b/src/test/java/org/finra/jtaf/core/mock/DebugPrintCommand.java @@ -1,18 +1,18 @@ -package org.finra.jtaf.core.mock; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class DebugPrintCommand extends Command { - public DebugPrintCommand(String name) throws NameFormatException { - super(name); - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - synchronized (DebugPrintCommand.class) { - System.err.println(getRequiredString("message")); - } - } -} +package org.finra.jtaf.core.mock; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class DebugPrintCommand extends Command { + public DebugPrintCommand(String name) throws NameFormatException { + super(name); + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + synchronized (DebugPrintCommand.class) { + System.err.println(getRequiredString("message")); + } + } +} diff --git a/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java b/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java index 77f58ac..268d899 100644 --- a/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java +++ b/src/test/java/org/finra/jtaf/core/mock/IThrowExceptionCmd.java @@ -1,22 +1,22 @@ -package org.finra.jtaf.core.mock; - -import java.sql.SQLException; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class IThrowExceptionCmd extends Command { - - public IThrowExceptionCmd(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - throw new SQLException("This is just a test"); - - } - -} +package org.finra.jtaf.core.mock; + +import java.sql.SQLException; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class IThrowExceptionCmd extends Command { + + public IThrowExceptionCmd(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + throw new SQLException("This is just a test"); + + } + +} diff --git a/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java b/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java index 76511cf..e984691 100644 --- a/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java +++ b/src/test/java/org/finra/jtaf/core/mock/MockCommand1.java @@ -1,21 +1,21 @@ -package org.finra.jtaf.core.mock; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class MockCommand1 extends Command { - - public MockCommand1(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - - getRequiredBoolean("param1"); - - } - -} +package org.finra.jtaf.core.mock; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class MockCommand1 extends Command { + + public MockCommand1(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + + getRequiredBoolean("param1"); + + } + +} diff --git a/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java b/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java index b1435a1..5f93424 100644 --- a/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java +++ b/src/test/java/org/finra/jtaf/core/mock/MockCommand2.java @@ -1,22 +1,22 @@ -package org.finra.jtaf.core.mock; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class MockCommand2 extends Command { - public static boolean testEnd; - - public MockCommand2(String name) throws NameFormatException { - super(name); - testEnd = false; - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - testEnd = true; - } - -} +package org.finra.jtaf.core.mock; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class MockCommand2 extends Command { + public static boolean testEnd; + + public MockCommand2(String name) throws NameFormatException { + super(name); + testEnd = false; + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + testEnd = true; + } + +} diff --git a/src/test/java/org/finra/jtaf/core/mock/Repeat.java b/src/test/java/org/finra/jtaf/core/mock/Repeat.java index 6007895..a6eaa09 100644 --- a/src/test/java/org/finra/jtaf/core/mock/Repeat.java +++ b/src/test/java/org/finra/jtaf/core/mock/Repeat.java @@ -1,20 +1,20 @@ -package org.finra.jtaf.core.mock; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; - -public class Repeat extends Command { - - public Repeat(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - //do nothing - } - -} +package org.finra.jtaf.core.mock; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; + +public class Repeat extends Command { + + public Repeat(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + //do nothing + } + +} diff --git a/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java b/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java index 2a91616..2a33550 100644 --- a/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java +++ b/src/test/java/org/finra/jtaf/core/mock/TestParamFetchingCmd.java @@ -1,91 +1,91 @@ -package org.finra.jtaf.core.mock; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.IInvocationContext; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.junit.Assert; - -public class TestParamFetchingCmd extends Command { - - public TestParamFetchingCmd(String name) throws NameFormatException { - super(name); - // TODO Auto-generated constructor stub - } - - @Override - protected void execute(IInvocationContext ctx) throws Throwable { - // TODO Auto-generated method stub - if (getName().equalsIgnoreCase("testoptionalParameters")) - testOptionalParameters(); - else if (getName().equalsIgnoreCase("testRequiredParameters")) - testRequiredParameters(); - else if (getName().equalsIgnoreCase("testParameters")) - testParameters(); - } - - private void testParameters() { - try { - getRequiredString("testStringRequired"); - } catch (Exception e) { - Assert.assertEquals("testParameters: missing required String attribute 'testStringRequired'", e.getMessage()); - - } - try { - getRequiredInteger("testIntegerRequired"); - } catch (Exception e) { - Assert.assertEquals("testParameters: missing required integer attribute 'testIntegerRequired'", e.getMessage()); - - } - try { - getRequiredBoolean("testBooleanRequired"); - } catch (Exception e) { - Assert.assertEquals("testParameters: missing required boolean attribute 'testBooleanRequired'", e.getMessage()); - - } - try { - getRequiredFloat("testFloatRequired"); - } catch (Exception e) { - Assert.assertEquals("testParameters: missing required float attribute 'testFloatRequired'", e.getMessage()); - - } - try { - getRequiredObject("testObjectRequired"); - } catch (Exception e) { - Assert.assertEquals("testParameters : The parameter with key [testObjectRequired] is not set.", e.getMessage()); - - } - getOptionalObject("testObjectOptional"); - Assert.assertTrue(getGlobalContext().get("OptString") != null); - - - } - - private void testOptionalParameters() { - Assert.assertEquals("test string", getRequiredString("testStringRequired")); - Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); - Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); - Assert.assertEquals(false, getRequiredBoolean("testBooleanRequired")); - Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); - Assert.assertEquals("test string optional", getOptionalString("testStringOptional")); - Assert.assertEquals("{cat, dog}", getOptionalObject("testObjectOptional")); - Assert.assertEquals(false, getBooleanOrDefault("testBooleanDefault", true)); - Assert.assertEquals("not the default string", getStringOrDefault("testStringDefault", "testString")); - Assert.assertEquals(2, getIntegerOrDefault("testIntegerDefault", 1)); - Assert.assertEquals(2.2f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); - } - - private void testRequiredParameters() { - Assert.assertEquals("test string required", getRequiredString("testStringRequired")); - Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); - Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); - Assert.assertEquals(true, getRequiredBoolean("testBooleanRequired")); - Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); - Assert.assertTrue(getOptionalString("testStringOptional") == null); - getOptionalObject("testObjectOptional"); - Assert.assertTrue(getGlobalContext().get("OptObj") != null); - Assert.assertEquals(true, getBooleanOrDefault("testBooleanDefault", true)); - Assert.assertEquals("default string", getStringOrDefault("testStringDefault", "default string")); - Assert.assertEquals(1, getIntegerOrDefault("testIntegerDefault", 1)); - Assert.assertEquals(1.1f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); - } -} +package org.finra.jtaf.core.mock; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.IInvocationContext; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.junit.Assert; + +public class TestParamFetchingCmd extends Command { + + public TestParamFetchingCmd(String name) throws NameFormatException { + super(name); + // TODO Auto-generated constructor stub + } + + @Override + protected void execute(IInvocationContext ctx) throws Throwable { + // TODO Auto-generated method stub + if (getName().equalsIgnoreCase("testoptionalParameters")) + testOptionalParameters(); + else if (getName().equalsIgnoreCase("testRequiredParameters")) + testRequiredParameters(); + else if (getName().equalsIgnoreCase("testParameters")) + testParameters(); + } + + private void testParameters() { + try { + getRequiredString("testStringRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required String attribute 'testStringRequired'", e.getMessage()); + + } + try { + getRequiredInteger("testIntegerRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required integer attribute 'testIntegerRequired'", e.getMessage()); + + } + try { + getRequiredBoolean("testBooleanRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required boolean attribute 'testBooleanRequired'", e.getMessage()); + + } + try { + getRequiredFloat("testFloatRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters: missing required float attribute 'testFloatRequired'", e.getMessage()); + + } + try { + getRequiredObject("testObjectRequired"); + } catch (Exception e) { + Assert.assertEquals("testParameters : The parameter with key [testObjectRequired] is not set.", e.getMessage()); + + } + getOptionalObject("testObjectOptional"); + Assert.assertTrue(getGlobalContext().get("OptString") != null); + + + } + + private void testOptionalParameters() { + Assert.assertEquals("test string", getRequiredString("testStringRequired")); + Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); + Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); + Assert.assertEquals(false, getRequiredBoolean("testBooleanRequired")); + Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); + Assert.assertEquals("test string optional", getOptionalString("testStringOptional")); + Assert.assertEquals("{cat, dog}", getOptionalObject("testObjectOptional")); + Assert.assertEquals(false, getBooleanOrDefault("testBooleanDefault", true)); + Assert.assertEquals("not the default string", getStringOrDefault("testStringDefault", "testString")); + Assert.assertEquals(2, getIntegerOrDefault("testIntegerDefault", 1)); + Assert.assertEquals(2.2f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); + } + + private void testRequiredParameters() { + Assert.assertEquals("test string required", getRequiredString("testStringRequired")); + Assert.assertEquals(1, getRequiredInteger("testIntegerRequired")); + Assert.assertEquals(1.1f, getRequiredFloat("testFloatRequired"), 0.2); + Assert.assertEquals(true, getRequiredBoolean("testBooleanRequired")); + Assert.assertEquals("{1,2}", getRequiredObject("testObjectRequired")); + Assert.assertTrue(getOptionalString("testStringOptional") == null); + getOptionalObject("testObjectOptional"); + Assert.assertTrue(getGlobalContext().get("OptObj") != null); + Assert.assertEquals(true, getBooleanOrDefault("testBooleanDefault", true)); + Assert.assertEquals("default string", getStringOrDefault("testStringDefault", "default string")); + Assert.assertEquals(1, getIntegerOrDefault("testIntegerDefault", 1)); + Assert.assertEquals(1.1f, getFloatOrDefault("testFloatDefault", 1.1f), 0.2); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java b/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java index 4e1eae9..e5f3988 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/ConcurrentSchedulerTest.java @@ -1,69 +1,69 @@ -package org.finra.jtaf.core.parallel; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class ConcurrentSchedulerTest { - - - @Test - public void testCheckTestsStatus() throws Exception { - - if (AutomationEngine.getInstance().getTestAgenda() == null) { - AutomationEngine.getInstance().buildModel(new File("testlibrary"), new File("testscripts")); - // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); - } - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "FAILED"); - AutomationEngine.getInstance().getTestAgenda().setThreadCount("-1"); - ConcurrentScheduler scheduler = new ConcurrentScheduler(); - - //scheduler.registerTestName("Test"); - scheduler.finished(); - - - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "READY"); - AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestA", "FAILED"); - - scheduler.finished(); - - } - - protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { - Node testRoot = null; - InputStream inputStream = new FileInputStream(scriptFileName); - Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( - inputStream).getDocumentElement(); - NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); - for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { - Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); - if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") - && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { - testRoot = suiteNodeChildNode; - break; - } - } - return testRoot; - } - - protected TestSuite buildTestSuite(Node testRoot) throws Exception { - TestSuite testSuite = new TestSuite("dummy test suite"); - TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( - (Element) testRoot, new MessageCollector()); - testSuite.add(testScript); - return testSuite; - } - -} +package org.finra.jtaf.core.parallel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class ConcurrentSchedulerTest { + + + @Test + public void testCheckTestsStatus() throws Exception { + + if (AutomationEngine.getInstance().getTestAgenda() == null) { + AutomationEngine.getInstance().buildModel(new File("testlibrary"), new File("testscripts")); + // TraceabilityMatrix.produceTraceabilityMatrix(testAgenda); + } + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "FAILED"); + AutomationEngine.getInstance().getTestAgenda().setThreadCount("-1"); + ConcurrentScheduler scheduler = new ConcurrentScheduler(); + + //scheduler.registerTestName("Test"); + scheduler.finished(); + + + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestB", "READY"); + AutomationEngine.getInstance().getTestDigraph().updateTestStatus("TestA", "FAILED"); + + scheduler.finished(); + + } + + protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { + Node testRoot = null; + InputStream inputStream = new FileInputStream(scriptFileName); + Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( + inputStream).getDocumentElement(); + NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); + for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { + Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); + if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") + && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() + .equals(testOfInterestName)) { + testRoot = suiteNodeChildNode; + break; + } + } + return testRoot; + } + + protected TestSuite buildTestSuite(Node testRoot) throws Exception { + TestSuite testSuite = new TestSuite("dummy test suite"); + TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( + (Element) testRoot, new MessageCollector()); + testSuite.add(testScript); + return testSuite; + } + +} diff --git a/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java b/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java index 27848d3..2877f37 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/MasterSuiteRunnersBuilderTest.java @@ -1,15 +1,15 @@ -package org.finra.jtaf.core.parallel; - -import org.junit.Assert; - -import org.junit.Test; - -public class MasterSuiteRunnersBuilderTest { - - @Test - public void testRunnerForClass() throws Throwable { - MasterSuiteRunnersBuilder builder = new MasterSuiteRunnersBuilder(); - Assert.assertEquals(null, builder.runnerForClass(null)); - } - -} +package org.finra.jtaf.core.parallel; + +import org.junit.Assert; + +import org.junit.Test; + +public class MasterSuiteRunnersBuilderTest { + + @Test + public void testRunnerForClass() throws Throwable { + MasterSuiteRunnersBuilder builder = new MasterSuiteRunnersBuilder(); + Assert.assertEquals(null, builder.runnerForClass(null)); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java b/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java index c55de6e..f55a2cb 100644 --- a/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java +++ b/src/test/java/org/finra/jtaf/core/parallel/ParallelScriptRunnerTest.java @@ -1,166 +1,166 @@ -package org.finra.jtaf.core.parallel; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.model.test.digraph.DiNode; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class ParallelScriptRunnerTest { - - private TestScript testScript = null; - private ParallelScriptRunner runner = null; - - @Test - public void testCreateJunitName() throws Exception { - Node testRoot = buildTestRoot("testscripts/ManipulateContextHelper.xml", "Manipulate"); - TestSuite testSuite = buildTestSuite(testRoot); - - List componentList = testSuite.getComponentList(); - testScript = (TestScript) componentList.get(0); - - List crs = new ArrayList(); - crs.add("Test"); - testScript.setCRs(crs); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), - "/dummy test suite/Manipulate CR=\"Test\" [ISSUE EXISTS]"); - - testScript.setCRs(new ArrayList()); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); - - testScript.setStatus("Pass"); - testScript.setCRs(null); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate STATUS=\"Pass\""); - - testScript.setStatus(null); - testScript.setIssue(""); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); - - testScript.setStatus(null); - testScript.setIssue(null); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); - - testScript.setStatus(null); - testScript.setIssue("Issue"); - runner = new ParallelScriptRunner(testScript); - Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate [ISSUE EXISTS]"); - - } - - @Test - public void testRunJtafTestScript() throws Throwable { - Node testRoot = buildTestRoot("testscripts/ParallelScriptRunner.xml", "Runner"); - TestSuite testSuite = buildTestSuite(testRoot); - - List componentList = testSuite.getComponentList(); - testScript = (TestScript) componentList.get(0); - if (AutomationEngine.getInstance().getTestDigraph().getVertex(testScript.getName()) != null) { - AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(), - "FAILED"); - - } else { - MyNode node = new MyNode(testScript); - node.setTestStatus("FAILED"); - - AutomationEngine.getInstance().getTestDigraph().addVertex(node); - } - - runner = new ParallelScriptRunner(testScript); - - Throwable error = null; - try { - runner.runJtafTestScript(); - } catch (Throwable e) { - error = e; - } - Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionError")); - Assert.assertTrue(error.getMessage().equals("One or more Dependent tests failed")); - - - AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(), - "SUCCESS"); - try { - runner.runJtafTestScript(); - } catch (Throwable e) { - error = e; - } - Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionFailedError")); - - } - - protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { - Node testRoot = null; - InputStream inputStream = new FileInputStream(scriptFileName); - Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( - inputStream).getDocumentElement(); - NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); - for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { - Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); - if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") - && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() - .equals(testOfInterestName)) { - testRoot = suiteNodeChildNode; - break; - } - } - return testRoot; - } - - protected TestSuite buildTestSuite(Node testRoot) throws Exception { - TestSuite testSuite = new TestSuite("dummy test suite"); - TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( - (Element) testRoot, new MessageCollector()); - testSuite.add(testScript); - return testSuite; - } - - private class MyNode extends DiNode { - - private String testName = ""; // This shouldnt change after being set - // initially - private String testStatus = ""; - private TestScript testScript = null; // This shouldnt change after - // being set initially - - public MyNode(TestScript ts) { - super(ts); - this.testName = ts.getName(); - this.testScript = ts; - } - - public String getTestStatus() { - return testStatus; - } - - protected void setTestStatus(String newTestStatus) { - testStatus = newTestStatus; - } - - public String getTestName() { - return testName; - } - - public TestScript getTestScript() { - return testScript; - } - } - -} +package org.finra.jtaf.core.parallel; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.model.test.digraph.DiNode; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class ParallelScriptRunnerTest { + + private TestScript testScript = null; + private ParallelScriptRunner runner = null; + + @Test + public void testCreateJunitName() throws Exception { + Node testRoot = buildTestRoot("testscripts/ManipulateContextHelper.xml", "Manipulate"); + TestSuite testSuite = buildTestSuite(testRoot); + + List componentList = testSuite.getComponentList(); + testScript = (TestScript) componentList.get(0); + + List crs = new ArrayList(); + crs.add("Test"); + testScript.setCRs(crs); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), + "/dummy test suite/Manipulate CR=\"Test\" [ISSUE EXISTS]"); + + testScript.setCRs(new ArrayList()); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); + + testScript.setStatus("Pass"); + testScript.setCRs(null); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate STATUS=\"Pass\""); + + testScript.setStatus(null); + testScript.setIssue(""); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); + + testScript.setStatus(null); + testScript.setIssue(null); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate"); + + testScript.setStatus(null); + testScript.setIssue("Issue"); + runner = new ParallelScriptRunner(testScript); + Assert.assertEquals(runner.getName(), "/dummy test suite/Manipulate [ISSUE EXISTS]"); + + } + + @Test + public void testRunJtafTestScript() throws Throwable { + Node testRoot = buildTestRoot("testscripts/ParallelScriptRunner.xml", "Runner"); + TestSuite testSuite = buildTestSuite(testRoot); + + List componentList = testSuite.getComponentList(); + testScript = (TestScript) componentList.get(0); + if (AutomationEngine.getInstance().getTestDigraph().getVertex(testScript.getName()) != null) { + AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(), + "FAILED"); + + } else { + MyNode node = new MyNode(testScript); + node.setTestStatus("FAILED"); + + AutomationEngine.getInstance().getTestDigraph().addVertex(node); + } + + runner = new ParallelScriptRunner(testScript); + + Throwable error = null; + try { + runner.runJtafTestScript(); + } catch (Throwable e) { + error = e; + } + Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionError")); + Assert.assertTrue(error.getMessage().equals("One or more Dependent tests failed")); + + + AutomationEngine.getInstance().getTestDigraph().updateTestStatus(testScript.getName(), + "SUCCESS"); + try { + runner.runJtafTestScript(); + } catch (Throwable e) { + error = e; + } + Assert.assertTrue(error.getClass().getSimpleName().equals("AssertionFailedError")); + + } + + protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { + Node testRoot = null; + InputStream inputStream = new FileInputStream(scriptFileName); + Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( + inputStream).getDocumentElement(); + NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); + for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { + Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); + if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") + && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent() + .equals(testOfInterestName)) { + testRoot = suiteNodeChildNode; + break; + } + } + return testRoot; + } + + protected TestSuite buildTestSuite(Node testRoot) throws Exception { + TestSuite testSuite = new TestSuite("dummy test suite"); + TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript( + (Element) testRoot, new MessageCollector()); + testSuite.add(testScript); + return testSuite; + } + + private class MyNode extends DiNode { + + private String testName = ""; // This shouldnt change after being set + // initially + private String testStatus = ""; + private TestScript testScript = null; // This shouldnt change after + // being set initially + + public MyNode(TestScript ts) { + super(ts); + this.testName = ts.getName(); + this.testScript = ts; + } + + public String getTestStatus() { + return testStatus; + } + + protected void setTestStatus(String newTestStatus) { + testStatus = newTestStatus; + } + + public String getTestName() { + return testName; + } + + public TestScript getTestScript() { + return testScript; + } + } + +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java index 50cc2ec..03527be 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/AutomationValueFilterPluginTest.java @@ -1,132 +1,132 @@ -package org.finra.jtaf.core.parsing; - -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.parsing.AutomationValueFilterPlugin; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - -public class AutomationValueFilterPluginTest { - private static final String AUTOMATION_VALUE_A = "A"; - private static final String AUTOMATION_VALUE_B = "B"; - private static final String AUTOMATION_VALUE_C = "C"; - private static final String AUTOMATION_VALUE_D = "D"; - - private TestAgenda testAgenda; - private TestScript dummyScriptA; - private TestScript dummyScriptB1; - private TestScript dummyScriptB2; - private TestScript dummyScriptC; - private PostAllParserPluginContext postAllParserPluginContext; - - @Before - public void setup() throws NameFormatException { - testAgenda = new TestAgenda(); - - dummyScriptA = buildDummyScript(testAgenda, "DummyScriptA", AUTOMATION_VALUE_A); - dummyScriptB1 = buildDummyScript(testAgenda, "DummyScriptB1", AUTOMATION_VALUE_B); - dummyScriptB2 = buildDummyScript(testAgenda, "DummyScriptB2", AUTOMATION_VALUE_B); - dummyScriptC = buildDummyScript(testAgenda, "DummyScriptC", AUTOMATION_VALUE_C); - - postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); - } - - private TestScript buildDummyScript(TestAgenda testAgenda, String name, String automationValueA) throws NameFormatException { - TestScript result = new TestScript(name, false); - result.setAutomationValue(automationValueA); - result.setFileName("DummyFileName.xml"); - testAgenda.getTestScripts().add(result); - return result; - } - - @Test - public void testExecuteNoAutomationValues() throws NameFormatException, ParserPluginException { - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueNoIncludedTests() throws NameFormatException, ParserPluginException { - testAgenda.addAutomationValue(AUTOMATION_VALUE_D); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueOneIncludedTest() throws NameFormatException, ParserPluginException { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteOneAutomationValueTwoIncludedTests() throws NameFormatException, ParserPluginException { - testAgenda.addAutomationValue(AUTOMATION_VALUE_B); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteTwoAutomationValuesThreeIncludedTests() throws NameFormatException, ParserPluginException { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - testAgenda.addAutomationValue(AUTOMATION_VALUE_B); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); - } - - @Test - public void testExecuteTwoAutomationValuesNoAutomationValueInTestOrStrategy() throws NameFormatException, ParserPluginException { - dummyScriptA.setAutomationValue(null); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); - } - - @Test - public void testExecuteTwoAutomationValuesNoAutomationValueInTestOneInStrategy() throws NameFormatException, ParserPluginException { - testAgenda.addAutomationValue(AUTOMATION_VALUE_A); - - dummyScriptA.setAutomationValue(null); - - AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); - automationValueFilterPlugin.execute(postAllParserPluginContext); - - Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); - } -} +package org.finra.jtaf.core.parsing; + +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.parsing.AutomationValueFilterPlugin; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class AutomationValueFilterPluginTest { + private static final String AUTOMATION_VALUE_A = "A"; + private static final String AUTOMATION_VALUE_B = "B"; + private static final String AUTOMATION_VALUE_C = "C"; + private static final String AUTOMATION_VALUE_D = "D"; + + private TestAgenda testAgenda; + private TestScript dummyScriptA; + private TestScript dummyScriptB1; + private TestScript dummyScriptB2; + private TestScript dummyScriptC; + private PostAllParserPluginContext postAllParserPluginContext; + + @Before + public void setup() throws NameFormatException { + testAgenda = new TestAgenda(); + + dummyScriptA = buildDummyScript(testAgenda, "DummyScriptA", AUTOMATION_VALUE_A); + dummyScriptB1 = buildDummyScript(testAgenda, "DummyScriptB1", AUTOMATION_VALUE_B); + dummyScriptB2 = buildDummyScript(testAgenda, "DummyScriptB2", AUTOMATION_VALUE_B); + dummyScriptC = buildDummyScript(testAgenda, "DummyScriptC", AUTOMATION_VALUE_C); + + postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); + } + + private TestScript buildDummyScript(TestAgenda testAgenda, String name, String automationValueA) throws NameFormatException { + TestScript result = new TestScript(name, false); + result.setAutomationValue(automationValueA); + result.setFileName("DummyFileName.xml"); + testAgenda.getTestScripts().add(result); + return result; + } + + @Test + public void testExecuteNoAutomationValues() throws NameFormatException, ParserPluginException { + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueNoIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_D); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueOneIncludedTest() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteOneAutomationValueTwoIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_B); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteTwoAutomationValuesThreeIncludedTests() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + testAgenda.addAutomationValue(AUTOMATION_VALUE_B); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB1)); + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptB2)); + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptC)); + } + + @Test + public void testExecuteTwoAutomationValuesNoAutomationValueInTestOrStrategy() throws NameFormatException, ParserPluginException { + dummyScriptA.setAutomationValue(null); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertTrue(testAgenda.getTestScripts().contains(dummyScriptA)); + } + + @Test + public void testExecuteTwoAutomationValuesNoAutomationValueInTestOneInStrategy() throws NameFormatException, ParserPluginException { + testAgenda.addAutomationValue(AUTOMATION_VALUE_A); + + dummyScriptA.setAutomationValue(null); + + AutomationValueFilterPlugin automationValueFilterPlugin = new AutomationValueFilterPlugin(); + automationValueFilterPlugin.execute(postAllParserPluginContext); + + Assert.assertFalse(testAgenda.getTestScripts().contains(dummyScriptA)); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java index 9c0785d..77cdd11 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/AutomationValuePluginTest.java @@ -1,47 +1,47 @@ -package org.finra.jtaf.core.parsing; - -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.parsing.AutomationValuePlugin; -import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class AutomationValuePluginTest { - private static final String AUTOMATION_VALUE_NAME = "automationValue"; - private static final String AUTOMATION_VALUE_TEST_STRATEGY_FILE = "AutomationValueTestStrategy.strategy.xml"; - private static final String FILE_AUTOMATION_VALUE = "DummyAutomationValue"; - - @Test - public void testExecute() throws Exception { - TestAgenda testAgenda = new TestAgenda(); - Assert.assertTrue("Test agenda automation values set is NOT empty", testAgenda.isAutomationValuesEmpty()); - AutomationValuePlugin automationValuePlugin = new AutomationValuePlugin(); - Element element = buildElement(); - PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); - automationValuePlugin.execute(postStrategyParserPluginContext); - Assert.assertFalse("Test agenda automation values set IS empty", testAgenda.isAutomationValuesEmpty()); - Assert.assertEquals("Test agenda has incorrect automation values size", 1, testAgenda.getAutomationValues().size()); - Assert.assertTrue("Automation Value: " + FILE_AUTOMATION_VALUE + " was NOT found", testAgenda.containsAutomationValue(FILE_AUTOMATION_VALUE)); - } - - private Element buildElement() throws Exception { - InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(AUTOMATION_VALUE_TEST_STRATEGY_FILE); - Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList nodeList = executeRoot.getChildNodes(); - Element element = null; - for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { - Node node = nodeList.item(nodeIndex); - if (node.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { - element = (Element) node; - } - } - return element; - } -} +package org.finra.jtaf.core.parsing; + +import java.io.InputStream; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.parsing.AutomationValuePlugin; +import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class AutomationValuePluginTest { + private static final String AUTOMATION_VALUE_NAME = "automationValue"; + private static final String AUTOMATION_VALUE_TEST_STRATEGY_FILE = "AutomationValueTestStrategy.strategy.xml"; + private static final String FILE_AUTOMATION_VALUE = "DummyAutomationValue"; + + @Test + public void testExecute() throws Exception { + TestAgenda testAgenda = new TestAgenda(); + Assert.assertTrue("Test agenda automation values set is NOT empty", testAgenda.isAutomationValuesEmpty()); + AutomationValuePlugin automationValuePlugin = new AutomationValuePlugin(); + Element element = buildElement(); + PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); + automationValuePlugin.execute(postStrategyParserPluginContext); + Assert.assertFalse("Test agenda automation values set IS empty", testAgenda.isAutomationValuesEmpty()); + Assert.assertEquals("Test agenda has incorrect automation values size", 1, testAgenda.getAutomationValues().size()); + Assert.assertTrue("Automation Value: " + FILE_AUTOMATION_VALUE + " was NOT found", testAgenda.containsAutomationValue(FILE_AUTOMATION_VALUE)); + } + + private Element buildElement() throws Exception { + InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(AUTOMATION_VALUE_TEST_STRATEGY_FILE); + Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList nodeList = executeRoot.getChildNodes(); + Element element = null; + for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { + Node node = nodeList.item(nodeIndex); + if (node.getNodeName().equalsIgnoreCase(AUTOMATION_VALUE_NAME)) { + element = (Element) node; + } + } + return element; + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java index f9d00bd..32443fb 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/DigraphPluginTest.java @@ -1,38 +1,38 @@ -package org.finra.jtaf.core.parsing; - -import java.io.File; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.model.test.TestScript; -import org.junit.Assert; -import org.junit.Test; - -public class DigraphPluginTest { - private static final String DEPENDENT_TEST = "Dependent Test with AutomationValue not Specified in Strategy"; - private static final String AUTOMATION_VALUE = "AutomationValueTest"; - - private TestAgenda testAgenda; - - @Test - public void testAutomationValueChangedWhenDependent() { - AutomationEngine automationEngine = AutomationEngine.getInstance(); - if (automationEngine.getTestAgenda() == null) - automationEngine.buildModel(new File("testlibrary"), new File("testscripts")); - testAgenda = automationEngine.getTestAgenda(); - - Assert.assertTrue(testAgendaIncludesTest(DEPENDENT_TEST)); - Assert.assertEquals(AUTOMATION_VALUE, getScriptByName(DEPENDENT_TEST).getAutomationValue()); - } - - private boolean testAgendaIncludesTest(String dependentTest) { - return getScriptByName(DEPENDENT_TEST) != null; - } - - private TestScript getScriptByName(String dependentTest) { - for (TestScript testScript : testAgenda.getTestScripts()) - if (testScript.getName().equals(dependentTest)) - return testScript; - return null; - } -} +package org.finra.jtaf.core.parsing; + +import java.io.File; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.model.test.TestScript; +import org.junit.Assert; +import org.junit.Test; + +public class DigraphPluginTest { + private static final String DEPENDENT_TEST = "Dependent Test with AutomationValue not Specified in Strategy"; + private static final String AUTOMATION_VALUE = "AutomationValueTest"; + + private TestAgenda testAgenda; + + @Test + public void testAutomationValueChangedWhenDependent() { + AutomationEngine automationEngine = AutomationEngine.getInstance(); + if (automationEngine.getTestAgenda() == null) + automationEngine.buildModel(new File("testlibrary"), new File("testscripts")); + testAgenda = automationEngine.getTestAgenda(); + + Assert.assertTrue(testAgendaIncludesTest(DEPENDENT_TEST)); + Assert.assertEquals(AUTOMATION_VALUE, getScriptByName(DEPENDENT_TEST).getAutomationValue()); + } + + private boolean testAgendaIncludesTest(String dependentTest) { + return getScriptByName(DEPENDENT_TEST) != null; + } + + private TestScript getScriptByName(String dependentTest) { + for (TestScript testScript : testAgenda.getTestScripts()) + if (testScript.getName().equals(dependentTest)) + return testScript; + return null; + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java index 5527d9b..80a9363 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/LoopPluginTest.java @@ -1,41 +1,41 @@ -package org.finra.jtaf.core.parsing; - -import java.util.List; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.parsing.LoopPlugin; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Node; - - -public class LoopPluginTest extends ParserPluginTest { - private static final String SCRIPT_FILE_NAME = "testscripts/LoopDebug.xml"; - private static final String TEST_OF_INTEREST_NAME = "Loop Debug Test"; - private static final int ITERATION_COUNT = 4; - - @Test - public void testExecute() throws Exception { - LoopPlugin loopPlugin = new LoopPlugin(AutomationEngine.getInstance()); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - Assert.assertEquals(1, testSuite.getComponentList().size()); - - List componentList = testSuite.getComponentList(); - String originalTestName = componentList.get(componentList.size() - 1).getName(); - Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); - - loopPlugin.execute(postTestParserPluginContext); - Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); - for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { - TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); - Assert.assertEquals(TEST_OF_INTEREST_NAME + " [iteration " + iterationNumber + " of " + ITERATION_COUNT + "]", iterationTestScript.getName()); - System.out.println(iterationTestScript.getName()); - } - } -} +package org.finra.jtaf.core.parsing; + +import java.util.List; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.parsing.LoopPlugin; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Node; + + +public class LoopPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/LoopDebug.xml"; + private static final String TEST_OF_INTEREST_NAME = "Loop Debug Test"; + private static final int ITERATION_COUNT = 4; + + @Test + public void testExecute() throws Exception { + LoopPlugin loopPlugin = new LoopPlugin(AutomationEngine.getInstance()); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + Assert.assertEquals(1, testSuite.getComponentList().size()); + + List componentList = testSuite.getComponentList(); + String originalTestName = componentList.get(componentList.size() - 1).getName(); + Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); + + loopPlugin.execute(postTestParserPluginContext); + Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); + for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { + TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); + Assert.assertEquals(TEST_OF_INTEREST_NAME + " [iteration " + iterationNumber + " of " + ITERATION_COUNT + "]", iterationTestScript.getName()); + System.out.println(iterationTestScript.getName()); + } + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java index cf6394c..8e80f2a 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/MaxThreadsPluginTest.java @@ -1,47 +1,47 @@ -package org.finra.jtaf.core.parsing; - -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.parsing.MaxThreadsPlugin; -import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -public class MaxThreadsPluginTest { - private static final String MAX_THREADS_NAME = "maxThreads"; - private static final String MAX_THREADS_TEST_STRATEGY_FILE = "MaxThreadsTestStrategy.strategy.xml"; - private static final int DEFAULT_THREAD_COUNT = 1; - private static final int FILE_THREAD_COUNT = 3; - - @Test - public void testExecute() throws Exception { - TestAgenda testAgenda = new TestAgenda(); - Assert.assertEquals(DEFAULT_THREAD_COUNT, testAgenda.getThreadCount()); - MaxThreadsPlugin maxThreadsPlugin = new MaxThreadsPlugin(); - Element element = buildElement(); - PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); - maxThreadsPlugin.execute(postStrategyParserPluginContext); - Assert.assertEquals(FILE_THREAD_COUNT, testAgenda.getThreadCount()); - } - - private Element buildElement() throws Exception { - InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(MAX_THREADS_TEST_STRATEGY_FILE); - Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList nodeList = executeRoot.getChildNodes(); - Element element = null; - for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { - Node node = nodeList.item(nodeIndex); - if (node.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { - element = (Element) node; - } - } - return element; - } -} +package org.finra.jtaf.core.parsing; + +import java.io.InputStream; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.parsing.MaxThreadsPlugin; +import org.finra.jtaf.core.plugins.parsing.PostStrategyElementParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +public class MaxThreadsPluginTest { + private static final String MAX_THREADS_NAME = "maxThreads"; + private static final String MAX_THREADS_TEST_STRATEGY_FILE = "MaxThreadsTestStrategy.strategy.xml"; + private static final int DEFAULT_THREAD_COUNT = 1; + private static final int FILE_THREAD_COUNT = 3; + + @Test + public void testExecute() throws Exception { + TestAgenda testAgenda = new TestAgenda(); + Assert.assertEquals(DEFAULT_THREAD_COUNT, testAgenda.getThreadCount()); + MaxThreadsPlugin maxThreadsPlugin = new MaxThreadsPlugin(); + Element element = buildElement(); + PostStrategyElementParserPluginContext postStrategyParserPluginContext = new PostStrategyElementParserPluginContext(testAgenda, element); + maxThreadsPlugin.execute(postStrategyParserPluginContext); + Assert.assertEquals(FILE_THREAD_COUNT, testAgenda.getThreadCount()); + } + + private Element buildElement() throws Exception { + InputStream inputStream = AutomationValuePluginTest.class.getClassLoader().getResourceAsStream(MAX_THREADS_TEST_STRATEGY_FILE); + Element executeRoot = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList nodeList = executeRoot.getChildNodes(); + Element element = null; + for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) { + Node node = nodeList.item(nodeIndex); + if (node.getNodeName().equalsIgnoreCase(MAX_THREADS_NAME)) { + element = (Element) node; + } + } + return element; + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java index 8781655..629d6ce 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/ParserPluginTest.java @@ -1,39 +1,39 @@ -package org.finra.jtaf.core.parsing; - -import java.io.FileInputStream; -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - - -public abstract class ParserPluginTest { - protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { - Node testRoot = null; - InputStream inputStream = new FileInputStream(scriptFileName); - Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); - NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); - for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { - Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); - if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent().equals(testOfInterestName)) { - testRoot = suiteNodeChildNode; - break; - } - } - return testRoot; - } - - protected TestSuite buildTestSuite(Node testRoot) throws Exception { - TestSuite testSuite = new TestSuite("dummy test suite"); - TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript((Element) testRoot, new MessageCollector()); - testSuite.add(testScript); - return testSuite; - } -} +package org.finra.jtaf.core.parsing; + +import java.io.FileInputStream; +import java.io.InputStream; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +public abstract class ParserPluginTest { + protected Node buildTestRoot(String scriptFileName, String testOfInterestName) throws Exception { + Node testRoot = null; + InputStream inputStream = new FileInputStream(scriptFileName); + Node suiteNode = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream).getDocumentElement(); + NodeList suiteNodeChildNodes = suiteNode.getChildNodes(); + for (int suiteNodeChildIndex = 0; suiteNodeChildIndex < suiteNodeChildNodes.getLength(); suiteNodeChildIndex++) { + Node suiteNodeChildNode = suiteNodeChildNodes.item(suiteNodeChildIndex); + if (suiteNodeChildNode.getNodeName().equalsIgnoreCase("test") && suiteNodeChildNode.getAttributes().getNamedItem("name").getTextContent().equals(testOfInterestName)) { + testRoot = suiteNodeChildNode; + break; + } + } + return testRoot; + } + + protected TestSuite buildTestSuite(Node testRoot) throws Exception { + TestSuite testSuite = new TestSuite("dummy test suite"); + TestScript testScript = AutomationEngine.getInstance().getScriptParser().processTestScript((Element) testRoot, new MessageCollector()); + testSuite.add(testScript); + return testSuite; + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java b/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java index 3a10d56..7b2e67c 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java +++ b/src/test/java/org/finra/jtaf/core/parsing/ScriptParserTests.java @@ -1,52 +1,52 @@ -package org.finra.jtaf.core.parsing; - -import java.io.File; -import java.io.FileNotFoundException; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.statement.InvocationList; -import org.finra.jtaf.core.model.test.TestNamespace; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Test; - -public class ScriptParserTests { - private static final String SCRIPT_FILE_NAME = "EveryTagSuite.xml"; - - - private static final String MISSING_FILE_NAME = "ThisFileDoesNotExist.xml"; - private static final String DUPLICATE_TEST_FILE_NAME = "parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml"; - - @Test - public void testHandleTestSource() throws Exception { - DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/every_tag/" + SCRIPT_FILE_NAME).getDocumentElement(); -// TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - TestNamespace fileNameSpace = AutomationEngine.getInstance().getScriptParser().handleTestSource(new File("parser_testing/every_tag"), new MessageCollector()); - TestSuite testSuite = (TestSuite) fileNameSpace.getComponentList().get(0); - TestScript testScript = (TestScript) testSuite.getComponentList().get(0); - - Assert.assertEquals("Test with Every Tag", testScript.getName()); - Assert.assertEquals("Some issue", testScript.getIssue()); - Assert.assertEquals(1, testScript.getCRs().size()); - Assert.assertEquals("cr123", testScript.getCRs().get(0)); - Assert.assertEquals("Some coverage", testScript.getCoverage()); - - InvocationList invocationList = testScript.getBody(); - Assert.assertEquals(1, invocationList.size()); - Assert.assertEquals("TryRecoverCleanup", invocationList.get(0).getTargetName()); - } - - @Test(expected = FileNotFoundException.class) - public void testHandleTestSourceNoFile() throws Exception { - (new ScriptParser()).handleTestSource(new File(MISSING_FILE_NAME), new MessageCollector()); - } - - @Test - public void testhandleTestSourceDuplicateTestName() throws Exception { - (new ScriptParser()).handleTestSource(new File(DUPLICATE_TEST_FILE_NAME), new MessageCollector()); - } -} +package org.finra.jtaf.core.parsing; + +import java.io.File; +import java.io.FileNotFoundException; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.statement.InvocationList; +import org.finra.jtaf.core.model.test.TestNamespace; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Test; + +public class ScriptParserTests { + private static final String SCRIPT_FILE_NAME = "EveryTagSuite.xml"; + + + private static final String MISSING_FILE_NAME = "ThisFileDoesNotExist.xml"; + private static final String DUPLICATE_TEST_FILE_NAME = "parser_testing/DuplicateTestNameFolder/DuplicateTestName.xml"; + + @Test + public void testHandleTestSource() throws Exception { + DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/every_tag/" + SCRIPT_FILE_NAME).getDocumentElement(); +// TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); + TestNamespace fileNameSpace = AutomationEngine.getInstance().getScriptParser().handleTestSource(new File("parser_testing/every_tag"), new MessageCollector()); + TestSuite testSuite = (TestSuite) fileNameSpace.getComponentList().get(0); + TestScript testScript = (TestScript) testSuite.getComponentList().get(0); + + Assert.assertEquals("Test with Every Tag", testScript.getName()); + Assert.assertEquals("Some issue", testScript.getIssue()); + Assert.assertEquals(1, testScript.getCRs().size()); + Assert.assertEquals("cr123", testScript.getCRs().get(0)); + Assert.assertEquals("Some coverage", testScript.getCoverage()); + + InvocationList invocationList = testScript.getBody(); + Assert.assertEquals(1, invocationList.size()); + Assert.assertEquals("TryRecoverCleanup", invocationList.get(0).getTargetName()); + } + + @Test(expected = FileNotFoundException.class) + public void testHandleTestSourceNoFile() throws Exception { + (new ScriptParser()).handleTestSource(new File(MISSING_FILE_NAME), new MessageCollector()); + } + + @Test + public void testhandleTestSourceDuplicateTestName() throws Exception { + (new ScriptParser()).handleTestSource(new File(DUPLICATE_TEST_FILE_NAME), new MessageCollector()); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java b/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java index 318eb1c..344180e 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/StatementParserTest.java @@ -1,144 +1,144 @@ -package org.finra.jtaf.core.parsing; - -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.model.statement.InvocationList; -import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; -import org.finra.jtaf.core.parsing.exceptions.ParsingException; -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.parsing.helpers.ParserHelper; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -// Only handles cases not covered by other tests -public class StatementParserTest { - private static final String TEST_ELEMENT = "test"; - private static final String TEST_STEPS_ELEMENT = "teststeps"; - private static final String TRY_RECOVER_CLEANUP_NAME = "TryRecoverCleanup"; - private static final String NAME_ATTRIBUTE = "name"; - private static final String FILE_NAME = "parser_testing/StatementParserTesting.xml"; - - private static final String NO_TEST_STEPS_SCRIPT_NAME = "No test steps"; - private static final String ONE_TEST_STEP_SCRIPT_NAME = "One test step"; - private static final String TRY_RECOVER_BLOCKS_SCRIPT_NAME = "Only try and recover at top level"; - private static final String RECOVER_FIRST_BLOCK_SCRIPT_NAME = "Only recover at top level"; - private static final String CLEANUP_FIRST_BLOCK_SCRIPT_NAME = "Only cleanup at top level"; - private static final String EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME = "Empty TryRecoverCleanup"; - private static final String BLOCK_PARAM_EXCEPTION_SCRIPT_NAME = "Block parameter has parsing exception"; - private static final String LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME = "List parameter has no parsing exception"; - private static final String LIST_PARAM_EXCEPTION_SCRIPT_NAME = "List parameter has parsing exception"; - - private static DocumentBuilder documentBuilder = null; - - private StatementParser statementParser = null; - - @BeforeClass - public static void beforeClass() throws Exception { - documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } - - @Before - public void before() { - statementParser = new StatementParser(); - } - - @Test - public void testProcessStatementListNoTestSteps() throws Exception { - Element testElement = getTestStepsElement(NO_TEST_STEPS_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(0, invocationList.size()); - } - - @Test - public void testProcessStatementListOneTestStep() throws Exception { - Element testElement = getTestStepsElement(ONE_TEST_STEP_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - } - - @Test - public void testProcessStatementListTryRecoverFirstBlocks() throws Exception { - Element testElement = getTestStepsElement(TRY_RECOVER_BLOCKS_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - } - - @Test(expected = UnexpectedElementException.class) - public void testProcessStatementListRecoverFirstBlock() throws Exception { - Element testElement = getTestStepsElement(RECOVER_FIRST_BLOCK_SCRIPT_NAME); - statementParser.processStatementList(testElement, new MessageCollector()); - } - - @Test(expected = UnexpectedElementException.class) - public void testProcessStatementListCleanupFirstBlock() throws Exception { - Element testElement = getTestStepsElement(CLEANUP_FIRST_BLOCK_SCRIPT_NAME); - statementParser.processStatementList(testElement, new MessageCollector()); - } - - @Test - public void testProcessStatementListEmptyTryRecoverCleanup() throws Exception { - Element testElement = getTestStepsElement(EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Assert.assertEquals(1, invocationList.size()); - Assert.assertEquals(TRY_RECOVER_CLEANUP_NAME, invocationList.get(0).getTargetName()); - } - - // this also covers the case of a map parameter having a parsing exception - @Test - public void testProcessStatementListInvocationBlockParameterHasException() throws Exception { - Element testElement = getTestStepsElement(BLOCK_PARAM_EXCEPTION_SCRIPT_NAME); - try { - statementParser.processStatementList(testElement, new MessageCollector()); - } catch (ParsingException parsingException) { - ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; - ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); - String message = "The element 'string' is missing the required attribute 'name'"; - Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); - } - } - - @Test - public void testProcessStatementListInvocationListParameterHasNoException() throws Exception { - Element testElement = getTestStepsElement(LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME); - InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); - Object listParameter = invocationList.get(0).getParameters().get("listParameter"); - Assert.assertNotNull(listParameter); - Assert.assertTrue(listParameter instanceof List); - } - - @Test - public void testProcessStatementListInvocationListParameterHasException() throws Exception { - Element testElement = getTestStepsElement(LIST_PARAM_EXCEPTION_SCRIPT_NAME); - try { - statementParser.processStatementList(testElement, new MessageCollector()); - } catch (ParsingException parsingException) { - ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; - ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); - String message = "The element 'string' is missing the required attribute 'name'"; - Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); - } - } - - protected Element getTestStepsElement(String testName) throws Exception { - Element documentElement = documentBuilder.parse(FILE_NAME).getDocumentElement(); - NodeList childNodes = documentElement.getChildNodes(); - for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { - Node testNode = childNodes.item(childNodeIndex); - if (!testNode.getNodeName().equalsIgnoreCase(TEST_ELEMENT)) - continue; - if (!testNode.getAttributes().getNamedItem(NAME_ATTRIBUTE).getTextContent().equals(testName)) - continue; - return ParserHelper.getFirstChildElementCaseInsensitive((Element) testNode, TEST_STEPS_ELEMENT); - } - return null; - } -} +package org.finra.jtaf.core.parsing; + +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.model.statement.InvocationList; +import org.finra.jtaf.core.parsing.exceptions.ExceptionAccumulator; +import org.finra.jtaf.core.parsing.exceptions.ParsingException; +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.parsing.helpers.ParserHelper; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +// Only handles cases not covered by other tests +public class StatementParserTest { + private static final String TEST_ELEMENT = "test"; + private static final String TEST_STEPS_ELEMENT = "teststeps"; + private static final String TRY_RECOVER_CLEANUP_NAME = "TryRecoverCleanup"; + private static final String NAME_ATTRIBUTE = "name"; + private static final String FILE_NAME = "parser_testing/StatementParserTesting.xml"; + + private static final String NO_TEST_STEPS_SCRIPT_NAME = "No test steps"; + private static final String ONE_TEST_STEP_SCRIPT_NAME = "One test step"; + private static final String TRY_RECOVER_BLOCKS_SCRIPT_NAME = "Only try and recover at top level"; + private static final String RECOVER_FIRST_BLOCK_SCRIPT_NAME = "Only recover at top level"; + private static final String CLEANUP_FIRST_BLOCK_SCRIPT_NAME = "Only cleanup at top level"; + private static final String EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME = "Empty TryRecoverCleanup"; + private static final String BLOCK_PARAM_EXCEPTION_SCRIPT_NAME = "Block parameter has parsing exception"; + private static final String LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME = "List parameter has no parsing exception"; + private static final String LIST_PARAM_EXCEPTION_SCRIPT_NAME = "List parameter has parsing exception"; + + private static DocumentBuilder documentBuilder = null; + + private StatementParser statementParser = null; + + @BeforeClass + public static void beforeClass() throws Exception { + documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } + + @Before + public void before() { + statementParser = new StatementParser(); + } + + @Test + public void testProcessStatementListNoTestSteps() throws Exception { + Element testElement = getTestStepsElement(NO_TEST_STEPS_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(0, invocationList.size()); + } + + @Test + public void testProcessStatementListOneTestStep() throws Exception { + Element testElement = getTestStepsElement(ONE_TEST_STEP_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + } + + @Test + public void testProcessStatementListTryRecoverFirstBlocks() throws Exception { + Element testElement = getTestStepsElement(TRY_RECOVER_BLOCKS_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + } + + @Test(expected = UnexpectedElementException.class) + public void testProcessStatementListRecoverFirstBlock() throws Exception { + Element testElement = getTestStepsElement(RECOVER_FIRST_BLOCK_SCRIPT_NAME); + statementParser.processStatementList(testElement, new MessageCollector()); + } + + @Test(expected = UnexpectedElementException.class) + public void testProcessStatementListCleanupFirstBlock() throws Exception { + Element testElement = getTestStepsElement(CLEANUP_FIRST_BLOCK_SCRIPT_NAME); + statementParser.processStatementList(testElement, new MessageCollector()); + } + + @Test + public void testProcessStatementListEmptyTryRecoverCleanup() throws Exception { + Element testElement = getTestStepsElement(EMPTY_TRY_RECOVER_CLEANUP_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Assert.assertEquals(1, invocationList.size()); + Assert.assertEquals(TRY_RECOVER_CLEANUP_NAME, invocationList.get(0).getTargetName()); + } + + // this also covers the case of a map parameter having a parsing exception + @Test + public void testProcessStatementListInvocationBlockParameterHasException() throws Exception { + Element testElement = getTestStepsElement(BLOCK_PARAM_EXCEPTION_SCRIPT_NAME); + try { + statementParser.processStatementList(testElement, new MessageCollector()); + } catch (ParsingException parsingException) { + ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; + ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); + String message = "The element 'string' is missing the required attribute 'name'"; + Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); + } + } + + @Test + public void testProcessStatementListInvocationListParameterHasNoException() throws Exception { + Element testElement = getTestStepsElement(LIST_PARAM_NO_EXCEPTION_SCRIPT_NAME); + InvocationList invocationList = statementParser.processStatementList(testElement, new MessageCollector()); + Object listParameter = invocationList.get(0).getParameters().get("listParameter"); + Assert.assertNotNull(listParameter); + Assert.assertTrue(listParameter instanceof List); + } + + @Test + public void testProcessStatementListInvocationListParameterHasException() throws Exception { + Element testElement = getTestStepsElement(LIST_PARAM_EXCEPTION_SCRIPT_NAME); + try { + statementParser.processStatementList(testElement, new MessageCollector()); + } catch (ParsingException parsingException) { + ExceptionAccumulator asExceptionAccumulator = (ExceptionAccumulator) parsingException; + ExceptionAccumulator innerExceptionAccumulator = (ExceptionAccumulator) asExceptionAccumulator.getExceptions().get(0); + String message = "The element 'string' is missing the required attribute 'name'"; + Assert.assertEquals(message, innerExceptionAccumulator.getExceptions().get(0).getMessage()); + } + } + + protected Element getTestStepsElement(String testName) throws Exception { + Element documentElement = documentBuilder.parse(FILE_NAME).getDocumentElement(); + NodeList childNodes = documentElement.getChildNodes(); + for (int childNodeIndex = 0; childNodeIndex < childNodes.getLength(); childNodeIndex++) { + Node testNode = childNodes.item(childNodeIndex); + if (!testNode.getNodeName().equalsIgnoreCase(TEST_ELEMENT)) + continue; + if (!testNode.getAttributes().getNamedItem(NAME_ATTRIBUTE).getTextContent().equals(testName)) + continue; + return ParserHelper.getFirstChildElementCaseInsensitive((Element) testNode, TEST_STEPS_ELEMENT); + } + return null; + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java index 9e465e8..200eec7 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/SuiteDependenciesPluginTest.java @@ -1,50 +1,50 @@ -package org.finra.jtaf.core.parsing; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Element; - - -public class SuiteDependenciesPluginTest extends ParserPluginTest { - private static final String TAG_NAME = "dependencies"; - private static final String SCRIPT_FILE_NAME = "SuiteDependencyParserTest.xml"; - private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteDependency.xml"; - private static final String DEPENDENT_SUITE_NAME = "JTAF CORE"; - private static final String DEPENDENT_TEST_NAME = "Block Testing"; - - @Test() - public void testExecute() throws Exception { - SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteDependenciesPlugin.execute(postSuiteParserPluginContext); - - Assert.assertEquals(1, testSuite.getDependencies().getDependenciesSuites().size()); - Assert.assertTrue(testSuite.getDependencies().getDependenciesSuites().contains(DEPENDENT_SUITE_NAME)); - - Assert.assertEquals(1, testSuite.getDependencies().getDependenciesTests().size()); - Assert.assertTrue(testSuite.getDependencies().getDependenciesTests().contains(DEPENDENT_TEST_NAME)); - } - - @Test(expected = ParserPluginException.class) - public void testExecuteUnexpectedElement() throws Exception { - SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteDependenciesPlugin.execute(postSuiteParserPluginContext); - } - - @Test - public void testGetTagName() { - Assert.assertEquals(TAG_NAME, new SuiteDependenciesPlugin().getTagName()); - } -} +package org.finra.jtaf.core.parsing; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Element; + + +public class SuiteDependenciesPluginTest extends ParserPluginTest { + private static final String TAG_NAME = "dependencies"; + private static final String SCRIPT_FILE_NAME = "SuiteDependencyParserTest.xml"; + private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteDependency.xml"; + private static final String DEPENDENT_SUITE_NAME = "JTAF CORE"; + private static final String DEPENDENT_TEST_NAME = "Block Testing"; + + @Test() + public void testExecute() throws Exception { + SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteDependenciesPlugin.execute(postSuiteParserPluginContext); + + Assert.assertEquals(1, testSuite.getDependencies().getDependenciesSuites().size()); + Assert.assertTrue(testSuite.getDependencies().getDependenciesSuites().contains(DEPENDENT_SUITE_NAME)); + + Assert.assertEquals(1, testSuite.getDependencies().getDependenciesTests().size()); + Assert.assertTrue(testSuite.getDependencies().getDependenciesTests().contains(DEPENDENT_TEST_NAME)); + } + + @Test(expected = ParserPluginException.class) + public void testExecuteUnexpectedElement() throws Exception { + SuiteDependenciesPlugin suiteDependenciesPlugin = new SuiteDependenciesPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteDependenciesPlugin.execute(postSuiteParserPluginContext); + } + + @Test + public void testGetTagName() { + Assert.assertEquals(TAG_NAME, new SuiteDependenciesPlugin().getTagName()); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java index d63257a..924c45b 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/SuiteExclusionsPluginTest.java @@ -1,50 +1,50 @@ -package org.finra.jtaf.core.parsing; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; -import org.finra.jtaf.core.utilities.logging.MessageCollector; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Element; - - -public class SuiteExclusionsPluginTest extends ParserPluginTest { - private static final String TAG_NAME = "exclusions"; - private static final String SCRIPT_FILE_NAME = "SuiteExclusionParserTest.xml"; - private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteExclusion.xml"; - private static final String EXCLUSION_SUITE_NAME = "JTAF CORE"; - private static final String EXCLUSION_TEST_NAME = "Block Testing"; - - @Test() - public void testExecute() throws Exception { - SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteExclusionsPlugin.execute(postSuiteParserPluginContext); - - Assert.assertEquals(1, testSuite.getExclusions().getDependenciesSuites().size()); - Assert.assertTrue(testSuite.getExclusions().getDependenciesSuites().contains(EXCLUSION_SUITE_NAME)); - - Assert.assertEquals(1, testSuite.getExclusions().getDependenciesTests().size()); - Assert.assertTrue(testSuite.getExclusions().getDependenciesTests().contains(EXCLUSION_TEST_NAME)); - } - - @Test(expected = ParserPluginException.class) - public void testExecuteUnexpectedElement() throws Exception { - SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); - Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); - TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); - PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); - suiteExclusionsPlugin.execute(postSuiteParserPluginContext); - } - - @Test - public void testGetTagName() { - Assert.assertEquals(TAG_NAME, new SuiteExclusionsPlugin().getTagName()); - } -} +package org.finra.jtaf.core.parsing; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostSuiteParserPluginContext; +import org.finra.jtaf.core.utilities.logging.MessageCollector; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Element; + + +public class SuiteExclusionsPluginTest extends ParserPluginTest { + private static final String TAG_NAME = "exclusions"; + private static final String SCRIPT_FILE_NAME = "SuiteExclusionParserTest.xml"; + private static final String UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME = "UnexpectedElementSuiteExclusion.xml"; + private static final String EXCLUSION_SUITE_NAME = "JTAF CORE"; + private static final String EXCLUSION_TEST_NAME = "Block Testing"; + + @Test() + public void testExecute() throws Exception { + SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteExclusionsPlugin.execute(postSuiteParserPluginContext); + + Assert.assertEquals(1, testSuite.getExclusions().getDependenciesSuites().size()); + Assert.assertTrue(testSuite.getExclusions().getDependenciesSuites().contains(EXCLUSION_SUITE_NAME)); + + Assert.assertEquals(1, testSuite.getExclusions().getDependenciesTests().size()); + Assert.assertTrue(testSuite.getExclusions().getDependenciesTests().contains(EXCLUSION_TEST_NAME)); + } + + @Test(expected = ParserPluginException.class) + public void testExecuteUnexpectedElement() throws Exception { + SuiteExclusionsPlugin suiteExclusionsPlugin = new SuiteExclusionsPlugin(); + Element element = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("parser_testing/" + UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME).getDocumentElement(); + TestSuite testSuite = AutomationEngine.getInstance().getScriptParser().processTestSuite(element, new MessageCollector(), UNEXPECTED_ELEMENT_SCRIPT_FILE_NAME); + PostSuiteParserPluginContext postSuiteParserPluginContext = new PostSuiteParserPluginContext(null, testSuite, element); + suiteExclusionsPlugin.execute(postSuiteParserPluginContext); + } + + @Test + public void testGetTagName() { + Assert.assertEquals(TAG_NAME, new SuiteExclusionsPlugin().getTagName()); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java index f8b47dd..4361a06 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestDataPluginTest.java @@ -1,44 +1,44 @@ -package org.finra.jtaf.core.parsing; - -import java.util.List; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.parsing.TestDataPlugin; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Node; - - -public class TestDataPluginTest extends ParserPluginTest { - private static final String SCRIPT_FILE_NAME = "testscripts/TestDataDebug.xml"; - private static final String TEST_OF_INTEREST_NAME = "TestData Debug Test"; - private static final int ITERATION_COUNT = 4; - private static final String[] TEST_NAMES_FROM_DATA_FILE = new String[]{"Print XYZ", "Print ABC", "Print 123", "Print 456"}; - - @Test - public void testExecute() throws Exception { -// LoopPlugin loopPlugin = new LoopPlugin(); - TestDataPlugin testDataPlugin = new TestDataPlugin(AutomationEngine.getInstance()); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - Assert.assertEquals(1, testSuite.getComponentList().size()); - - List componentList = testSuite.getComponentList(); - String originalTestName = componentList.get(componentList.size() - 1).getName(); - Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); - - testDataPlugin.execute(postTestParserPluginContext); - Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); - for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { - TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); - String testNameFromDataFile = TEST_NAMES_FROM_DATA_FILE[iterationNumber - 1]; - Assert.assertEquals(TEST_OF_INTEREST_NAME + " [data file row #" + iterationNumber + "] ; testNameFromDataFile-" + testNameFromDataFile, iterationTestScript.getName()); - System.out.println(iterationTestScript.getName()); - } - } -} +package org.finra.jtaf.core.parsing; + +import java.util.List; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.parsing.TestDataPlugin; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Node; + + +public class TestDataPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/TestDataDebug.xml"; + private static final String TEST_OF_INTEREST_NAME = "TestData Debug Test"; + private static final int ITERATION_COUNT = 4; + private static final String[] TEST_NAMES_FROM_DATA_FILE = new String[]{"Print XYZ", "Print ABC", "Print 123", "Print 456"}; + + @Test + public void testExecute() throws Exception { +// LoopPlugin loopPlugin = new LoopPlugin(); + TestDataPlugin testDataPlugin = new TestDataPlugin(AutomationEngine.getInstance()); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + Assert.assertEquals(1, testSuite.getComponentList().size()); + + List componentList = testSuite.getComponentList(); + String originalTestName = componentList.get(componentList.size() - 1).getName(); + Assert.assertEquals(TEST_OF_INTEREST_NAME, originalTestName); + + testDataPlugin.execute(postTestParserPluginContext); + Assert.assertEquals(ITERATION_COUNT, testSuite.getComponentList().size()); + for (int iterationNumber = 1; iterationNumber <= ITERATION_COUNT; iterationNumber++) { + TestScript iterationTestScript = (TestScript) componentList.get(iterationNumber - 1); + String testNameFromDataFile = TEST_NAMES_FROM_DATA_FILE[iterationNumber - 1]; + Assert.assertEquals(TEST_OF_INTEREST_NAME + " [data file row #" + iterationNumber + "] ; testNameFromDataFile-" + testNameFromDataFile, iterationTestScript.getName()); + System.out.println(iterationTestScript.getName()); + } + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java index eeb97e2..409606d 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestDependenciesPluginTest.java @@ -1,37 +1,37 @@ -package org.finra.jtaf.core.parsing; - -import java.util.List; - -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.model.test.digraph.Dependencies; -import org.finra.jtaf.core.parsing.TestDependenciesPlugin; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Node; - - -public class TestDependenciesPluginTest extends ParserPluginTest { - private static final String SCRIPT_FILE_NAME = "testscripts/DependencyTest.xml"; - private static final String TEST_OF_INTEREST_NAME = "Dependency Plugin Debug Test F"; - private static final String TEST_DEPENDENCY_1 = "Dependency Plugin Debug Test C"; - private static final String TEST_DEPENDENCY_2 = "Dependency Plugin Debug Test D"; - - @Test - public void testExecute() throws Exception { - TestDependenciesPlugin testDependenciesPlugin = new TestDependenciesPlugin(); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - testDependenciesPlugin.execute(postTestParserPluginContext); - - List componentList = testSuite.getComponentList(); - TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); - Dependencies dependencies = latestTestScript.getDependencies(); - Assert.assertEquals(2, dependencies.getDependenciesTests().size()); - Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_1)); - Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_2)); - } -} +package org.finra.jtaf.core.parsing; + +import java.util.List; + +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.model.test.digraph.Dependencies; +import org.finra.jtaf.core.parsing.TestDependenciesPlugin; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Node; + + +public class TestDependenciesPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/DependencyTest.xml"; + private static final String TEST_OF_INTEREST_NAME = "Dependency Plugin Debug Test F"; + private static final String TEST_DEPENDENCY_1 = "Dependency Plugin Debug Test C"; + private static final String TEST_DEPENDENCY_2 = "Dependency Plugin Debug Test D"; + + @Test + public void testExecute() throws Exception { + TestDependenciesPlugin testDependenciesPlugin = new TestDependenciesPlugin(); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + testDependenciesPlugin.execute(postTestParserPluginContext); + + List componentList = testSuite.getComponentList(); + TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); + Dependencies dependencies = latestTestScript.getDependencies(); + Assert.assertEquals(2, dependencies.getDependenciesTests().size()); + Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_1)); + Assert.assertTrue(dependencies.getDependenciesTests().contains(TEST_DEPENDENCY_2)); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java index 04ce67b..3612776 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestExclusionsPluginTest.java @@ -1,37 +1,37 @@ -package org.finra.jtaf.core.parsing; - -import java.util.List; - -import org.finra.jtaf.core.model.test.TestComponent; -import org.finra.jtaf.core.model.test.TestScript; -import org.finra.jtaf.core.model.test.TestSuite; -import org.finra.jtaf.core.model.test.digraph.Dependencies; -import org.finra.jtaf.core.parsing.TestExclusionsPlugin; -import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Node; - - -public class TestExclusionsPluginTest extends ParserPluginTest { - private static final String SCRIPT_FILE_NAME = "testscripts/ExclusionTest.xml"; - private static final String TEST_OF_INTEREST_NAME = "Exclusion Plugin Debug Test F"; - private static final String TEST_EXCLUSION_1 = "Exclusion Plugin Debug Test C"; - private static final String TEST_EXCLUSION_2 = "Exclusion Plugin Debug Test D"; - - @Test - public void testExecute() throws Exception { - TestExclusionsPlugin testExclusionsPlugin = new TestExclusionsPlugin(); - Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); - TestSuite testSuite = buildTestSuite(testRoot); - PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); - testExclusionsPlugin.execute(postTestParserPluginContext); - - List componentList = testSuite.getComponentList(); - TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); - Dependencies exclusions = latestTestScript.getExclusions(); - Assert.assertEquals(2, exclusions.getDependenciesTests().size()); - Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_1)); - Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_2)); - } -} +package org.finra.jtaf.core.parsing; + +import java.util.List; + +import org.finra.jtaf.core.model.test.TestComponent; +import org.finra.jtaf.core.model.test.TestScript; +import org.finra.jtaf.core.model.test.TestSuite; +import org.finra.jtaf.core.model.test.digraph.Dependencies; +import org.finra.jtaf.core.parsing.TestExclusionsPlugin; +import org.finra.jtaf.core.plugins.parsing.PostTestParserPluginContext; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Node; + + +public class TestExclusionsPluginTest extends ParserPluginTest { + private static final String SCRIPT_FILE_NAME = "testscripts/ExclusionTest.xml"; + private static final String TEST_OF_INTEREST_NAME = "Exclusion Plugin Debug Test F"; + private static final String TEST_EXCLUSION_1 = "Exclusion Plugin Debug Test C"; + private static final String TEST_EXCLUSION_2 = "Exclusion Plugin Debug Test D"; + + @Test + public void testExecute() throws Exception { + TestExclusionsPlugin testExclusionsPlugin = new TestExclusionsPlugin(); + Node testRoot = buildTestRoot(SCRIPT_FILE_NAME, TEST_OF_INTEREST_NAME); + TestSuite testSuite = buildTestSuite(testRoot); + PostTestParserPluginContext postTestParserPluginContext = new PostTestParserPluginContext(null, testSuite, testRoot); + testExclusionsPlugin.execute(postTestParserPluginContext); + + List componentList = testSuite.getComponentList(); + TestScript latestTestScript = (TestScript) componentList.get(componentList.size() - 1); + Dependencies exclusions = latestTestScript.getExclusions(); + Assert.assertEquals(2, exclusions.getDependenciesTests().size()); + Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_1)); + Assert.assertTrue(exclusions.getDependenciesTests().contains(TEST_EXCLUSION_2)); + } +} diff --git a/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java b/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java index f5540b3..41d924c 100644 --- a/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java +++ b/src/test/java/org/finra/jtaf/core/parsing/TestStrategyParserTest.java @@ -1,32 +1,32 @@ -package org.finra.jtaf.core.parsing; - -import java.io.File; -import java.util.ArrayList; - -import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; -import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; -import org.junit.Before; -import org.junit.Test; - -public class TestStrategyParserTest { - private static final String INVALID_ROOT_STRATEGY_FILE_NAME = "parser_testing/InvalidRoot.strategy.xml"; - private static final String MISSING_TARGET_NAME_STRATEGY_FILE_NAME = "parser_testing/MissingTargetNameAttribute.strategy.xml"; - - private TestStrategyParser testStrategyParser; - - @Before - public void before() throws Exception { - testStrategyParser = new TestStrategyParser(); - testStrategyParser.setPostParseStrategyElementPlugins(new ArrayList()); - } - - @Test(expected = UnexpectedElementException.class) - public void testParseInvalidRoot() throws Exception { - testStrategyParser.parse(new File(INVALID_ROOT_STRATEGY_FILE_NAME)); - } - - @Test - public void testParseMissingTargetName() throws Exception { - testStrategyParser.parse(new File(MISSING_TARGET_NAME_STRATEGY_FILE_NAME)); - } -} +package org.finra.jtaf.core.parsing; + +import java.io.File; +import java.util.ArrayList; + +import org.finra.jtaf.core.parsing.exceptions.UnexpectedElementException; +import org.finra.jtaf.core.plugins.parsing.IPostParseStrategyElementPlugin; +import org.junit.Before; +import org.junit.Test; + +public class TestStrategyParserTest { + private static final String INVALID_ROOT_STRATEGY_FILE_NAME = "parser_testing/InvalidRoot.strategy.xml"; + private static final String MISSING_TARGET_NAME_STRATEGY_FILE_NAME = "parser_testing/MissingTargetNameAttribute.strategy.xml"; + + private TestStrategyParser testStrategyParser; + + @Before + public void before() throws Exception { + testStrategyParser = new TestStrategyParser(); + testStrategyParser.setPostParseStrategyElementPlugins(new ArrayList()); + } + + @Test(expected = UnexpectedElementException.class) + public void testParseInvalidRoot() throws Exception { + testStrategyParser.parse(new File(INVALID_ROOT_STRATEGY_FILE_NAME)); + } + + @Test + public void testParseMissingTargetName() throws Exception { + testStrategyParser.parse(new File(MISSING_TARGET_NAME_STRATEGY_FILE_NAME)); + } +} diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java index 8077cbe..7c8578f 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyCommandRunnerPlugin.java @@ -1,38 +1,38 @@ -package org.finra.jtaf.core.plugins.execution; - -import org.finra.jtaf.core.mock.MockCommand2; -import org.finra.jtaf.core.plugins.execution.CommandRunnerPluginContext; -import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; -import org.finra.jtaf.core.plugins.execution.RunnerPluginException; -import org.junit.Assert; - - -public class DummyCommandRunnerPlugin implements ICommandRunnerPlugin { - - CommandRunnerPluginContext before; - CommandRunnerPluginContext after; - - @Override - public void handleCommandBefore(CommandRunnerPluginContext args) - throws RunnerPluginException { - - before = args; - if (before.getTestStepsDetails().getName().equals("mockstep2")) - Assert.assertEquals(false, MockCommand2.testEnd); - - } - - @Override - public void handleCommandAfter(CommandRunnerPluginContext args) - throws RunnerPluginException { - after = args; - if (before.getTestStepsDetails().getName().equals("mockstep2")) { - Assert.assertEquals(true, MockCommand2.testEnd); - - } - - if (after.getTestStepsDetails().getName().equals("mockstep1")) - Assert.assertEquals(true, after.getTestStepsDetails().getActualResult()); - } - -} +package org.finra.jtaf.core.plugins.execution; + +import org.finra.jtaf.core.mock.MockCommand2; +import org.finra.jtaf.core.plugins.execution.CommandRunnerPluginContext; +import org.finra.jtaf.core.plugins.execution.ICommandRunnerPlugin; +import org.finra.jtaf.core.plugins.execution.RunnerPluginException; +import org.junit.Assert; + + +public class DummyCommandRunnerPlugin implements ICommandRunnerPlugin { + + CommandRunnerPluginContext before; + CommandRunnerPluginContext after; + + @Override + public void handleCommandBefore(CommandRunnerPluginContext args) + throws RunnerPluginException { + + before = args; + if (before.getTestStepsDetails().getName().equals("mockstep2")) + Assert.assertEquals(false, MockCommand2.testEnd); + + } + + @Override + public void handleCommandAfter(CommandRunnerPluginContext args) + throws RunnerPluginException { + after = args; + if (before.getTestStepsDetails().getName().equals("mockstep2")) { + Assert.assertEquals(true, MockCommand2.testEnd); + + } + + if (after.getTestStepsDetails().getName().equals("mockstep1")) + Assert.assertEquals(true, after.getTestStepsDetails().getActualResult()); + } + +} diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java index fa9f17e..f34745d 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/DummyTestRunnerPlugin.java @@ -1,42 +1,42 @@ -package org.finra.jtaf.core.plugins.execution; - -import org.finra.jtaf.core.plugins.execution.RunnerPluginException; -import org.finra.jtaf.core.plugins.execution.TestRunnerPluginContext; -import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; - - -/** - * Dummy implementation for testing purposes - */ -public class DummyTestRunnerPlugin implements ITestRunnerPlugin { - - TestRunnerPluginContext argsBefore; - TestRunnerPluginContext argsAfter; - - @Override - public void handleTestStart(TestRunnerPluginContext args) - throws RunnerPluginException { - argsBefore = new TestRunnerPluginContext(null, null, null); - argsBefore = args; - - } - - @Override - public void handleTestFinish(TestRunnerPluginContext args) - throws RunnerPluginException { - argsAfter = new TestRunnerPluginContext(null, null, null); - argsAfter = args; - try { - if (argsAfter.getTestResult().getTestStepsDetails().size() > 0) { - if (argsAfter.getTestResult().getTestStepsDetails().get(0).getName().equalsIgnoreCase("mockstep2")) - throw new RunnerPluginException("Testing Plugin Exceptions"); - } - - } catch (RunnerPluginException e) { - throw new RunnerPluginException("Plugin Exception", e); - } - - - } - -} +package org.finra.jtaf.core.plugins.execution; + +import org.finra.jtaf.core.plugins.execution.RunnerPluginException; +import org.finra.jtaf.core.plugins.execution.TestRunnerPluginContext; +import org.finra.jtaf.core.plugins.execution.ITestRunnerPlugin; + + +/** + * Dummy implementation for testing purposes + */ +public class DummyTestRunnerPlugin implements ITestRunnerPlugin { + + TestRunnerPluginContext argsBefore; + TestRunnerPluginContext argsAfter; + + @Override + public void handleTestStart(TestRunnerPluginContext args) + throws RunnerPluginException { + argsBefore = new TestRunnerPluginContext(null, null, null); + argsBefore = args; + + } + + @Override + public void handleTestFinish(TestRunnerPluginContext args) + throws RunnerPluginException { + argsAfter = new TestRunnerPluginContext(null, null, null); + argsAfter = args; + try { + if (argsAfter.getTestResult().getTestStepsDetails().size() > 0) { + if (argsAfter.getTestResult().getTestStepsDetails().get(0).getName().equalsIgnoreCase("mockstep2")) + throw new RunnerPluginException("Testing Plugin Exceptions"); + } + + } catch (RunnerPluginException e) { + throw new RunnerPluginException("Plugin Exception", e); + } + + + } + +} diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java b/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java index a186d77..8f042f5 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/ExecutionPluginsTest.java @@ -1,179 +1,179 @@ -package org.finra.jtaf.core.plugins.execution; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.List; - -import org.finra.jtaf.core.CommandRegistry; -import org.finra.jtaf.core.DefaultAutomationClassLoader; -import org.finra.jtaf.core.IAutomationClassLoader; -import org.finra.jtaf.core.model.exceptions.NameFormatException; -import org.finra.jtaf.core.model.execution.Interpreter; -import org.finra.jtaf.core.model.invocationtarget.Command; -import org.finra.jtaf.core.model.statement.Invocation; -import org.finra.jtaf.core.model.statement.InvocationList; -import org.finra.jtaf.core.model.test.TestResult; -import org.finra.jtaf.core.model.test.TestScript; -import org.junit.Assert; -import org.junit.Test; - -public class ExecutionPluginsTest { - - private Command c1; - private Command c2; - private CommandRegistry cmdReg; - private Interpreter iv; - - private DummyTestRunnerPlugin dummyTestPlugin; - private DummyCommandRunnerPlugin dummyCommandPlugin; - private Invocation stmt; - private InvocationList statements; - private TestResult tr; - private IAutomationClassLoader automationClassLoader = new DefaultAutomationClassLoader(); - - private void setUpCommands() throws Throwable { - Class targetClass1 = automationClassLoader - .loadClass("org.finra.jtaf.core.mock.MockCommand1"); - Constructor constructor = targetClass1.getConstructor(String.class); - c1 = (Command) constructor.newInstance("mockstep1"); - - Class targetClass2 = automationClassLoader - .loadClass("org.finra.jtaf.core.mock.MockCommand2"); - Constructor constructor2 = targetClass2.getConstructor(String.class); - c2 = (Command) constructor2.newInstance("mockstep2"); - - } - - public void setUpRegistry() throws Throwable { - cmdReg = new CommandRegistry(); - cmdReg.registerInvocationTarget("mockstep1", c1); - cmdReg.registerInvocationTarget("mockstep2", c2); - } - - private void setupInterpreter(CommandRegistry cr) - throws NameFormatException { - dummyTestPlugin = new DummyTestRunnerPlugin(); - dummyCommandPlugin = new DummyCommandRunnerPlugin(); - List testRunnerPlugins = new ArrayList(); - testRunnerPlugins.add(dummyTestPlugin); - - List commandRunnerPlugins = new ArrayList(); - commandRunnerPlugins.add(dummyCommandPlugin); - - iv = new Interpreter(); - iv.setCommandRegistry(cr); - iv.setTestRunnerPlugins(testRunnerPlugins); - iv.setCommandRunnerPlugins(commandRunnerPlugins); - - } - - @Test - /* Test Success and Command Success */ - public void pluginCallbacksForTestSuccess() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts1 = new TestScript("DummyScript1", false); - stmt = new Invocation(c2.getName()); - statements = new InvocationList(); - statements.add(stmt); - - ts1.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts1); - } catch (Throwable e) { - e.printStackTrace(); - } - - Assert.assertEquals("DummyScript1", dummyTestPlugin.argsBefore - .getTestScript().getName()); - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep2", dummyCommandPlugin.before - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.before - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Passed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsAfter.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep2", dummyCommandPlugin.after - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.after - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Passed", tr.getTestStatus().toString()); - } - - @Test - /* Test Failure */ - public void pluginCallbacksForTestFailure1() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts2 = new TestScript("DummyScript2", false); - stmt = new Invocation("CommandDoesNotExist"); - statements = new InvocationList(); - statements.add(stmt); - ts2.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts2); - } catch (Throwable e) { - e.printStackTrace(); - } - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - - Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - - Assert.assertEquals("Failed", tr.getTestStatus().toString()); - } - - @Test - /* Test failure and Command failure */ - public void pluginCallbacksForTestFailure2() throws Throwable { - setUpCommands(); - setUpRegistry(); - TestScript ts3 = new TestScript("DummyScript3", false); - stmt = new Invocation(c1.getName()); - statements = new InvocationList(); - statements.add(stmt); - ts3.setBody(statements); - try { - setupInterpreter(cmdReg); - tr = iv.interpret(ts3); - } catch (Throwable e) { - e.printStackTrace(); - } - - dummyTestPlugin.argsBefore.getIInvocationContext(); - Assert.assertEquals("Running", dummyTestPlugin.argsBefore - .getTestResult().getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep1", dummyCommandPlugin.before - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.before - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() - .getTestStatus().toString()); - Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() - .getTestScript().getBody().contains(stmt)); - Assert.assertEquals("mockstep1", dummyCommandPlugin.after - .getTestStepsDetails().getName()); - Assert.assertEquals(true, dummyCommandPlugin.after - .getTestStepsDetails().getActualResult()); - - Assert.assertEquals("Failed", tr.getTestStatus().toString()); - } - +package org.finra.jtaf.core.plugins.execution; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.List; + +import org.finra.jtaf.core.CommandRegistry; +import org.finra.jtaf.core.DefaultAutomationClassLoader; +import org.finra.jtaf.core.IAutomationClassLoader; +import org.finra.jtaf.core.model.exceptions.NameFormatException; +import org.finra.jtaf.core.model.execution.Interpreter; +import org.finra.jtaf.core.model.invocationtarget.Command; +import org.finra.jtaf.core.model.statement.Invocation; +import org.finra.jtaf.core.model.statement.InvocationList; +import org.finra.jtaf.core.model.test.TestResult; +import org.finra.jtaf.core.model.test.TestScript; +import org.junit.Assert; +import org.junit.Test; + +public class ExecutionPluginsTest { + + private Command c1; + private Command c2; + private CommandRegistry cmdReg; + private Interpreter iv; + + private DummyTestRunnerPlugin dummyTestPlugin; + private DummyCommandRunnerPlugin dummyCommandPlugin; + private Invocation stmt; + private InvocationList statements; + private TestResult tr; + private IAutomationClassLoader automationClassLoader = new DefaultAutomationClassLoader(); + + private void setUpCommands() throws Throwable { + Class targetClass1 = automationClassLoader + .loadClass("org.finra.jtaf.core.mock.MockCommand1"); + Constructor constructor = targetClass1.getConstructor(String.class); + c1 = (Command) constructor.newInstance("mockstep1"); + + Class targetClass2 = automationClassLoader + .loadClass("org.finra.jtaf.core.mock.MockCommand2"); + Constructor constructor2 = targetClass2.getConstructor(String.class); + c2 = (Command) constructor2.newInstance("mockstep2"); + + } + + public void setUpRegistry() throws Throwable { + cmdReg = new CommandRegistry(); + cmdReg.registerInvocationTarget("mockstep1", c1); + cmdReg.registerInvocationTarget("mockstep2", c2); + } + + private void setupInterpreter(CommandRegistry cr) + throws NameFormatException { + dummyTestPlugin = new DummyTestRunnerPlugin(); + dummyCommandPlugin = new DummyCommandRunnerPlugin(); + List testRunnerPlugins = new ArrayList(); + testRunnerPlugins.add(dummyTestPlugin); + + List commandRunnerPlugins = new ArrayList(); + commandRunnerPlugins.add(dummyCommandPlugin); + + iv = new Interpreter(); + iv.setCommandRegistry(cr); + iv.setTestRunnerPlugins(testRunnerPlugins); + iv.setCommandRunnerPlugins(commandRunnerPlugins); + + } + + @Test + /* Test Success and Command Success */ + public void pluginCallbacksForTestSuccess() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts1 = new TestScript("DummyScript1", false); + stmt = new Invocation(c2.getName()); + statements = new InvocationList(); + statements.add(stmt); + + ts1.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts1); + } catch (Throwable e) { + e.printStackTrace(); + } + + Assert.assertEquals("DummyScript1", dummyTestPlugin.argsBefore + .getTestScript().getName()); + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep2", dummyCommandPlugin.before + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.before + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Passed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsAfter.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep2", dummyCommandPlugin.after + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.after + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Passed", tr.getTestStatus().toString()); + } + + @Test + /* Test Failure */ + public void pluginCallbacksForTestFailure1() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts2 = new TestScript("DummyScript2", false); + stmt = new Invocation("CommandDoesNotExist"); + statements = new InvocationList(); + statements.add(stmt); + ts2.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts2); + } catch (Throwable e) { + e.printStackTrace(); + } + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + + Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + + Assert.assertEquals("Failed", tr.getTestStatus().toString()); + } + + @Test + /* Test failure and Command failure */ + public void pluginCallbacksForTestFailure2() throws Throwable { + setUpCommands(); + setUpRegistry(); + TestScript ts3 = new TestScript("DummyScript3", false); + stmt = new Invocation(c1.getName()); + statements = new InvocationList(); + statements.add(stmt); + ts3.setBody(statements); + try { + setupInterpreter(cmdReg); + tr = iv.interpret(ts3); + } catch (Throwable e) { + e.printStackTrace(); + } + + dummyTestPlugin.argsBefore.getIInvocationContext(); + Assert.assertEquals("Running", dummyTestPlugin.argsBefore + .getTestResult().getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep1", dummyCommandPlugin.before + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.before + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Failed", dummyTestPlugin.argsAfter.getTestResult() + .getTestStatus().toString()); + Assert.assertTrue(dummyTestPlugin.argsBefore.getIInvocationContext() + .getTestScript().getBody().contains(stmt)); + Assert.assertEquals("mockstep1", dummyCommandPlugin.after + .getTestStepsDetails().getName()); + Assert.assertEquals(true, dummyCommandPlugin.after + .getTestStepsDetails().getActualResult()); + + Assert.assertEquals("Failed", tr.getTestStatus().toString()); + } + } \ No newline at end of file diff --git a/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java b/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java index 5225521..b00790a 100644 --- a/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java +++ b/src/test/java/org/finra/jtaf/core/plugins/execution/TearDownTestPlugin.java @@ -1,8 +1,8 @@ -package org.finra.jtaf.core.plugins.execution; - -public class TearDownTestPlugin implements ITearDownPlugin { - @Override - public void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException { - tearDownPluginContext.getInvocationContext().getAllObjects().put("tearDownTestActualValue".toLowerCase(), "Test successful"); - } -} +package org.finra.jtaf.core.plugins.execution; + +public class TearDownTestPlugin implements ITearDownPlugin { + @Override + public void handleBeforeTearDown(TearDownPluginContext tearDownPluginContext) throws RunnerPluginException { + tearDownPluginContext.getInvocationContext().getAllObjects().put("tearDownTestActualValue".toLowerCase(), "Test successful"); + } +} diff --git a/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java b/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java index 52aa7ee..c8060f9 100644 --- a/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java +++ b/src/test/java/org/finra/jtaf/core/traceability/TraceabilityMatrixPluginTest.java @@ -1,58 +1,58 @@ -package org.finra.jtaf.core.traceability; - -import java.io.File; - -import org.finra.jtaf.core.AutomationEngine; -import org.finra.jtaf.core.model.test.TestAgenda; -import org.finra.jtaf.core.parsing.TestStrategyParser; -import org.finra.jtaf.core.plugins.parsing.ParserPluginException; -import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - -public class TraceabilityMatrixPluginTest { - private File file; - - @Before - public void setup() { - file = new File(TraceabilityMatrix.OUTPUT_FILE); - if (file.exists()) - file.delete(); - } - - @After - public void teardown() { - file.delete(); - } - - // Only verify that the file was created. Content validation will be part of the TraceabilityMatrix unit test - @Test - public void testExecute() throws ParserPluginException { - TestAgenda testAgenda = new TestAgenda(); - PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); - TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); - traceabilityMatrixPlugin.execute(postAllParserPluginContext); - Assert.assertTrue(file.exists()); - } - - @Test - public void testNoAutomationValue() throws ParserPluginException { - try { - TestStrategyParser tsp = new TestStrategyParser(); - TestAgenda ta = new TestAgenda(); - tsp.parse(new File(System.getProperty("user.dir") + "/profiles/strategies/test.strategy.xml")); - tsp.setDigraph(AutomationEngine.getInstance().getTestDigraph()); - ta = tsp.getTestPlan(); - PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(ta, null); - TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); - traceabilityMatrixPlugin.execute(postAllParserPluginContext); - Assert.assertTrue(file.exists()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - } -} +package org.finra.jtaf.core.traceability; + +import java.io.File; + +import org.finra.jtaf.core.AutomationEngine; +import org.finra.jtaf.core.model.test.TestAgenda; +import org.finra.jtaf.core.parsing.TestStrategyParser; +import org.finra.jtaf.core.plugins.parsing.ParserPluginException; +import org.finra.jtaf.core.plugins.parsing.PostAllParserPluginContext; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + + +public class TraceabilityMatrixPluginTest { + private File file; + + @Before + public void setup() { + file = new File(TraceabilityMatrix.OUTPUT_FILE); + if (file.exists()) + file.delete(); + } + + @After + public void teardown() { + file.delete(); + } + + // Only verify that the file was created. Content validation will be part of the TraceabilityMatrix unit test + @Test + public void testExecute() throws ParserPluginException { + TestAgenda testAgenda = new TestAgenda(); + PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(testAgenda, null); + TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); + traceabilityMatrixPlugin.execute(postAllParserPluginContext); + Assert.assertTrue(file.exists()); + } + + @Test + public void testNoAutomationValue() throws ParserPluginException { + try { + TestStrategyParser tsp = new TestStrategyParser(); + TestAgenda ta = new TestAgenda(); + tsp.parse(new File(System.getProperty("user.dir") + "/profiles/strategies/test.strategy.xml")); + tsp.setDigraph(AutomationEngine.getInstance().getTestDigraph()); + ta = tsp.getTestPlan(); + PostAllParserPluginContext postAllParserPluginContext = new PostAllParserPluginContext(ta, null); + TraceabilityMatrixPlugin traceabilityMatrixPlugin = new TraceabilityMatrixPlugin(); + traceabilityMatrixPlugin.execute(postAllParserPluginContext); + Assert.assertTrue(file.exists()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + } +} diff --git a/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java b/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java index bfaefef..1964361 100644 --- a/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java +++ b/src/test/java/org/finra/jtaf/core/utilities/JTAFPropertyManagerTests.java @@ -1,37 +1,37 @@ -package org.finra.jtaf.core.utilities; - -import org.junit.Assert; -import org.junit.Test; - -public class JTAFPropertyManagerTests { - private static final String PRESET_SYSTEM_PROPERTY = "test.property.system"; - private static final String PRESET_SYSTEM_PROPERTY_VALUE = "preset system property value"; - - private static final String FILE_PROPERTY = "test.property.file"; - private static final String FILE_PROPERTY_VALUE = "file property value"; // make sure to set in jtaf.properties also - - private static final String BOTH_PROPERTY = "test.property.both"; - private static final String BOTH_PROPERTY_VALUE_SYSTEM = "set in both (system)"; - private static final String BOTH_PROPERTY_VALUE_FILE = "set in both (file)"; - - @Test - public void testPresetSystemProperty() { - System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + PRESET_SYSTEM_PROPERTY, PRESET_SYSTEM_PROPERTY_VALUE); - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(PRESET_SYSTEM_PROPERTY); - Assert.assertEquals(PRESET_SYSTEM_PROPERTY_VALUE, fetchedValue); - } - - @Test - public void testFileProperty() { - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(FILE_PROPERTY); - Assert.assertEquals(FILE_PROPERTY_VALUE, fetchedValue); - } - - @Test - public void testPresetSystemPropertyAndFileProperty() { - System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + BOTH_PROPERTY, BOTH_PROPERTY_VALUE_SYSTEM); - String fetchedValue = JTAFPropertyManager.getInstance().getProperty(BOTH_PROPERTY); - Assert.assertFalse(BOTH_PROPERTY_VALUE_FILE.equals(fetchedValue)); - Assert.assertEquals(BOTH_PROPERTY_VALUE_SYSTEM, fetchedValue); - } -} +package org.finra.jtaf.core.utilities; + +import org.junit.Assert; +import org.junit.Test; + +public class JTAFPropertyManagerTests { + private static final String PRESET_SYSTEM_PROPERTY = "test.property.system"; + private static final String PRESET_SYSTEM_PROPERTY_VALUE = "preset system property value"; + + private static final String FILE_PROPERTY = "test.property.file"; + private static final String FILE_PROPERTY_VALUE = "file property value"; // make sure to set in jtaf.properties also + + private static final String BOTH_PROPERTY = "test.property.both"; + private static final String BOTH_PROPERTY_VALUE_SYSTEM = "set in both (system)"; + private static final String BOTH_PROPERTY_VALUE_FILE = "set in both (file)"; + + @Test + public void testPresetSystemProperty() { + System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + PRESET_SYSTEM_PROPERTY, PRESET_SYSTEM_PROPERTY_VALUE); + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(PRESET_SYSTEM_PROPERTY); + Assert.assertEquals(PRESET_SYSTEM_PROPERTY_VALUE, fetchedValue); + } + + @Test + public void testFileProperty() { + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(FILE_PROPERTY); + Assert.assertEquals(FILE_PROPERTY_VALUE, fetchedValue); + } + + @Test + public void testPresetSystemPropertyAndFileProperty() { + System.setProperty(JTAFPropertyManager.PROPERTY_PREFIX + "." + BOTH_PROPERTY, BOTH_PROPERTY_VALUE_SYSTEM); + String fetchedValue = JTAFPropertyManager.getInstance().getProperty(BOTH_PROPERTY); + Assert.assertFalse(BOTH_PROPERTY_VALUE_FILE.equals(fetchedValue)); + Assert.assertEquals(BOTH_PROPERTY_VALUE_SYSTEM, fetchedValue); + } +} diff --git a/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java b/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java index 30d4f91..baeae30 100644 --- a/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java +++ b/src/test/java/org/finra/jtaf/core/ztest/DuplicateRepeatTest.java @@ -1,28 +1,28 @@ -package org.finra.jtaf.core.ztest; - -import java.io.File; - -import org.finra.jtaf.core.AutomationEngine; -import org.junit.Assert; -import org.junit.Test; - -public class DuplicateRepeatTest { - private static AutomationEngine engine = null; - - - @Test - public void testBuildmodel() { - engine = AutomationEngine.getInstance(); - - try { - engine.buildModel(new File("mocktestlibrary/dupe.commands.xml"), new File("mocktestscripts")); - Assert.assertEquals("Oops! We have more then one command with same name ('repeat') (case insensitive)! Fix your test commands, please.", engine.mc.getCurrentSection().getName()); - - } catch (Exception e) { - e.printStackTrace(); - } - - - } - -} +package org.finra.jtaf.core.ztest; + +import java.io.File; + +import org.finra.jtaf.core.AutomationEngine; +import org.junit.Assert; +import org.junit.Test; + +public class DuplicateRepeatTest { + private static AutomationEngine engine = null; + + + @Test + public void testBuildmodel() { + engine = AutomationEngine.getInstance(); + + try { + engine.buildModel(new File("mocktestlibrary/dupe.commands.xml"), new File("mocktestscripts")); + Assert.assertEquals("Oops! We have more then one command with same name ('repeat') (case insensitive)! Fix your test commands, please.", engine.mc.getCurrentSection().getName()); + + } catch (Exception e) { + e.printStackTrace(); + } + + + } + +} diff --git a/src/test/resources/AutomationValueTestStrategy.strategy.xml b/src/test/resources/AutomationValueTestStrategy.strategy.xml index 9ececab..6c2958c 100644 --- a/src/test/resources/AutomationValueTestStrategy.strategy.xml +++ b/src/test/resources/AutomationValueTestStrategy.strategy.xml @@ -1,7 +1,7 @@ - - - - DummyAutomationValue - - + + + + DummyAutomationValue + + \ No newline at end of file diff --git a/src/test/resources/MaxThreadsTestStrategy.strategy.xml b/src/test/resources/MaxThreadsTestStrategy.strategy.xml index 3b0101a..7558811 100644 --- a/src/test/resources/MaxThreadsTestStrategy.strategy.xml +++ b/src/test/resources/MaxThreadsTestStrategy.strategy.xml @@ -1,7 +1,7 @@ - - - - 3 - - + + + + 3 + + \ No newline at end of file diff --git a/src/test/resources/jtaf.properties b/src/test/resources/jtaf.properties index e6fd8b8..2979468 100644 --- a/src/test/resources/jtaf.properties +++ b/src/test/resources/jtaf.properties @@ -1,3 +1,3 @@ -strategy=profiles/strategies/Default.strategy.xml -test.property.file=file property value +strategy=profiles/strategies/Default.strategy.xml +test.property.file=file property value test.property.both=set in both (file) \ No newline at end of file diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties index 314d303..aafc1cc 100644 --- a/src/test/resources/log4j.properties +++ b/src/test/resources/log4j.properties @@ -1,6 +1,6 @@ -log4j.rootLogger=ALL, stdout -log4j.logger.qc.automation.framework.AutomationEngine=ALL, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.rootLogger=ALL, stdout +log4j.logger.qc.automation.framework.AutomationEngine=ALL, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm} [%-5p] [%t] [%c] [%F:%L] - %m%n \ No newline at end of file diff --git a/src/test/resources/testlibrary/anyfolder/verify.commands.xml b/src/test/resources/testlibrary/anyfolder/verify.commands.xml index 8e1f1ce..6c7efcf 100644 --- a/src/test/resources/testlibrary/anyfolder/verify.commands.xml +++ b/src/test/resources/testlibrary/anyfolder/verify.commands.xml @@ -1,17 +1,17 @@ - - - - - - ExtendedHello - - - - - - ExtendedHello - - - - + + + + + + ExtendedHello + + + + + + ExtendedHello + + + + \ No newline at end of file diff --git a/src/test/resources/testlibrary/context.test.commands.xml b/src/test/resources/testlibrary/context.test.commands.xml index 8c1ba5e..737acbf 100644 --- a/src/test/resources/testlibrary/context.test.commands.xml +++ b/src/test/resources/testlibrary/context.test.commands.xml @@ -1,42 +1,42 @@ - - - - - Sets an object in context - - the key of value to store in the function - - - - - - - Creates a list in context containing the string value of the passed in key's value in context - - the key of value to store in the list in the function - - - the key of value to store in the list in the function - - $contextKey(originalKey) - - - - - - - $contextKey(originalKey) - - - - - - Invokes a block in context - - the block to invoke - - - - - - + + + + + Sets an object in context + + the key of value to store in the function + + + + + + + Creates a list in context containing the string value of the passed in key's value in context + + the key of value to store in the list in the function + + + the key of value to store in the list in the function + + $contextKey(originalKey) + + + + + + + $contextKey(originalKey) + + + + + + Invokes a block in context + + the block to invoke + + + + + + diff --git a/src/test/resources/testlibrary/hello.commands.xml b/src/test/resources/testlibrary/hello.commands.xml index 1c2d559..8338724 100644 --- a/src/test/resources/testlibrary/hello.commands.xml +++ b/src/test/resources/testlibrary/hello.commands.xml @@ -1,16 +1,16 @@ - - - - - - ExtendedBye - - - - - - ExtendedBye - - - + + + + + + ExtendedBye + + + + + + ExtendedBye + + + \ No newline at end of file diff --git a/src/test/resources/testlibrary/mock.commands.xml b/src/test/resources/testlibrary/mock.commands.xml index da5bd84..e319992 100644 --- a/src/test/resources/testlibrary/mock.commands.xml +++ b/src/test/resources/testlibrary/mock.commands.xml @@ -1,34 +1,34 @@ - - - - - - mock command 1 - - - - - mock command 2 - - - - - mock command 3 - - - - - mock command 3 - - - - - mock command 3 - - - - - - - + + + + + + mock command 1 + + + + + mock command 2 + + + + + mock command 3 + + + + + mock command 3 + + + + + mock command 3 + + + + + + + \ No newline at end of file diff --git a/testdata/debug/testdataDebug.csv b/testdata/debug/testdataDebug.csv index 0ebc520..d417c0c 100644 --- a/testdata/debug/testdataDebug.csv +++ b/testdata/debug/testdataDebug.csv @@ -1,5 +1,5 @@ -JTAF.test.name,valA -Print XYZ,XYZ -Print ABC,ABC -Print 123,123 +JTAF.test.name,valA +Print XYZ,XYZ +Print ABC,ABC +Print 123,123 Print 456,456 \ No newline at end of file diff --git a/testscripts/AddListToListCmdTest.xml b/testscripts/AddListToListCmdTest.xml index b638e3a..a24cd1a 100644 --- a/testscripts/AddListToListCmdTest.xml +++ b/testscripts/AddListToListCmdTest.xml @@ -1,212 +1,212 @@ - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - item3 - - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - item3 - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - item3 - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - - - - - - - + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + item3 + + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + item3 + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + item3 + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + + + + + + + diff --git a/testscripts/AddObjectToListCmdTest.xml b/testscripts/AddObjectToListCmdTest.xml index d80fc8c..41522c8 100644 --- a/testscripts/AddObjectToListCmdTest.xml +++ b/testscripts/AddObjectToListCmdTest.xml @@ -1,341 +1,341 @@ - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - High - - - - item1 - - - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - High - - - - item1 - - - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - High - - - - item1 - - - - - - - - - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - - High - - - - item1 - - - - - item2 - - - - - - - - - item2 - - - - - - - - - - High - - - - item1 - - - - - - - - - - - - - - - - - - High - - - - - - - - - - - - - - - - - + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + High + + + + item1 + + + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + High + + + + item1 + + + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + High + + + + item1 + + + + + + + + + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + + High + + + + item1 + + + + + item2 + + + + + + + + + item2 + + + + + + + + + + High + + + + item1 + + + + + + + + + + + + + + + + + + High + + + + + + + + + + + + + + + + + diff --git a/testscripts/AutomationValue.xml b/testscripts/AutomationValue.xml index 74c6b01..0ba83f7 100644 --- a/testscripts/AutomationValue.xml +++ b/testscripts/AutomationValue.xml @@ -1,63 +1,63 @@ - - - - High - This test should be in the test agenda since the automationValue is in the strategy - - - - - - - DontPutThisInTheStrategy - This test should not be in the test agenda since the automationValue is not in the strategy - - - - - - - This test should not be in any test agenda unless the strategy doesn't specify any automationValue. - - - - - - - AutomationValueTest - This script should be in the agenda even if it has an automationValue that isn't listed first in the strategy - - - - - - - DontPutThisInTheStrategy - - This test has an automationValue that is not specified in the - strategy, but should be added to the agenda anyways because the - below test is dependent on it. - - - - - - - - AutomationValueTest - - This test has an automationValue that *is* specified in the - strategy, but is dependent on a test whose automationValue is *not* - specified in the strategy. This should cause the dependent test to - be added to the strategy anyways. - - - - - - - - - - + + + + High + This test should be in the test agenda since the automationValue is in the strategy + + + + + + + DontPutThisInTheStrategy + This test should not be in the test agenda since the automationValue is not in the strategy + + + + + + + This test should not be in any test agenda unless the strategy doesn't specify any automationValue. + + + + + + + AutomationValueTest + This script should be in the agenda even if it has an automationValue that isn't listed first in the strategy + + + + + + + DontPutThisInTheStrategy + + This test has an automationValue that is not specified in the + strategy, but should be added to the agenda anyways because the + below test is dependent on it. + + + + + + + + AutomationValueTest + + This test has an automationValue that *is* specified in the + strategy, but is dependent on a test whose automationValue is *not* + specified in the strategy. This should cause the dependent test to + be added to the strategy anyways. + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/Block.xml b/testscripts/Block.xml index f144ad4..9686294 100644 --- a/testscripts/Block.xml +++ b/testscripts/Block.xml @@ -1,43 +1,43 @@ - - - - - - - - - - High - - - huh - - - - - - - - High - - - - - - - - huh - - - - - - - High - - - - - - + + + + + + + + + + High + + + huh + + + + + + + + High + + + + + + + + huh + + + + + + + High + + + + + + \ No newline at end of file diff --git a/testscripts/CommandTest.xml b/testscripts/CommandTest.xml index 447d786..e7167be 100644 --- a/testscripts/CommandTest.xml +++ b/testscripts/CommandTest.xml @@ -1,47 +1,47 @@ - - - - - - - High - - - - - - - - - - High - - - - - - - - - - - High - - - - - - + + + + + + + High + + + + + + + + + + High + + + + + + + + + + + High + + + + + + \ No newline at end of file diff --git a/testscripts/CommandThrowingExceptionTest.xml b/testscripts/CommandThrowingExceptionTest.xml index cd585a9..41f8fea 100644 --- a/testscripts/CommandThrowingExceptionTest.xml +++ b/testscripts/CommandThrowingExceptionTest.xml @@ -1,20 +1,20 @@ - - - - - - - High - - - - - SQLException - - - - - - - + + + + + + + High + + + + + SQLException + + + + + + + \ No newline at end of file diff --git a/testscripts/ConcurrentScheduler.xml b/testscripts/ConcurrentScheduler.xml index 2c99ee6..77b8725 100644 --- a/testscripts/ConcurrentScheduler.xml +++ b/testscripts/ConcurrentScheduler.xml @@ -1,42 +1,42 @@ - - - - - - - High - - - - -1 - - - - - - - - - High - -1 - - - - - - - - - - High - -1 - - - - - - - - - + + + + + + + High + + + + -1 + + + + + + + + + High + -1 + + + + + + + + + + High + -1 + + + + + + + + + \ No newline at end of file diff --git a/testscripts/Coverage.xml b/testscripts/Coverage.xml index 834f4a1..ac1338d 100644 --- a/testscripts/Coverage.xml +++ b/testscripts/Coverage.xml @@ -1,12 +1,12 @@ - - - - - - - - - - - + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/DependencyTest.xml b/testscripts/DependencyTest.xml index 9ff8f31..417ded7 100644 --- a/testscripts/DependencyTest.xml +++ b/testscripts/DependencyTest.xml @@ -1,88 +1,88 @@ - - - - - - - - - - - Test that fails - - High - - - - - - - - - - Expected this test to fail as dependent test fail - - High - - - - - Test value in context - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + Test that fails + + High + + + + + + + + + + Expected this test to fail as dependent test fail + + High + + + + + Test value in context + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/DoNotAddToStrategy.xml b/testscripts/DoNotAddToStrategy.xml index fc54469..2ec3cff 100644 --- a/testscripts/DoNotAddToStrategy.xml +++ b/testscripts/DoNotAddToStrategy.xml @@ -1,10 +1,10 @@ - - - - DontPutThisInTheStrategy - - - - - + + + + DontPutThisInTheStrategy + + + + + \ No newline at end of file diff --git a/testscripts/ExclusionTest.xml b/testscripts/ExclusionTest.xml index 3421106..02ab4c4 100644 --- a/testscripts/ExclusionTest.xml +++ b/testscripts/ExclusionTest.xml @@ -1,28 +1,28 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/ExpectFailure.xml b/testscripts/ExpectFailure.xml index 5e50761..793b8be 100644 --- a/testscripts/ExpectFailure.xml +++ b/testscripts/ExpectFailure.xml @@ -1,62 +1,62 @@ - - - - - - - High - - - - - - - - - - High - - - ExpectedFailureException - - - huh - - - - - - - - - High - - - ExpectedFailureException - - - huh - - - huh - - - - - - - - - - High - - - ExpectedFailureException - - - - - - - + + + + + + + High + + + + + + + + + + High + + + ExpectedFailureException + + + huh + + + + + + + + + High + + + ExpectedFailureException + + + huh + + + huh + + + + + + + + + + High + + + ExpectedFailureException + + + + + + + \ No newline at end of file diff --git a/testscripts/Function.xml b/testscripts/Function.xml index d2de344..e910091 100644 --- a/testscripts/Function.xml +++ b/testscripts/Function.xml @@ -1,26 +1,26 @@ - - - - - Test that a calling a function produces the expected result - - High - - - - - - - Test that a calling a function produces the expected result - - High - - - - - Test value in context - - - - - + + + + + Test that a calling a function produces the expected result + + High + + + + + + + Test that a calling a function produces the expected result + + High + + + + + Test value in context + + + + + diff --git a/testscripts/IgnoreErrors.xml b/testscripts/IgnoreErrors.xml index 5438b74..e4d18e8 100644 --- a/testscripts/IgnoreErrors.xml +++ b/testscripts/IgnoreErrors.xml @@ -1,44 +1,44 @@ - - - - - - High - AssertionFailedError - - - - - - - - - High - - - huh - - - - - - - High - - - - - - - - High - AssertionFailedError - - - - - - - - + + + + + + High + AssertionFailedError + + + + + + + + + High + + + huh + + + + + + + High + + + + + + + + High + AssertionFailedError + + + + + + + + \ No newline at end of file diff --git a/testscripts/Invoke.xml b/testscripts/Invoke.xml index 874acc3..8c07ac7 100644 --- a/testscripts/Invoke.xml +++ b/testscripts/Invoke.xml @@ -1,17 +1,17 @@ - - - - - Test that a block passed to a function which invokes it produces the expected result - - High - - - - - - - - - - + + + + + Test that a block passed to a function which invokes it produces the expected result + + High + + + + + + + + + + diff --git a/testscripts/LoopDebug.xml b/testscripts/LoopDebug.xml index 56431de..d7dc4dd 100644 --- a/testscripts/LoopDebug.xml +++ b/testscripts/LoopDebug.xml @@ -1,13 +1,13 @@ - - - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/ManipulateContextHelper.xml b/testscripts/ManipulateContextHelper.xml index b35c115..0a0971c 100644 --- a/testscripts/ManipulateContextHelper.xml +++ b/testscripts/ManipulateContextHelper.xml @@ -1,17 +1,17 @@ - - - - - - - High - - - huh - - - - - - + + + + + + + High + + + huh + + + + + + \ No newline at end of file diff --git a/testscripts/MockTestScript.xml b/testscripts/MockTestScript.xml index 0a0f602..a80fe05 100644 --- a/testscripts/MockTestScript.xml +++ b/testscripts/MockTestScript.xml @@ -1,17 +1,17 @@ - - - - - - - High - - - - - - - - - + + + + + + + High + + + + + + + + + \ No newline at end of file diff --git a/testscripts/Multipath.xml b/testscripts/Multipath.xml index 8ae597c..c5fda7b 100644 --- a/testscripts/Multipath.xml +++ b/testscripts/Multipath.xml @@ -1,34 +1,34 @@ - - - - - Test that a single run through a multipath block with identical paths produces the expected result - - High - - - - - - - - - - - - - - - - - - - Test that a single run through a multipath block with identical paths produces the expected result - - High - - - - - - + + + + + Test that a single run through a multipath block with identical paths produces the expected result + + High + + + + + + + + + + + + + + + + + + + Test that a single run through a multipath block with identical paths produces the expected result + + High + + + + + + diff --git a/testscripts/ParallelScriptRunner.xml b/testscripts/ParallelScriptRunner.xml index 131f751..a746497 100644 --- a/testscripts/ParallelScriptRunner.xml +++ b/testscripts/ParallelScriptRunner.xml @@ -1,14 +1,14 @@ - - - - - - - Low - - - - - - + + + + + + + Low + + + + + + \ No newline at end of file diff --git a/testscripts/PutObjectInMapCmdTest.xml b/testscripts/PutObjectInMapCmdTest.xml index 6c2b2fb..a3da0d5 100644 --- a/testscripts/PutObjectInMapCmdTest.xml +++ b/testscripts/PutObjectInMapCmdTest.xml @@ -1,32 +1,32 @@ - - - - - High - - - - item1 - - - - - - - - - - - - High - - - - - - - - - - - + + + + + High + + + + item1 + + + + + + + + + + + + High + + + + + + + + + + + diff --git a/testscripts/RandomGenerator.xml b/testscripts/RandomGenerator.xml index a15b817..a1e1462 100644 --- a/testscripts/RandomGenerator.xml +++ b/testscripts/RandomGenerator.xml @@ -1,102 +1,102 @@ - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - - - - High - - - - + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + + + + High + + + + \ No newline at end of file diff --git a/testscripts/RemoveObjectFromContextCmdTest.xml b/testscripts/RemoveObjectFromContextCmdTest.xml index a67940f..2b57566 100644 --- a/testscripts/RemoveObjectFromContextCmdTest.xml +++ b/testscripts/RemoveObjectFromContextCmdTest.xml @@ -1,19 +1,19 @@ - - - - - High - - - - - - IllegalArgumentException - - - - - - - - + + + + + High + + + + + + IllegalArgumentException + + + + + + + + diff --git a/testscripts/Repeat.xml b/testscripts/Repeat.xml index f020557..a4ae1a5 100644 --- a/testscripts/Repeat.xml +++ b/testscripts/Repeat.xml @@ -1,50 +1,50 @@ - - - - - - - High - - - huh - - - - - - - High - - - huh - - huh - - - - - - - - High - - - huh - - huh - - - - - - - - - High - - - - - + + + + + + + High + + + huh + + + + + + + High + + + huh + + huh + + + + + + + + High + + + huh + + huh + + + + + + + + + High + + + + + \ No newline at end of file diff --git a/testscripts/ReplaceContext.xml b/testscripts/ReplaceContext.xml index 8224526..31aa6a9 100644 --- a/testscripts/ReplaceContext.xml +++ b/testscripts/ReplaceContext.xml @@ -1,57 +1,57 @@ - - - - - - High - - - huh - - - - - - - - High - - - - - - - - - High - - - this will be replaced - this will be overwritten as well - this should be deleted - - - testString - test String - test Str - - - - - - - - - - - - - - - - + + + + + + High + + + huh + + + + + + + + High + + + + + + + + + High + + + this will be replaced + this will be overwritten as well + this should be deleted + + + testString + test String + test Str + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/StoreObjectAsStringCmdTest.xml b/testscripts/StoreObjectAsStringCmdTest.xml index 8103d4c..7b3a471 100644 --- a/testscripts/StoreObjectAsStringCmdTest.xml +++ b/testscripts/StoreObjectAsStringCmdTest.xml @@ -1,41 +1,41 @@ - - - - - High - - - - - - - - - High - - - - - - - - - - - - - - - - - - High - - - - - - - - - + + + + + High + + + + + + + + + High + + + + + + + + + + + + + + + + + + High + + + + + + + + + diff --git a/testscripts/StoreObjectFromListCmdTest.xml b/testscripts/StoreObjectFromListCmdTest.xml index 0d4ad83..6a9f3ce 100644 --- a/testscripts/StoreObjectFromListCmdTest.xml +++ b/testscripts/StoreObjectFromListCmdTest.xml @@ -1,63 +1,63 @@ - - - - - High - - - - Test value in context - - - - - - - - - - - High - - - - Value1 - Value2 - - - - - - - - - - - - - - - - High - - - - Value1 - - - - - - - - - - + + + + + High + + + + Test value in context + + + + + + + + + + + High + + + + Value1 + Value2 + + + + + + + + + + + + + + + + High + + + + Value1 + + + + + + + + + + diff --git a/testscripts/StoreObjectFromMapCmdTest.xml b/testscripts/StoreObjectFromMapCmdTest.xml index 135e611..eb7e049 100644 --- a/testscripts/StoreObjectFromMapCmdTest.xml +++ b/testscripts/StoreObjectFromMapCmdTest.xml @@ -1,37 +1,37 @@ - - - - - High - - - - Test value in context - - - - - - - - - - - High - - - - Value1 - Value2 - - - - - - - - - - - - + + + + + High + + + + Test value in context + + + + + + + + + + + High + + + + Value1 + Value2 + + + + + + + + + + + + diff --git a/testscripts/StoreObjectInContextCmdTest.xml b/testscripts/StoreObjectInContextCmdTest.xml index 1426de7..7debedb 100644 --- a/testscripts/StoreObjectInContextCmdTest.xml +++ b/testscripts/StoreObjectInContextCmdTest.xml @@ -1,24 +1,24 @@ - - - - - High - - - - - - - - High - - - - - - - - - - - + + + + + High + + + + + + + + High + + + + + + + + + + + diff --git a/testscripts/TearDownPluginsTests.xml b/testscripts/TearDownPluginsTests.xml index 30a4269..50b67b5 100644 --- a/testscripts/TearDownPluginsTests.xml +++ b/testscripts/TearDownPluginsTests.xml @@ -1,25 +1,25 @@ - - - - - High - AssertionFailedError - - - - - - - - - - - - - - - - + + + + + High + AssertionFailedError + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/TestCommandLibraryDiscovery.xml b/testscripts/TestCommandLibraryDiscovery.xml index 115d46e..b0bbebd 100644 --- a/testscripts/TestCommandLibraryDiscovery.xml +++ b/testscripts/TestCommandLibraryDiscovery.xml @@ -1,44 +1,44 @@ - - - - High - - - - - - - - - - High - - - - - - - - - - - High - - - - - - - - - - High - - - - - - - - + + + + High + + + + + + + + + + High + + + + + + + + + + + High + + + + + + + + + + High + + + + + + + + \ No newline at end of file diff --git a/testscripts/TestDataDebug.xml b/testscripts/TestDataDebug.xml index 70193db..8d18118 100644 --- a/testscripts/TestDataDebug.xml +++ b/testscripts/TestDataDebug.xml @@ -1,16 +1,16 @@ - - - - TDD - - - - - - - - - - - + + + + TDD + + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/TryRecoverCleanup.xml b/testscripts/TryRecoverCleanup.xml index f8be888..fbcf983 100644 --- a/testscripts/TryRecoverCleanup.xml +++ b/testscripts/TryRecoverCleanup.xml @@ -1,175 +1,175 @@ - - - - - - High - - - AssertionFailedError - - - - - - huh - - - - huh - - - - - - - - - High - - - AssertionFailedError - - - - - huh - - - - huh - - - - - - - - High - - - AssertionFailedError - - - - - huh - - - - - - - - - High - - - huh - - - - huh - - - - - - - High - - - - - - - - - - High - - - AssertionFailedError - - - - - - - - - - - - - - High - - - AssertionFailedError - - - - - - - - - - - High - - - AssertionFailedError - - - - - - huh - - - - - - - - - - - - High - - - AssertionFailedError - - - - - - - - - - - - - - High - - - AssertionFailedError - - - huh - - - - - - - - - - + + + + + + High + + + AssertionFailedError + + + + + + huh + + + + huh + + + + + + + + + High + + + AssertionFailedError + + + + + huh + + + + huh + + + + + + + + High + + + AssertionFailedError + + + + + huh + + + + + + + + + High + + + huh + + + + huh + + + + + + + High + + + + + + + + + + High + + + AssertionFailedError + + + + + + + + + + + + + + High + + + AssertionFailedError + + + + + + + + + + + High + + + AssertionFailedError + + + + + + huh + + + + + + + + + + + + High + + + AssertionFailedError + + + + + + + + + + + + + + High + + + AssertionFailedError + + + huh + + + + + + + + + + \ No newline at end of file diff --git a/testscripts/VerifyObjectInContextTest.xml b/testscripts/VerifyObjectInContextTest.xml index f0e02f6..73ac77b 100644 --- a/testscripts/VerifyObjectInContextTest.xml +++ b/testscripts/VerifyObjectInContextTest.xml @@ -1,70 +1,70 @@ - - - - - Test that a calling a function produces the expected result - JTAF-420 - High - - - - - - - - - - Test that a calling a function produces the expected result - JTAF-420 - High - - - - Test value in context - - - - - Test value in context - - - - - Try new default - - - - - Test value in context - - - - - - - - - - - High - - - AssertionError - - - - - - - - High - - - AssertionError - - - - - - - + + + + + Test that a calling a function produces the expected result + JTAF-420 + High + + + + + + + + + + Test that a calling a function produces the expected result + JTAF-420 + High + + + + Test value in context + + + + + Test value in context + + + + + Try new default + + + + + Test value in context + + + + + + + + + + + High + + + AssertionError + + + + + + + + High + + + AssertionError + + + + + + + diff --git a/testscripts/mock/TraceabilityTest.xml b/testscripts/mock/TraceabilityTest.xml index b7b0887..b2e4237 100644 --- a/testscripts/mock/TraceabilityTest.xml +++ b/testscripts/mock/TraceabilityTest.xml @@ -1,18 +1,18 @@ - - - - - - Test for building the Traceability Matrix when NO Automation Value exists in Strategy file - - High - - - - - - - - - + + + + + + Test for building the Traceability Matrix when NO Automation Value exists in Strategy file + + High + + + + + + + + + \ No newline at end of file