You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jmeter.apache.org by vl...@apache.org on 2019/10/03 19:50:31 UTC
[jmeter] branch master updated: Whitespace,
comments etc. tidy up before migration to JUnit 5
This is an automated email from the ASF dual-hosted git repository.
vladimirsitnikov pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/jmeter.git
The following commit(s) were added to refs/heads/master by this push:
new 6df752c Whitespace, comments etc. tidy up before migration to JUnit 5
6df752c is described below
commit 6df752c773871dcd8c7936c76deffa687d4bd207
Author: Graham Russell <gr...@ham1.co.uk>
AuthorDate: Thu Oct 3 11:49:48 2019 +0100
Whitespace, comments etc. tidy up before migration to JUnit 5
---
.../jmeter/assertions/XMLSchemaAssertionTest.java | 3 +-
.../jmeter/assertions/XPathAssertionTest.java | 3 -
.../assertions/gui/TestJSONPathAssertionGui.java | 1 -
.../org/apache/jmeter/config/TestCVSDataSet.java | 5 -
.../jmeter/config/gui/TestArgumentsPanel.java | 33 +-
.../jmeter/control/TestGenericController.java | 54 +-
.../apache/jmeter/control/TestIfController.java | 21 +-
.../jmeter/control/TestInterleaveControl.java | 370 +++---
.../apache/jmeter/control/TestLoopController.java | 212 ++--
.../jmeter/control/TestTransactionController.java | 5 -
.../apache/jmeter/control/TestWhileController.java | 578 +++++-----
.../jmeter/extractor/TestHtmlExtractorJSoup.java | 6 +-
.../jmeter/extractor/TestJSONPostProcessor.java | 3 +-
.../jmeter/extractor/TestXPath2Extractor.java | 8 +-
.../jmeter/extractor/TestXPathExtractor.java | 557 +++++-----
.../org/apache/jmeter/gui/action/TestSave.java | 37 +-
.../apache/jmeter/reporters/TestResultSaver.java | 4 -
.../PreciseThroughputTimerTest.java | 3 +-
.../backend/SamplerMetricFixedModeTest.java | 9 +-
.../apache/jmeter/report/core/CsvSampleWriter.java | 42 +-
.../test/java/org/apache/jmeter/JMeterTest.java | 5 +-
.../org/apache/jmeter/engine/LocalHostTest.java | 12 +-
.../org/apache/jmeter/engine/TestTreeCloner.java | 90 +-
.../jmeter/engine/util/TestValueReplacer.java | 292 ++---
.../gui/logging/TestGuiLogEventAppender.java | 19 +-
.../apache/jmeter/listeners/TestResultAction.java | 4 -
.../jmeter/report/core/TestCsvSampleWriter.java | 19 +-
.../processor/ErrorsSummaryConsumerTest.java | 15 +-
.../graph/impl/CustomGraphConsumerTest.java | 30 +-
.../apache/jmeter/samplers/TestSampleResult.java | 670 ++++++-----
.../testbeans/gui/TestBooleanPropertyEditor.java | 14 +-
.../testbeans/gui/TestComboStringEditor.java | 70 +-
.../testbeans/gui/TestFieldStringEditor.java | 58 +-
.../org/apache/jmeter/testelement/PackageTest.java | 1 -
.../jmeter/testelement/TestNumberProperty.java | 5 +-
.../jmeter/testelement/property/PackageTest.java | 8 +-
.../jmeter/threads/TestJMeterContextService.java | 1 +
.../apache/jmeter/threads/TestJMeterThread.java | 13 +-
.../apache/jmeter/threads/TestTestCompiler.java | 54 +-
.../apache/jmeter/util/JMeterContextExtension.java | 8 +-
.../apache/jmeter/util/StringUtilitiesTest.java | 1 -
.../java/org/apache/jmeter/util/XPathUtilTest.java | 17 +-
.../org/apache/jorphan/reflect/TestFunctor.java | 7 +-
.../jmeter/control/TestSwitchController.java | 496 ++++-----
.../jmeter/resources/TestPropertiesFiles.java | 1 -
.../java/org/apache/jorphan/TestFunctorUsers.java | 33 +-
.../apache/jmeter/functions/EvalFunctionTest.java | 1 -
.../functions/StringFromFileFunctionTest.java | 4 +-
.../apache/jmeter/functions/TestChangeCase.java | 6 -
.../functions/TestDateTimeConvertFunction.java | 7 +-
.../jmeter/functions/TestDigestFunction.java | 13 +-
.../jmeter/functions/TestEscapeOroRegexpChars.java | 5 +-
.../jmeter/functions/TestFileRowColContainer.java | 2 -
.../apache/jmeter/functions/TestFileToString.java | 5 +-
.../jmeter/functions/TestGroovyFunction.java | 7 +-
.../apache/jmeter/functions/TestIsPropDefined.java | 12 +-
.../apache/jmeter/functions/TestIsVarDefined.java | 12 +-
.../jmeter/functions/TestJavascriptFunction.java | 5 +-
.../functions/TestJavascriptFunctionWithRhino.java | 6 +-
.../apache/jmeter/functions/TestJexl2Function.java | 5 +-
.../apache/jmeter/functions/TestMachineIPName.java | 6 +-
.../functions/TestRandomFromMultipleVars.java | 5 +-
.../apache/jmeter/functions/TestRegexFunction.java | 766 +++++++------
.../jmeter/functions/TestSamplerNameFunction.java | 6 +-
.../apache/jmeter/functions/TestSetProperty.java | 5 +-
.../jmeter/functions/TestSimpleFunctions.java | 3 +-
.../apache/jmeter/functions/TestTimeFunction.java | 322 +++---
.../functions/TestTimeRandomDateFunction.java | 4 -
.../jmeter/functions/TestTimeShiftFunction.java | 9 +-
.../jmeter/functions/TestUrlEncodeDecode.java | 5 +-
.../java/org/apache/jorphan/util/JOrphanUtils.java | 289 +++--
.../apache/commons/cli/avalon/ClutilTestCase.java | 55 +-
.../apache/jorphan/collections/PackageTest.java | 277 +++--
.../org/apache/jorphan/exec/TestKeyToolUtils.java | 3 +-
.../apache/jorphan/gui/ObjectTableModelTest.java | 3 -
.../apache/jorphan/gui/ObjectTableSorterTest.java | 81 +-
.../apache/jorphan/math/TestStatCalculator.java | 21 +-
.../org/apache/jorphan/reflect/TestClassTools.java | 47 +-
.../org/apache/jorphan/util/TestConverter.java | 38 +-
.../org/apache/jorphan/util/TestJorphanUtils.java | 202 ++--
.../apache/jmeter/curl/BasicCurlParserTest.java | 22 +-
.../http/config/MultipartUrlConfigTest.java | 1 -
.../jmeter/protocol/http/config/UrlConfigTest.java | 3 +-
.../protocol/http/control/TestAuthManager.java | 160 +--
.../control/TestAuthManagerThreadIteration.java | 8 +-
.../http/control/TestHC4CookieManager.java | 1173 ++++++++++----------
.../http/control/gui/TestHttpTestSampleGui.java | 5 +-
.../protocol/http/modifier/TestAnchorModifier.java | 592 +++++-----
.../http/modifier/TestURLRewritingModifier.java | 539 +++++----
.../protocol/http/parser/TestHtmlParsingUtils.java | 162 ++-
.../protocol/http/proxy/TestProxyControl.java | 2 +-
.../protocol/http/sampler/PostWriterTest.java | 41 +-
.../protocol/http/sampler/SamplingNamingTest.java | 7 +-
.../protocol/http/sampler/TestHTTPSamplers.java | 545 +++++----
.../protocol/http/util/TestHTTPArgument.java | 126 +--
.../http/util/accesslog/TestLogFilter.java | 246 ++--
.../http/util/accesslog/TestTCLogParser.java | 64 +-
.../http/visualizers/RequestViewHTTPTest.java | 1 +
.../jmeter/testelement/TestHeaderManager.java | 1 +
.../protocol/jms/sampler/PublisherSamplerTest.java | 3 -
.../sampler/render/BinaryMessageRendererTest.java | 3 +-
.../jms/sampler/render/MessageRendererTest.java | 2 +-
.../src/main/java/test/DummyAnnotatedTest.java | 1 -
.../src/main/java/test/Junit4AnnotationsTest.java | 11 +-
.../protocol/ldap/config/gui/PackageTest.java | 31 +-
.../tcp/sampler/TCPClientDecoratorTest.java | 3 -
106 files changed, 4712 insertions(+), 5174 deletions(-)
diff --git a/src/components/src/test/java/org/apache/jmeter/assertions/XMLSchemaAssertionTest.java b/src/components/src/test/java/org/apache/jmeter/assertions/XMLSchemaAssertionTest.java
index b67670c..12a695e 100644
--- a/src/components/src/test/java/org/apache/jmeter/assertions/XMLSchemaAssertionTest.java
+++ b/src/components/src/test/java/org/apache/jmeter/assertions/XMLSchemaAssertionTest.java
@@ -48,8 +48,7 @@ public class XMLSchemaAssertionTest extends JMeterTestCase {
public void setUp() throws Exception {
jmctx = JMeterContextService.getContext();
assertion = new XMLSchemaAssertion();
- assertion.setThreadContext(jmctx);// This would be done by the run
- // command
+ assertion.setThreadContext(jmctx);// This would be done by the run command
result = new SampleResult();
JMeterVariables vars = new JMeterVariables();
jmctx.setVariables(vars);
diff --git a/src/components/src/test/java/org/apache/jmeter/assertions/XPathAssertionTest.java b/src/components/src/test/java/org/apache/jmeter/assertions/XPathAssertionTest.java
index 18aee3e..73110a2 100644
--- a/src/components/src/test/java/org/apache/jmeter/assertions/XPathAssertionTest.java
+++ b/src/components/src/test/java/org/apache/jmeter/assertions/XPathAssertionTest.java
@@ -41,11 +41,8 @@ public class XPathAssertionTest extends JMeterTestCase {
private static final Logger log = LoggerFactory.getLogger(XPathAssertionTest.class);
private XPathAssertion assertion;
-
private SampleResult result;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
diff --git a/src/components/src/test/java/org/apache/jmeter/assertions/gui/TestJSONPathAssertionGui.java b/src/components/src/test/java/org/apache/jmeter/assertions/gui/TestJSONPathAssertionGui.java
index 055ab3f..d0233cc 100644
--- a/src/components/src/test/java/org/apache/jmeter/assertions/gui/TestJSONPathAssertionGui.java
+++ b/src/components/src/test/java/org/apache/jmeter/assertions/gui/TestJSONPathAssertionGui.java
@@ -25,7 +25,6 @@ import org.junit.Test;
public class TestJSONPathAssertionGui {
-
@Test
public void testInit() {
JSONPathAssertionGui instance = new JSONPathAssertionGui();
diff --git a/src/components/src/test/java/org/apache/jmeter/config/TestCVSDataSet.java b/src/components/src/test/java/org/apache/jmeter/config/TestCVSDataSet.java
index 679ae66..01ed5b2 100644
--- a/src/components/src/test/java/org/apache/jmeter/config/TestCVSDataSet.java
+++ b/src/components/src/test/java/org/apache/jmeter/config/TestCVSDataSet.java
@@ -35,9 +35,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-/**
- * Package to test FileServer methods
- */
public class TestCVSDataSet extends JMeterTestCase implements JMeterSerialTest {
private JMeterVariables threadVars;
@@ -71,7 +68,6 @@ public class TestCVSDataSet extends JMeterTestCase implements JMeterSerialTest {
ignored.getMessage());
}
-
csv = new CSVDataSet();
csv.setFilename(findTestPath("testfiles/testempty.csv"));
csv.setVariableNames("a,b,c");
@@ -212,7 +208,6 @@ public class TestCVSDataSet extends JMeterTestCase implements JMeterSerialTest {
csv.iterationStart(null);
fail("Expected JMeterStopThreadException");
} catch (JMeterStopThreadException expected) {
-
}
}
diff --git a/src/components/src/test/java/org/apache/jmeter/config/gui/TestArgumentsPanel.java b/src/components/src/test/java/org/apache/jmeter/config/gui/TestArgumentsPanel.java
index 6d4dae0..a3931cc 100644
--- a/src/components/src/test/java/org/apache/jmeter/config/gui/TestArgumentsPanel.java
+++ b/src/components/src/test/java/org/apache/jmeter/config/gui/TestArgumentsPanel.java
@@ -28,27 +28,22 @@ import org.junit.Test;
* A GUI panel allowing the user to enter name-value argument pairs. These
* arguments (or parameters) are usually used to provide configuration values
* for some other component.
- *
*/
public class TestArgumentsPanel {
+ /**
+ * Test that adding an argument to the table results in an appropriate
+ * TestElement being created.
+ */
+ @Test
+ public void testArgumentCreation() throws Exception {
+ ArgumentsPanel gui = new ArgumentsPanel();
+ gui.tableModel.addRow(new Argument());
+ gui.tableModel.setValueAt("howdy", 0, 0);
+ gui.tableModel.addRow(new Argument());
+ gui.tableModel.setValueAt("doody", 0, 1);
- /**
- * Test that adding an argument to the table results in an appropriate
- * TestElement being created.
- *
- * @throws Exception
- * if an exception occurred during the test
- */
- @Test
- public void testArgumentCreation() throws Exception {
- ArgumentsPanel gui = new ArgumentsPanel();
- gui.tableModel.addRow(new Argument());
- gui.tableModel.setValueAt("howdy", 0, 0);
- gui.tableModel.addRow(new Argument());
- gui.tableModel.setValueAt("doody", 0, 1);
-
- assertEquals("=", ((Argument) ((Arguments) gui.createTestElement()).getArguments().get(0).getObjectValue())
- .getMetaData());
- }
+ assertEquals("=", ((Argument) ((Arguments) gui.createTestElement()).getArguments().get(0).getObjectValue())
+ .getMetaData());
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestGenericController.java b/src/components/src/test/java/org/apache/jmeter/control/TestGenericController.java
index 4cc2197..2b840aa 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestGenericController.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestGenericController.java
@@ -27,33 +27,33 @@ import org.junit.Test;
public class TestGenericController extends JMeterTestCase {
- @Test
- public void testProcessing() throws Exception {
- testLog.debug("Testing Generic Controller");
- GenericController controller = new GenericController();
- GenericController sub_1 = new GenericController();
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
- controller.addTestElement(sub_1);
- controller.addTestElement(new TestSampler("three"));
- GenericController sub_2 = new GenericController();
- GenericController sub_3 = new GenericController();
- sub_2.addTestElement(new TestSampler("four"));
- sub_3.addTestElement(new TestSampler("five"));
- sub_3.addTestElement(new TestSampler("six"));
- sub_2.addTestElement(sub_3);
- sub_2.addTestElement(new TestSampler("seven"));
- controller.addTestElement(sub_2);
- String[] order = new String[] { "one", "two", "three", "four", "five", "six", "seven" };
- int counter = 7;
- controller.initialize();
- for (int i = 0; i < 2; i++) {
- assertEquals(7, counter);
- counter = 0;
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals(order[counter++], sampler.getName());
- }
+ @Test
+ public void testProcessing() throws Exception {
+ testLog.debug("Testing Generic Controller");
+ GenericController controller = new GenericController();
+ GenericController sub_1 = new GenericController();
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+ controller.addTestElement(sub_1);
+ controller.addTestElement(new TestSampler("three"));
+ GenericController sub_2 = new GenericController();
+ GenericController sub_3 = new GenericController();
+ sub_2.addTestElement(new TestSampler("four"));
+ sub_3.addTestElement(new TestSampler("five"));
+ sub_3.addTestElement(new TestSampler("six"));
+ sub_2.addTestElement(sub_3);
+ sub_2.addTestElement(new TestSampler("seven"));
+ controller.addTestElement(sub_2);
+ String[] order = new String[]{"one", "two", "three", "four", "five", "six", "seven"};
+ int counter = 7;
+ controller.initialize();
+ for (int i = 0; i < 2; i++) {
+ assertEquals(7, counter);
+ counter = 0;
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals(order[counter++], sampler.getName());
}
}
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestIfController.java b/src/components/src/test/java/org/apache/jmeter/control/TestIfController.java
index ba699eb..dfe2bc8 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestIfController.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestIfController.java
@@ -28,6 +28,7 @@ import org.apache.jmeter.junit.stubs.TestSampler;
import org.apache.jmeter.modifiers.CounterConfig;
import org.apache.jmeter.sampler.DebugSampler;
import org.apache.jmeter.samplers.Sampler;
+import org.apache.jmeter.testkit.BugId;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
@@ -36,12 +37,7 @@ import org.junit.Test;
public class TestIfController extends JMeterTestCase {
- /**
- * See Bug 56160
- *
- * @throws Exception
- * if something fails
- */
+ @BugId("56160")
@Test
public void testStackOverflow() throws Exception {
LoopController controller = new LoopController();
@@ -76,12 +72,7 @@ public class TestIfController extends JMeterTestCase {
}
}
- /**
- * See Bug 53768
- *
- * @throws Exception
- * if something fails
- */
+ @BugId("53768")
@Test
public void testBug53768() throws Exception {
LoopController controller = new LoopController();
@@ -217,9 +208,6 @@ public class TestIfController extends JMeterTestCase {
/**
* Test false return on sample3 (sample4 doesn't execute)
- *
- * @throws Exception
- * if something fails
*/
@Test
public void testEvaluateAllChildrenWithoutSubController() throws Exception {
@@ -256,9 +244,6 @@ public class TestIfController extends JMeterTestCase {
/**
* test 2 loops with a sub generic controller (sample4 doesn't execute)
- *
- * @throws Exception
- * if something fails
*/
@Test
public void testEvaluateAllChildrenWithSubController() throws Exception {
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestInterleaveControl.java b/src/components/src/test/java/org/apache/jmeter/control/TestInterleaveControl.java
index 48adf5e..a1015ee 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestInterleaveControl.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestInterleaveControl.java
@@ -27,207 +27,207 @@ import org.junit.Test;
public class TestInterleaveControl extends JMeterTestCase {
- @Test
- public void testProcessing() throws Exception {
- testLog.debug("Testing Interleave Controller 1");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
- controller.addTestElement(sub_1);
- controller.addTestElement(new TestSampler("three"));
- LoopController sub_2 = new LoopController();
- sub_2.setLoops(3);
- GenericController sub_3 = new GenericController();
- sub_2.addTestElement(new TestSampler("four"));
- sub_3.addTestElement(new TestSampler("five"));
- sub_3.addTestElement(new TestSampler("six"));
- sub_2.addTestElement(sub_3);
- sub_2.addTestElement(new TestSampler("seven"));
- controller.addTestElement(sub_2);
- String[] interleaveOrder = new String[] { "one", "two" };
- String[] order = new String[] { "dummy", "three", "four", "five", "six", "seven", "four", "five", "six",
- "seven", "four", "five", "six", "seven" };
- int counter = 14;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- for (int i = 0; i < 4; i++) {
- assertEquals(14, counter);
- counter = 0;
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- if (counter == 0) {
- assertEquals(interleaveOrder[i % 2], sampler.getName());
- } else {
- assertEquals(order[counter], sampler.getName());
- }
- counter++;
+ @Test
+ public void testProcessing() throws Exception {
+ testLog.debug("Testing Interleave Controller 1");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+ controller.addTestElement(sub_1);
+ controller.addTestElement(new TestSampler("three"));
+ LoopController sub_2 = new LoopController();
+ sub_2.setLoops(3);
+ GenericController sub_3 = new GenericController();
+ sub_2.addTestElement(new TestSampler("four"));
+ sub_3.addTestElement(new TestSampler("five"));
+ sub_3.addTestElement(new TestSampler("six"));
+ sub_2.addTestElement(sub_3);
+ sub_2.addTestElement(new TestSampler("seven"));
+ controller.addTestElement(sub_2);
+ String[] interleaveOrder = new String[]{"one", "two"};
+ String[] order = new String[]{"dummy", "three", "four", "five", "six", "seven", "four", "five", "six",
+ "seven", "four", "five", "six", "seven"};
+ int counter = 14;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ for (int i = 0; i < 4; i++) {
+ assertEquals(14, counter);
+ counter = 0;
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ if (counter == 0) {
+ assertEquals(interleaveOrder[i % 2], sampler.getName());
+ } else {
+ assertEquals(order[counter], sampler.getName());
}
+ counter++;
}
}
+ }
- @Test
- public void testProcessing6() throws Exception {
- testLog.debug("Testing Interleave Controller 6");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- controller.addTestElement(new TestSampler("one"));
- sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
- controller.addTestElement(sub_1);
- LoopController sub_2 = new LoopController();
- sub_1.addTestElement(sub_2);
- sub_2.setLoops(3);
- int counter = 1;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- controller.initialize();
- for (int i = 0; i < 4; i++) {
- assertEquals(1, counter);
- counter = 0;
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals("one", sampler.getName());
- counter++;
- }
+ @Test
+ public void testProcessing6() throws Exception {
+ testLog.debug("Testing Interleave Controller 6");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ controller.addTestElement(new TestSampler("one"));
+ sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
+ controller.addTestElement(sub_1);
+ LoopController sub_2 = new LoopController();
+ sub_1.addTestElement(sub_2);
+ sub_2.setLoops(3);
+ int counter = 1;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ controller.initialize();
+ for (int i = 0; i < 4; i++) {
+ assertEquals(1, counter);
+ counter = 0;
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals("one", sampler.getName());
+ counter++;
}
}
+ }
- @Test
- public void testProcessing2() throws Exception {
- testLog.debug("Testing Interleave Controller 2");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
- controller.addTestElement(sub_1);
- controller.addTestElement(new TestSampler("three"));
- LoopController sub_2 = new LoopController();
- sub_2.setLoops(3);
- GenericController sub_3 = new GenericController();
- sub_2.addTestElement(new TestSampler("four"));
- sub_3.addTestElement(new TestSampler("five"));
- sub_3.addTestElement(new TestSampler("six"));
- sub_2.addTestElement(sub_3);
- sub_2.addTestElement(new TestSampler("seven"));
- sub_1.addTestElement(sub_2);
- String[] order = new String[] { "one", "three", "two", "three", "four", "three", "one", "three", "two",
- "three", "five", "three", "one", "three", "two", "three", "six", "three", "one", "three" };
- int counter = 0;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- while (counter < order.length) {
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals("failed on " + counter, order[counter], sampler.getName());
- counter++;
- }
+ @Test
+ public void testProcessing2() throws Exception {
+ testLog.debug("Testing Interleave Controller 2");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+ controller.addTestElement(sub_1);
+ controller.addTestElement(new TestSampler("three"));
+ LoopController sub_2 = new LoopController();
+ sub_2.setLoops(3);
+ GenericController sub_3 = new GenericController();
+ sub_2.addTestElement(new TestSampler("four"));
+ sub_3.addTestElement(new TestSampler("five"));
+ sub_3.addTestElement(new TestSampler("six"));
+ sub_2.addTestElement(sub_3);
+ sub_2.addTestElement(new TestSampler("seven"));
+ sub_1.addTestElement(sub_2);
+ String[] order = new String[]{"one", "three", "two", "three", "four", "three", "one", "three", "two",
+ "three", "five", "three", "one", "three", "two", "three", "six", "three", "one", "three"};
+ int counter = 0;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ while (counter < order.length) {
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals("failed on " + counter, order[counter], sampler.getName());
+ counter++;
}
}
+ }
- @Test
- public void testProcessing3() throws Exception {
- testLog.debug("Testing Interleave Controller 3");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- sub_1.setStyle(InterleaveControl.USE_SUB_CONTROLLERS);
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
- controller.addTestElement(sub_1);
- controller.addTestElement(new TestSampler("three"));
- LoopController sub_2 = new LoopController();
- sub_2.setLoops(3);
- GenericController sub_3 = new GenericController();
- sub_2.addTestElement(new TestSampler("four"));
- sub_3.addTestElement(new TestSampler("five"));
- sub_3.addTestElement(new TestSampler("six"));
- sub_2.addTestElement(sub_3);
- sub_2.addTestElement(new TestSampler("seven"));
- sub_1.addTestElement(sub_2);
- String[] order = new String[] { "one", "three", "two", "three", "four", "five", "six", "seven", "four",
- "five", "six", "seven", "four", "five", "six", "seven", "three", "one", "three", "two", "three" };
- int counter = 0;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- while (counter < order.length) {
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals("failed on" + counter, order[counter], sampler.getName());
- counter++;
- }
+ @Test
+ public void testProcessing3() throws Exception {
+ testLog.debug("Testing Interleave Controller 3");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ sub_1.setStyle(InterleaveControl.USE_SUB_CONTROLLERS);
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+ controller.addTestElement(sub_1);
+ controller.addTestElement(new TestSampler("three"));
+ LoopController sub_2 = new LoopController();
+ sub_2.setLoops(3);
+ GenericController sub_3 = new GenericController();
+ sub_2.addTestElement(new TestSampler("four"));
+ sub_3.addTestElement(new TestSampler("five"));
+ sub_3.addTestElement(new TestSampler("six"));
+ sub_2.addTestElement(sub_3);
+ sub_2.addTestElement(new TestSampler("seven"));
+ sub_1.addTestElement(sub_2);
+ String[] order = new String[]{"one", "three", "two", "three", "four", "five", "six", "seven", "four",
+ "five", "six", "seven", "four", "five", "six", "seven", "three", "one", "three", "two", "three"};
+ int counter = 0;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ while (counter < order.length) {
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals("failed on" + counter, order[counter], sampler.getName());
+ counter++;
}
}
+ }
- @Test
- public void testProcessing4() throws Exception {
- testLog.debug("Testing Interleave Controller 4");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
- controller.addTestElement(sub_1);
- GenericController sub_2 = new GenericController();
- sub_2.addTestElement(new TestSampler("one"));
- sub_2.addTestElement(new TestSampler("two"));
- sub_1.addTestElement(sub_2);
- GenericController sub_3 = new GenericController();
- sub_3.addTestElement(new TestSampler("three"));
- sub_3.addTestElement(new TestSampler("four"));
- sub_1.addTestElement(sub_3);
- String[] order = new String[] { "one", "three", "two", "four" };
- int counter = 0;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- while (counter < order.length) {
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals("failed on" + counter, order[counter], sampler.getName());
- counter++;
- }
+ @Test
+ public void testProcessing4() throws Exception {
+ testLog.debug("Testing Interleave Controller 4");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ sub_1.setStyle(InterleaveControl.IGNORE_SUB_CONTROLLERS);
+ controller.addTestElement(sub_1);
+ GenericController sub_2 = new GenericController();
+ sub_2.addTestElement(new TestSampler("one"));
+ sub_2.addTestElement(new TestSampler("two"));
+ sub_1.addTestElement(sub_2);
+ GenericController sub_3 = new GenericController();
+ sub_3.addTestElement(new TestSampler("three"));
+ sub_3.addTestElement(new TestSampler("four"));
+ sub_1.addTestElement(sub_3);
+ String[] order = new String[]{"one", "three", "two", "four"};
+ int counter = 0;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ while (counter < order.length) {
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals("failed on" + counter, order[counter], sampler.getName());
+ counter++;
}
}
+ }
- @Test
- public void testProcessing5() throws Exception {
- testLog.debug("Testing Interleave Controller 5");
- GenericController controller = new GenericController();
- InterleaveControl sub_1 = new InterleaveControl();
- sub_1.setStyle(InterleaveControl.USE_SUB_CONTROLLERS);
- controller.addTestElement(sub_1);
- GenericController sub_2 = new GenericController();
- sub_2.addTestElement(new TestSampler("one"));
- sub_2.addTestElement(new TestSampler("two"));
- sub_1.addTestElement(sub_2);
- GenericController sub_3 = new GenericController();
- sub_3.addTestElement(new TestSampler("three"));
- sub_3.addTestElement(new TestSampler("four"));
- sub_1.addTestElement(sub_3);
- String[] order = new String[] { "one", "two", "three", "four" };
- int counter = 0;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- while (counter < order.length) {
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals("failed on" + counter, order[counter], sampler.getName());
- counter++;
- }
+ @Test
+ public void testProcessing5() throws Exception {
+ testLog.debug("Testing Interleave Controller 5");
+ GenericController controller = new GenericController();
+ InterleaveControl sub_1 = new InterleaveControl();
+ sub_1.setStyle(InterleaveControl.USE_SUB_CONTROLLERS);
+ controller.addTestElement(sub_1);
+ GenericController sub_2 = new GenericController();
+ sub_2.addTestElement(new TestSampler("one"));
+ sub_2.addTestElement(new TestSampler("two"));
+ sub_1.addTestElement(sub_2);
+ GenericController sub_3 = new GenericController();
+ sub_3.addTestElement(new TestSampler("three"));
+ sub_3.addTestElement(new TestSampler("four"));
+ sub_1.addTestElement(sub_3);
+ String[] order = new String[]{"one", "two", "three", "four"};
+ int counter = 0;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ while (counter < order.length) {
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals("failed on" + counter, order[counter], sampler.getName());
+ counter++;
}
}
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestLoopController.java b/src/components/src/test/java/org/apache/jmeter/control/TestLoopController.java
index b25673c..6ca2614 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestLoopController.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestLoopController.java
@@ -41,124 +41,122 @@ import org.junit.Test;
public class TestLoopController extends JMeterTestCase {
- @Test
- public void testProcessing() throws Exception {
- JMeterContext jmctx = JMeterContextService.getContext();
- JMeterVariables variables = new JMeterVariables();
- jmctx.setVariables(variables);
+ @Test
+ public void testProcessing() throws Exception {
+ JMeterContext jmctx = JMeterContextService.getContext();
+ JMeterVariables variables = new JMeterVariables();
+ jmctx.setVariables(variables);
- GenericController controller = new GenericController();
- GenericController sub_1 = new GenericController();
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
- controller.addTestElement(sub_1);
- controller.addTestElement(new TestSampler("three"));
- LoopController sub_2 = new LoopController();
- String lcName = "LC";
- sub_2.setName(lcName);
- sub_2.setLoops(3);
- GenericController sub_3 = new GenericController();
- sub_2.addTestElement(new TestSampler("four"));
- sub_3.addTestElement(new TestSampler("five"));
- sub_3.addTestElement(new TestSampler("six"));
- sub_2.addTestElement(sub_3);
- sub_2.addTestElement(new TestSampler("seven"));
- controller.addTestElement(sub_2);
- String[] order = new String[] { "one", "two", "three", "four", "five", "six", "seven", "four", "five",
- "six", "seven", "four", "five", "six", "seven" };
- int counter = 15;
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- sub_3.setRunningVersion(true);
- controller.initialize();
- int loopControl = 0;
- for (int i = 0; i < 2; i++) {
- loopControl = 0;
- assertEquals(15, counter);
- counter = 0;
- TestElement sampler = null;
- while ((sampler = controller.next()) != null) {
- assertEquals(order[counter++], sampler.getName());
- if("four".equals(sampler.getName())) {
- Integer value = (Integer) variables.getObject(
- JMeterUtils.formatJMeterExportedVariableName(lcName+LoopController.INDEX_VAR_NAME_SUFFIX));
- assertNotNull(value);
- assertEquals(Integer.valueOf(loopControl++), value);
- }
+ GenericController controller = new GenericController();
+ GenericController sub_1 = new GenericController();
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+ controller.addTestElement(sub_1);
+ controller.addTestElement(new TestSampler("three"));
+ LoopController sub_2 = new LoopController();
+ String lcName = "LC";
+ sub_2.setName(lcName);
+ sub_2.setLoops(3);
+ GenericController sub_3 = new GenericController();
+ sub_2.addTestElement(new TestSampler("four"));
+ sub_3.addTestElement(new TestSampler("five"));
+ sub_3.addTestElement(new TestSampler("six"));
+ sub_2.addTestElement(sub_3);
+ sub_2.addTestElement(new TestSampler("seven"));
+ controller.addTestElement(sub_2);
+ String[] order = new String[]{"one", "two", "three", "four", "five", "six", "seven", "four", "five",
+ "six", "seven", "four", "five", "six", "seven"};
+ int counter = 15;
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ sub_3.setRunningVersion(true);
+ controller.initialize();
+ int loopControl = 0;
+ for (int i = 0; i < 2; i++) {
+ loopControl = 0;
+ assertEquals(15, counter);
+ counter = 0;
+ TestElement sampler = null;
+ while ((sampler = controller.next()) != null) {
+ assertEquals(order[counter++], sampler.getName());
+ if ("four".equals(sampler.getName())) {
+ Integer value = (Integer) variables.getObject(
+ JMeterUtils.formatJMeterExportedVariableName(lcName + LoopController.INDEX_VAR_NAME_SUFFIX));
+ assertNotNull(value);
+ assertEquals(Integer.valueOf(loopControl++), value);
}
-
}
-
}
+ }
- @Test
- public void testLoopZeroTimes() throws Exception {
- JMeterContext jmctx = JMeterContextService.getContext();
- JMeterVariables variables = new JMeterVariables();
- jmctx.setVariables(variables);
+ @Test
+ public void testLoopZeroTimes() throws Exception {
+ JMeterContext jmctx = JMeterContextService.getContext();
+ JMeterVariables variables = new JMeterVariables();
+ jmctx.setVariables(variables);
- LoopController loop = new LoopController();
- String lcName = "LC";
- loop.setName(lcName);
- loop.setLoops(0);
- loop.addTestElement(new TestSampler("never run"));
- loop.initialize();
- assertNull(loop.next());
+ LoopController loop = new LoopController();
+ String lcName = "LC";
+ loop.setName(lcName);
+ loop.setLoops(0);
+ loop.addTestElement(new TestSampler("never run"));
+ loop.initialize();
+ assertNull(loop.next());
+ Integer value = (Integer) variables.getObject(
+ JMeterUtils.formatJMeterExportedVariableName(lcName + LoopController.INDEX_VAR_NAME_SUFFIX));
+ assertNotNull(value);
+ assertEquals(Integer.valueOf(0), value);
+ }
+
+ @Test
+ public void testInfiniteLoop() throws Exception {
+ JMeterContext jmctx = JMeterContextService.getContext();
+ LoopController loop = new LoopController();
+ String lcName = "LC";
+ loop.setName(lcName);
+ loop.setLoops(LoopController.INFINITE_LOOP_COUNT);
+ loop.addTestElement(new TestSampler("never run"));
+ JMeterVariables variables = new JMeterVariables();
+ jmctx.setVariables(variables);
+ loop.setRunningVersion(true);
+ loop.initialize();
+ for (int i = 0; i < 42; i++) {
+ assertNotNull(loop.next());
Integer value = (Integer) variables.getObject(
- JMeterUtils.formatJMeterExportedVariableName(lcName+LoopController.INDEX_VAR_NAME_SUFFIX));
+ JMeterUtils.formatJMeterExportedVariableName(lcName + LoopController.INDEX_VAR_NAME_SUFFIX));
assertNotNull(value);
- assertEquals(Integer.valueOf(0), value);
- }
-
- @Test
- public void testInfiniteLoop() throws Exception {
- JMeterContext jmctx = JMeterContextService.getContext();
- LoopController loop = new LoopController();
- String lcName = "LC";
- loop.setName(lcName);
- loop.setLoops(LoopController.INFINITE_LOOP_COUNT);
- loop.addTestElement(new TestSampler("never run"));
- JMeterVariables variables = new JMeterVariables();
- jmctx.setVariables(variables);
- loop.setRunningVersion(true);
- loop.initialize();
- for (int i = 0; i < 42; i++) {
- assertNotNull(loop.next());
- Integer value = (Integer) variables.getObject(
- JMeterUtils.formatJMeterExportedVariableName(lcName+LoopController.INDEX_VAR_NAME_SUFFIX));
- assertNotNull(value);
- assertEquals(Integer.valueOf(i), value);
- }
+ assertEquals(Integer.valueOf(i), value);
}
+ }
- @Test
- public void testBug54467() throws Exception {
- JMeterContext jmctx = JMeterContextService.getContext();
- String lcName = "LC";
- LoopController loop = new LoopController();
- loop.setName(lcName);
- Map<String, String> variables = new HashMap<>();
- ReplaceStringWithFunctions transformer = new ReplaceStringWithFunctions(new CompoundVariable(), variables);
- jmctx.setVariables(new JMeterVariables());
+ @Test
+ public void testBug54467() throws Exception {
+ JMeterContext jmctx = JMeterContextService.getContext();
+ String lcName = "LC";
+ LoopController loop = new LoopController();
+ loop.setName(lcName);
+ Map<String, String> variables = new HashMap<>();
+ ReplaceStringWithFunctions transformer = new ReplaceStringWithFunctions(new CompoundVariable(), variables);
+ jmctx.setVariables(new JMeterVariables());
- StringProperty prop = new StringProperty(LoopController.LOOPS,"${__Random(1,12,)}");
- JMeterProperty newProp = transformer.transformValue(prop);
- newProp.setRunningVersion(true);
+ StringProperty prop = new StringProperty(LoopController.LOOPS, "${__Random(1,12,)}");
+ JMeterProperty newProp = transformer.transformValue(prop);
+ newProp.setRunningVersion(true);
- loop.setProperty(newProp);
- loop.addTestElement(new TestSampler("random run"));
- loop.setRunningVersion(true);
- loop.initialize();
- int loops = loop.getLoops();
- for (int i = 0; i < loops; i++) {
- Sampler s = loop.next();
- assertNotNull(s);
- Integer value = (Integer) jmctx.getVariables().getObject(
- JMeterUtils.formatJMeterExportedVariableName(lcName+LoopController.INDEX_VAR_NAME_SUFFIX));
- assertNotNull(value);
- assertEquals(Integer.valueOf(i), value);
- }
- assertNull(loop.next());
+ loop.setProperty(newProp);
+ loop.addTestElement(new TestSampler("random run"));
+ loop.setRunningVersion(true);
+ loop.initialize();
+ int loops = loop.getLoops();
+ for (int i = 0; i < loops; i++) {
+ Sampler s = loop.next();
+ assertNotNull(s);
+ Integer value = (Integer) jmctx.getVariables().getObject(
+ JMeterUtils.formatJMeterExportedVariableName(lcName + LoopController.INDEX_VAR_NAME_SUFFIX));
+ assertNotNull(value);
+ assertEquals(Integer.valueOf(i), value);
}
+ assertNull(loop.next());
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestTransactionController.java b/src/components/src/test/java/org/apache/jmeter/control/TestTransactionController.java
index 9e3610b..348c23e 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestTransactionController.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestTransactionController.java
@@ -41,15 +41,10 @@ import org.junit.Test;
public class TestTransactionController extends JMeterTestCase {
- /**
- * @see "http://bz.apache.org/bugzilla/show_bug.cgi?id=57958"
- * @throws Exception when something breaks
- */
@Test
public void testIssue57958() throws Exception {
JMeterContextService.getContext().setVariables(new JMeterVariables());
-
TestSampleListener listener = new TestSampleListener();
TransactionController transactionController = new TransactionController();
diff --git a/src/components/src/test/java/org/apache/jmeter/control/TestWhileController.java b/src/components/src/test/java/org/apache/jmeter/control/TestWhileController.java
index e100048..701fdbe 100644
--- a/src/components/src/test/java/org/apache/jmeter/control/TestWhileController.java
+++ b/src/components/src/test/java/org/apache/jmeter/control/TestWhileController.java
@@ -37,8 +37,8 @@ import org.junit.Test;
public class TestWhileController extends JMeterTestCase {
- private JMeterContext jmctx;
- private JMeterVariables jmvars;
+ private JMeterContext jmctx;
+ private JMeterVariables jmvars;
@Before
public void setUp() {
@@ -47,322 +47,322 @@ public class TestWhileController extends JMeterTestCase {
jmvars = jmctx.getVariables();
}
- private void setLastSampleStatus(boolean status){
- jmvars.put(JMeterThread.LAST_SAMPLE_OK,Boolean.toString(status));
- }
+ private void setLastSampleStatus(boolean status) {
+ jmvars.put(JMeterThread.LAST_SAMPLE_OK, Boolean.toString(status));
+ }
- private void setRunning(TestElement el){
- PropertyIterator pi = el.propertyIterator();
- while(pi.hasNext()){
- pi.next().setRunningVersion(true);
- }
+ private void setRunning(TestElement el) {
+ PropertyIterator pi = el.propertyIterator();
+ while (pi.hasNext()) {
+ pi.next().setRunningVersion(true);
}
+ }
- // Get next sample and its name
- private String nextName(GenericController c) {
- Sampler s = c.next();
- if (s == null) {
- return null;
- }
- return s.getName();
+ // Get next sample and its name
+ private String nextName(GenericController c) {
+ Sampler s = c.next();
+ if (s == null) {
+ return null;
}
+ return s.getName();
+ }
- // While (blank), previous sample OK - should loop until false
- @Test
- public void testBlankPrevOK() throws Exception {
- runtestPrevOK("");
- }
+ // While (blank), previous sample OK - should loop until false
+ @Test
+ public void testBlankPrevOK() throws Exception {
+ runtestPrevOK("");
+ }
- // While (LAST), previous sample OK - should loop until false
- @Test
- public void testLastPrevOK() throws Exception {
- runtestPrevOK("LAST");
- }
+ // While (LAST), previous sample OK - should loop until false
+ @Test
+ public void testLastPrevOK() throws Exception {
+ runtestPrevOK("LAST");
+ }
- private static final String OTHER = "X"; // Dummy for testing functions
+ private static final String OTHER = "X"; // Dummy for testing functions
- // While (LAST), previous sample OK - should loop until false
- @Test
- public void testOtherPrevOK() throws Exception {
- runtestPrevOK(OTHER);
- }
+ // While (LAST), previous sample OK - should loop until false
+ @Test
+ public void testOtherPrevOK() throws Exception {
+ runtestPrevOK(OTHER);
+ }
- private void runtestPrevOK(String type) throws Exception {
- GenericController controller = new GenericController();
- WhileController while_cont = new WhileController();
- setLastSampleStatus(true);
- while_cont.setCondition(type);
- while_cont.addTestElement(new TestSampler("one"));
- while_cont.addTestElement(new TestSampler("two"));
- while_cont.addTestElement(new TestSampler("three"));
- controller.addTestElement(while_cont);
- controller.addTestElement(new TestSampler("four"));
- controller.initialize();
- assertEquals("one", nextName(controller));
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- assertEquals("one", nextName(controller));
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- assertEquals("one", nextName(controller));
- setLastSampleStatus(false);
- if (type.equals(OTHER)){
- while_cont.setCondition("false");
- }
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- setLastSampleStatus(true);
- if (type.equals(OTHER)) {
- while_cont.setCondition(OTHER);
- }
- assertEquals("one", nextName(controller));
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- setLastSampleStatus(false);
- if (type.equals(OTHER)) {
- while_cont.setCondition("false");
- }
- assertEquals("four", nextName(controller));
- assertNull(nextName(controller));
- setLastSampleStatus(true);
- if (type.equals(OTHER)) {
- while_cont.setCondition(OTHER);
- }
- assertEquals("one", nextName(controller));
+ private void runtestPrevOK(String type) throws Exception {
+ GenericController controller = new GenericController();
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(true);
+ while_cont.setCondition(type);
+ while_cont.addTestElement(new TestSampler("one"));
+ while_cont.addTestElement(new TestSampler("two"));
+ while_cont.addTestElement(new TestSampler("three"));
+ controller.addTestElement(while_cont);
+ controller.addTestElement(new TestSampler("four"));
+ controller.initialize();
+ assertEquals("one", nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ assertEquals("one", nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ assertEquals("one", nextName(controller));
+ setLastSampleStatus(false);
+ if (type.equals(OTHER)) {
+ while_cont.setCondition("false");
}
-
- // While (blank), previous sample failed - should run once
- @Test
- public void testBlankPrevFailed() throws Exception {
- GenericController controller = new GenericController();
- controller.setRunningVersion(true);
- WhileController while_cont = new WhileController();
- setLastSampleStatus(false);
- while_cont.setCondition("");
- while_cont.addTestElement(new TestSampler("one"));
- while_cont.addTestElement(new TestSampler("two"));
- controller.addTestElement(while_cont);
- controller.addTestElement(new TestSampler("three"));
- controller.initialize();
- assertEquals("one", nextName(controller));
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- assertNull(nextName(controller));
- // Run entire test again
- assertEquals("one", nextName(controller));
- assertEquals("two", nextName(controller));
- assertEquals("three", nextName(controller));
- assertNull(nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ setLastSampleStatus(true);
+ if (type.equals(OTHER)) {
+ while_cont.setCondition(OTHER);
+ }
+ assertEquals("one", nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ setLastSampleStatus(false);
+ if (type.equals(OTHER)) {
+ while_cont.setCondition("false");
}
+ assertEquals("four", nextName(controller));
+ assertNull(nextName(controller));
+ setLastSampleStatus(true);
+ if (type.equals(OTHER)) {
+ while_cont.setCondition(OTHER);
+ }
+ assertEquals("one", nextName(controller));
+ }
- /*
- * Generic Controller
- * - before
- * - While Controller ${VAR}
- * - - one
- * - - two
- * - - Simple Controller
- * - - - three
- * - - - four
- * - after
- */
- @Test
- public void testVariable1() throws Exception {
- GenericController controller = new GenericController();
- WhileController while_cont = new WhileController();
- setLastSampleStatus(false);
- while_cont.setCondition("${VAR}");
- jmvars.put("VAR", "");
- ValueReplacer vr = new ValueReplacer();
- vr.replaceValues(while_cont);
- setRunning(while_cont);
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(while_cont);
- while_cont.addTestElement(new TestSampler("one"));
- while_cont.addTestElement(new TestSampler("two"));
- GenericController simple = new GenericController();
- while_cont.addTestElement(simple);
- simple.addTestElement(new TestSampler("three"));
- simple.addTestElement(new TestSampler("four"));
- controller.addTestElement(new TestSampler("after"));
- controller.initialize();
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- assertEquals("Loop: "+i,"one", nextName(controller));
- assertEquals("Loop: "+i,"two", nextName(controller));
- assertEquals("Loop: "+i,"three", nextName(controller));
- assertEquals("Loop: "+i,"four", nextName(controller));
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
- }
- jmvars.put("VAR", "LAST"); // Should not enter the loop
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
- }
- jmvars.put("VAR", "");
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- if (i==1) {
- assertEquals("Loop: "+i,"one", nextName(controller));
- assertEquals("Loop: "+i,"two", nextName(controller));
- assertEquals("Loop: "+i,"three", nextName(controller));
- jmvars.put("VAR", "LAST"); // Should not enter the loop next time
- assertEquals("Loop: "+i,"four", nextName(controller));
- }
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
+ // While (blank), previous sample failed - should run once
+ @Test
+ public void testBlankPrevFailed() throws Exception {
+ GenericController controller = new GenericController();
+ controller.setRunningVersion(true);
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(false);
+ while_cont.setCondition("");
+ while_cont.addTestElement(new TestSampler("one"));
+ while_cont.addTestElement(new TestSampler("two"));
+ controller.addTestElement(while_cont);
+ controller.addTestElement(new TestSampler("three"));
+ controller.initialize();
+ assertEquals("one", nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ assertNull(nextName(controller));
+ // Run entire test again
+ assertEquals("one", nextName(controller));
+ assertEquals("two", nextName(controller));
+ assertEquals("three", nextName(controller));
+ assertNull(nextName(controller));
+ }
+
+ /*
+ * Generic Controller
+ * - before
+ * - While Controller ${VAR}
+ * - - one
+ * - - two
+ * - - Simple Controller
+ * - - - three
+ * - - - four
+ * - after
+ */
+ @Test
+ public void testVariable1() throws Exception {
+ GenericController controller = new GenericController();
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(false);
+ while_cont.setCondition("${VAR}");
+ jmvars.put("VAR", "");
+ ValueReplacer vr = new ValueReplacer();
+ vr.replaceValues(while_cont);
+ setRunning(while_cont);
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(while_cont);
+ while_cont.addTestElement(new TestSampler("one"));
+ while_cont.addTestElement(new TestSampler("two"));
+ GenericController simple = new GenericController();
+ while_cont.addTestElement(simple);
+ simple.addTestElement(new TestSampler("three"));
+ simple.addTestElement(new TestSampler("four"));
+ controller.addTestElement(new TestSampler("after"));
+ controller.initialize();
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ assertEquals("Loop: " + i, "one", nextName(controller));
+ assertEquals("Loop: " + i, "two", nextName(controller));
+ assertEquals("Loop: " + i, "three", nextName(controller));
+ assertEquals("Loop: " + i, "four", nextName(controller));
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
+ }
+ jmvars.put("VAR", "LAST"); // Should not enter the loop
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
+ }
+ jmvars.put("VAR", "");
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ if (i == 1) {
+ assertEquals("Loop: " + i, "one", nextName(controller));
+ assertEquals("Loop: " + i, "two", nextName(controller));
+ assertEquals("Loop: " + i, "three", nextName(controller));
+ jmvars.put("VAR", "LAST"); // Should not enter the loop next time
+ assertEquals("Loop: " + i, "four", nextName(controller));
}
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
}
+ }
- // Test with SimpleController as first item
- @Test
- public void testVariable2() throws Exception {
- GenericController controller = new GenericController();
- WhileController while_cont = new WhileController();
- setLastSampleStatus(false);
- while_cont.setCondition("${VAR}");
- jmvars.put("VAR", "");
- ValueReplacer vr = new ValueReplacer();
- vr.replaceValues(while_cont);
- setRunning(while_cont);
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(while_cont);
- GenericController simple = new GenericController();
- while_cont.addTestElement(simple);
- simple.addTestElement(new TestSampler("one"));
- simple.addTestElement(new TestSampler("two"));
- while_cont.addTestElement(new TestSampler("three"));
- while_cont.addTestElement(new TestSampler("four"));
- controller.addTestElement(new TestSampler("after"));
- controller.initialize();
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- assertEquals("Loop: "+i,"one", nextName(controller));
- assertEquals("Loop: "+i,"two", nextName(controller));
- assertEquals("Loop: "+i,"three", nextName(controller));
- assertEquals("Loop: "+i,"four", nextName(controller));
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
- }
- jmvars.put("VAR", "LAST"); // Should not enter the loop
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
- }
- jmvars.put("VAR", "");
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop: "+i,"before", nextName(controller));
- if (i==1){
- assertEquals("Loop: "+i,"one", nextName(controller));
- assertEquals("Loop: "+i,"two", nextName(controller));
- jmvars.put("VAR", "LAST"); // Should not enter the loop next time
- // But should continue to the end of the loop
- assertEquals("Loop: "+i,"three", nextName(controller));
- assertEquals("Loop: "+i,"four", nextName(controller));
- }
- assertEquals("Loop: "+i,"after", nextName(controller));
- assertNull("Loop: "+i,nextName(controller));
+ // Test with SimpleController as first item
+ @Test
+ public void testVariable2() throws Exception {
+ GenericController controller = new GenericController();
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(false);
+ while_cont.setCondition("${VAR}");
+ jmvars.put("VAR", "");
+ ValueReplacer vr = new ValueReplacer();
+ vr.replaceValues(while_cont);
+ setRunning(while_cont);
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(while_cont);
+ GenericController simple = new GenericController();
+ while_cont.addTestElement(simple);
+ simple.addTestElement(new TestSampler("one"));
+ simple.addTestElement(new TestSampler("two"));
+ while_cont.addTestElement(new TestSampler("three"));
+ while_cont.addTestElement(new TestSampler("four"));
+ controller.addTestElement(new TestSampler("after"));
+ controller.initialize();
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ assertEquals("Loop: " + i, "one", nextName(controller));
+ assertEquals("Loop: " + i, "two", nextName(controller));
+ assertEquals("Loop: " + i, "three", nextName(controller));
+ assertEquals("Loop: " + i, "four", nextName(controller));
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
+ }
+ jmvars.put("VAR", "LAST"); // Should not enter the loop
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
+ }
+ jmvars.put("VAR", "");
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop: " + i, "before", nextName(controller));
+ if (i == 1) {
+ assertEquals("Loop: " + i, "one", nextName(controller));
+ assertEquals("Loop: " + i, "two", nextName(controller));
+ jmvars.put("VAR", "LAST"); // Should not enter the loop next time
+ // But should continue to the end of the loop
+ assertEquals("Loop: " + i, "three", nextName(controller));
+ assertEquals("Loop: " + i, "four", nextName(controller));
}
+ assertEquals("Loop: " + i, "after", nextName(controller));
+ assertNull("Loop: " + i, nextName(controller));
}
+ }
- // While LAST, previous sample failed - should not run
- @Test
- public void testLASTPrevFailed() throws Exception {
- runTestPrevFailed("LAST");
- }
+ // While LAST, previous sample failed - should not run
+ @Test
+ public void testLASTPrevFailed() throws Exception {
+ runTestPrevFailed("LAST");
+ }
- // While False, previous sample failed - should not run
- @Test
- public void testfalsePrevFailed() throws Exception {
- runTestPrevFailed("False");
- }
+ // While False, previous sample failed - should not run
+ @Test
+ public void testfalsePrevFailed() throws Exception {
+ runTestPrevFailed("False");
+ }
- private void runTestPrevFailed(String s) throws Exception {
- GenericController controller = new GenericController();
- WhileController while_cont = new WhileController();
- setLastSampleStatus(false);
- while_cont.setCondition(s);
- while_cont.addTestElement(new TestSampler("one"));
- while_cont.addTestElement(new TestSampler("two"));
- controller.addTestElement(while_cont);
- controller.addTestElement(new TestSampler("three"));
- controller.initialize();
- assertEquals("three", nextName(controller));
- assertNull(nextName(controller));
- assertEquals("three", nextName(controller));
- assertNull(nextName(controller));
- }
+ private void runTestPrevFailed(String s) throws Exception {
+ GenericController controller = new GenericController();
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(false);
+ while_cont.setCondition(s);
+ while_cont.addTestElement(new TestSampler("one"));
+ while_cont.addTestElement(new TestSampler("two"));
+ controller.addTestElement(while_cont);
+ controller.addTestElement(new TestSampler("three"));
+ controller.initialize();
+ assertEquals("three", nextName(controller));
+ assertNull(nextName(controller));
+ assertEquals("three", nextName(controller));
+ assertNull(nextName(controller));
+ }
- @Test
- public void testLastFailedBlank() throws Exception{
- runTestLastFailed("");
- }
+ @Test
+ public void testLastFailedBlank() throws Exception {
+ runTestLastFailed("");
+ }
- @Test
- public void testLastFailedLast() throws Exception{
- runTestLastFailed("LAST");
- }
+ @Test
+ public void testLastFailedLast() throws Exception {
+ runTestLastFailed("LAST");
+ }
- // Should behave the same for blank and LAST because success on input
- private void runTestLastFailed(String s) throws Exception {
- GenericController controller = new GenericController();
- controller.addTestElement(new TestSampler("1"));
- WhileController while_cont = new WhileController();
- controller.addTestElement(while_cont);
- while_cont.setCondition(s);
- GenericController sub = new GenericController();
- while_cont.addTestElement(sub);
- sub.addTestElement(new TestSampler("2"));
- sub.addTestElement(new TestSampler("3"));
+ // Should behave the same for blank and LAST because success on input
+ private void runTestLastFailed(String s) throws Exception {
+ GenericController controller = new GenericController();
+ controller.addTestElement(new TestSampler("1"));
+ WhileController while_cont = new WhileController();
+ controller.addTestElement(while_cont);
+ while_cont.setCondition(s);
+ GenericController sub = new GenericController();
+ while_cont.addTestElement(sub);
+ sub.addTestElement(new TestSampler("2"));
+ sub.addTestElement(new TestSampler("3"));
- controller.addTestElement(new TestSampler("4"));
+ controller.addTestElement(new TestSampler("4"));
- setLastSampleStatus(true);
- controller.initialize();
- assertEquals("1", nextName(controller));
- assertEquals("2", nextName(controller));
- setLastSampleStatus(false);
- assertEquals("3", nextName(controller));
- assertEquals("4", nextName(controller));
- assertNull(nextName(controller));
- }
+ setLastSampleStatus(true);
+ controller.initialize();
+ assertEquals("1", nextName(controller));
+ assertEquals("2", nextName(controller));
+ setLastSampleStatus(false);
+ assertEquals("3", nextName(controller));
+ assertEquals("4", nextName(controller));
+ assertNull(nextName(controller));
+ }
- // Tests for Stack Overflow (bug 33954)
- @Test
- public void testAlwaysFailOK() throws Exception {
- runTestAlwaysFail(true); // Should be OK
- }
+ // Tests for Stack Overflow (bug 33954)
+ @Test
+ public void testAlwaysFailOK() throws Exception {
+ runTestAlwaysFail(true); // Should be OK
+ }
- @Test
- public void testAlwaysFailBAD() throws Exception {
- runTestAlwaysFail(false);
- }
+ @Test
+ public void testAlwaysFailBAD() throws Exception {
+ runTestAlwaysFail(false);
+ }
- private void runTestAlwaysFail(boolean other) {
- LoopController controller = new LoopController();
- controller.setContinueForever(true);
- controller.setLoops(-1);
- WhileController while_cont = new WhileController();
- setLastSampleStatus(false);
- while_cont.setCondition("false");
- while_cont.addTestElement(new TestSampler("one"));
- while_cont.addTestElement(new TestSampler("two"));
- controller.addTestElement(while_cont);
+ private void runTestAlwaysFail(boolean other) {
+ LoopController controller = new LoopController();
+ controller.setContinueForever(true);
+ controller.setLoops(-1);
+ WhileController while_cont = new WhileController();
+ setLastSampleStatus(false);
+ while_cont.setCondition("false");
+ while_cont.addTestElement(new TestSampler("one"));
+ while_cont.addTestElement(new TestSampler("two"));
+ controller.addTestElement(while_cont);
+ if (other) {
+ controller.addTestElement(new TestSampler("three"));
+ }
+ controller.initialize();
+ try {
if (other) {
- controller.addTestElement(new TestSampler("three"));
- }
- controller.initialize();
- try {
- if (other) {
- assertEquals("three", nextName(controller));
- } else {
- assertNull(nextName(controller));
- }
- } catch (StackOverflowError e) {
- fail(e.toString());
+ assertEquals("three", nextName(controller));
+ } else {
+ assertNull(nextName(controller));
}
+ } catch (StackOverflowError e) {
+ fail(e.toString());
}
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/extractor/TestHtmlExtractorJSoup.java b/src/components/src/test/java/org/apache/jmeter/extractor/TestHtmlExtractorJSoup.java
index 910f7e1..2707443 100644
--- a/src/components/src/test/java/org/apache/jmeter/extractor/TestHtmlExtractorJSoup.java
+++ b/src/components/src/test/java/org/apache/jmeter/extractor/TestHtmlExtractorJSoup.java
@@ -33,19 +33,15 @@ import org.junit.Test;
public class TestHtmlExtractorJSoup {
protected HtmlExtractor extractor;
-
protected SampleResult result;
-
protected JMeterVariables vars;
-
protected JMeterContext jmctx;
@Before
public void setUp() {
jmctx = JMeterContextService.getContext();
extractor = new HtmlExtractor();
- extractor.setThreadContext(jmctx);// This would be done by the run
- // command
+ extractor.setThreadContext(jmctx);// This would be done by the run command
extractor.setRefName("regVal");
result = new SampleResult();
String data = "<p>An <a href='http://example.com/'><b>example1</b></a> link.</p>"+
diff --git a/src/components/src/test/java/org/apache/jmeter/extractor/TestJSONPostProcessor.java b/src/components/src/test/java/org/apache/jmeter/extractor/TestJSONPostProcessor.java
index 36c3f7e..a6317bf 100644
--- a/src/components/src/test/java/org/apache/jmeter/extractor/TestJSONPostProcessor.java
+++ b/src/components/src/test/java/org/apache/jmeter/extractor/TestJSONPostProcessor.java
@@ -229,8 +229,7 @@ public class TestJSONPostProcessor {
Assert.assertEquals("3", vars.get(VAR_NAME + "_matchNr"));
}
- private JSONPostProcessor setupProcessor(JMeterContext context,
- String matchNumbers) {
+ private JSONPostProcessor setupProcessor(JMeterContext context, String matchNumbers) {
return setupProcessor(context, matchNumbers, true);
}
diff --git a/src/components/src/test/java/org/apache/jmeter/extractor/TestXPath2Extractor.java b/src/components/src/test/java/org/apache/jmeter/extractor/TestXPath2Extractor.java
index a529b2e..c8cdc4e 100644
--- a/src/components/src/test/java/org/apache/jmeter/extractor/TestXPath2Extractor.java
+++ b/src/components/src/test/java/org/apache/jmeter/extractor/TestXPath2Extractor.java
@@ -44,8 +44,7 @@ public class TestXPath2Extractor {
public void setUp() throws UnsupportedEncodingException {
jmctx = JMeterContextService.getContext();
extractor = new XPath2Extractor();
- extractor.setThreadContext(jmctx);// This would be done by the run
- // command
+ extractor.setThreadContext(jmctx);// This would be done by the run command
extractor.setRefName(VAL_NAME);
extractor.setDefaultValue("Default");
result = new SampleResult();
@@ -162,10 +161,8 @@ public class TestXPath2Extractor {
extractor.setXPathQuery("/book/page[2]/text()");
extractor.process();
assertEquals("two", vars.get(VAL_NAME));
-
}
- //
@Test
public void testScope() {
extractor.setXPathQuery("/book/preface");
@@ -280,8 +277,7 @@ public class TestXPath2Extractor {
public void testPreviousResultIsEmpty() throws Exception {
JMeterContext jmc = JMeterContextService.getContext();
extractor = new XPath2Extractor();
- extractor.setThreadContext(jmctx);// This would be done by the run
- // command
+ extractor.setThreadContext(jmctx);// This would be done by the run command
extractor.setRefName(VAL_NAME);
extractor.setDefaultValue("Default");
jmc.setPreviousResult(null);
diff --git a/src/components/src/test/java/org/apache/jmeter/extractor/TestXPathExtractor.java b/src/components/src/test/java/org/apache/jmeter/extractor/TestXPathExtractor.java
index 1541369..a009e30 100644
--- a/src/components/src/test/java/org/apache/jmeter/extractor/TestXPathExtractor.java
+++ b/src/components/src/test/java/org/apache/jmeter/extractor/TestXPathExtractor.java
@@ -38,290 +38,285 @@ import org.junit.Before;
import org.junit.Test;
public class TestXPathExtractor {
- private XPathExtractor extractor;
- private SampleResult result;
-
- private String data;
-
- private JMeterVariables vars;
-
-
- private JMeterContext jmctx;
-
- private static final String VAL_NAME = "value";
- private static final String VAL_NAME_NR = "value_matchNr";
-
- @Before
- public void setUp() throws UnsupportedEncodingException {
- jmctx = JMeterContextService.getContext();
- extractor = new XPathExtractor();
- extractor.setThreadContext(jmctx);// This would be done by the run command
- extractor.setRefName(VAL_NAME);
- extractor.setDefaultValue("Default");
- result = new SampleResult();
- data = "<book><preface title='Intro'>zero</preface><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
- result.setResponseData(data.getBytes("UTF-8"));
- vars = new JMeterVariables();
- jmctx.setVariables(vars);
- jmctx.setPreviousResult(result);
- }
-
- @Test
- public void testAttributeExtraction() throws Exception {
- extractor.setXPathQuery("/book/preface/@title");
- extractor.process();
- assertEquals("Intro", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("Intro", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- extractor.setXPathQuery("/book/preface[@title]");
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- extractor.setXPathQuery("/book/preface[@title='Intro']");
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- extractor.setXPathQuery("/book/preface[@title='xyz']");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- assertNull(vars.get(VAL_NAME+"_1"));
- }
-
- @Test
- public void testVariableExtraction() throws Exception {
- extractor.setXPathQuery("/book/preface");
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- extractor.setXPathQuery("/book/page");
- extractor.process();
- assertEquals("one", vars.get(VAL_NAME));
- assertEquals("2", vars.get(VAL_NAME_NR));
- assertEquals("one", vars.get(VAL_NAME+"_1"));
- assertEquals("two", vars.get(VAL_NAME+"_2"));
- assertNull(vars.get(VAL_NAME+"_3"));
-
- // Test match 1
- extractor.setXPathQuery("/book/page");
- extractor.setMatchNumber(1);
- extractor.process();
- assertEquals("one", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("one", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
- assertNull(vars.get(VAL_NAME+"_3"));
-
- // Test match Random
- extractor.setXPathQuery("/book/page");
- extractor.setMatchNumber(0);
- extractor.process();
- assertEquals("1", vars.get(VAL_NAME_NR));
- Assert.assertTrue(StringUtils.isNoneEmpty(vars.get(VAL_NAME)));
- Assert.assertTrue(StringUtils.isNoneEmpty(vars.get(VAL_NAME+"_1")));
- assertNull(vars.get(VAL_NAME+"_2"));
- assertNull(vars.get(VAL_NAME+"_3"));
-
- // Put back default value
- extractor.setMatchNumber(-1);
-
- extractor.setXPathQuery("/book/page[2]");
- extractor.process();
- assertEquals("two", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("two", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
- assertNull(vars.get(VAL_NAME+"_3"));
-
- extractor.setXPathQuery("/book/index");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- assertNull(vars.get(VAL_NAME+"_1"));
-
- // Has child, but child is empty
- extractor.setXPathQuery("/book/a");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertNull(vars.get(VAL_NAME+"_1"));
-
- // Has no child
- extractor.setXPathQuery("/book/empty");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertNull(vars.get(VAL_NAME+"_1"));
-
- // No text
- extractor.setXPathQuery("//a");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
-
- // No text all matches
- extractor.setXPathQuery("//a");
- extractor.process();
- extractor.setMatchNumber(-1);
- assertEquals("Default", vars.get(VAL_NAME));
-
- // No text match second
- extractor.setXPathQuery("//a");
- extractor.process();
- extractor.setMatchNumber(2);
- assertEquals("Default", vars.get(VAL_NAME));
-
- // No text match random
- extractor.setXPathQuery("//a");
- extractor.process();
- extractor.setMatchNumber(0);
- assertEquals("Default", vars.get(VAL_NAME));
-
- extractor.setMatchNumber(-1);
- // Test fragment
- extractor.setXPathQuery("/book/page[2]");
- extractor.setFragment(true);
- extractor.process();
- assertEquals("<page>two</page>", vars.get(VAL_NAME));
- // Now get its text
- extractor.setXPathQuery("/book/page[2]/text()");
- extractor.process();
- assertEquals("two", vars.get(VAL_NAME));
-
- // No text, but using fragment mode
- extractor.setXPathQuery("//a");
- extractor.process();
- assertEquals("<a><b/></a>", vars.get(VAL_NAME));
- }
-
- @Test
- public void testScope(){
- extractor.setXPathQuery("/book/preface");
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- extractor.setScopeChildren(); // There aren't any
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- assertNull(vars.get(VAL_NAME+"_1"));
-
- extractor.setScopeAll(); // same as Parent
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- // Try to get data from subresult
- result.sampleStart(); // Needed for addSubResult()
- result.sampleEnd();
- SampleResult subResult = new SampleResult();
- subResult.sampleStart();
- subResult.setResponseData(result.getResponseData());
- subResult.sampleEnd();
- result.addSubResult(subResult);
-
-
- // Get data from both
- extractor.setScopeAll();
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("2", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertEquals("zero", vars.get(VAL_NAME+"_2"));
- assertNull(vars.get(VAL_NAME+"_3"));
-
- // get data from child
- extractor.setScopeChildren();
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
-
- // get data from child
- extractor.setScopeVariable("result");
- result = new SampleResult();
- vars.put("result", data);
- extractor.process();
- assertEquals("zero", vars.get(VAL_NAME));
- assertEquals("1", vars.get(VAL_NAME_NR));
- assertEquals("zero", vars.get(VAL_NAME+"_1"));
- assertNull(vars.get(VAL_NAME+"_2"));
-
- // get data from child
- extractor.setScopeVariable("result");
- result = new SampleResult();
- vars.remove("result");
- extractor.process();
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- }
-
- @Test
- public void testInvalidXpath() throws Exception {
- // The test fails in other locales for some reason
- extractor.setXPathQuery("<");
- extractor.process();
- assertEquals(1, result.getAssertionResults().length);
- AssertionResult firstResult = result.getAssertionResults()[0];
- assertEquals(extractor.getName(), firstResult.getName());
+ private XPathExtractor extractor;
+ private SampleResult result;
+ private String data;
+ private JMeterVariables vars;
+ private JMeterContext jmctx;
+ private static final String VAL_NAME = "value";
+ private static final String VAL_NAME_NR = "value_matchNr";
+
+ @Before
+ public void setUp() throws UnsupportedEncodingException {
+ jmctx = JMeterContextService.getContext();
+ extractor = new XPathExtractor();
+ extractor.setThreadContext(jmctx);// This would be done by the run command
+ extractor.setRefName(VAL_NAME);
+ extractor.setDefaultValue("Default");
+ result = new SampleResult();
+ data = "<book><preface title='Intro'>zero</preface><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
+ result.setResponseData(data.getBytes("UTF-8"));
+ vars = new JMeterVariables();
+ jmctx.setVariables(vars);
+ jmctx.setPreviousResult(result);
+ }
+
+ @Test
+ public void testAttributeExtraction() throws Exception {
+ extractor.setXPathQuery("/book/preface/@title");
+ extractor.process();
+ assertEquals("Intro", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("Intro", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ extractor.setXPathQuery("/book/preface[@title]");
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ extractor.setXPathQuery("/book/preface[@title='Intro']");
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ extractor.setXPathQuery("/book/preface[@title='xyz']");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ assertNull(vars.get(VAL_NAME + "_1"));
+ }
+
+ @Test
+ public void testVariableExtraction() throws Exception {
+ extractor.setXPathQuery("/book/preface");
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ extractor.setXPathQuery("/book/page");
+ extractor.process();
+ assertEquals("one", vars.get(VAL_NAME));
+ assertEquals("2", vars.get(VAL_NAME_NR));
+ assertEquals("one", vars.get(VAL_NAME + "_1"));
+ assertEquals("two", vars.get(VAL_NAME + "_2"));
+ assertNull(vars.get(VAL_NAME + "_3"));
+
+ // Test match 1
+ extractor.setXPathQuery("/book/page");
+ extractor.setMatchNumber(1);
+ extractor.process();
+ assertEquals("one", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("one", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+ assertNull(vars.get(VAL_NAME + "_3"));
+
+ // Test match Random
+ extractor.setXPathQuery("/book/page");
+ extractor.setMatchNumber(0);
+ extractor.process();
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ Assert.assertTrue(StringUtils.isNoneEmpty(vars.get(VAL_NAME)));
+ Assert.assertTrue(StringUtils.isNoneEmpty(vars.get(VAL_NAME + "_1")));
+ assertNull(vars.get(VAL_NAME + "_2"));
+ assertNull(vars.get(VAL_NAME + "_3"));
+
+ // Put back default value
+ extractor.setMatchNumber(-1);
+
+ extractor.setXPathQuery("/book/page[2]");
+ extractor.process();
+ assertEquals("two", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("two", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+ assertNull(vars.get(VAL_NAME + "_3"));
+
+ extractor.setXPathQuery("/book/index");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ assertNull(vars.get(VAL_NAME + "_1"));
+
+ // Has child, but child is empty
+ extractor.setXPathQuery("/book/a");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertNull(vars.get(VAL_NAME + "_1"));
+
+ // Has no child
+ extractor.setXPathQuery("/book/empty");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertNull(vars.get(VAL_NAME + "_1"));
+
+ // No text
+ extractor.setXPathQuery("//a");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+
+ // No text all matches
+ extractor.setXPathQuery("//a");
+ extractor.process();
+ extractor.setMatchNumber(-1);
+ assertEquals("Default", vars.get(VAL_NAME));
+
+ // No text match second
+ extractor.setXPathQuery("//a");
+ extractor.process();
+ extractor.setMatchNumber(2);
+ assertEquals("Default", vars.get(VAL_NAME));
+
+ // No text match random
+ extractor.setXPathQuery("//a");
+ extractor.process();
+ extractor.setMatchNumber(0);
+ assertEquals("Default", vars.get(VAL_NAME));
+
+ extractor.setMatchNumber(-1);
+ // Test fragment
+ extractor.setXPathQuery("/book/page[2]");
+ extractor.setFragment(true);
+ extractor.process();
+ assertEquals("<page>two</page>", vars.get(VAL_NAME));
+ // Now get its text
+ extractor.setXPathQuery("/book/page[2]/text()");
+ extractor.process();
+ assertEquals("two", vars.get(VAL_NAME));
+
+ // No text, but using fragment mode
+ extractor.setXPathQuery("//a");
+ extractor.process();
+ assertEquals("<a><b/></a>", vars.get(VAL_NAME));
+ }
+
+ @Test
+ public void testScope() {
+ extractor.setXPathQuery("/book/preface");
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ extractor.setScopeChildren(); // There aren't any
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ assertNull(vars.get(VAL_NAME + "_1"));
+
+ extractor.setScopeAll(); // same as Parent
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ // Try to get data from subresult
+ result.sampleStart(); // Needed for addSubResult()
+ result.sampleEnd();
+ SampleResult subResult = new SampleResult();
+ subResult.sampleStart();
+ subResult.setResponseData(result.getResponseData());
+ subResult.sampleEnd();
+ result.addSubResult(subResult);
+
+
+ // Get data from both
+ extractor.setScopeAll();
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("2", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertEquals("zero", vars.get(VAL_NAME + "_2"));
+ assertNull(vars.get(VAL_NAME + "_3"));
+
+ // get data from child
+ extractor.setScopeChildren();
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+
+ // get data from child
+ extractor.setScopeVariable("result");
+ result = new SampleResult();
+ vars.put("result", data);
+ extractor.process();
+ assertEquals("zero", vars.get(VAL_NAME));
+ assertEquals("1", vars.get(VAL_NAME_NR));
+ assertEquals("zero", vars.get(VAL_NAME + "_1"));
+ assertNull(vars.get(VAL_NAME + "_2"));
+
+ // get data from child
+ extractor.setScopeVariable("result");
+ result = new SampleResult();
+ vars.remove("result");
+ extractor.process();
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ }
+
+ @Test
+ public void testInvalidXpath() throws Exception {
+ // The test fails in other locales for some reason
+ extractor.setXPathQuery("<");
+ extractor.process();
+ assertEquals(1, result.getAssertionResults().length);
+ AssertionResult firstResult = result.getAssertionResults()[0];
+ assertEquals(extractor.getName(), firstResult.getName());
+ assertThat(
+ "'<' is an invalid character in xpath, so it is expected to be present in the error message",
+ firstResult.getFailureMessage(),
+ containsString("<")
+ );
+ if (Locale.getDefault().getLanguage().startsWith(Locale.ENGLISH.getLanguage())) {
assertThat(
- "'<' is an invalid character in xpath, so it is expected to be present in the error message",
firstResult.getFailureMessage(),
- containsString("<")
+ containsString("A location path was expected, but the following token was encountered")
);
- if (Locale.getDefault().getLanguage().startsWith(Locale.ENGLISH.getLanguage())) {
- assertThat(
- firstResult.getFailureMessage(),
- containsString("A location path was expected, but the following token was encountered")
- );
- }
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- }
-
- @Test
- public void testNonXmlDocument() throws Exception {
- result.setResponseData("Error:exception occurred", null);
- extractor.setXPathQuery("//test");
- extractor.process();
- assertEquals(1, result.getAssertionResults().length);
- assertEquals(extractor.getName(), result.getAssertionResults()[0].getName());
- assertThat(result.getAssertionResults()[0].getFailureMessage(),
- containsString("Content is not allowed in prolog"));
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
- }
-
- @Test
- public void testInvalidDocument() throws Exception {
- result.setResponseData("<z>", null);
- extractor.setXPathQuery("//test");
- extractor.process();
-
- assertEquals(1, result.getAssertionResults().length);
- assertEquals(extractor.getName(), result.getAssertionResults()[0].getName());
- assertThat(result.getAssertionResults()[0].getFailureMessage(),
- containsString("XML document structures must start and end within the same entity"));
-
- assertEquals("Default", vars.get(VAL_NAME));
- assertEquals("0", vars.get(VAL_NAME_NR));
}
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ }
+
+ @Test
+ public void testNonXmlDocument() throws Exception {
+ result.setResponseData("Error:exception occurred", null);
+ extractor.setXPathQuery("//test");
+ extractor.process();
+ assertEquals(1, result.getAssertionResults().length);
+ assertEquals(extractor.getName(), result.getAssertionResults()[0].getName());
+ assertThat(result.getAssertionResults()[0].getFailureMessage(),
+ containsString("Content is not allowed in prolog"));
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ }
+
+ @Test
+ public void testInvalidDocument() throws Exception {
+ result.setResponseData("<z>", null);
+ extractor.setXPathQuery("//test");
+ extractor.process();
+
+ assertEquals(1, result.getAssertionResults().length);
+ assertEquals(extractor.getName(), result.getAssertionResults()[0].getName());
+ assertThat(result.getAssertionResults()[0].getFailureMessage(),
+ containsString("XML document structures must start and end within the same entity"));
+
+ assertEquals("Default", vars.get(VAL_NAME));
+ assertEquals("0", vars.get(VAL_NAME_NR));
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/gui/action/TestSave.java b/src/components/src/test/java/org/apache/jmeter/gui/action/TestSave.java
index acf759f..bceca77 100644
--- a/src/components/src/test/java/org/apache/jmeter/gui/action/TestSave.java
+++ b/src/components/src/test/java/org/apache/jmeter/gui/action/TestSave.java
@@ -28,25 +28,24 @@ import org.junit.Before;
import org.junit.Test;
public class TestSave {
- private Save save;
+ private Save save;
+ @Before
+ public void setUp() {
+ save = new Save();
+ }
- @Before
- public void setUp() {
- save = new Save();
- }
-
- @Test
- public void testTreeConversion() throws Exception {
- HashTree tree = new ListedHashTree();
- JMeterTreeNode root = new JMeterTreeNode(new Arguments(), null);
- tree.add(root, root);
- tree.getTree(root).add(root, root);
- save.convertSubTree(tree);
- assertEquals(tree.getArray()[0].getClass().getName(), root.getTestElement().getClass().getName());
- tree = tree.getTree(tree.getArray()[0]);
- assertEquals(tree.getArray()[0].getClass().getName(), root.getTestElement().getClass().getName());
- assertEquals(tree.getTree(tree.getArray()[0]).getArray()[0].getClass().getName(), root.getTestElement()
- .getClass().getName());
- }
+ @Test
+ public void testTreeConversion() throws Exception {
+ HashTree tree = new ListedHashTree();
+ JMeterTreeNode root = new JMeterTreeNode(new Arguments(), null);
+ tree.add(root, root);
+ tree.getTree(root).add(root, root);
+ save.convertSubTree(tree);
+ assertEquals(tree.getArray()[0].getClass().getName(), root.getTestElement().getClass().getName());
+ tree = tree.getTree(tree.getArray()[0]);
+ assertEquals(tree.getArray()[0].getClass().getName(), root.getTestElement().getClass().getName());
+ assertEquals(tree.getTree(tree.getArray()[0]).getArray()[0].getClass().getName(), root.getTestElement()
+ .getClass().getName());
+ }
}
diff --git a/src/components/src/test/java/org/apache/jmeter/reporters/TestResultSaver.java b/src/components/src/test/java/org/apache/jmeter/reporters/TestResultSaver.java
index df64239..8026067 100644
--- a/src/components/src/test/java/org/apache/jmeter/reporters/TestResultSaver.java
+++ b/src/components/src/test/java/org/apache/jmeter/reporters/TestResultSaver.java
@@ -32,9 +32,6 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-/**
- * Test for {@link ResultSaver}
- */
public class TestResultSaver extends JMeterTestCase implements JMeterSerialTest {
private ResultSaver resultSaver;
private SampleResult sampleResult;
@@ -134,6 +131,5 @@ public class TestResultSaver extends JMeterTestCase implements JMeterSerialTest
resultSaver.testStarted();
Assert.assertEquals("test.unknown", resultSaver.makeFileName(null, true, false));
-
}
}
diff --git a/src/components/src/test/java/org/apache/jmeter/timers/poissonarrivals/PreciseThroughputTimerTest.java b/src/components/src/test/java/org/apache/jmeter/timers/poissonarrivals/PreciseThroughputTimerTest.java
index 73bd696..4e8be3d 100644
--- a/src/components/src/test/java/org/apache/jmeter/timers/poissonarrivals/PreciseThroughputTimerTest.java
+++ b/src/components/src/test/java/org/apache/jmeter/timers/poissonarrivals/PreciseThroughputTimerTest.java
@@ -56,7 +56,8 @@ public class PreciseThroughputTimerTest {
int testDuration = 5;
for (int i = 0; i < 1000; i++) {
- ConstantPoissonProcessGenerator gen = getConstantPoissonProcessGenerator(2, testDuration, rnd.nextLong());
+ ConstantPoissonProcessGenerator gen =
+ getConstantPoissonProcessGenerator(2, testDuration, rnd.nextLong());
gen.generateNext();
for (int j = 0; j < 10; j++) {
double next = gen.next();
diff --git a/src/components/src/test/java/org/apache/jmeter/visualizers/backend/SamplerMetricFixedModeTest.java b/src/components/src/test/java/org/apache/jmeter/visualizers/backend/SamplerMetricFixedModeTest.java
index 3243f50..429270f 100644
--- a/src/components/src/test/java/org/apache/jmeter/visualizers/backend/SamplerMetricFixedModeTest.java
+++ b/src/components/src/test/java/org/apache/jmeter/visualizers/backend/SamplerMetricFixedModeTest.java
@@ -36,7 +36,6 @@ public class SamplerMetricFixedModeTest {
@Test
public void checkResetOkAndAllStats() throws Exception {
-
SamplerMetric metric = new SamplerMetric();
metric.add(createSampleResult(true));
assertEquals("Before reset ok.max", DEFAULT_ELAPSED_TIME, metric.getOkMaxTime(), 0.001);
@@ -45,8 +44,7 @@ public class SamplerMetricFixedModeTest {
assertEquals("Before reset sent bytes", 1000, metric.getSentBytes(), 0.0);
assertEquals("Before reset received bytes", 2000, metric.getReceivedBytes(), 0.0);
- // In fixed mode DescriptiveStatistics are not reset, just sliding on a
- // window
+ // In fixed mode DescriptiveStatistics are not reset, just sliding on a window
metric.resetForTimeInterval();
assertEquals("After reset in FIXED mode ok.max", DEFAULT_ELAPSED_TIME, metric.getOkMaxTime(), 0.001);
@@ -58,7 +56,6 @@ public class SamplerMetricFixedModeTest {
@Test
public void checkResetKoAndAllStats() throws Exception {
-
SamplerMetric metric = new SamplerMetric();
metric.add(createSampleResult(false));
assertEquals("Before reset ko.max", DEFAULT_ELAPSED_TIME, metric.getKoMaxTime(), 0.001);
@@ -67,8 +64,7 @@ public class SamplerMetricFixedModeTest {
assertEquals("Before reset sent bytes", 1000, metric.getSentBytes(), 0.0);
assertEquals("Before reset received bytes", 2000, metric.getReceivedBytes(), 0.0);
- // In fixed mode DescriptiveStatistics are not reset, just sliding on a
- // window
+ // In fixed mode DescriptiveStatistics are not reset, just sliding on a window
metric.resetForTimeInterval();
assertEquals("After reset in FIXED mode ko.max", DEFAULT_ELAPSED_TIME, metric.getKoMaxTime(), 0.0);
@@ -80,7 +76,6 @@ public class SamplerMetricFixedModeTest {
@Test
public void checkErrorsDetailStat() {
-
SamplerMetric metric = new SamplerMetric();
metric.add(createSampleResult("400", "bad request"));
metric.add(createSampleResult("400", "Bad Request "));
diff --git a/src/core/src/main/java/org/apache/jmeter/report/core/CsvSampleWriter.java b/src/core/src/main/java/org/apache/jmeter/report/core/CsvSampleWriter.java
index 59032bc..93e884c 100644
--- a/src/core/src/main/java/org/apache/jmeter/report/core/CsvSampleWriter.java
+++ b/src/core/src/main/java/org/apache/jmeter/report/core/CsvSampleWriter.java
@@ -51,13 +51,10 @@ public class CsvSampleWriter extends AbstractSampleWriter {
private long sampleCount;
/**
- * Constructor for a CsvSampleWriter.<br>
- * The newly created instance has to be supplied with a Writer to work
- * properly.
+ * The new instance has to be supplied with a Writer to work properly.
*
- * @param metadata
- * the description for data that this writer will write. (
- * {@code metadata} must not be {@code null}.)
+ * @param metadata the description for data that this writer will write
+ * ({@code metadata} must not be {@code null}).
*/
public CsvSampleWriter(SampleMetadata metadata) {
super();
@@ -68,13 +65,9 @@ public class CsvSampleWriter extends AbstractSampleWriter {
}
/**
- * Constructor for a CsvSampleWriter.
- *
- * @param output
- * the writer to write data to. (Must not be {@code null})
- * @param metadata
- * the description for data that this writer will write. (
- * {@code metadata} must not be {@code null}.)
+ * @param output the writer to write data to. (Must not be {@code null})
+ * @param metadata the description for data that this writer will write. (
+ * {@code metadata} must not be {@code null}.)
*/
public CsvSampleWriter(Writer output, SampleMetadata metadata) {
this(metadata);
@@ -82,13 +75,9 @@ public class CsvSampleWriter extends AbstractSampleWriter {
}
/**
- * Constructor for a CsvSampleWriter.
- *
- * @param output
- * the output stream to write data to. (Must not be {@code null})
- * @param metadata
- * the description for data that this writer will write. (
- * {@code metadata} must not be {@code null}.)
+ * @param output the output stream to write data to. (Must not be {@code null})
+ * @param metadata the description for data that this writer will write. (
+ * {@code metadata} must not be {@code null}.)
*/
public CsvSampleWriter(OutputStream output, SampleMetadata metadata) {
this(metadata);
@@ -96,13 +85,9 @@ public class CsvSampleWriter extends AbstractSampleWriter {
}
/**
- * Constructor for a CsvSampleWriter.
- *
- * @param output
- * the output file to write data to. (Must not be {@code null})
- * @param metadata
- * the description for data that this writer will write. (
- * {@code metadata} must not be {@code null}.)
+ * @param output the output file to write data to. (Must not be {@code null})
+ * @param metadata the description for data that this writer will write. (
+ * {@code metadata} must not be {@code null}.)
*/
public CsvSampleWriter(File output, SampleMetadata metadata) {
this(metadata);
@@ -112,8 +97,7 @@ public class CsvSampleWriter extends AbstractSampleWriter {
/**
* Set the char to use for separation of data in a line.
*
- * @param separator
- * to use
+ * @param separator to use
*/
public void setSeparator(char separator) {
this.separator = separator;
diff --git a/src/core/src/test/java/org/apache/jmeter/JMeterTest.java b/src/core/src/test/java/org/apache/jmeter/JMeterTest.java
index 31874af..51c729d 100644
--- a/src/core/src/test/java/org/apache/jmeter/JMeterTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/JMeterTest.java
@@ -32,6 +32,7 @@ import org.apache.jorphan.test.JMeterSerialTest;
import org.junit.Test;
public class JMeterTest extends JMeterTestCase implements JMeterSerialTest {
+
@Test
public void testFailureWhenJmxDoesntExist() {
JMeter jmeter = new JMeter();
@@ -39,8 +40,6 @@ public class JMeterTest extends JMeterTestCase implements JMeterSerialTest {
jmeter.runNonGui("testPlan.jmx", null, false, null, false);
fail("Expected ConfigurationException to be thrown");
} catch (ConfigurationException e) {
- assertTrue("When the plugin doesn't exist, the method 'runNonGui' should throw a ConfigurationException",
- e instanceof ConfigurationException);
assertTrue("When the file doesn't exist, this method 'runNonGui' should have a detailed message",
e.getMessage().contains("doesn't exist or can't be opened"));
}
@@ -113,8 +112,6 @@ public class JMeterTest extends JMeterTestCase implements JMeterSerialTest {
jmeter.runNonGui(temp.getAbsolutePath(), null, false, null, false);
fail("Expected ConfigurationException to be thrown");
} catch (ConfigurationException e) {
- assertTrue("When the plugin doesn't exist, the method 'runNonGui' should throw a ConfigurationException",
- e instanceof ConfigurationException);
assertTrue("When the plugin doesn't exist, the method 'runNonGui' should have a detailed message",
e.getMessage().contains("Error in NonGUIDriver Problem loading XML from"));
} finally {
diff --git a/src/core/src/test/java/org/apache/jmeter/engine/LocalHostTest.java b/src/core/src/test/java/org/apache/jmeter/engine/LocalHostTest.java
index 04d3bc0..b55a1a3 100644
--- a/src/core/src/test/java/org/apache/jmeter/engine/LocalHostTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/engine/LocalHostTest.java
@@ -99,7 +99,7 @@ public class LocalHostTest {
String host = System.getProperties().getProperty(key); // $NON-NLS-1$
perr(key + "=" + host);
InetAddress localHost;
- if( host==null ) {
+ if (host == null) {
localHost = InetAddress.getLocalHost();
} else {
localHost = InetAddress.getByName(host);
@@ -109,11 +109,11 @@ public class LocalHostTest {
private static void showAddress(InetAddress localHost) {
perr(localHost);
- perr("isSiteLocalAddress:"+localHost.isSiteLocalAddress());
- perr("isAnyLocalAddress:"+localHost.isAnyLocalAddress());
- perr("isLinkLocalAddress:"+localHost.isLinkLocalAddress());
- perr("isLoopbackAddress:"+localHost.isLoopbackAddress());
- perr("isMulticastAddress:"+localHost.isMulticastAddress());
+ perr("isSiteLocalAddress:" + localHost.isSiteLocalAddress());
+ perr("isAnyLocalAddress:" + localHost.isAnyLocalAddress());
+ perr("isLinkLocalAddress:" + localHost.isLinkLocalAddress());
+ perr("isLoopbackAddress:" + localHost.isLoopbackAddress());
+ perr("isMulticastAddress:" + localHost.isMulticastAddress());
}
private static void perr(Object s) {
diff --git a/src/core/src/test/java/org/apache/jmeter/engine/TestTreeCloner.java b/src/core/src/test/java/org/apache/jmeter/engine/TestTreeCloner.java
index 0dc0367..6515546 100644
--- a/src/core/src/test/java/org/apache/jmeter/engine/TestTreeCloner.java
+++ b/src/core/src/test/java/org/apache/jmeter/engine/TestTreeCloner.java
@@ -36,50 +36,50 @@ import org.junit.Test;
public class TestTreeCloner extends JMeterTestCase {
- @Test
- public void testCloning() throws Exception {
- ListedHashTree original = new ListedHashTree();
- GenericController controller = new GenericController();
- controller.setName("controller");
- Arguments args = new Arguments();
- args.setName("args");
- TestPlan plan = new TestPlan();
- plan.addParameter("server", "jakarta");
- original.add(controller, args);
- original.add(plan);
- ResultCollector listener = new ResultCollector();
- listener.setName("Collector");
- original.add(controller, listener);
- TreeCloner cloner = new TreeCloner();
- original.traverse(cloner);
- ListedHashTree newTree = cloner.getClonedTree();
- assertTrue(original != newTree);
- assertEquals(original.size(), newTree.size());
- assertEquals(original.getTree(original.getArray()[0]).size(), newTree.getTree(newTree.getArray()[0]).size());
- assertTrue(original.getArray()[0] != newTree.getArray()[0]);
- assertEquals(((GenericController) original.getArray()[0]).getName(), ((GenericController) newTree
- .getArray()[0]).getName());
- assertSame(original.getTree(original.getArray()[0]).getArray()[1], newTree.getTree(newTree.getArray()[0])
- .getArray()[1]);
- TestPlan clonedTestPlan = (TestPlan) newTree.getArray()[1];
- clonedTestPlan.setRunningVersion(true);
- clonedTestPlan.recoverRunningVersion();
- assertTrue(!plan.getUserDefinedVariablesAsProperty().isRunningVersion());
- assertTrue(clonedTestPlan.getUserDefinedVariablesAsProperty().isRunningVersion());
- Arguments vars = (Arguments) plan.getUserDefinedVariablesAsProperty().getObjectValue();
- PropertyIterator iter = ((CollectionProperty) vars.getProperty(Arguments.ARGUMENTS)).iterator();
- while (iter.hasNext()) {
- JMeterProperty argProp = iter.next();
- assertTrue(!argProp.isRunningVersion());
- assertTrue(argProp.getObjectValue() instanceof Argument);
- Argument arg = (Argument) argProp.getObjectValue();
- arg.setValue("yahoo");
- assertEquals("yahoo", arg.getValue());
- }
- vars = (Arguments) clonedTestPlan.getUserDefinedVariablesAsProperty().getObjectValue();
- iter = vars.propertyIterator();
- while (iter.hasNext()) {
- assertTrue(iter.next().isRunningVersion());
- }
+ @Test
+ public void testCloning() throws Exception {
+ ListedHashTree original = new ListedHashTree();
+ GenericController controller = new GenericController();
+ controller.setName("controller");
+ Arguments args = new Arguments();
+ args.setName("args");
+ TestPlan plan = new TestPlan();
+ plan.addParameter("server", "jakarta");
+ original.add(controller, args);
+ original.add(plan);
+ ResultCollector listener = new ResultCollector();
+ listener.setName("Collector");
+ original.add(controller, listener);
+ TreeCloner cloner = new TreeCloner();
+ original.traverse(cloner);
+ ListedHashTree newTree = cloner.getClonedTree();
+ assertTrue(original != newTree);
+ assertEquals(original.size(), newTree.size());
+ assertEquals(original.getTree(original.getArray()[0]).size(), newTree.getTree(newTree.getArray()[0]).size());
+ assertTrue(original.getArray()[0] != newTree.getArray()[0]);
+ assertEquals(((GenericController) original.getArray()[0]).getName(), ((GenericController) newTree
+ .getArray()[0]).getName());
+ assertSame(original.getTree(original.getArray()[0]).getArray()[1], newTree.getTree(newTree.getArray()[0])
+ .getArray()[1]);
+ TestPlan clonedTestPlan = (TestPlan) newTree.getArray()[1];
+ clonedTestPlan.setRunningVersion(true);
+ clonedTestPlan.recoverRunningVersion();
+ assertTrue(!plan.getUserDefinedVariablesAsProperty().isRunningVersion());
+ assertTrue(clonedTestPlan.getUserDefinedVariablesAsProperty().isRunningVersion());
+ Arguments vars = (Arguments) plan.getUserDefinedVariablesAsProperty().getObjectValue();
+ PropertyIterator iter = ((CollectionProperty) vars.getProperty(Arguments.ARGUMENTS)).iterator();
+ while (iter.hasNext()) {
+ JMeterProperty argProp = iter.next();
+ assertTrue(!argProp.isRunningVersion());
+ assertTrue(argProp.getObjectValue() instanceof Argument);
+ Argument arg = (Argument) argProp.getObjectValue();
+ arg.setValue("yahoo");
+ assertEquals("yahoo", arg.getValue());
}
+ vars = (Arguments) clonedTestPlan.getUserDefinedVariablesAsProperty().getObjectValue();
+ iter = vars.propertyIterator();
+ while (iter.hasNext()) {
+ assertTrue(iter.next().isRunningVersion());
+ }
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/engine/util/TestValueReplacer.java b/src/core/src/test/java/org/apache/jmeter/engine/util/TestValueReplacer.java
index 8e6cefe..16cd90f 100644
--- a/src/core/src/test/java/org/apache/jmeter/engine/util/TestValueReplacer.java
+++ b/src/core/src/test/java/org/apache/jmeter/engine/util/TestValueReplacer.java
@@ -38,150 +38,150 @@ import org.junit.Before;
import org.junit.Test;
public class TestValueReplacer extends JMeterTestCase {
- private TestPlan variables;
-
- @Before
- public void setUp() {
- variables = new TestPlan();
- variables.addParameter("server", "jakarta.apache.org");
- variables.addParameter("username", "jack");
- // The following used to be jacks_password, but the Arguments class uses
- // HashMap for which the order is not defined.
- variables.addParameter("password", "his_password");
- variables.addParameter("normal_regex", "Hello .*");
- variables.addParameter("bounded_regex", "(<.*>)");
- JMeterVariables vars = new JMeterVariables();
- vars.put("server", "jakarta.apache.org");
- JMeterContextService.getContext().setVariables(vars);
- JMeterContextService.getContext().setSamplingStarted(true);
- }
-
- @Test
- public void testReverseReplacement() throws Exception {
- ValueReplacer replacer = new ValueReplacer(variables);
- assertTrue(variables.getUserDefinedVariables().containsKey("server"));
- assertTrue(replacer.containsKey("server"));
- TestElement element = new TestPlan();
- element.setProperty(new StringProperty("domain", "jakarta.apache.org"));
- List<Object> argsin = new ArrayList<>();
- argsin.add("username is jack");
- argsin.add("his_password");
- element.setProperty(new CollectionProperty("args", argsin));
- replacer.reverseReplace(element);
- assertEquals("${server}", element.getPropertyAsString("domain"));
- @SuppressWarnings("unchecked")
- List<JMeterProperty> args = (List<JMeterProperty>) element.getProperty("args").getObjectValue();
- assertEquals("username is ${username}", args.get(0).getStringValue());
- assertEquals("${password}", args.get(1).getStringValue());
- }
-
- @Test
- public void testReverseReplacementXml() throws Exception {
- ValueReplacer replacer = new ValueReplacer(variables);
- assertTrue(variables.getUserDefinedVariables().containsKey("bounded_regex"));
- assertTrue(variables.getUserDefinedVariables().containsKey("normal_regex"));
- assertTrue(replacer.containsKey("bounded_regex"));
- assertTrue(replacer.containsKey("normal_regex"));
- TestElement element = new TestPlan();
- element.setProperty(new StringProperty("domain", "<this><is>xml</this></is>"));
- List<Object> argsin = new ArrayList<>();
- argsin.add("<this><is>xml</this></is>");
- argsin.add("And I say: Hello World.");
- element.setProperty(new CollectionProperty("args", argsin));
- replacer.reverseReplace(element, true);
- @SuppressWarnings("unchecked")
- List<JMeterProperty> args = (List<JMeterProperty>) element.getProperty("args").getObjectValue();
- assertEquals("${bounded_regex}", element.getPropertyAsString("domain"));
- assertEquals("${bounded_regex}", args.get(0).getStringValue());
- }
-
- @Test
- public void testOverlappingMatches() throws Exception {
- TestPlan plan = new TestPlan();
- plan.addParameter("longMatch", "servername");
- plan.addParameter("shortMatch", ".*");
- ValueReplacer replacer = new ValueReplacer(plan);
- TestElement element = new TestPlan();
- element.setProperty(new StringProperty("domain", "servername.domain"));
- replacer.reverseReplace(element, true);
- String replacedDomain = element.getPropertyAsString("domain");
- assertEquals("${${shortMatch}", replacedDomain);
- }
-
- @Test
- public void testPartialWordMatchesWithoutParens() throws Exception {
- assertEquals("toto%40005", replaceWord("005", "toto%40005"));
- }
-
- @Test
- public void testPartialWordMatchesWithParens() throws Exception {
- assertEquals("toto%40${domainMatcher}", replaceWord("(005)", "toto%40005"));
- }
-
- @Test
- public void testCompleteWordMatchesWithoutParens() throws Exception {
- assertEquals("toto@${domainMatcher}", replaceWord("005", "toto@005"));
- }
-
- @Test
- public void testCompleteWordMatchesWithParens() throws Exception {
- assertEquals("toto@${domainMatcher}", replaceWord("(005)", "toto@005"));
- }
-
- private String replaceWord(String matchRegex, String testData) throws Exception {
- TestPlan plan = new TestPlan();
- plan.addParameter("domainMatcher", matchRegex);
- ValueReplacer replacer = new ValueReplacer(plan);
- TestElement element = new TestPlan();
- element.setProperty(new StringProperty("mail", testData));
- replacer.reverseReplace(element, true);
- return element.getPropertyAsString("mail");
- }
-
- @Test
- public void testReplace() throws Exception {
- ValueReplacer replacer = new ValueReplacer();
- replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
- TestElement element = new ConfigTestElement();
- element.setProperty(new StringProperty("domain", "${server}"));
- replacer.replaceValues(element);
- element.setRunningVersion(true);
- assertEquals("jakarta.apache.org", element.getPropertyAsString("domain"));
- }
-
- @Test
- public void testReplaceStringWithBackslash() throws Exception {
- ValueReplacer replacer = new ValueReplacer();
- replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
- TestElement element = new ConfigTestElement();
- String input = "\\${server} \\ \\\\ \\\\\\ \\, ";
- element.setProperty(new StringProperty("domain", input));
- replacer.replaceValues(element);
- element.setRunningVersion(true);
- assertEquals(input, element.getPropertyAsString("domain"));
- }
-
- /*
- * This test should be compared with the one above.
- * Here, the string contains a valid variable reference, so all
- * backslashes are also processed.
- *
- * See https://bz.apache.org/bugzilla/show_bug.cgi?id=53534
- */
- @Test
- public void testReplaceFunctionWithBackslash() throws Exception {
- ValueReplacer replacer = new ValueReplacer();
- replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
- TestElement element = new ConfigTestElement();
- String input = "${server} \\ \\\\ \\\\\\ \\, ";
- element.setProperty(new StringProperty("domain", input));
- replacer.replaceValues(element);
- element.setRunningVersion(true);
- assertEquals("jakarta.apache.org \\ \\ \\\\ , ", element.getPropertyAsString("domain"));
- }
-
- @After
- public void tearDown() throws Exception {
- JMeterContextService.getContext().setSamplingStarted(false);
- }
+ private TestPlan variables;
+
+ @Before
+ public void setUp() {
+ variables = new TestPlan();
+ variables.addParameter("server", "jakarta.apache.org");
+ variables.addParameter("username", "jack");
+ // The following used to be jacks_password, but the Arguments class uses
+ // HashMap for which the order is not defined.
+ variables.addParameter("password", "his_password");
+ variables.addParameter("normal_regex", "Hello .*");
+ variables.addParameter("bounded_regex", "(<.*>)");
+ JMeterVariables vars = new JMeterVariables();
+ vars.put("server", "jakarta.apache.org");
+ JMeterContextService.getContext().setVariables(vars);
+ JMeterContextService.getContext().setSamplingStarted(true);
+ }
+
+ @Test
+ public void testReverseReplacement() throws Exception {
+ ValueReplacer replacer = new ValueReplacer(variables);
+ assertTrue(variables.getUserDefinedVariables().containsKey("server"));
+ assertTrue(replacer.containsKey("server"));
+ TestElement element = new TestPlan();
+ element.setProperty(new StringProperty("domain", "jakarta.apache.org"));
+ List<Object> argsin = new ArrayList<>();
+ argsin.add("username is jack");
+ argsin.add("his_password");
+ element.setProperty(new CollectionProperty("args", argsin));
+ replacer.reverseReplace(element);
+ assertEquals("${server}", element.getPropertyAsString("domain"));
+ @SuppressWarnings("unchecked")
+ List<JMeterProperty> args = (List<JMeterProperty>) element.getProperty("args").getObjectValue();
+ assertEquals("username is ${username}", args.get(0).getStringValue());
+ assertEquals("${password}", args.get(1).getStringValue());
+ }
+
+ @Test
+ public void testReverseReplacementXml() throws Exception {
+ ValueReplacer replacer = new ValueReplacer(variables);
+ assertTrue(variables.getUserDefinedVariables().containsKey("bounded_regex"));
+ assertTrue(variables.getUserDefinedVariables().containsKey("normal_regex"));
+ assertTrue(replacer.containsKey("bounded_regex"));
+ assertTrue(replacer.containsKey("normal_regex"));
+ TestElement element = new TestPlan();
+ element.setProperty(new StringProperty("domain", "<this><is>xml</this></is>"));
+ List<Object> argsin = new ArrayList<>();
+ argsin.add("<this><is>xml</this></is>");
+ argsin.add("And I say: Hello World.");
+ element.setProperty(new CollectionProperty("args", argsin));
+ replacer.reverseReplace(element, true);
+ @SuppressWarnings("unchecked")
+ List<JMeterProperty> args = (List<JMeterProperty>) element.getProperty("args").getObjectValue();
+ assertEquals("${bounded_regex}", element.getPropertyAsString("domain"));
+ assertEquals("${bounded_regex}", args.get(0).getStringValue());
+ }
+
+ @Test
+ public void testOverlappingMatches() throws Exception {
+ TestPlan plan = new TestPlan();
+ plan.addParameter("longMatch", "servername");
+ plan.addParameter("shortMatch", ".*");
+ ValueReplacer replacer = new ValueReplacer(plan);
+ TestElement element = new TestPlan();
+ element.setProperty(new StringProperty("domain", "servername.domain"));
+ replacer.reverseReplace(element, true);
+ String replacedDomain = element.getPropertyAsString("domain");
+ assertEquals("${${shortMatch}", replacedDomain);
+ }
+
+ @Test
+ public void testPartialWordMatchesWithoutParens() throws Exception {
+ assertEquals("toto%40005", replaceWord("005", "toto%40005"));
+ }
+
+ @Test
+ public void testPartialWordMatchesWithParens() throws Exception {
+ assertEquals("toto%40${domainMatcher}", replaceWord("(005)", "toto%40005"));
+ }
+
+ @Test
+ public void testCompleteWordMatchesWithoutParens() throws Exception {
+ assertEquals("toto@${domainMatcher}", replaceWord("005", "toto@005"));
+ }
+
+ @Test
+ public void testCompleteWordMatchesWithParens() throws Exception {
+ assertEquals("toto@${domainMatcher}", replaceWord("(005)", "toto@005"));
+ }
+
+ private String replaceWord(String matchRegex, String testData) throws Exception {
+ TestPlan plan = new TestPlan();
+ plan.addParameter("domainMatcher", matchRegex);
+ ValueReplacer replacer = new ValueReplacer(plan);
+ TestElement element = new TestPlan();
+ element.setProperty(new StringProperty("mail", testData));
+ replacer.reverseReplace(element, true);
+ return element.getPropertyAsString("mail");
+ }
+
+ @Test
+ public void testReplace() throws Exception {
+ ValueReplacer replacer = new ValueReplacer();
+ replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
+ TestElement element = new ConfigTestElement();
+ element.setProperty(new StringProperty("domain", "${server}"));
+ replacer.replaceValues(element);
+ element.setRunningVersion(true);
+ assertEquals("jakarta.apache.org", element.getPropertyAsString("domain"));
+ }
+
+ @Test
+ public void testReplaceStringWithBackslash() throws Exception {
+ ValueReplacer replacer = new ValueReplacer();
+ replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
+ TestElement element = new ConfigTestElement();
+ String input = "\\${server} \\ \\\\ \\\\\\ \\, ";
+ element.setProperty(new StringProperty("domain", input));
+ replacer.replaceValues(element);
+ element.setRunningVersion(true);
+ assertEquals(input, element.getPropertyAsString("domain"));
+ }
+
+ /*
+ * This test should be compared with the one above.
+ * Here, the string contains a valid variable reference, so all
+ * backslashes are also processed.
+ *
+ * See https://bz.apache.org/bugzilla/show_bug.cgi?id=53534
+ */
+ @Test
+ public void testReplaceFunctionWithBackslash() throws Exception {
+ ValueReplacer replacer = new ValueReplacer();
+ replacer.setUserDefinedVariables(variables.getUserDefinedVariables());
+ TestElement element = new ConfigTestElement();
+ String input = "${server} \\ \\\\ \\\\\\ \\, ";
+ element.setProperty(new StringProperty("domain", input));
+ replacer.replaceValues(element);
+ element.setRunningVersion(true);
+ assertEquals("jakarta.apache.org \\ \\ \\\\ , ", element.getPropertyAsString("domain"));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ JMeterContextService.getContext().setSamplingStarted(false);
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/gui/logging/TestGuiLogEventAppender.java b/src/core/src/test/java/org/apache/jmeter/gui/logging/TestGuiLogEventAppender.java
index 49b8688..36b013b 100644
--- a/src/core/src/test/java/org/apache/jmeter/gui/logging/TestGuiLogEventAppender.java
+++ b/src/core/src/test/java/org/apache/jmeter/gui/logging/TestGuiLogEventAppender.java
@@ -42,9 +42,6 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- * Unit test for {@link GuiLogEventAppender}.
- */
public class TestGuiLogEventAppender {
private static List<String> log4j2LevelErrorMessages = Collections.synchronizedList(new LinkedList<>());
@@ -58,21 +55,23 @@ public class TestGuiLogEventAppender {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setPackages("org.apache.jmeter.gui.logging");
- AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
- ConsoleAppender.Target.SYSTEM_OUT);
- appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d %p %c{1.}: %m%n"));
+ AppenderComponentBuilder appenderBuilder = builder
+ .newAppender("Stdout", "CONSOLE")
+ .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT)
+ .add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d %p %c{1.}: %m%n"));
builder.add(appenderBuilder);
- appenderBuilder = builder.newAppender("gui-log-event", "GuiLogEvent");
- appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d %p %c{1.}: %m%n"));
+ appenderBuilder = builder
+ .newAppender("gui-log-event", "GuiLogEvent")
+ .add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d %p %c{1.}: %m%n"));
builder.add(appenderBuilder);
RootLoggerComponentBuilder rootLoggerBuilder = builder.newRootLogger(Level.INFO);
rootLoggerBuilder.add(builder.newAppenderRef("Stdout")).add(builder.newAppenderRef("gui-log-event"));
builder.add(rootLoggerBuilder);
- final LoggerContext loggerContext = Configurator.initialize(builder.build());
- final Appender guiLogEventAppender = loggerContext.getRootLogger().getAppenders().get("gui-log-event");
+ LoggerContext loggerContext = Configurator.initialize(builder.build());
+ Appender guiLogEventAppender = loggerContext.getRootLogger().getAppenders().get("gui-log-event");
guiLogEventAppender.stop();
guiLogEventAppender.setHandler(new ErrorHandler() {
diff --git a/src/core/src/test/java/org/apache/jmeter/listeners/TestResultAction.java b/src/core/src/test/java/org/apache/jmeter/listeners/TestResultAction.java
index 4b76185..d126f90 100644
--- a/src/core/src/test/java/org/apache/jmeter/listeners/TestResultAction.java
+++ b/src/core/src/test/java/org/apache/jmeter/listeners/TestResultAction.java
@@ -29,10 +29,6 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-
-/**
- * Test for {@link ResultAction}
- */
public class TestResultAction extends JMeterTestCase {
private ResultAction resultAction;
private SampleResult sampleResult;
diff --git a/src/core/src/test/java/org/apache/jmeter/report/core/TestCsvSampleWriter.java b/src/core/src/test/java/org/apache/jmeter/report/core/TestCsvSampleWriter.java
index 24b21b2..432a8b1 100644
--- a/src/core/src/test/java/org/apache/jmeter/report/core/TestCsvSampleWriter.java
+++ b/src/core/src/test/java/org/apache/jmeter/report/core/TestCsvSampleWriter.java
@@ -44,16 +44,13 @@ public class TestCsvSampleWriter {
@Test(expected=NullPointerException.class)
public void testCsvSampleWriterConstructorWithNull() throws Exception {
- CsvSampleWriter dummy = new CsvSampleWriter(null);
- dummy.close(); // We should never get here, but it would be a
- // writer, so close it
+ new CsvSampleWriter(null);
}
@Test
public void testCsvSampleWriterConstructorWithWriter() throws Exception {
try (Writer writer = new StringWriter();
- CsvSampleWriter csvWriter = new CsvSampleWriter(writer,
- metadata)) {
+ CsvSampleWriter csvWriter = new CsvSampleWriter(writer, metadata)) {
csvWriter.writeHeader();
csvWriter.flush();
assertEquals("a,b" + LINE_SEP, writer.toString());
@@ -63,8 +60,7 @@ public class TestCsvSampleWriter {
@Test
public void testWriteWithoutWriter() throws Exception {
try (CsvSampleWriter csvWriter = new CsvSampleWriter(metadata)) {
- Sample sample = new SampleBuilder(metadata).add("a1").add("b1")
- .build();
+ Sample sample = new SampleBuilder(metadata).add("a1").add("b1").build();
try {
csvWriter.write(sample);
fail("ISE expected");
@@ -77,8 +73,7 @@ public class TestCsvSampleWriter {
@Test
public void testWriteWithoutSample() throws Exception {
try (Writer writer = new StringWriter();
- CsvSampleWriter csvWriter = new CsvSampleWriter(writer,
- metadata)) {
+ CsvSampleWriter csvWriter = new CsvSampleWriter(writer, metadata)) {
try {
csvWriter.write(null);
fail("NPE expected");
@@ -91,10 +86,8 @@ public class TestCsvSampleWriter {
@Test
public void testWrite() throws Exception {
try (Writer writer = new StringWriter();
- CsvSampleWriter csvWriter = new CsvSampleWriter(writer,
- metadata)) {
- Sample sample = new SampleBuilder(metadata).add("a1").add("b1")
- .build();
+ CsvSampleWriter csvWriter = new CsvSampleWriter(writer, metadata)) {
+ Sample sample = new SampleBuilder(metadata).add("a1").add("b1").build();
csvWriter.write(sample);
csvWriter.flush();
assertEquals("a1,b1" + LINE_SEP, writer.toString());
diff --git a/src/core/src/test/java/org/apache/jmeter/report/processor/ErrorsSummaryConsumerTest.java b/src/core/src/test/java/org/apache/jmeter/report/processor/ErrorsSummaryConsumerTest.java
index 4ec322a..885ff44 100644
--- a/src/core/src/test/java/org/apache/jmeter/report/processor/ErrorsSummaryConsumerTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/report/processor/ErrorsSummaryConsumerTest.java
@@ -54,7 +54,6 @@ public class ErrorsSummaryConsumerTest {
Assert.assertEquals("500/Server Error", ErrorsSummaryConsumer.getErrorKey(sample));
}
-
@Test
public void testErrorSampleCounter() {
ErrorsSummaryConsumer consumer = new ErrorsSummaryConsumer();
@@ -68,19 +67,9 @@ public class ErrorsSummaryConsumerTest {
Assert.assertEquals(Long.valueOf(2), info.getData());
}
- /**
- * Create a dummy sample that is either successful or a failure depending on
- * the {@code success} flag
- *
- * @param success
- * flag do determine if the sample should be successful or not
- * @return newly created sample
- */
private Sample createSample(boolean success) {
- SampleMetadata metadata = new SampleMetadata(',',
- CSVSaveService.SUCCESSFUL);
- Sample sample = new Sample(0, metadata, String.valueOf(success));
- return sample;
+ SampleMetadata metadata = new SampleMetadata(',', CSVSaveService.SUCCESSFUL);
+ return new Sample(0, metadata, String.valueOf(success));
}
}
diff --git a/src/core/src/test/java/org/apache/jmeter/report/processor/graph/impl/CustomGraphConsumerTest.java b/src/core/src/test/java/org/apache/jmeter/report/processor/graph/impl/CustomGraphConsumerTest.java
index f7287bd..5e612ca 100644
--- a/src/core/src/test/java/org/apache/jmeter/report/processor/graph/impl/CustomGraphConsumerTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/report/processor/graph/impl/CustomGraphConsumerTest.java
@@ -42,7 +42,6 @@ public class CustomGraphConsumerTest {
private CustomGraphConsumer customGraphConsumer;
private MapResultData resultData;
- private TimeStampKeysSelector keysSelector;
private Map<String, GroupInfo> map;
// data array can't be initialized in the init()
private String[] data = {"1527089951383", "0", "Read-compute", "200", "OK", "setupRegion 1-1", "true", "", "492", "0", "1", "1",
@@ -79,25 +78,24 @@ public class CustomGraphConsumerTest {
assertThat(customGraphConsumer.getIsNativeSampleVariableName(), equalTo(true));
}
-
@Test
public void testInitializeExtraResults() {
customGraphConsumer.initializeExtraResults(resultData);
JsonizerVisitor jsonizer = new JsonizerVisitor();
- for(Entry<String, ResultData> entrySet : resultData.entrySet()) {
+ for (Entry<String, ResultData> entrySet : resultData.entrySet()) {
Object testedValue = entrySet.getValue().accept(jsonizer);
String key = entrySet.getKey();
- if(key.equals("granularity")) {
+ if (key.equals("granularity")) {
assertThat(testedValue, equalTo("60000"));
- }else if(key.equals("X_Axis")) {
+ } else if (key.equals("X_Axis")) {
assertThat(testedValue, equalTo("\"X axis name\""));
- }else if(key.equals("Y_Axis")) {
+ } else if (key.equals("Y_Axis")) {
assertThat(testedValue, equalTo("\"Y axis name\""));
}else if(key.equals("sample_Metric_Name")) {
assertThat(testedValue, equalTo("\"ulp_lag_ratio\""));
- }else if(key.equals("content_Message")) {
+ } else if (key.equals("content_Message")) {
assertThat(testedValue, equalTo("\"content message\""));
}
}
@@ -105,7 +103,7 @@ public class CustomGraphConsumerTest {
@Test
public void testCreateTimeStampKeysSelector() {
- keysSelector = new TimeStampKeysSelector();
+ TimeStampKeysSelector keysSelector = new TimeStampKeysSelector();
keysSelector.setSelectBeginTime(false);
assertThat(customGraphConsumer.createTimeStampKeysSelector().getGranularity(), equalTo(keysSelector.getGranularity()));
}
@@ -125,7 +123,7 @@ public class CustomGraphConsumerTest {
customGraphConsumer.setSampleVariableName("bytes");
Sample sample = new Sample(0, sampleMetaData, data);
Double testedValue = map.get("Generic group").getValueSelector().select("bytes", sample);
- assertThat(testedValue, equalTo((Double) 492.0));
+ assertThat(testedValue, equalTo(492.0));
// Testing non-native sample variable
customGraphConsumer.setSampleVariableName("mm-miss");
@@ -159,7 +157,7 @@ public class CustomGraphConsumerTest {
assertThat(testString, equalTo("[ulp_lag_ratio]"));
}
- // Create a static SampleMetadatObject
+ // Create a static SampleMetadataObject
private SampleMetadata createTestMetaData() {
String columnsString = "timeStamp,elapsed,label,responseCode,responseMessage,threadName,success,failureMessage,bytes,sentBytes,"
+ "grpThreads,allThreads,URL,Latency,IdleTime,Connect,\"stream\",\"aws_region\",\"bitrate\",\"ulp_buffer_fill\",\"ulp_lag_time\","
@@ -168,16 +166,16 @@ public class CustomGraphConsumerTest {
String[] columns = new String[34];
int lastComa = 0;
int columnIndex = 0;
- for(int i = 0; i < columnsString.length(); i++) {
- if (columnsString.charAt(i)==',') {
+ for (int i = 0; i < columnsString.length(); i++) {
+ if (columnsString.charAt(i) == ',') {
columns[columnIndex] = columnsString.substring(lastComa, i);
- lastComa=i+1;
+ lastComa = i + 1;
columnIndex++;
- }else if(i+1 == columnsString.length()) {
- columns[columnIndex] = columnsString.substring(lastComa, i+1);
+ } else if (i + 1 == columnsString.length()) {
+ columns[columnIndex] = columnsString.substring(lastComa, i + 1);
}
}
- return new SampleMetadata(',',columns);
+ return new SampleMetadata(',', columns);
}
}
diff --git a/src/core/src/test/java/org/apache/jmeter/samplers/TestSampleResult.java b/src/core/src/test/java/org/apache/jmeter/samplers/TestSampleResult.java
index 377e6cb..f7b5730 100644
--- a/src/core/src/test/java/org/apache/jmeter/samplers/TestSampleResult.java
+++ b/src/core/src/test/java/org/apache/jmeter/samplers/TestSampleResult.java
@@ -32,354 +32,352 @@ import org.apache.jmeter.util.LogRecordingDelegatingLogger;
import org.apache.jorphan.test.JMeterSerialTest;
import org.junit.Test;
-// TODO need more tests - particularly for the new functions
-
public class TestSampleResult implements JMeterSerialTest {
- @Test
- public void testElapsedTrue() throws Exception {
- SampleResult res = new SampleResult(true);
-
- // Check sample increments OK
- res.sampleStart();
- Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
- res.sampleEnd();
- long time = res.getTime();
- if(time < 100){
- fail("Sample time should be >=100, actual "+time);
- }
+ @Test
+ public void testElapsedTrue() throws Exception {
+ SampleResult res = new SampleResult(true);
+
+ // Check sample increments OK
+ res.sampleStart();
+ Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
+ res.sampleEnd();
+ long time = res.getTime();
+ if (time < 100) {
+ fail("Sample time should be >=100, actual " + time);
}
-
- @Test
- public void testElapsedFalse() throws Exception {
- SampleResult res = new SampleResult(false);
-
- // Check sample increments OK
- res.sampleStart();
- Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
- res.sampleEnd();
- long time = res.getTime();
- if(time < 100){
- fail("Sample time should be >=100, actual "+time);
- }
+ }
+
+ @Test
+ public void testElapsedFalse() throws Exception {
+ SampleResult res = new SampleResult(false);
+
+ // Check sample increments OK
+ res.sampleStart();
+ Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
+ res.sampleEnd();
+ long time = res.getTime();
+ if (time < 100) {
+ fail("Sample time should be >=100, actual " + time);
}
-
- @Test
- public void testPauseFalse() throws Exception {
- SampleResult res = new SampleResult(false);
- // Check sample increments OK
- res.sampleStart();
- long totalSampleTime = sleep(100); // accumulate the time spent 'sampling'
- res.samplePause();
-
- Thread.sleep(200); // This should be ignored
-
- // Re-increment
- res.sampleResume();
- totalSampleTime += sleep(100);
- res.sampleEnd();
- long sampleTime = res.getTime();
- assertEquals("Accumulated sample time", totalSampleTime, sampleTime, 50);
- }
-
- @Test
- public void testPauseTrue() throws Exception {
- SampleResult res = new SampleResult(true);
- // Check sample increments OK
- res.sampleStart();
- long totalSampleTime = sleep(100); // accumulate the time spent 'sampling'
- res.samplePause();
-
- Thread.sleep(200); // this should be ignored
-
- // Re-increment
- res.sampleResume();
- totalSampleTime += sleep(100);
- res.sampleEnd();
- long sampleTime = res.getTime();
- assertEquals("Accumulated sample time", totalSampleTime, sampleTime, 50);
+ }
+
+ @Test
+ public void testPauseFalse() throws Exception {
+ SampleResult res = new SampleResult(false);
+ // Check sample increments OK
+ res.sampleStart();
+ long totalSampleTime = sleep(100); // accumulate the time spent 'sampling'
+ res.samplePause();
+
+ Thread.sleep(200); // This should be ignored
+
+ // Re-increment
+ res.sampleResume();
+ totalSampleTime += sleep(100);
+ res.sampleEnd();
+ long sampleTime = res.getTime();
+ assertEquals("Accumulated sample time", totalSampleTime, sampleTime, 50);
+ }
+
+ @Test
+ public void testPauseTrue() throws Exception {
+ SampleResult res = new SampleResult(true);
+ // Check sample increments OK
+ res.sampleStart();
+ long totalSampleTime = sleep(100); // accumulate the time spent 'sampling'
+ res.samplePause();
+
+ Thread.sleep(200); // this should be ignored
+
+ // Re-increment
+ res.sampleResume();
+ totalSampleTime += sleep(100);
+ res.sampleEnd();
+ long sampleTime = res.getTime();
+ assertEquals("Accumulated sample time", totalSampleTime, sampleTime, 50);
+ }
+
+ private LogRecordingDelegatingLogger recordLogger;
+
+ private void divertLog() {// N.B. This needs to divert the log for SampleResult
+ if (SampleResult.log instanceof LogRecordingDelegatingLogger) {
+ recordLogger = (LogRecordingDelegatingLogger) SampleResult.log;
+ } else {
+ recordLogger = new LogRecordingDelegatingLogger(SampleResult.log);
+ SampleResult.log = recordLogger;
}
-
- private LogRecordingDelegatingLogger recordLogger;
-
- private void divertLog() {// N.B. This needs to divert the log for SampleResult
- if (SampleResult.log instanceof LogRecordingDelegatingLogger) {
- recordLogger = (LogRecordingDelegatingLogger) SampleResult.log;
- } else {
- recordLogger = new LogRecordingDelegatingLogger(SampleResult.log);
- SampleResult.log = recordLogger;
- }
- recordLogger.clearLogRecords();
+ recordLogger.clearLogRecords();
+ }
+
+ @Test
+ public void testPause2True() throws Exception {
+ divertLog();
+ SampleResult res = new SampleResult(true);
+ res.sampleStart();
+ res.samplePause();
+ assertEquals(0, recordLogger.getLogRecordCount());
+ res.samplePause();
+ assertNotEquals(0, recordLogger.getLogRecordCount());
+ }
+
+ @Test
+ public void testPause2False() throws Exception {
+ divertLog();
+ SampleResult res = new SampleResult(false);
+ res.sampleStart();
+ res.samplePause();
+ assertEquals(0, recordLogger.getLogRecordCount());
+ res.samplePause();
+ assertNotEquals(0, recordLogger.getLogRecordCount());
+ }
+
+ @Test
+ public void testByteCount() throws Exception {
+ SampleResult res = new SampleResult();
+
+ res.sampleStart();
+ res.setBytes(100L);
+ res.setSampleLabel("sample of size 100 bytes");
+ res.sampleEnd();
+ assertEquals(100, res.getBytesAsLong());
+ assertEquals("sample of size 100 bytes", res.getSampleLabel());
+ }
+
+ @Test
+ public void testSubResultsTrue() throws Exception {
+ testSubResults(true, 0);
+ }
+
+ @Test
+ public void testSubResultsTrueThread() throws Exception {
+ testSubResults(true, 500L, 0);
+ }
+
+ @Test
+ public void testSubResultsFalse() throws Exception {
+ testSubResults(false, 0);
+ }
+
+ @Test
+ public void testSubResultsFalseThread() throws Exception {
+ testSubResults(false, 500L, 0);
+ }
+
+ @Test
+ public void testSubResultsTruePause() throws Exception {
+ testSubResults(true, 100);
+ }
+
+ @Test
+ public void testSubResultsTruePauseThread() throws Exception {
+ testSubResults(true, 500L, 100);
+ }
+
+ @Test
+ public void testSubResultsFalsePause() throws Exception {
+ testSubResults(false, 100);
+ }
+
+ @Test
+ public void testSubResultsFalsePauseThread() throws Exception {
+ testSubResults(false, 500L, 100);
+ }
+
+ // temp test case for exploring settings
+ public void xtestUntilFail() throws Exception {
+ while (true) {
+ testSubResultsTruePause();
+ testSubResultsFalsePause();
}
-
- @Test
- public void testPause2True() throws Exception {
- divertLog();
- SampleResult res = new SampleResult(true);
- res.sampleStart();
- res.samplePause();
- assertEquals(0, recordLogger.getLogRecordCount());
- res.samplePause();
- assertNotEquals(0, recordLogger.getLogRecordCount());
+ }
+
+ private void testSubResults(boolean nanoTime, long pause) throws Exception {
+ testSubResults(nanoTime, 0L, pause); // Don't use nanoThread
+ }
+
+ private void testSubResults(boolean nanoTime, long nanoThreadSleep, long pause) throws Exception {
+ // This test tries to emulate a http sample, with two
+ // subsamples, representing images that are downloaded for the
+ // page representing the first sample.
+
+ // Sample that will get two sub results, simulates a web page load
+ SampleResult parent = new SampleResult(nanoTime, nanoThreadSleep);
+
+ JMeterTestCase.assertPrimitiveEquals(nanoTime, parent.useNanoTime);
+ assertEquals(nanoThreadSleep, parent.nanoThreadSleep);
+
+ long beginTest = parent.currentTimeInMillis();
+
+ parent.sampleStart();
+ Thread.sleep(100);
+ parent.setBytes(300L);
+ parent.setSampleLabel("Parent Sample");
+ parent.setSuccessful(true);
+ parent.sampleEnd();
+ long parentElapsed = parent.getTime();
+
+ // Sample with no sub results, simulates an image download
+ SampleResult child1 = new SampleResult(nanoTime);
+ child1.sampleStart();
+ Thread.sleep(100);
+ child1.setBytes(100L);
+ child1.setSampleLabel("Child1 Sample");
+ child1.setSuccessful(true);
+ child1.sampleEnd();
+ long child1Elapsed = child1.getTime();
+
+ assertTrue(child1.isSuccessful());
+ assertEquals(100, child1.getBytesAsLong());
+ assertEquals("Child1 Sample", child1.getSampleLabel());
+ assertEquals(1, child1.getSampleCount());
+ assertEquals(0, child1.getSubResults().length);
+
+ long actualPause = 0;
+ if (pause > 0) {
+ long t1 = parent.currentTimeInMillis();
+ Thread.sleep(pause);
+ actualPause = parent.currentTimeInMillis() - t1;
}
- @Test
- public void testPause2False() throws Exception {
- divertLog();
- SampleResult res = new SampleResult(false);
- res.sampleStart();
- res.samplePause();
- assertEquals(0, recordLogger.getLogRecordCount());
- res.samplePause();
- assertNotEquals(0, recordLogger.getLogRecordCount());
+ // Sample with no sub results, simulates an image download
+ SampleResult child2 = new SampleResult(nanoTime);
+ child2.sampleStart();
+ Thread.sleep(100);
+ child2.setBytes(200L);
+ child2.setSampleLabel("Child2 Sample");
+ child2.setSuccessful(true);
+ child2.sampleEnd();
+ long child2Elapsed = child2.getTime();
+
+ assertTrue(child2.isSuccessful());
+ assertEquals(200, child2.getBytesAsLong());
+ assertEquals("Child2 Sample", child2.getSampleLabel());
+ assertEquals(1, child2.getSampleCount());
+ assertEquals(0, child2.getSubResults().length);
+
+ // Now add the subsamples to the sample
+ parent.addSubResult(child1);
+ parent.addSubResult(child2);
+ assertTrue(parent.isSuccessful());
+ assertEquals(600, parent.getBytesAsLong());
+ assertEquals("Parent Sample", parent.getSampleLabel());
+ assertEquals(1, parent.getSampleCount());
+ assertEquals(2, parent.getSubResults().length);
+ long parentElapsedTotal = parent.getTime();
+
+ long overallTime = parent.currentTimeInMillis() - beginTest;
+
+ long sumSamplesTimes = parentElapsed + child1Elapsed + actualPause + child2Elapsed;
+
+ /*
+ * Parent elapsed total should be no smaller than the sum of the individual samples.
+ * It may be greater by the timer granularity.
+ */
+
+ long diff = parentElapsedTotal - sumSamplesTimes;
+ long maxDiff = nanoTime ? 10 : 16; // TimeMillis has granularity of 10-20
+ if (diff < 0 || diff > maxDiff) {
+ fail("ParentElapsed: " + parentElapsedTotal + " - " + " sum(samples): " + sumSamplesTimes
+ + " => " + diff + " not in [0," + maxDiff + "]; nanotime=" + nanoTime);
}
- @Test
- public void testByteCount() throws Exception {
- SampleResult res = new SampleResult();
-
- res.sampleStart();
- res.setBytes(100L);
- res.setSampleLabel("sample of size 100 bytes");
- res.sampleEnd();
- assertEquals(100, res.getBytesAsLong());
- assertEquals("sample of size 100 bytes", res.getSampleLabel());
- }
+ // The overall time to run the test must be no less than,
+ // and may be greater (but not much greater) than the parent elapsed time
- @Test
- public void testSubResultsTrue() throws Exception {
- testSubResults(true, 0);
+ diff = overallTime - parentElapsedTotal;
+ if (diff < 0 || diff > maxDiff) {
+ fail("TestElapsed: " + overallTime + " - " + " ParentElapsed: " + parentElapsedTotal
+ + " => " + diff + " not in [0," + maxDiff + "]; nanotime=" + nanoTime);
}
- @Test
- public void testSubResultsTrueThread() throws Exception {
- testSubResults(true, 500L, 0);
- }
-
- @Test
- public void testSubResultsFalse() throws Exception {
- testSubResults(false, 0);
- }
-
- @Test
- public void testSubResultsFalseThread() throws Exception {
- testSubResults(false, 500L, 0);
- }
-
- @Test
- public void testSubResultsTruePause() throws Exception {
- testSubResults(true, 100);
- }
-
- @Test
- public void testSubResultsTruePauseThread() throws Exception {
- testSubResults(true, 500L, 100);
- }
-
- @Test
- public void testSubResultsFalsePause() throws Exception {
- testSubResults(false, 100);
- }
-
- @Test
- public void testSubResultsFalsePauseThread() throws Exception {
- testSubResults(false, 500L, 100);
- }
-
- // temp test case for exploring settings
- public void xtestUntilFail() throws Exception {
- while(true) {
- testSubResultsTruePause();
- testSubResultsFalsePause();
- }
- }
-
- private void testSubResults(boolean nanoTime, long pause) throws Exception {
- testSubResults(nanoTime, 0L, pause); // Don't use nanoThread
- }
-
- private void testSubResults(boolean nanoTime, long nanoThreadSleep, long pause) throws Exception {
- // This test tries to emulate a http sample, with two
- // subsamples, representing images that are downloaded for the
- // page representing the first sample.
-
- // Sample that will get two sub results, simulates a web page load
- SampleResult parent = new SampleResult(nanoTime, nanoThreadSleep);
-
- JMeterTestCase.assertPrimitiveEquals(nanoTime, parent.useNanoTime);
- assertEquals(nanoThreadSleep, parent.nanoThreadSleep);
-
- long beginTest = parent.currentTimeInMillis();
-
- parent.sampleStart();
- Thread.sleep(100);
- parent.setBytes(300L);
- parent.setSampleLabel("Parent Sample");
- parent.setSuccessful(true);
- parent.sampleEnd();
- long parentElapsed = parent.getTime();
-
- // Sample with no sub results, simulates an image download
- SampleResult child1 = new SampleResult(nanoTime);
- child1.sampleStart();
- Thread.sleep(100);
- child1.setBytes(100L);
- child1.setSampleLabel("Child1 Sample");
- child1.setSuccessful(true);
- child1.sampleEnd();
- long child1Elapsed = child1.getTime();
-
- assertTrue(child1.isSuccessful());
- assertEquals(100, child1.getBytesAsLong());
- assertEquals("Child1 Sample", child1.getSampleLabel());
- assertEquals(1, child1.getSampleCount());
- assertEquals(0, child1.getSubResults().length);
-
- long actualPause = 0;
- if (pause > 0) {
- long t1 = parent.currentTimeInMillis();
- Thread.sleep(pause);
- actualPause = parent.currentTimeInMillis() - t1;
- }
-
- // Sample with no sub results, simulates an image download
- SampleResult child2 = new SampleResult(nanoTime);
- child2.sampleStart();
- Thread.sleep(100);
- child2.setBytes(200L);
- child2.setSampleLabel("Child2 Sample");
- child2.setSuccessful(true);
- child2.sampleEnd();
- long child2Elapsed = child2.getTime();
-
- assertTrue(child2.isSuccessful());
- assertEquals(200, child2.getBytesAsLong());
- assertEquals("Child2 Sample", child2.getSampleLabel());
- assertEquals(1, child2.getSampleCount());
- assertEquals(0, child2.getSubResults().length);
-
- // Now add the subsamples to the sample
- parent.addSubResult(child1);
- parent.addSubResult(child2);
- assertTrue(parent.isSuccessful());
- assertEquals(600, parent.getBytesAsLong());
- assertEquals("Parent Sample", parent.getSampleLabel());
- assertEquals(1, parent.getSampleCount());
- assertEquals(2, parent.getSubResults().length);
- long parentElapsedTotal = parent.getTime();
-
- long overallTime = parent.currentTimeInMillis() - beginTest;
-
- long sumSamplesTimes = parentElapsed + child1Elapsed + actualPause + child2Elapsed;
-
- /*
- * Parent elapsed total should be no smaller than the sum of the individual samples.
- * It may be greater by the timer granularity.
- */
-
- long diff = parentElapsedTotal - sumSamplesTimes;
- long maxDiff = nanoTime ? 10 : 16; // TimeMillis has granularity of 10-20
- if (diff < 0 || diff > maxDiff) {
- fail("ParentElapsed: " + parentElapsedTotal + " - " + " sum(samples): " + sumSamplesTimes
- + " => " + diff + " not in [0," + maxDiff + "]; nanotime=" + nanoTime);
- }
-
- // The overall time to run the test must be no less than,
- // and may be greater (but not much greater) than the parent elapsed time
-
- diff = overallTime - parentElapsedTotal;
- if (diff < 0 || diff > maxDiff) {
- fail("TestElapsed: " + overallTime + " - " + " ParentElapsed: " + parentElapsedTotal
- + " => " + diff + " not in [0," + maxDiff + "]; nanotime="+nanoTime);
- }
-
- // Check that calculator gets the correct statistics from the sample
- Calculator calculator = new Calculator();
- calculator.addSample(parent);
- assertEquals(600, calculator.getTotalBytes());
- assertEquals(1, calculator.getCount());
- assertEquals(1d / (parentElapsedTotal / 1000d), calculator.getRate(),0.0001d); // Allow for some margin of error
- // Check that the throughput uses the time elapsed for the sub results
- assertFalse(1d / (parentElapsed / 1000d) <= calculator.getRate());
- }
-
- // TODO some more invalid sequence tests needed
-
- @Test
- public void testEncodingAndType() throws Exception {
- // check default
- SampleResult res = new SampleResult();
- assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
- assertEquals("DataType should be blank","",res.getDataType());
- assertNull(res.getDataEncodingNoDefault());
-
- // check null changes nothing
- res.setEncodingAndType(null);
- assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
- assertEquals("DataType should be blank","",res.getDataType());
- assertNull(res.getDataEncodingNoDefault());
-
- // check no charset
- res.setEncodingAndType("text/html");
- assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
- assertEquals("text",res.getDataType());
- assertNull(res.getDataEncodingNoDefault());
-
- // Check unquoted charset
- res.setEncodingAndType("text/html; charset=aBcd");
- assertEquals("aBcd",res.getDataEncodingWithDefault());
- assertEquals("aBcd",res.getDataEncodingNoDefault());
- assertEquals("text",res.getDataType());
-
- // Check quoted charset
- res.setEncodingAndType("text/html; charset=\"aBCd\"");
- assertEquals("aBCd",res.getDataEncodingWithDefault());
- assertEquals("aBCd",res.getDataEncodingNoDefault());
- assertEquals("text",res.getDataType());
- }
-
- // sleep and return how long we actually slept
- // may be rather longer if the system is busy
- private long sleep(long ms) throws InterruptedException {
- long start = System.currentTimeMillis();
- Thread.sleep(ms);
- return System.currentTimeMillis() - start;
- }
-
- @Test
- public void testCompareSampleLabels() {
- final boolean prevValue = TestPlan.getFunctionalMode();
- TestPlan plan = new TestPlan();
- plan.setFunctionalMode(true);
- try {
- SampleResult result = new SampleResult();
- result.setStartTime(System.currentTimeMillis());
- result.setSampleLabel("parent label");
-
- SampleResult subResult = new SampleResult();
- subResult.setStartTime(System.currentTimeMillis());
- subResult.setSampleLabel("subResult label");
-
- result.addSubResult(subResult);
- assertEquals("subResult label", subResult.getSampleLabel());
-
- plan.setFunctionalMode(false);
- subResult.setSampleLabel("parent label");
- result.addRawSubResult(subResult);
- assertEquals("parent label-0", subResult.getSampleLabel());
- } finally {
- plan.setFunctionalMode(prevValue);
- }
- }
-
- @Test
- public void testBug63433() {
- SampleResult firstResult = new SampleResult();
- assertFalse("Expected false on first call of markFile", firstResult.markFile("result.csv"));
- assertTrue("Expected true on second call of markFile", firstResult.markFile("result.csv"));
-
- SampleResult secondResult = new SampleResult();
- assertFalse("Expected false on first call of markFile with null", secondResult.markFile(null));
- assertTrue("Expected true on second call of markFile with null", secondResult.markFile(null));
+ // Check that calculator gets the correct statistics from the sample
+ Calculator calculator = new Calculator();
+ calculator.addSample(parent);
+ assertEquals(600, calculator.getTotalBytes());
+ assertEquals(1, calculator.getCount());
+ assertEquals(1d / (parentElapsedTotal / 1000d), calculator.getRate(), 0.0001d); // Allow for some margin of error
+ // Check that the throughput uses the time elapsed for the sub results
+ assertFalse(1d / (parentElapsed / 1000d) <= calculator.getRate());
+ }
+
+ // TODO some more invalid sequence tests needed
+
+ @Test
+ public void testEncodingAndType() throws Exception {
+ // check default
+ SampleResult res = new SampleResult();
+ assertEquals(SampleResult.DEFAULT_ENCODING, res.getDataEncodingWithDefault());
+ assertEquals("DataType should be blank", "", res.getDataType());
+ assertNull(res.getDataEncodingNoDefault());
+
+ // check null changes nothing
+ res.setEncodingAndType(null);
+ assertEquals(SampleResult.DEFAULT_ENCODING, res.getDataEncodingWithDefault());
+ assertEquals("DataType should be blank", "", res.getDataType());
+ assertNull(res.getDataEncodingNoDefault());
+
+ // check no charset
+ res.setEncodingAndType("text/html");
+ assertEquals(SampleResult.DEFAULT_ENCODING, res.getDataEncodingWithDefault());
+ assertEquals("text", res.getDataType());
+ assertNull(res.getDataEncodingNoDefault());
+
+ // Check unquoted charset
+ res.setEncodingAndType("text/html; charset=aBcd");
+ assertEquals("aBcd", res.getDataEncodingWithDefault());
+ assertEquals("aBcd", res.getDataEncodingNoDefault());
+ assertEquals("text", res.getDataType());
+
+ // Check quoted charset
+ res.setEncodingAndType("text/html; charset=\"aBCd\"");
+ assertEquals("aBCd", res.getDataEncodingWithDefault());
+ assertEquals("aBCd", res.getDataEncodingNoDefault());
+ assertEquals("text", res.getDataType());
+ }
+
+ // sleep and return how long we actually slept
+ // may be rather longer if the system is busy
+ private long sleep(long ms) throws InterruptedException {
+ long start = System.currentTimeMillis();
+ Thread.sleep(ms);
+ return System.currentTimeMillis() - start;
+ }
+
+ @Test
+ public void testCompareSampleLabels() {
+ final boolean prevValue = TestPlan.getFunctionalMode();
+ TestPlan plan = new TestPlan();
+ plan.setFunctionalMode(true);
+ try {
+ SampleResult result = new SampleResult();
+ result.setStartTime(System.currentTimeMillis());
+ result.setSampleLabel("parent label");
+
+ SampleResult subResult = new SampleResult();
+ subResult.setStartTime(System.currentTimeMillis());
+ subResult.setSampleLabel("subResult label");
+
+ result.addSubResult(subResult);
+ assertEquals("subResult label", subResult.getSampleLabel());
+
+ plan.setFunctionalMode(false);
+ subResult.setSampleLabel("parent label");
+ result.addRawSubResult(subResult);
+ assertEquals("parent label-0", subResult.getSampleLabel());
+ } finally {
+ plan.setFunctionalMode(prevValue);
}
+ }
+
+ @Test
+ public void testBug63433() {
+ SampleResult firstResult = new SampleResult();
+ assertFalse("Expected false on first call of markFile", firstResult.markFile("result.csv"));
+ assertTrue("Expected true on second call of markFile", firstResult.markFile("result.csv"));
+
+ SampleResult secondResult = new SampleResult();
+ assertFalse("Expected false on first call of markFile with null", secondResult.markFile(null));
+ assertTrue("Expected true on second call of markFile with null", secondResult.markFile(null));
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestBooleanPropertyEditor.java b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestBooleanPropertyEditor.java
index b26fddb..496c9d3 100644
--- a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestBooleanPropertyEditor.java
+++ b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestBooleanPropertyEditor.java
@@ -27,23 +27,19 @@ import java.beans.PropertyEditorManager;
import org.junit.Test;
/**
- * Test class to check that the JVM provides sensible behaviour for the boolean PropertyEditor, i.e.
- * that getAsText() can only return values that match getTags().
+ * Test class to check that the JVM provides sensible behaviour for the boolean
+ * {@link PropertyEditor}, i.e. that getAsText() only returns values that match getTags().
*
* Also checks that BooleanPropertyEditor behaves in the same way.
*/
public class TestBooleanPropertyEditor {
- /*
- * N.B.
- * These values are NOT the same as Boolean.FALSE|TRUE.toString()
- * which returns lower-case only. The getAsText() method converts
- * the result to mixed case.
- */
+ // N.B. These values are NOT the same as Boolean.FALSE|TRUE.toString()
+ // which returns lower-case only.
+ // The getAsText() method converts the result to mixed case.
private static final String FALSE = "False"; // $NON-NLS-1$
private static final String TRUE = "True"; // $NON-NLS-1$
-
@Test
public void testBooleanEditor(){
PropertyEditor propertyEditor = PropertyEditorManager.findEditor(boolean.class);
diff --git a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestComboStringEditor.java b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestComboStringEditor.java
index 517e9ea..93cd019 100644
--- a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestComboStringEditor.java
+++ b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestComboStringEditor.java
@@ -25,39 +25,39 @@ import org.junit.Test;
public class TestComboStringEditor {
- private void testSetGet(ComboStringEditor e, Object value) throws Exception {
- e.setValue(value);
- assertEquals(value, e.getValue());
- }
-
- private void testSetGetAsText(ComboStringEditor e, String text) throws Exception {
- e.setAsText(text);
- assertEquals(text, e.getAsText());
- }
-
- @Test
- public void testSetGet() throws Exception {
- @SuppressWarnings("deprecation") // test code, intentional
- ComboStringEditor e = new ComboStringEditor();
-
- testSetGet(e, "any string");
- testSetGet(e, "");
- testSetGet(e, null);
- testSetGet(e, "${var}");
- }
-
- @Test
- public void testSetGetAsText() throws Exception {
- @SuppressWarnings("deprecation") // test code, intentional
- ComboStringEditor e = new ComboStringEditor();
-
- testSetGetAsText(e, "any string");
- testSetGetAsText(e, "");
- testSetGetAsText(e, null);
- testSetGetAsText(e, "${var}");
-
- // Check "Undefined" does not become a "reserved word":
- e.setAsText(e.UNDEFINED.toString());
- assertNotNull(e.getAsText());
- }
+ private void testSetGet(ComboStringEditor e, Object value) throws Exception {
+ e.setValue(value);
+ assertEquals(value, e.getValue());
+ }
+
+ private void testSetGetAsText(ComboStringEditor e, String text) throws Exception {
+ e.setAsText(text);
+ assertEquals(text, e.getAsText());
+ }
+
+ @Test
+ public void testSetGet() throws Exception {
+ @SuppressWarnings("deprecation") // test code, intentional
+ ComboStringEditor e = new ComboStringEditor();
+
+ testSetGet(e, "any string");
+ testSetGet(e, "");
+ testSetGet(e, null);
+ testSetGet(e, "${var}");
+ }
+
+ @Test
+ public void testSetGetAsText() throws Exception {
+ @SuppressWarnings("deprecation") // test code, intentional
+ ComboStringEditor e = new ComboStringEditor();
+
+ testSetGetAsText(e, "any string");
+ testSetGetAsText(e, "");
+ testSetGetAsText(e, null);
+ testSetGetAsText(e, "${var}");
+
+ // Check "Undefined" does not become a "reserved word":
+ e.setAsText(e.UNDEFINED.toString());
+ assertNotNull(e.getAsText());
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestFieldStringEditor.java b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestFieldStringEditor.java
index 78a269c..5f170b6 100644
--- a/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestFieldStringEditor.java
+++ b/src/core/src/test/java/org/apache/jmeter/testbeans/gui/TestFieldStringEditor.java
@@ -24,33 +24,33 @@ import org.junit.Test;
public class TestFieldStringEditor {
- private void testSetGet(ComboStringEditor e, Object value) throws Exception {
- e.setValue(value);
- assertEquals(value, e.getValue());
- }
-
- private void testSetGetAsText(ComboStringEditor e, String text) throws Exception {
- e.setAsText(text);
- assertEquals(text, e.getAsText());
- }
-
- @Test
- public void testSetGet() throws Exception {
- @SuppressWarnings("deprecation") // test code, intentional
- ComboStringEditor e = new ComboStringEditor();
-
- testSetGet(e, "any string");
- testSetGet(e, "");
- testSetGet(e, "${var}");
- }
-
- @Test
- public void testSetGetAsText() throws Exception {
- @SuppressWarnings("deprecation") // test code, intentional
- ComboStringEditor e = new ComboStringEditor();
-
- testSetGetAsText(e, "any string");
- testSetGetAsText(e, "");
- testSetGetAsText(e, "${var}");
- }
+ private void testSetGet(ComboStringEditor e, Object value) throws Exception {
+ e.setValue(value);
+ assertEquals(value, e.getValue());
+ }
+
+ private void testSetGetAsText(ComboStringEditor e, String text) throws Exception {
+ e.setAsText(text);
+ assertEquals(text, e.getAsText());
+ }
+
+ @Test
+ public void testSetGet() throws Exception {
+ @SuppressWarnings("deprecation") // test code, intentional
+ ComboStringEditor e = new ComboStringEditor();
+
+ testSetGet(e, "any string");
+ testSetGet(e, "");
+ testSetGet(e, "${var}");
+ }
+
+ @Test
+ public void testSetGetAsText() throws Exception {
+ @SuppressWarnings("deprecation") // test code, intentional
+ ComboStringEditor e = new ComboStringEditor();
+
+ testSetGetAsText(e, "any string");
+ testSetGetAsText(e, "");
+ testSetGetAsText(e, "${var}");
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/testelement/PackageTest.java b/src/core/src/test/java/org/apache/jmeter/testelement/PackageTest.java
index d49e3a7..9ad10b9 100644
--- a/src/core/src/test/java/org/apache/jmeter/testelement/PackageTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/testelement/PackageTest.java
@@ -69,6 +69,5 @@ public class PackageTest {
te.addTestElement(te2);
assertEquals(2, args.getArgumentCount());
assertEquals("config1=configValue", args.getArgument(1).toString());
-
}
}
diff --git a/src/core/src/test/java/org/apache/jmeter/testelement/TestNumberProperty.java b/src/core/src/test/java/org/apache/jmeter/testelement/TestNumberProperty.java
index cff283c..266dc77 100644
--- a/src/core/src/test/java/org/apache/jmeter/testelement/TestNumberProperty.java
+++ b/src/core/src/test/java/org/apache/jmeter/testelement/TestNumberProperty.java
@@ -18,6 +18,7 @@
package org.apache.jmeter.testelement;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.jmeter.testelement.property.DoubleProperty;
@@ -31,14 +32,14 @@ public class TestNumberProperty {
public void testDZeroCompareToDZero() {
NumberProperty n1 = new DoubleProperty("n1", 0.0);
NumberProperty n2 = new DoubleProperty("n2", 0.0);
- assertTrue(n1.compareTo(n2) == 0);
+ assertEquals(0, n1.compareTo(n2));
}
@Test
public void testIZeroCompareToDZero() {
NumberProperty n1 = new IntegerProperty("n1", 0);
NumberProperty n2 = new DoubleProperty("n2", 0.0);
- assertTrue(n1.compareTo(n2) == 0);
+ assertEquals(0, n1.compareTo(n2));
}
@Test
diff --git a/src/core/src/test/java/org/apache/jmeter/testelement/property/PackageTest.java b/src/core/src/test/java/org/apache/jmeter/testelement/property/PackageTest.java
index bef3b2c..d52ca6f 100644
--- a/src/core/src/test/java/org/apache/jmeter/testelement/property/PackageTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/testelement/property/PackageTest.java
@@ -25,12 +25,9 @@ import static org.junit.Assert.fail;
import org.apache.jmeter.config.LoginConfig;
import org.junit.Test;
-/**
- * Class for testing the property package.
- */
+/** Class for testing the property package. */
public class PackageTest {
-
@Test
public void testStringProperty() throws Exception {
StringProperty prop = new StringProperty("name", "value");
@@ -79,7 +76,6 @@ public class PackageTest {
assertEquals(jp1, jp1);
assertEquals(jp2, jp2);
assertEquals(jp1.hashCode(), jp2.hashCode());
-
}
private void checkNotEquals(JMeterProperty jp1, JMeterProperty jp2) {
@@ -311,8 +307,8 @@ public class PackageTest {
fail("Should have generated an Illegal Argument Exception");
} catch (IllegalArgumentException e) {
}
-
}
+
@Test
public void testAddingProperties() throws Exception {
CollectionProperty coll = new CollectionProperty();
diff --git a/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterContextService.java b/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterContextService.java
index d94314a..cf8f16c 100644
--- a/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterContextService.java
+++ b/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterContextService.java
@@ -44,6 +44,7 @@ public class TestJMeterContextService {
public static void incrNumberOfThreads(){
JMeterContextService.incrNumberOfThreads();
}
+
// Give access to the method for test code
public static void decrNumberOfThreads(){
JMeterContextService.decrNumberOfThreads();
diff --git a/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterThread.java b/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterThread.java
index 2e98c92..10ba7bf 100644
--- a/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterThread.java
+++ b/src/core/src/test/java/org/apache/jmeter/threads/TestJMeterThread.java
@@ -33,9 +33,6 @@ import org.apache.jmeter.timers.Timer;
import org.apache.jorphan.collections.HashTree;
import org.junit.Test;
-/**
- * Tests for {@link JMeterThread}
- */
public class TestJMeterThread {
private static final class DummySampler extends AbstractSampler {
@@ -91,7 +88,6 @@ public class TestJMeterThread {
}
private static class ThrowingThreadListener implements ThreadListener {
-
private boolean throwError;
public ThrowingThreadListener(boolean throwError) {
@@ -100,7 +96,7 @@ public class TestJMeterThread {
@Override
public void threadStarted() {
- if(throwError) {
+ if (throwError) {
throw new NoClassDefFoundError("Throw for Bug TestJMeterThread");
} else {
throw new RuntimeException("Throw for Bug TestJMeterThread");
@@ -109,7 +105,7 @@ public class TestJMeterThread {
@Override
public void threadFinished() {
- if(throwError) {
+ if (throwError) {
throw new NoClassDefFoundError("Throw for Bug TestJMeterThread");
} else {
throw new RuntimeException("Throw for Bug TestJMeterThread");
@@ -127,8 +123,8 @@ public class TestJMeterThread {
}
@Test
- public void testBug61661OnException(){
- HashTree hashTree =new HashTree();
+ public void testBug61661OnException() {
+ HashTree hashTree = new HashTree();
hashTree.add("Test", new ThrowingThreadListener(false));
JMeterThread.ThreadListenerTraverser traverser =
new JMeterThread.ThreadListenerTraverser(true);
@@ -137,7 +133,6 @@ public class TestJMeterThread {
@Test
public void testBug63490EndTestWhenDelayIsTooLongForScheduler() {
-
JMeterContextService.getContext().setVariables(new JMeterVariables());
HashTree testTree = new HashTree();
diff --git a/src/core/src/test/java/org/apache/jmeter/threads/TestTestCompiler.java b/src/core/src/test/java/org/apache/jmeter/threads/TestTestCompiler.java
index 2f8df57..20f91c6 100644
--- a/src/core/src/test/java/org/apache/jmeter/threads/TestTestCompiler.java
+++ b/src/core/src/test/java/org/apache/jmeter/threads/TestTestCompiler.java
@@ -29,36 +29,36 @@ import org.junit.Test;
public class TestTestCompiler {
- @Test
- public void testConfigGathering() throws Exception {
- ListedHashTree testing = new ListedHashTree();
- GenericController controller = new GenericController();
- ConfigTestElement config1 = new ConfigTestElement();
- config1.setName("config1");
- config1.setProperty("test.property", "A test value");
- TestSampler sampler = new TestSampler();
- sampler.setName("sampler");
- testing.add(controller, config1);
- testing.add(controller, sampler);
- TestCompiler.initialize();
+ @Test
+ public void testConfigGathering() throws Exception {
+ ListedHashTree testing = new ListedHashTree();
+ GenericController controller = new GenericController();
+ ConfigTestElement config1 = new ConfigTestElement();
+ config1.setName("config1");
+ config1.setProperty("test.property", "A test value");
+ TestSampler sampler = new TestSampler();
+ sampler.setName("sampler");
+ testing.add(controller, config1);
+ testing.add(controller, sampler);
+ TestCompiler.initialize();
- TestCompiler compiler = new TestCompiler(testing);
- testing.traverse(compiler);
- sampler = (TestSampler) compiler.configureSampler(sampler).getSampler();
- assertEquals("A test value", sampler.getPropertyAsString("test.property"));
- }
+ TestCompiler compiler = new TestCompiler(testing);
+ testing.traverse(compiler);
+ sampler = (TestSampler) compiler.configureSampler(sampler).getSampler();
+ assertEquals("A test value", sampler.getPropertyAsString("test.property"));
+ }
- class TestSampler extends AbstractSampler {
- private static final long serialVersionUID = 240L;
+ class TestSampler extends AbstractSampler {
+ private static final long serialVersionUID = 240L;
- @Override
- public SampleResult sample(org.apache.jmeter.samplers.Entry e) {
- return null;
- }
+ @Override
+ public SampleResult sample(org.apache.jmeter.samplers.Entry e) {
+ return null;
+ }
- @Override
- public Object clone() {
- return new TestSampler();
- }
+ @Override
+ public Object clone() {
+ return new TestSampler();
}
+ }
}
diff --git a/src/core/src/test/java/org/apache/jmeter/util/JMeterContextExtension.java b/src/core/src/test/java/org/apache/jmeter/util/JMeterContextExtension.java
index f68df7c..adca4cc 100644
--- a/src/core/src/test/java/org/apache/jmeter/util/JMeterContextExtension.java
+++ b/src/core/src/test/java/org/apache/jmeter/util/JMeterContextExtension.java
@@ -32,12 +32,14 @@ import org.junit.jupiter.api.extension.ParameterResolver;
* The extension starts and initializes {@link JMeterContext} before each test.
* The extension can inject {@link JMeterVariables} to a test method parameter.
*/
-public class JMeterContextExtension implements BeforeEachCallback, AfterEachCallback,
- ParameterResolver {
+public class JMeterContextExtension
+ implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
+
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Class<?> parameterType = parameterContext.getParameter().getType();
- return parameterType == JMeterContext.class || parameterType == JMeterVariables.class;
+ return parameterType == JMeterContext.class
+ || parameterType == JMeterVariables.class;
}
@Override
diff --git a/src/core/src/test/java/org/apache/jmeter/util/StringUtilitiesTest.java b/src/core/src/test/java/org/apache/jmeter/util/StringUtilitiesTest.java
index 783084e..a7bb47d 100644
--- a/src/core/src/test/java/org/apache/jmeter/util/StringUtilitiesTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/util/StringUtilitiesTest.java
@@ -25,7 +25,6 @@ import org.junit.Test;
public class StringUtilitiesTest {
-
@Test
public void testServer() throws Exception {
BeanShellServer bshs = new BeanShellServer(9876, "");
diff --git a/src/core/src/test/java/org/apache/jmeter/util/XPathUtilTest.java b/src/core/src/test/java/org/apache/jmeter/util/XPathUtilTest.java
index e927bcc..7d523ea 100644
--- a/src/core/src/test/java/org/apache/jmeter/util/XPathUtilTest.java
+++ b/src/core/src/test/java/org/apache/jmeter/util/XPathUtilTest.java
@@ -72,7 +72,6 @@ public class XPathUtilTest {
@Test
public void testputValuesForXPathInListUsingSaxon() throws SaxonApiException, FactoryConfigurationError{
-
String xPathQuery="//Employees/Employee/role";
ArrayList<String> matchStrings = new ArrayList<String>();
boolean fragment = false;
@@ -162,18 +161,17 @@ public class XPathUtilTest {
"")));
}
- @Test()
+ @Test
public void testFormatXmlInvalid() {
PrintStream origErr = System.err;
- // The parser will print an error, so let it go somewhere, where we will
- // not see it
+ // The parser will print an error, so let it go where we will not see it
System.setErr(null);
assertThat("No well formed xml here", CoreMatchers
.is(XPathUtil.formatXml("No well formed xml here")));
System.setErr(origErr);
}
- @Test()
+ @Test
public void testMakeDocument() throws ParserConfigurationException, SAXException, IOException, TidyException {
String responseData = "<book><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
Document testDoc = XPathUtil.makeDocument(
@@ -201,7 +199,7 @@ public class XPathUtilTest {
assertTrue("Should be an error", res.isError());
}
- @Test()
+ @Test
public void testMakeDocumentIsnegated()
throws ParserConfigurationException, SAXException, IOException, TidyException {
String responseData = "<book><preface>zero</preface><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
@@ -226,7 +224,7 @@ public class XPathUtilTest {
assertFalse("Should not be a failure", res.isFailure());
}
- @Test()
+ @Test
public void testGetNamespaces() throws XMLStreamException, FactoryConfigurationError {
String responseData = "<age:ag xmlns:age=\"http://www.w3.org/wgs84_pos#\">\n"
+ "<hd:head xmlns:hd=\"http://www.w3.org/wgs85_pos#\"><title>test</title></hd:head></age:ag>";
@@ -237,7 +235,7 @@ public class XPathUtilTest {
assertEquals("http://www.w3.org/wgs85_pos#", res.get(1)[1]);
}
- @Test()
+ @Test
public void testComputeAssertionResultUsingSaxon() throws SaxonApiException, FactoryConfigurationError {
//test xpath2 assertion
AssertionResult res = new AssertionResult("test");
@@ -262,7 +260,8 @@ public class XPathUtilTest {
assertFalse("Should not be an error", res.isError());
assertTrue("Should be a failure", res.isFailure());
}
- @Test()
+
+ @Test
public void testPutValuesForXPathInList() throws ParserConfigurationException, SAXException, IOException, TidyException, TransformerException {
String responseData = "<book><page>one</page><page>two</page><empty></empty><a><b></b></a></book>";
Document testDoc = XPathUtil.makeDocument(
diff --git a/src/core/src/test/java/org/apache/jorphan/reflect/TestFunctor.java b/src/core/src/test/java/org/apache/jorphan/reflect/TestFunctor.java
index 5b0009d..269e123 100644
--- a/src/core/src/test/java/org/apache/jorphan/reflect/TestFunctor.java
+++ b/src/core/src/test/java/org/apache/jorphan/reflect/TestFunctor.java
@@ -31,10 +31,7 @@ import org.apache.logging.log4j.core.config.Configurator;
import org.junit.Before;
import org.junit.Test;
-/*
- * Unit tests for classes that use Functors
- *
- */
+/** Unit tests for classes that use Functors */
public class TestFunctor extends JMeterTestCase {
interface HasName {
@@ -141,6 +138,7 @@ public class TestFunctor extends JMeterTestCase {
} catch (JMeterError ok){
}
}
+
@Test
public void testObjectName() throws Exception{
Test1 t1 = new Test1("t1");
@@ -217,6 +215,7 @@ public class TestFunctor extends JMeterTestCase {
fail("should have generated IllegalArgumentException;");
} catch (IllegalArgumentException ok){}
}
+
@Test
public void testIllegalState() throws Exception{
Functor f = new Functor("method");
diff --git a/src/dist-check/src/test/java/org/apache/jmeter/control/TestSwitchController.java b/src/dist-check/src/test/java/org/apache/jmeter/control/TestSwitchController.java
index b7d6d2b..3bfbf35 100644
--- a/src/dist-check/src/test/java/org/apache/jmeter/control/TestSwitchController.java
+++ b/src/dist-check/src/test/java/org/apache/jmeter/control/TestSwitchController.java
@@ -38,269 +38,269 @@ import org.junit.Test;
public class TestSwitchController extends JMeterTestCase {
- // Get next sample and its name
- private String nextName(GenericController c) {
- Sampler s = c.next();
- String n;
- if (s == null) {
- return null;
- }
- n = s.getName();
- return n;
- }
-
- @Test
- public void test() throws Exception {
- runSimpleTests("", "zero");
+ // Get next sample and its name
+ private String nextName(GenericController c) {
+ Sampler s = c.next();
+ String n;
+ if (s == null) {
+ return null;
}
-
- @Test
- public void test0() throws Exception {
- runSimpleTests("0", "zero");
+ n = s.getName();
+ return n;
+ }
+
+ @Test
+ public void test() throws Exception {
+ runSimpleTests("", "zero");
+ }
+
+ @Test
+ public void test0() throws Exception {
+ runSimpleTests("0", "zero");
+ }
+
+ @Test
+ public void test1() throws Exception {
+ runSimpleTests("1", "one");
+ runSimpleTests(" 1 ", "one");
+ runSimpleTests("one", "one"); // Match by name
+ runSimpleTests("one ", "one"); // Match by name with space
+ }
+
+ @Test
+ public void test2() throws Exception {
+ runSimpleTests("2", "two");
+ runSimpleTests("two", "two"); // Match by name
+ }
+
+ @Test
+ public void test3() throws Exception {
+ runSimpleTests("3", "three");
+ runSimpleTests("three", "three"); // Match by name
+ }
+
+ @Test
+ public void test4() throws Exception {
+ runSimpleTests("4", "zero");
+ }
+
+ @Test
+ public void testX() throws Exception {
+ runSimpleTests("X", null); // should not run any children
+ runSimpleTest2("X", "one", "Default"); // should match the default entry
+ }
+
+ private void runSimpleTests(String cond, String exp) throws Exception {
+ runSimpleTest(cond, exp);
+ runSimpleTest2(cond, exp, "one");
+ }
+
+ /*
+ * Simple test with single Selection controller
+ * Generic Controller
+ * + Sampler "before"
+ * + Switch Controller
+ * + + Sampler "zero"
+ * + + Sampler "one"
+ * + + Sampler "two"
+ * + + Sampler "three"
+ * + Sampler "after"
+ */
+ private void runSimpleTest(String cond, String exp) throws Exception {
+ GenericController controller = new GenericController();
+
+ SwitchController switch_cont = new SwitchController();
+ switch_cont.setSelection(cond);
+
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(switch_cont);
+
+ switch_cont.addTestElement(new TestSampler("zero"));
+ switch_cont.addTestElement(new TestSampler("one"));
+ switch_cont.addTestElement(new TestSampler("two"));
+ switch_cont.addTestElement(new TestSampler("three"));
+
+ controller.addTestElement(new TestSampler("after"));
+
+ controller.initialize();
+
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop " + i, "before", nextName(controller));
+ if (exp != null) {
+ assertEquals("Loop " + i, exp, nextName(controller));
+ }
+ assertEquals("Loop " + i, "after", nextName(controller));
+ assertNull(nextName(controller));
}
-
- @Test
- public void test1() throws Exception {
- runSimpleTests("1", "one");
- runSimpleTests(" 1 ", "one");
- runSimpleTests("one", "one"); // Match by name
- runSimpleTests("one ", "one"); // Match by name with space
+ }
+
+ // Selection controller with two sub-controllers, but each has only 1
+ // child
+ /*
+ * Controller
+ * + Before
+ * + Switch (cond)
+ * + + zero
+ * + + Controller sub_1
+ * + + + one
+ * + + two
+ * + + Controller sub_2
+ * + + + three
+ * + After
+ */
+ private void runSimpleTest2(String cond, String exp, String sub1Name) throws Exception {
+ GenericController controller = new GenericController();
+ GenericController sub_1 = new GenericController();
+ GenericController sub_2 = new GenericController();
+
+ SwitchController switch_cont = new SwitchController();
+ switch_cont.setSelection(cond);
+
+ switch_cont.addTestElement(new TestSampler("zero"));
+ switch_cont.addTestElement(sub_1);
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.setName(sub1Name);
+
+ switch_cont.addTestElement(new TestSampler("two"));
+
+ switch_cont.addTestElement(sub_2);
+ sub_2.addTestElement(new TestSampler("three"));
+ sub_2.setName("three");
+
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(switch_cont);
+ controller.addTestElement(new TestSampler("after"));
+ controller.initialize();
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop=" + i, "before", nextName(controller));
+ if (exp != null) {
+ assertEquals("Loop=" + i, exp, nextName(controller));
+ }
+ assertEquals("Loop=" + i, "after", nextName(controller));
+ assertNull("Loop=" + i, nextName(controller));
}
-
- @Test
- public void test2() throws Exception {
- runSimpleTests("2", "two");
- runSimpleTests("two", "two"); // Match by name
+ }
+
+ @Test
+ public void testTest2() throws Exception {
+ runTest2("", new String[]{"zero"});
+ runTest2("0", new String[]{"zero"});
+ runTest2("7", new String[]{"zero"});
+ runTest2("5", new String[]{"zero"});
+ runTest2("4", new String[]{"six"});
+ runTest2("4 ", new String[]{"six"});
+ runTest2("3", new String[]{"five"});
+ runTest2("1", new String[]{"one", "two"});
+ runTest2("2", new String[]{"three", "four"});
+ }
+
+ /*
+ * Test:
+ * Before
+ * Selection Controller
+ * - zero (default)
+ * - simple controller 1
+ * - - one
+ * - - two
+ * - simple controller 2
+ * - - three
+ * - - four
+ * - five
+ * - six
+ * After
+ *
+ * cond = Switch condition
+ * exp[] = expected results
+ */
+ private void runTest2(String cond, String[] exp) throws Exception {
+ int loops = 3;
+ LoopController controller = new LoopController();
+ controller.setLoops(loops);
+ controller.setContinueForever(false);
+ GenericController sub_1 = new GenericController();
+ GenericController sub_2 = new GenericController();
+
+ SwitchController switch_cont = new SwitchController();
+ switch_cont.setSelection(cond);
+
+ switch_cont.addTestElement(new TestSampler("zero"));
+ switch_cont.addTestElement(sub_1);
+ sub_1.addTestElement(new TestSampler("one"));
+ sub_1.addTestElement(new TestSampler("two"));
+
+ switch_cont.addTestElement(sub_2);
+ sub_2.addTestElement(new TestSampler("three"));
+ sub_2.addTestElement(new TestSampler("four"));
+
+ switch_cont.addTestElement(new TestSampler("five"));
+ switch_cont.addTestElement(new TestSampler("six"));
+
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(switch_cont);
+ controller.addTestElement(new TestSampler("after"));
+ controller.setRunningVersion(true);
+ sub_1.setRunningVersion(true);
+ sub_2.setRunningVersion(true);
+ switch_cont.setRunningVersion(true);
+ controller.initialize();
+ for (int i = 1; i <= 3; i++) {
+ assertEquals("Loop:" + i, "before", nextName(controller));
+ for (String anExp : exp) {
+ assertEquals("Loop:" + i, anExp, nextName(controller));
+ }
+ assertEquals("Loop:" + i, "after", nextName(controller));
}
+ assertNull("Loops:" + loops, nextName(controller));
+ }
- @Test
- public void test3() throws Exception {
- runSimpleTests("3", "three");
- runSimpleTests("three", "three"); // Match by name
- }
+ /*
+ * N.B. Requires ApacheJMeter_functions.jar to be on the classpath,
+ * otherwise the function cannot be resolved.
+ */
+ @Test
+ public void testFunction() throws Exception {
+ JMeterContext jmctx = JMeterContextService.getContext();
+ Map<String, String> variables = new HashMap<>();
+ ReplaceStringWithFunctions transformer = new ReplaceStringWithFunctions(new CompoundVariable(), variables);
+ jmctx.setVariables(new JMeterVariables());
+ JMeterVariables jmvars = jmctx.getVariables();
+ jmvars.put("VAR", "100");
+ StringProperty prop = new StringProperty(SwitchController.SWITCH_VALUE, "${__counter(TRUE,VAR)}");
+ JMeterProperty newProp = transformer.transformValue(prop);
+ newProp.setRunningVersion(true);
- @Test
- public void test4() throws Exception {
- runSimpleTests("4", "zero");
- }
+ GenericController controller = new GenericController();
- @Test
- public void testX() throws Exception {
- runSimpleTests("X", null); // should not run any children
- runSimpleTest2("X", "one", "Default"); // should match the default entry
- }
+ SwitchController switch_cont = new SwitchController();
+ switch_cont.setProperty(newProp);
- private void runSimpleTests(String cond, String exp) throws Exception {
- runSimpleTest(cond, exp);
- runSimpleTest2(cond, exp, "one");
- }
+ controller.addTestElement(new TestSampler("before"));
+ controller.addTestElement(switch_cont);
- /*
- * Simple test with single Selection controller
- * Generic Controller
- * + Sampler "before"
- * + Switch Controller
- * + + Sampler "zero"
- * + + Sampler "one"
- * + + Sampler "two"
- * + + Sampler "three"
- * + Sampler "after"
- */
- private void runSimpleTest(String cond, String exp) throws Exception {
- GenericController controller = new GenericController();
-
- SwitchController switch_cont = new SwitchController();
- switch_cont.setSelection(cond);
-
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(switch_cont);
-
- switch_cont.addTestElement(new TestSampler("zero"));
- switch_cont.addTestElement(new TestSampler("one"));
- switch_cont.addTestElement(new TestSampler("two"));
- switch_cont.addTestElement(new TestSampler("three"));
-
- controller.addTestElement(new TestSampler("after"));
-
- controller.initialize();
-
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop " + i, "before", nextName(controller));
- if (exp!=null){
- assertEquals("Loop " + i, exp, nextName(controller));
- }
- assertEquals("Loop " + i, "after", nextName(controller));
- assertNull(nextName(controller));
- }
- }
+ switch_cont.addTestElement(new TestSampler("0"));
+ switch_cont.addTestElement(new TestSampler("1"));
+ switch_cont.addTestElement(new TestSampler("2"));
+ switch_cont.addTestElement(new TestSampler("3"));
- // Selection controller with two sub-controllers, but each has only 1
- // child
- /*
- * Controller
- * + Before
- * + Switch (cond)
- * + + zero
- * + + Controller sub_1
- * + + + one
- * + + two
- * + + Controller sub_2
- * + + + three
- * + After
- */
- private void runSimpleTest2(String cond, String exp, String sub1Name) throws Exception {
- GenericController controller = new GenericController();
- GenericController sub_1 = new GenericController();
- GenericController sub_2 = new GenericController();
-
- SwitchController switch_cont = new SwitchController();
- switch_cont.setSelection(cond);
-
- switch_cont.addTestElement(new TestSampler("zero"));
- switch_cont.addTestElement(sub_1);
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.setName(sub1Name);
-
- switch_cont.addTestElement(new TestSampler("two"));
-
- switch_cont.addTestElement(sub_2);
- sub_2.addTestElement(new TestSampler("three"));
- sub_2.setName("three");
-
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(switch_cont);
- controller.addTestElement(new TestSampler("after"));
- controller.initialize();
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop="+i,"before", nextName(controller));
- if (exp!=null){
- assertEquals("Loop="+i,exp, nextName(controller));
- }
- assertEquals("Loop="+i,"after", nextName(controller));
- assertNull("Loop="+i,nextName(controller));
- }
- }
+ controller.addTestElement(new TestSampler("after"));
- @Test
- public void testTest2() throws Exception {
- runTest2("", new String[] { "zero" });
- runTest2("0", new String[] { "zero" });
- runTest2("7", new String[] { "zero" });
- runTest2("5", new String[] { "zero" });
- runTest2("4", new String[] { "six" });
- runTest2("4 ", new String[] { "six" });
- runTest2("3", new String[] { "five" });
- runTest2("1", new String[] { "one", "two" });
- runTest2("2", new String[] { "three", "four" });
- }
+ controller.initialize();
- /*
- * Test:
- * Before
- * Selection Controller
- * - zero (default)
- * - simple controller 1
- * - - one
- * - - two
- * - simple controller 2
- * - - three
- * - - four
- * - five
- * - six
- * After
- *
- * cond = Switch condition
- * exp[] = expected results
- */
- private void runTest2(String cond, String[] exp) throws Exception {
- int loops = 3;
- LoopController controller = new LoopController();
- controller.setLoops(loops);
- controller.setContinueForever(false);
- GenericController sub_1 = new GenericController();
- GenericController sub_2 = new GenericController();
-
- SwitchController switch_cont = new SwitchController();
- switch_cont.setSelection(cond);
-
- switch_cont.addTestElement(new TestSampler("zero"));
- switch_cont.addTestElement(sub_1);
- sub_1.addTestElement(new TestSampler("one"));
- sub_1.addTestElement(new TestSampler("two"));
-
- switch_cont.addTestElement(sub_2);
- sub_2.addTestElement(new TestSampler("three"));
- sub_2.addTestElement(new TestSampler("four"));
-
- switch_cont.addTestElement(new TestSampler("five"));
- switch_cont.addTestElement(new TestSampler("six"));
-
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(switch_cont);
- controller.addTestElement(new TestSampler("after"));
- controller.setRunningVersion(true);
- sub_1.setRunningVersion(true);
- sub_2.setRunningVersion(true);
- switch_cont.setRunningVersion(true);
- controller.initialize();
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop:" + i, "before", nextName(controller));
- for (String anExp : exp) {
- assertEquals("Loop:" + i, anExp, nextName(controller));
- }
- assertEquals("Loop:" + i, "after", nextName(controller));
- }
- assertNull("Loops:" + loops, nextName(controller));
- }
+ assertEquals("100", jmvars.get("VAR"));
- /*
- * N.B. Requires ApacheJMeter_functions.jar to be on the classpath,
- * otherwise the function cannot be resolved.
- */
- @Test
- public void testFunction() throws Exception {
- JMeterContext jmctx = JMeterContextService.getContext();
- Map<String, String> variables = new HashMap<>();
- ReplaceStringWithFunctions transformer = new ReplaceStringWithFunctions(new CompoundVariable(), variables);
- jmctx.setVariables(new JMeterVariables());
- JMeterVariables jmvars = jmctx.getVariables();
- jmvars.put("VAR", "100");
- StringProperty prop = new StringProperty(SwitchController.SWITCH_VALUE,"${__counter(TRUE,VAR)}");
- JMeterProperty newProp = transformer.transformValue(prop);
- newProp.setRunningVersion(true);
-
- GenericController controller = new GenericController();
-
- SwitchController switch_cont = new SwitchController();
- switch_cont.setProperty(newProp);
-
- controller.addTestElement(new TestSampler("before"));
- controller.addTestElement(switch_cont);
-
- switch_cont.addTestElement(new TestSampler("0"));
- switch_cont.addTestElement(new TestSampler("1"));
- switch_cont.addTestElement(new TestSampler("2"));
- switch_cont.addTestElement(new TestSampler("3"));
-
- controller.addTestElement(new TestSampler("after"));
-
- controller.initialize();
-
- assertEquals("100",jmvars.get("VAR"));
-
- for (int i = 1; i <= 3; i++) {
- assertEquals("Loop " + i, "before", nextName(controller));
- assertEquals("Loop " + i, ""+i, nextName(controller));
- assertEquals("Loop " + i, ""+i, jmvars.get("VAR"));
- assertEquals("Loop " + i, "after", nextName(controller));
- assertNull(nextName(controller));
- }
- int i = 4;
+ for (int i = 1; i <= 3; i++) {
assertEquals("Loop " + i, "before", nextName(controller));
- assertEquals("Loop " + i, "0", nextName(controller));
- assertEquals("Loop " + i, ""+i, jmvars.get("VAR"));
+ assertEquals("Loop " + i, "" + i, nextName(controller));
+ assertEquals("Loop " + i, "" + i, jmvars.get("VAR"));
assertEquals("Loop " + i, "after", nextName(controller));
assertNull(nextName(controller));
- assertEquals("4",jmvars.get("VAR"));
}
+ int i = 4;
+ assertEquals("Loop " + i, "before", nextName(controller));
+ assertEquals("Loop " + i, "0", nextName(controller));
+ assertEquals("Loop " + i, "" + i, jmvars.get("VAR"));
+ assertEquals("Loop " + i, "after", nextName(controller));
+ assertNull(nextName(controller));
+ assertEquals("4", jmvars.get("VAR"));
+ }
}
diff --git a/src/dist-check/src/test/java/org/apache/jmeter/resources/TestPropertiesFiles.java b/src/dist-check/src/test/java/org/apache/jmeter/resources/TestPropertiesFiles.java
index 861d939..b03e78c 100644
--- a/src/dist-check/src/test/java/org/apache/jmeter/resources/TestPropertiesFiles.java
+++ b/src/dist-check/src/test/java/org/apache/jmeter/resources/TestPropertiesFiles.java
@@ -32,7 +32,6 @@ import org.junit.Test;
public class TestPropertiesFiles extends JMeterTestCase {
-
@Test
public void testUserProperties() throws Exception {
Properties props = loadProps(new File(JMeterUtils.getJMeterBinDir(), "user.properties"));
diff --git a/src/dist-check/src/test/java/org/apache/jorphan/TestFunctorUsers.java b/src/dist-check/src/test/java/org/apache/jorphan/TestFunctorUsers.java
index ff16742..b7d9550 100644
--- a/src/dist-check/src/test/java/org/apache/jorphan/TestFunctorUsers.java
+++ b/src/dist-check/src/test/java/org/apache/jorphan/TestFunctorUsers.java
@@ -30,46 +30,43 @@ import org.apache.jmeter.visualizers.SummaryReport;
import org.apache.jmeter.visualizers.TableVisualizer;
import org.junit.Test;
-/*
- * Unit tests for classes that use Functors
- *
- */
+/** Unit tests for classes that use Functors */
public class TestFunctorUsers extends JMeterTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testSummaryReport() throws Exception{
- assertTrue("SummaryReport Functor",SummaryReport.testFunctors());
+ public void testSummaryReport() throws Exception {
+ assertTrue("SummaryReport Functor", SummaryReport.testFunctors());
}
@Test
- public void testTableVisualizer() throws Exception{
- assertTrue("TableVisualizer Functor",TableVisualizer.testFunctors());
+ public void testTableVisualizer() throws Exception {
+ assertTrue("TableVisualizer Functor", TableVisualizer.testFunctors());
}
@Test
- public void testStatGraphVisualizer() throws Exception{
- assertTrue("StatGraphVisualizer Functor",StatGraphVisualizer.testFunctors());
+ public void testStatGraphVisualizer() throws Exception {
+ assertTrue("StatGraphVisualizer Functor", StatGraphVisualizer.testFunctors());
}
@Test
@SuppressWarnings("deprecation")
- public void testStatVisualizer() throws Exception{
- assertTrue("StatVisualizer Functor",StatVisualizer.testFunctors());
+ public void testStatVisualizer() throws Exception {
+ assertTrue("StatVisualizer Functor", StatVisualizer.testFunctors());
}
@Test
- public void testArgumentsPanel() throws Exception{
- assertTrue("ArgumentsPanel Functor",ArgumentsPanel.testFunctors());
+ public void testArgumentsPanel() throws Exception {
+ assertTrue("ArgumentsPanel Functor", ArgumentsPanel.testFunctors());
}
@Test
- public void testHTTPArgumentsPanel() throws Exception{
- assertTrue("HTTPArgumentsPanel Functor",HTTPArgumentsPanel.testFunctors());
+ public void testHTTPArgumentsPanel() throws Exception {
+ assertTrue("HTTPArgumentsPanel Functor", HTTPArgumentsPanel.testFunctors());
}
@Test
- public void testLDAPArgumentsPanel() throws Exception{
- assertTrue("LDAPArgumentsPanel Functor",LDAPArgumentsPanel.testFunctors());
+ public void testLDAPArgumentsPanel() throws Exception {
+ assertTrue("LDAPArgumentsPanel Functor", LDAPArgumentsPanel.testFunctors());
}
}
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/EvalFunctionTest.java b/src/functions/src/test/java/org/apache/jmeter/functions/EvalFunctionTest.java
index bd0158b..c3c893f 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/EvalFunctionTest.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/EvalFunctionTest.java
@@ -56,7 +56,6 @@ public class EvalFunctionTest extends JMeterTestCase {
eval.setParameters(parms);
s = eval.execute(null,null);
assertEquals("select name from customers",s);
-
}
@Test
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/StringFromFileFunctionTest.java b/src/functions/src/test/java/org/apache/jmeter/functions/StringFromFileFunctionTest.java
index 6382c29..3e9c2a4 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/StringFromFileFunctionTest.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/StringFromFileFunctionTest.java
@@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class StringFromFileFunctionTest {
- public static Path dir;
+ private static Path dir;
@BeforeAll
public static void init(@TempDir Path tempDir) throws IOException {
@@ -144,7 +144,7 @@ public class StringFromFileFunctionTest {
}
// Create the StringFromFile function and set its parameters.
- private StringFromFile createSFF(Object...params) throws Exception {
+ private StringFromFile createSFF(Object... params) throws Exception {
StringFromFile sff = new StringFromFile();
sff.setParameters(FunctionTestHelper.makeParams(params));
return sff;
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestChangeCase.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestChangeCase.java
index fcd711a..1ee38cb 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestChangeCase.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestChangeCase.java
@@ -34,12 +34,6 @@ import org.apache.jmeter.threads.JMeterVariables;
import org.junit.Before;
import org.junit.Test;
-/**
- * Test{@link ChangeCase} ChangeCase
- *
- * @see ChangeCase
- * @since 4.0
- */
public class TestChangeCase extends JMeterTestCase {
private AbstractFunction changeCase;
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestDateTimeConvertFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestDateTimeConvertFunction.java
index c4b617f..084b432 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestDateTimeConvertFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestDateTimeConvertFunction.java
@@ -37,18 +37,13 @@ import org.junit.Test;
/**
* Test {@link DateTimeConvertFunction}
* We implement JMeterSerialTest as we change TimeZone
- * @since 4.0
*/
public class TestDateTimeConvertFunction extends JMeterTestCase implements JMeterSerialTest {
- protected AbstractFunction dateConvert;
-
+ private AbstractFunction dateConvert;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestDigestFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestDigestFunction.java
index 69f88f5..325c384 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestDigestFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestDigestFunction.java
@@ -31,21 +31,13 @@ import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.junit.Before;
import org.junit.Test;
-/**
- * Test Digest function
- * @see DigestEncodeFunction
- * @since 4.0
- *
- */
+
public class TestDigestFunction extends JMeterTestCase {
- protected AbstractFunction digest;
+ private AbstractFunction digest;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
@@ -61,7 +53,6 @@ public class TestDigestFunction extends JMeterTestCase {
params = new LinkedList<>();
}
-
@Test
public void testParameterCount512() throws Exception {
checkInvalidParameterCounts(digest, 2, 5);
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestEscapeOroRegexpChars.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestEscapeOroRegexpChars.java
index 97924c7..55cd7dc 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestEscapeOroRegexpChars.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestEscapeOroRegexpChars.java
@@ -33,14 +33,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestEscapeOroRegexpChars extends JMeterTestCase {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestFileRowColContainer.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestFileRowColContainer.java
index daa0466..6769ec98 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestFileRowColContainer.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestFileRowColContainer.java
@@ -70,7 +70,6 @@ public class TestFileRowColContainer extends JMeterTestCase implements JMeterSer
assertEquals(2, f.nextRow());
assertEquals(3, f.nextRow());
assertEquals(0, f.nextRow());
-
}
@Test
@@ -84,7 +83,6 @@ public class TestFileRowColContainer extends JMeterTestCase implements JMeterSer
assertEquals(2, f.nextRow());
assertEquals(3, f.nextRow());
assertEquals(0, f.nextRow());
-
}
@Test
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestFileToString.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestFileToString.java
index dbb3210..9043d66 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestFileToString.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestFileToString.java
@@ -36,14 +36,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestFileToString extends JMeterTestCase {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestGroovyFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestGroovyFunction.java
index 1212187..204b52c 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestGroovyFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestGroovyFunction.java
@@ -36,14 +36,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestGroovyFunction extends JMeterTestCase implements JMeterSerialTest {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@After
@@ -104,7 +101,7 @@ public class TestGroovyFunction extends JMeterTestCase implements JMeterSerialTe
function.setParameters(params);
String ret = function.execute(result, null);
assertEquals("/query.cgi?s1=1&s2=2&s3=3", ret);
- assertEquals(ret,vars.getObject("URL"));
+ assertEquals(ret, vars.getObject("URL"));
}
@Test
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestIsPropDefined.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestIsPropDefined.java
index 9e84f81..242bc31 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestIsPropDefined.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestIsPropDefined.java
@@ -32,22 +32,12 @@ import org.apache.jmeter.threads.JMeterVariables;
import org.junit.Before;
import org.junit.Test;
-/**
- *
- * Test {@link IsPropDefined} Function
- *
- * @see IsPropDefined
- *
- */
public class TestIsPropDefined extends JMeterTestCase {
- protected AbstractFunction isPropDefined;
+ private AbstractFunction isPropDefined;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestIsVarDefined.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestIsVarDefined.java
index 5745879..d5da3f5 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestIsVarDefined.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestIsVarDefined.java
@@ -32,22 +32,12 @@ import org.apache.jmeter.threads.JMeterVariables;
import org.junit.Before;
import org.junit.Test;
-/**
- *
- * Test {@link IsVarDefined} Function
- *
- * @see IsVarDefined
- *
- */
public class TestIsVarDefined extends JMeterTestCase {
- protected AbstractFunction isVarDefined;
+ private AbstractFunction isVarDefined;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunction.java
index 4ceb2a6..4fdd127 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunction.java
@@ -35,14 +35,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestJavascriptFunction extends JMeterTestCase {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@After
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunctionWithRhino.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunctionWithRhino.java
index b12c5b5..e0ad13b 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunctionWithRhino.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestJavascriptFunctionWithRhino.java
@@ -22,11 +22,9 @@ import org.apache.jmeter.util.JMeterUtils;
import org.junit.After;
import org.junit.Before;
-/**
- * Test JavaScript function with Rhino engine
- *
- */
+/** Test JavaScript function with Rhino engine */
public class TestJavascriptFunctionWithRhino extends TestJavascriptFunction {
+
@Before
public void setUp() {
JMeterUtils.getJMeterProperties().put("javascript.use_rhino", "true");
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestJexl2Function.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestJexl2Function.java
index 6479043..c7f3caf 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestJexl2Function.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestJexl2Function.java
@@ -33,14 +33,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestJexl2Function extends JMeterTestCase {
- protected AbstractFunction function;
+ protected AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestMachineIPName.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestMachineIPName.java
index e617c72..02d0ab3 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestMachineIPName.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestMachineIPName.java
@@ -34,14 +34,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestMachineIPName extends JMeterTestCase {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
@@ -89,7 +86,6 @@ public class TestMachineIPName extends JMeterTestCase {
function.setParameters(params);
String ret = function.execute(result, null);
assertEquals(JMeterUtils.getLocalHostIP(), ret);
-
}
@Test
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestRandomFromMultipleVars.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestRandomFromMultipleVars.java
index 2373330..8bc11c8 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestRandomFromMultipleVars.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestRandomFromMultipleVars.java
@@ -35,14 +35,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestRandomFromMultipleVars extends JMeterTestCase {
- private SampleResult result;
+ private SampleResult result;
private AbstractFunction function;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestRegexFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestRegexFunction.java
index 4f870cf..dabf700 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestRegexFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestRegexFunction.java
@@ -34,390 +34,386 @@ import org.junit.Before;
import org.junit.Test;
public class TestRegexFunction extends JMeterTestCase {
- private static final String INPUT_VARIABLE_NAME = "INVAR";
- private RegexFunction variable;
-
- private SampleResult result;
-
- private Collection<CompoundVariable> params;
-
- private JMeterVariables vars;
-
- private JMeterContext jmctx;
-
- @Before
- public void setUp() {
- variable = new RegexFunction();
- result = new SampleResult();
- jmctx = JMeterContextService.getContext();
- String data = "<company-xmlext-query-ret><row>" + "<value field=\"RetCode\">" + "LIS_OK</value><value"
- + " field=\"RetCodeExtension\"></value>" + "<value field=\"alias\"></value><value"
- + " field=\"positioncount\"></value>" + "<value field=\"invalidpincount\">0</value><value"
- + " field=\"pinposition1\">1</value><value" + " field=\"pinpositionvalue1\"></value><value"
- + " field=\"pinposition2\">5</value><value" + " field=\"pinpositionvalue2\"></value><value"
- + " field=\"pinposition3\">6</value><value" + " field=\"pinpositionvalue3\"></value>"
- + "</row></company-xmlext-query-ret>";
- result.setResponseData(data, null);
- vars = new JMeterVariables();
- String data2 = "The quick brown fox jumped over the lazy dog 123 times";
- vars.put(INPUT_VARIABLE_NAME, data2);
- jmctx.setVariables(vars);
- jmctx.setPreviousResult(result);
- }
-
- @Test
- public void testVariableExtraction() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$"));
- params.add(new CompoundVariable("2"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("5", match);
- }
-
- // Test with output variable name
- @Test
- public void testVariableExtraction1a() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$")); // template
- params.add(new CompoundVariable("2")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("3", vars.getObject("OUTVAR_matchNr"));
- assertEquals("5", match);
- assertEquals("5", vars.getObject("OUTVAR"));
- assertEquals("<value field=\"pinposition2\">5</value>", vars.getObject("OUTVAR_g0"));
- assertEquals("pinposition2", vars.getObject("OUTVAR_g1"));
- assertEquals("5", vars.getObject("OUTVAR_g2"));
- }
-
- // Test with empty output variable name
- @Test
- public void testVariableExtraction1b() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$")); // template
- params.add(new CompoundVariable("2")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable(""));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("5", match);
- assertNull(vars.getObject("OUTVAR"));
- }
-
- @Test
- public void testVariableExtractionFromVariable() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("$2$")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("times", match);
- assertEquals("times", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable2() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("$1$$2$")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("123times", match);
- assertEquals("123times", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable3() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("pre$2$post")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("pretimespost", match);
- assertEquals("pretimespost", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable4() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("pre$2$")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("pretimes", match);
- assertEquals("pretimes", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable5() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("$2$post")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("timespost", match);
- assertEquals("timespost", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable6() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("$2$$2$")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("timestimes", match);
- assertEquals("timestimes", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable7() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("pre$1$mid$2$post")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("pre123midtimespost", match);
- assertEquals("pre123midtimespost", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable8() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("pre$1$mid$2$")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("pre123midtimes", match);
- assertEquals("pre123midtimes", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtractionFromVariable9() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
- params.add(new CompoundVariable("$1$mid$2$post")); // template
- params.add(new CompoundVariable("1")); // match number
- params.add(new CompoundVariable("-")); // ALL separator
- params.add(new CompoundVariable("default"));
- params.add(new CompoundVariable("OUTVAR"));
- params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1", vars.getObject("OUTVAR_matchNr"));
- assertEquals("123midtimespost", match);
- assertEquals("123midtimespost", vars.getObject("OUTVAR"));
- assertEquals("123 times", vars.getObject("OUTVAR_g0"));
- assertEquals("123", vars.getObject("OUTVAR_g1"));
- assertEquals("times", vars.getObject("OUTVAR_g2"));
- }
-
- @Test
- public void testVariableExtraction2() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$1$"));
- params.add(new CompoundVariable("3"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("pinposition3", match);
- }
-
- @Test
- public void testVariableExtraction5() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$1$"));
- params.add(new CompoundVariable("ALL"));
- params.add(new CompoundVariable("_"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("pinposition1_pinposition2_pinposition3", match);
- }
-
- @Test
- public void testVariableExtraction6() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$"));
- params.add(new CompoundVariable("4"));
- params.add(new CompoundVariable(""));
- params.add(new CompoundVariable("default"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("default", match);
- }
-
- @Test
- public void testComma() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value,? field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$1$"));
- params.add(new CompoundVariable("3"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("pinposition3", match);
- }
-
- @Test
- public void testVariableExtraction3() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("_$1$"));
- params.add(new CompoundVariable("2"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("_pinposition2", match);
- }
-
- @Test
- public void testExtractionIndexTooHigh() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("_$1$"));
- params.add(new CompoundVariable("10"));
- params.add(new CompoundVariable(""));
- params.add(new CompoundVariable("No Value Found"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("No Value Found", match);
- }
-
- @Test
- public void testRandomExtraction() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<company-xmlext-query-ret>(.+?)</company-xmlext-query-ret>"));
- params.add(new CompoundVariable("$1$"));
- params.add(new CompoundVariable("RAND"));
- params.add(new CompoundVariable(""));
- params.add(new CompoundVariable("No Value Found"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("<row>" + "<value field=\"RetCode\">" + "LIS_OK</value><value"
- + " field=\"RetCodeExtension\"></value>" + "<value field=\"alias\"></value><value"
- + " field=\"positioncount\"></value>" + "<value field=\"invalidpincount\">0</value><value"
- + " field=\"pinposition1\">1</value><value" + " field=\"pinpositionvalue1\"></value><value"
- + " field=\"pinposition2\">5</value><value" + " field=\"pinpositionvalue2\"></value><value"
- + " field=\"pinposition3\">6</value><value" + " field=\"pinpositionvalue3\"></value>"
- + "</row>", match);
- }
-
-
- @Test(expected=NumberFormatException.class)
- public void testExtractionIndexNotNumeric() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("_$1$"));
- params.add(new CompoundVariable("0.333a"));
- params.add(new CompoundVariable(""));
- params.add(new CompoundVariable("No Value Found"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("No Value Found", match);
- }
-
- @Test
- public void testVariableExtraction4() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$, "));
- params.add(new CompoundVariable(".333"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("1, ", match);
- }
-
- @Test
- public void testDefaultValue() throws Exception {
- params = new LinkedList<>();
- params.add(new CompoundVariable("<value,, field=\"(pinposition\\d+)\">(\\d+)</value>"));
- params.add(new CompoundVariable("$2$, "));
- params.add(new CompoundVariable(".333"));
- params.add(new CompoundVariable(""));
- params.add(new CompoundVariable("No Value Found"));
- variable.setParameters(params);
- String match = variable.execute(result, null);
- assertEquals("No Value Found", match);
- }
+ private static final String INPUT_VARIABLE_NAME = "INVAR";
+
+ private RegexFunction variable;
+ private SampleResult result;
+ private Collection<CompoundVariable> params;
+ private JMeterVariables vars;
+ private JMeterContext jmctx;
+
+ @Before
+ public void setUp() {
+ variable = new RegexFunction();
+ result = new SampleResult();
+ jmctx = JMeterContextService.getContext();
+ String data = "<company-xmlext-query-ret><row>" + "<value field=\"RetCode\">" + "LIS_OK</value><value"
+ + " field=\"RetCodeExtension\"></value>" + "<value field=\"alias\"></value><value"
+ + " field=\"positioncount\"></value>" + "<value field=\"invalidpincount\">0</value><value"
+ + " field=\"pinposition1\">1</value><value" + " field=\"pinpositionvalue1\"></value><value"
+ + " field=\"pinposition2\">5</value><value" + " field=\"pinpositionvalue2\"></value><value"
+ + " field=\"pinposition3\">6</value><value" + " field=\"pinpositionvalue3\"></value>"
+ + "</row></company-xmlext-query-ret>";
+ result.setResponseData(data, null);
+ vars = new JMeterVariables();
+ String data2 = "The quick brown fox jumped over the lazy dog 123 times";
+ vars.put(INPUT_VARIABLE_NAME, data2);
+ jmctx.setVariables(vars);
+ jmctx.setPreviousResult(result);
+ }
+
+ @Test
+ public void testVariableExtraction() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$"));
+ params.add(new CompoundVariable("2"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("5", match);
+ }
+
+ // Test with output variable name
+ @Test
+ public void testVariableExtraction1a() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$")); // template
+ params.add(new CompoundVariable("2")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("3", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("5", match);
+ assertEquals("5", vars.getObject("OUTVAR"));
+ assertEquals("<value field=\"pinposition2\">5</value>", vars.getObject("OUTVAR_g0"));
+ assertEquals("pinposition2", vars.getObject("OUTVAR_g1"));
+ assertEquals("5", vars.getObject("OUTVAR_g2"));
+ }
+
+ // Test with empty output variable name
+ @Test
+ public void testVariableExtraction1b() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$")); // template
+ params.add(new CompoundVariable("2")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable(""));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("5", match);
+ assertNull(vars.getObject("OUTVAR"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("$2$")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("times", match);
+ assertEquals("times", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable2() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("$1$$2$")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("123times", match);
+ assertEquals("123times", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable3() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("pre$2$post")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("pretimespost", match);
+ assertEquals("pretimespost", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable4() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("pre$2$")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("pretimes", match);
+ assertEquals("pretimes", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable5() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("$2$post")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("timespost", match);
+ assertEquals("timespost", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable6() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("$2$$2$")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("timestimes", match);
+ assertEquals("timestimes", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable7() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("pre$1$mid$2$post")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("pre123midtimespost", match);
+ assertEquals("pre123midtimespost", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable8() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("pre$1$mid$2$")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("pre123midtimes", match);
+ assertEquals("pre123midtimes", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtractionFromVariable9() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("(\\d+)\\s+(\\w+)"));
+ params.add(new CompoundVariable("$1$mid$2$post")); // template
+ params.add(new CompoundVariable("1")); // match number
+ params.add(new CompoundVariable("-")); // ALL separator
+ params.add(new CompoundVariable("default"));
+ params.add(new CompoundVariable("OUTVAR"));
+ params.add(new CompoundVariable(INPUT_VARIABLE_NAME));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1", vars.getObject("OUTVAR_matchNr"));
+ assertEquals("123midtimespost", match);
+ assertEquals("123midtimespost", vars.getObject("OUTVAR"));
+ assertEquals("123 times", vars.getObject("OUTVAR_g0"));
+ assertEquals("123", vars.getObject("OUTVAR_g1"));
+ assertEquals("times", vars.getObject("OUTVAR_g2"));
+ }
+
+ @Test
+ public void testVariableExtraction2() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$1$"));
+ params.add(new CompoundVariable("3"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("pinposition3", match);
+ }
+
+ @Test
+ public void testVariableExtraction5() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$1$"));
+ params.add(new CompoundVariable("ALL"));
+ params.add(new CompoundVariable("_"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("pinposition1_pinposition2_pinposition3", match);
+ }
+
+ @Test
+ public void testVariableExtraction6() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$"));
+ params.add(new CompoundVariable("4"));
+ params.add(new CompoundVariable(""));
+ params.add(new CompoundVariable("default"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("default", match);
+ }
+
+ @Test
+ public void testComma() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value,? field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$1$"));
+ params.add(new CompoundVariable("3"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("pinposition3", match);
+ }
+
+ @Test
+ public void testVariableExtraction3() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("_$1$"));
+ params.add(new CompoundVariable("2"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("_pinposition2", match);
+ }
+
+ @Test
+ public void testExtractionIndexTooHigh() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("_$1$"));
+ params.add(new CompoundVariable("10"));
+ params.add(new CompoundVariable(""));
+ params.add(new CompoundVariable("No Value Found"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("No Value Found", match);
+ }
+
+ @Test
+ public void testRandomExtraction() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<company-xmlext-query-ret>(.+?)</company-xmlext-query-ret>"));
+ params.add(new CompoundVariable("$1$"));
+ params.add(new CompoundVariable("RAND"));
+ params.add(new CompoundVariable(""));
+ params.add(new CompoundVariable("No Value Found"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("<row>" + "<value field=\"RetCode\">" + "LIS_OK</value><value"
+ + " field=\"RetCodeExtension\"></value>" + "<value field=\"alias\"></value><value"
+ + " field=\"positioncount\"></value>" + "<value field=\"invalidpincount\">0</value><value"
+ + " field=\"pinposition1\">1</value><value" + " field=\"pinpositionvalue1\"></value><value"
+ + " field=\"pinposition2\">5</value><value" + " field=\"pinpositionvalue2\"></value><value"
+ + " field=\"pinposition3\">6</value><value" + " field=\"pinpositionvalue3\"></value>"
+ + "</row>", match);
+ }
+
+ @Test(expected=NumberFormatException.class)
+ public void testExtractionIndexNotNumeric() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("_$1$"));
+ params.add(new CompoundVariable("0.333a"));
+ params.add(new CompoundVariable(""));
+ params.add(new CompoundVariable("No Value Found"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("No Value Found", match);
+ }
+
+ @Test
+ public void testVariableExtraction4() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$, "));
+ params.add(new CompoundVariable(".333"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("1, ", match);
+ }
+
+ @Test
+ public void testDefaultValue() throws Exception {
+ params = new LinkedList<>();
+ params.add(new CompoundVariable("<value,, field=\"(pinposition\\d+)\">(\\d+)</value>"));
+ params.add(new CompoundVariable("$2$, "));
+ params.add(new CompoundVariable(".333"));
+ params.add(new CompoundVariable(""));
+ params.add(new CompoundVariable("No Value Found"));
+ variable.setParameters(params);
+ String match = variable.execute(result, null);
+ assertEquals("No Value Found", match);
+ }
}
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestSamplerNameFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestSamplerNameFunction.java
index 47b1d38..90baf20 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestSamplerNameFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestSamplerNameFunction.java
@@ -34,16 +34,12 @@ import org.junit.Before;
import org.junit.Test;
public class TestSamplerNameFunction extends JMeterTestCase {
- private Function variable;
+ private Function variable;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx = null;
-
private String value;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestSetProperty.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestSetProperty.java
index be92fee..76cfc09 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestSetProperty.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestSetProperty.java
@@ -36,14 +36,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestSetProperty extends JMeterTestCase implements JMeterSerialTest {
- protected AbstractFunction function;
+ private AbstractFunction function;
private SampleResult result;
-
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestSimpleFunctions.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestSimpleFunctions.java
index d5f5b18..55eb718 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestSimpleFunctions.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestSimpleFunctions.java
@@ -38,8 +38,8 @@ import org.junit.Before;
import org.junit.Test;
public class TestSimpleFunctions extends JMeterTestCase implements JMeterSerialTest {
- private SampleResult result;
+ private SampleResult result;
private Collection<CompoundVariable> params;
private JMeterVariables vars;
private JMeterContext jmctx;
@@ -107,7 +107,6 @@ public class TestSimpleFunctions extends JMeterTestCase implements JMeterSerialT
assertEquals("1", ret);
}
-
@Test
public void testUuid() throws Exception {
AbstractFunction function = new Uuid();
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeFunction.java
index f098b87..93ec11f 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeFunction.java
@@ -37,170 +37,166 @@ import org.junit.Before;
import org.junit.Test;
public class TestTimeFunction extends JMeterTestCase {
- private Function variable;
- private SampleResult result;
-
- private Collection<CompoundVariable> params;
-
- private JMeterVariables vars;
-
- private JMeterContext jmctx = null;
-
- private String value;
-
- @Before
- public void setUp() {
- jmctx = JMeterContextService.getContext();
- vars = new JMeterVariables();
- jmctx.setVariables(vars);
- jmctx.setPreviousResult(result);
- params = new LinkedList<>();
- result = new SampleResult();
- variable = new TimeFunction();
- }
-
- @Test
- public void testDefault() throws Exception {
- variable.setParameters(params);
- long before = System.currentTimeMillis();
- value = variable.execute(result, null);
- long now= Long.parseLong(value);
- long after = System.currentTimeMillis();
- assertTrue(now >= before && now <= after);
- }
-
- @Test
- public void testDefault1() throws Exception {
- params.add(new CompoundVariable());
- variable.setParameters(params);
- long before = System.currentTimeMillis();
- value = variable.execute(result, null);
- long now= Long.parseLong(value);
- long after = System.currentTimeMillis();
- assertTrue(now >= before && now <= after);
- }
-
- @Test
- public void testDefault2() throws Exception {
- params.add(new CompoundVariable());
- params.add(new CompoundVariable());
- variable.setParameters(params);
- long before = System.currentTimeMillis();
- value = variable.execute(result, null);
- long now= Long.parseLong(value);
- long after = System.currentTimeMillis();
- assertTrue(now >= before && now <= after);
- }
-
- @Test
- public void testDefaultNone() throws Exception {
- long before = System.currentTimeMillis();
- value = variable.execute(result, null);
- long now= Long.parseLong(value);
- long after = System.currentTimeMillis();
- assertTrue(now >= before && now <= after);
- }
-
- @Test
- public void testTooMany() throws Exception {
- params.add(new CompoundVariable("YMD"));
- params.add(new CompoundVariable("NAME"));
- params.add(new CompoundVariable("YMD"));
- try {
- variable.setParameters(params);
- fail("Should have raised InvalidVariableException");
- } catch (InvalidVariableException ignored){
- }
- }
-
- @Test
- public void testYMD() throws Exception {
- params.add(new CompoundVariable("YMD"));
- params.add(new CompoundVariable("NAME"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(8,value.length());
- assertEquals(value,vars.get("NAME"));
- }
-
- @Test
- public void testYMDnoV() throws Exception {
- params.add(new CompoundVariable("YMD"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(8,value.length());
- assertNull(vars.get("NAME"));
- }
-
- @Test
- public void testHMS() throws Exception {
- params.add(new CompoundVariable("HMS"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(6,value.length());
- }
-
- @Test
- public void testYMDHMS() throws Exception {
- params.add(new CompoundVariable("YMDHMS"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(15,value.length());
- }
-
- @Test
- public void testUSER1() throws Exception {
- params.add(new CompoundVariable("USER1"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(0,value.length());
- }
-
- @Test
- public void testUSER2() throws Exception {
- params.add(new CompoundVariable("USER2"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals(0,value.length());
- }
-
- @Test
- public void testFixed() throws Exception {
- params.add(new CompoundVariable("'Fixed text'"));
- variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals("Fixed text",value);
- }
-
- @Test
- public void testMixed() throws Exception {
- params.add(new CompoundVariable("G"));
- variable.setParameters(params);
- Locale locale = Locale.getDefault();
- Locale.setDefault(Locale.ENGLISH);
- value = variable.execute(result, null);
- Locale.setDefault(locale);
- assertEquals("AD",value);
- }
-
- @Test
- public void testDivisor() throws Exception {
- params.add(new CompoundVariable("/1000"));
- variable.setParameters(params);
- long before = System.currentTimeMillis()/1000;
- value = variable.execute(result, null);
- long now= Long.parseLong(value);
- long after = System.currentTimeMillis()/1000;
- assertTrue(now >= before && now <= after);
- }
-
- @Test
- public void testDivisorNoMatch() throws Exception {
- params.add(new CompoundVariable("/1000 ")); // trailing space
+ private Function variable;
+ private SampleResult result;
+ private Collection<CompoundVariable> params;
+ private JMeterVariables vars;
+ private JMeterContext jmctx = null;
+ private String value;
+
+ @Before
+ public void setUp() {
+ jmctx = JMeterContextService.getContext();
+ vars = new JMeterVariables();
+ jmctx.setVariables(vars);
+ jmctx.setPreviousResult(result);
+ params = new LinkedList<>();
+ result = new SampleResult();
+ variable = new TimeFunction();
+ }
+
+ @Test
+ public void testDefault() throws Exception {
+ variable.setParameters(params);
+ long before = System.currentTimeMillis();
+ value = variable.execute(result, null);
+ long now = Long.parseLong(value);
+ long after = System.currentTimeMillis();
+ assertTrue(now >= before && now <= after);
+ }
+
+ @Test
+ public void testDefault1() throws Exception {
+ params.add(new CompoundVariable());
+ variable.setParameters(params);
+ long before = System.currentTimeMillis();
+ value = variable.execute(result, null);
+ long now = Long.parseLong(value);
+ long after = System.currentTimeMillis();
+ assertTrue(now >= before && now <= after);
+ }
+
+ @Test
+ public void testDefault2() throws Exception {
+ params.add(new CompoundVariable());
+ params.add(new CompoundVariable());
+ variable.setParameters(params);
+ long before = System.currentTimeMillis();
+ value = variable.execute(result, null);
+ long now = Long.parseLong(value);
+ long after = System.currentTimeMillis();
+ assertTrue(now >= before && now <= after);
+ }
+
+ @Test
+ public void testDefaultNone() throws Exception {
+ long before = System.currentTimeMillis();
+ value = variable.execute(result, null);
+ long now = Long.parseLong(value);
+ long after = System.currentTimeMillis();
+ assertTrue(now >= before && now <= after);
+ }
+
+ @Test
+ public void testTooMany() throws Exception {
+ params.add(new CompoundVariable("YMD"));
+ params.add(new CompoundVariable("NAME"));
+ params.add(new CompoundVariable("YMD"));
+ try {
variable.setParameters(params);
- value = variable.execute(result, null);
- assertEquals("/1000 ", value);
- }
+ fail("Should have raised InvalidVariableException");
+ } catch (InvalidVariableException ignored) {
+ }
+ }
+
+ @Test
+ public void testYMD() throws Exception {
+ params.add(new CompoundVariable("YMD"));
+ params.add(new CompoundVariable("NAME"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(8, value.length());
+ assertEquals(value, vars.get("NAME"));
+ }
+
+ @Test
+ public void testYMDnoV() throws Exception {
+ params.add(new CompoundVariable("YMD"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(8, value.length());
+ assertNull(vars.get("NAME"));
+ }
+
+ @Test
+ public void testHMS() throws Exception {
+ params.add(new CompoundVariable("HMS"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(6, value.length());
+ }
+
+ @Test
+ public void testYMDHMS() throws Exception {
+ params.add(new CompoundVariable("YMDHMS"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(15, value.length());
+ }
+
+ @Test
+ public void testUSER1() throws Exception {
+ params.add(new CompoundVariable("USER1"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(0, value.length());
+ }
+
+ @Test
+ public void testUSER2() throws Exception {
+ params.add(new CompoundVariable("USER2"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals(0, value.length());
+ }
+
+ @Test
+ public void testFixed() throws Exception {
+ params.add(new CompoundVariable("'Fixed text'"));
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals("Fixed text", value);
+ }
+
+ @Test
+ public void testMixed() throws Exception {
+ params.add(new CompoundVariable("G"));
+ variable.setParameters(params);
+ Locale locale = Locale.getDefault();
+ Locale.setDefault(Locale.ENGLISH);
+ value = variable.execute(result, null);
+ Locale.setDefault(locale);
+ assertEquals("AD", value);
+ }
+
+ @Test
+ public void testDivisor() throws Exception {
+ params.add(new CompoundVariable("/1000"));
+ variable.setParameters(params);
+ long before = System.currentTimeMillis() / 1000;
+ value = variable.execute(result, null);
+ long now = Long.parseLong(value);
+ long after = System.currentTimeMillis() / 1000;
+ assertTrue(now >= before && now <= after);
+ }
+
+ @Test
+ public void testDivisorNoMatch() throws Exception {
+ params.add(new CompoundVariable("/1000 ")); // trailing space
+ variable.setParameters(params);
+ value = variable.execute(result, null);
+ assertEquals("/1000 ", value);
+ }
}
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeRandomDateFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeRandomDateFunction.java
index 0e2e70b..0302d55 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeRandomDateFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeRandomDateFunction.java
@@ -41,13 +41,9 @@ import org.junit.Test;
public class TestTimeRandomDateFunction extends JMeterTestCase {
private AbstractFunction function;
-
private SampleResult result;
-
private JMeterVariables vars;
-
private JMeterContext jmctx = null;
-
private String value;
@Before
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeShiftFunction.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeShiftFunction.java
index 0ef1d5b..bd2f94e 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeShiftFunction.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestTimeShiftFunction.java
@@ -44,14 +44,11 @@ import org.junit.Before;
import org.junit.Test;
public class TestTimeShiftFunction extends JMeterTestCase {
- private Function function;
+ private Function function;
private SampleResult result;
-
private JMeterVariables vars;
-
private JMeterContext jmctx = null;
-
private String value;
@Before
@@ -135,6 +132,7 @@ public class TestTimeShiftFunction extends JMeterTestCase {
public static void main(String[] args) {
System.out.println(java.time.Duration.parse("P10DT-1H-5M5S").toMillis());
}
+
@Test
public void testWrongAmountToAdd() throws Exception {
// Nothing is add with wrong value, so check if return is now
@@ -155,7 +153,6 @@ public class TestTimeShiftFunction extends JMeterTestCase {
assertThat(value, is(equalTo("")));
}
-
@Test
public void testRandomPeriod() throws Exception {
Random r = new Random();
@@ -173,10 +170,8 @@ public class TestTimeShiftFunction extends JMeterTestCase {
randomFutureDate = LocalDateTime.parse(value);
checkFutureDate = LocalDateTime.now().plusMinutes(randomInt);
assertThat(randomFutureDate, within(5, ChronoUnit.SECONDS, checkFutureDate) );
-
}
-
@Test
public void testNowPlusOneDayWithLocale() throws Exception {
Collection<CompoundVariable> params = makeParams("yyyy-MMMM-dd", "2017-juillet-01", "P1D", "fr_FR", "");
diff --git a/src/functions/src/test/java/org/apache/jmeter/functions/TestUrlEncodeDecode.java b/src/functions/src/test/java/org/apache/jmeter/functions/TestUrlEncodeDecode.java
index 6ed7010..d68eded 100644
--- a/src/functions/src/test/java/org/apache/jmeter/functions/TestUrlEncodeDecode.java
+++ b/src/functions/src/test/java/org/apache/jmeter/functions/TestUrlEncodeDecode.java
@@ -33,12 +33,10 @@ import org.junit.Before;
import org.junit.Test;
public class TestUrlEncodeDecode extends JMeterTestCase {
- private SampleResult result;
+ private SampleResult result;
private Collection<CompoundVariable> params;
-
private JMeterVariables vars;
-
private JMeterContext jmctx;
@Before
@@ -71,7 +69,6 @@ public class TestUrlEncodeDecode extends JMeterTestCase {
assertEquals("Veni%2C+vidi%2C+vici+%3F", returnValue);
}
-
@Test
public void testUrlDecode() throws Exception {
AbstractFunction function = new UrlDecode();
diff --git a/src/jorphan/src/main/java/org/apache/jorphan/util/JOrphanUtils.java b/src/jorphan/src/main/java/org/apache/jorphan/util/JOrphanUtils.java
index a8fbb2d..dc5aa0b 100644
--- a/src/jorphan/src/main/java/org/apache/jorphan/util/JOrphanUtils.java
+++ b/src/jorphan/src/main/java/org/apache/jorphan/util/JOrphanUtils.java
@@ -68,19 +68,13 @@ public final class JOrphanUtils {
* This piece of code used to be part of JMeterUtils, but was moved here
* because some JOrphan classes use it too.
*
- * @param splittee
- * String to be split
- * @param splitChar
- * Character(s) to split the string on, these are treated as a single unit
- * @param truncate
- * Should adjacent and leading/trailing splitChars be removed?
- *
+ * @param splittee String to be split
+ * @param splitChar Character(s) to split the string on, these are treated as a single unit
+ * @param truncate Should adjacent and leading/trailing splitChars be removed?
* @return Array of all the tokens; empty if the input string is {@code null} or the splitChar is {@code null}
- *
* @see #split(String, String, String)
- *
*/
- public static String[] split(String splittee, String splitChar,boolean truncate) { //NOSONAR
+ public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
@@ -89,16 +83,16 @@ public final class JOrphanUtils {
final int splitLength = splitChar.length();
final String adjacentSplit = splitChar + splitChar;
final int adjacentSplitLength = adjacentSplit.length();
- if(truncate) {
+ if (truncate) {
while ((spot = splittee.indexOf(adjacentSplit)) != -1) {
splittee = splittee.substring(0, spot + splitLength)
+ splittee.substring(spot + adjacentSplitLength, splittee.length());
}
- if(splittee.startsWith(splitChar)) {
+ if (splittee.startsWith(splitChar)) {
splittee = splittee.substring(splitLength);
}
- if(splittee.endsWith(splitChar)) { // Remove trailing splitter
- splittee = splittee.substring(0,splittee.length()-splitLength);
+ if (splittee.endsWith(splitChar)) { // Remove trailing splitter
+ splittee = splittee.substring(0, splittee.length() - splitLength);
}
}
List<String> returns = new ArrayList<>();
@@ -108,24 +102,21 @@ public final class JOrphanUtils {
while (start < length && (spot = splittee.indexOf(splitChar, start)) > -1) {
if (spot > 0) {
returns.add(splittee.substring(start, spot));
- }
- else
- {
+ } else {
returns.add(EMPTY_ELEMENT);
}
start = spot + splitLength;
}
if (start < length) {
returns.add(splittee.substring(start));
- } else if (spot == length - splitLength){// Found splitChar at end of line
+ } else if (spot == length - splitLength) {// Found splitChar at end of line
returns.add(EMPTY_ELEMENT);
}
return returns.toArray(new String[returns.size()]);
}
- public static String[] split(String splittee,String splitChar)
- {
- return split(splittee,splitChar,true);
+ public static String[] split(String splittee, String splitChar) {
+ return split(splittee, splitChar, true);
}
/**
@@ -134,38 +125,32 @@ public final class JOrphanUtils {
* <p>
* Trailing delimiters are significant (unless the default = null)
*
- * @param splittee
- * String to be split.
- * @param delims
- * Delimiter character(s) to split the string on
- * @param def
- * Default value to place between two split chars that have
- * nothing between them. If null, then ignore omitted elements.
- *
+ * @param splittee String to be split.
+ * @param delims Delimiter character(s) to split the string on
+ * @param def Default value to place between two split chars that have
+ * nothing between them. If null, then ignore omitted elements.
* @return Array of all the tokens.
- *
* @throws NullPointerException if splittee or delims are {@code null}
- *
* @see #split(String, String, boolean)
* @see #split(String, String)
- *
+ * <p>
* This is a rewritten version of JMeterUtils.split()
*/
public static String[] split(String splittee, String delims, String def) {
- StringTokenizer tokens = new StringTokenizer(splittee,delims,def!=null);
- boolean lastWasDelim=false;
+ StringTokenizer tokens = new StringTokenizer(splittee, delims, def != null);
+ boolean lastWasDelim = false;
List<String> strList = new ArrayList<>();
while (tokens.hasMoreTokens()) {
- String tok=tokens.nextToken();
- if ( tok.length()==1 // we have a single character; could be a token
- && delims.contains(tok)) // it is a token
+ String tok = tokens.nextToken();
+ if (tok.length() == 1 // we have a single character; could be a token
+ && delims.contains(tok)) // it is a token
{
if (lastWasDelim) {// we saw a delimiter last time
strList.add(def);// so add the default
}
- lastWasDelim=true;
+ lastWasDelim = true;
} else {
- lastWasDelim=false;
+ lastWasDelim = false;
strList.add(tok);
}
}
@@ -180,12 +165,10 @@ public final class JOrphanUtils {
private static final int SPACES_LEN = SPACES_CHARS.length;
/**
- * Right aligns some text in a StringBuilder N.B. modifies the input buffer
+ * Right aligns some text in a StringBuilder N.B. modifies the input builder
*
- * @param in
- * StringBuilder containing some text
- * @param len
- * output length desired
+ * @param in StringBuilder containing some text
+ * @param len output length desired
* @return input StringBuilder, with leading spaces
*/
public static StringBuilder rightAlign(StringBuilder in, int len) {
@@ -201,12 +184,10 @@ public final class JOrphanUtils {
}
/**
- * Left aligns some text in a StringBuilder N.B. modifies the input buffer
+ * Left aligns some text in a StringBuilder N.B. modifies the input builder
*
- * @param in
- * StringBuilder containing some text
- * @param len
- * output length desired
+ * @param in StringBuilder containing some text
+ * @param len output length desired
* @return input StringBuilder, with trailing spaces
*/
public static StringBuilder leftAlign(StringBuilder in, int len) {
@@ -225,8 +206,7 @@ public final class JOrphanUtils {
* Convert a boolean to its upper case string representation.
* Equivalent to Boolean.valueOf(boolean).toString().toUpperCase().
*
- * @param value
- * boolean to convert
+ * @param value boolean to convert
* @return "TRUE" or "FALSE"
*/
public static String booleanToSTRING(boolean value) {
@@ -236,12 +216,9 @@ public final class JOrphanUtils {
/**
* Simple-minded String.replace() for JDK1.3 Should probably be recoded...
*
- * @param source
- * input string
- * @param search
- * string to look for (no regular expressions)
- * @param replace
- * string to replace the search string
+ * @param source input string
+ * @param search string to look for (no regular expressions)
+ * @param replace string to replace the search string
* @return the output string
*/
public static String replaceFirst(String source, String search, String replace) {
@@ -260,30 +237,28 @@ public final class JOrphanUtils {
* Version of String.replaceAll() for JDK1.3
* See below for another version which replaces strings rather than chars
* and provides a fast path which does not allocate memory
- * @param source
- * input string
- * @param search
- * char to look for (no regular expressions)
- * @param replace
- * string to replace the search string
+ *
+ * @param source input string
+ * @param search char to look for (no regular expressions)
+ * @param replace string to replace the search string
* @return the output string
*/
public static String replaceAllChars(String source, char search, String replace) {
int indexOf = source.indexOf(search);
- if(indexOf == -1) {
+ if (indexOf == -1) {
return source;
}
int offset = 0;
char[] chars = source.toCharArray();
- StringBuilder sb = new StringBuilder(source.length()+20);
- while(indexOf != -1) {
- sb.append(chars, offset, indexOf-offset);
+ StringBuilder sb = new StringBuilder(source.length() + 20);
+ while (indexOf != -1) {
+ sb.append(chars, offset, indexOf - offset);
sb.append(replace);
- offset = indexOf +1;
+ offset = indexOf + 1;
indexOf = source.indexOf(search, offset);
}
- sb.append(chars, offset, chars.length- offset);
+ sb.append(chars, offset, chars.length - offset);
return sb.toString();
}
@@ -291,12 +266,11 @@ public final class JOrphanUtils {
/**
* Replace all patterns in a String
*
- * @see String#replaceAll(String regex,String replacement) - JDK1.4 only
- *
- * @param input - string to be transformed
+ * @param input - string to be transformed
* @param pattern - pattern to replace
- * @param sub - replacement
+ * @param sub - replacement
* @return the updated string
+ * @see String#replaceAll(String regex, String replacement) - JDK1.4 only
*/
public static String substitute(final String input, final String pattern, final String sub) {
StringBuilder ret = new StringBuilder(input.length());
@@ -315,26 +289,23 @@ public final class JOrphanUtils {
/**
* Trim a string by the tokens provided.
*
- * @param input string to trim
+ * @param input string to trim
* @param delims list of delimiters
* @return input trimmed at the first delimiter
*/
- public static String trim(final String input, final String delims){
- StringTokenizer tokens = new StringTokenizer(input,delims);
+ public static String trim(final String input, final String delims) {
+ StringTokenizer tokens = new StringTokenizer(input, delims);
return tokens.hasMoreTokens() ? tokens.nextToken() : "";
}
/**
* Returns a slice of a byte array.
- *
+ * <p>
* TODO - add bounds checking?
*
- * @param array -
- * input array
- * @param begin -
- * start of slice
- * @param end -
- * end of slice
+ * @param array input array
+ * @param begin start of slice
+ * @param end end of slice
* @return slice from the input array
*/
public static byte[] getByteArraySlice(byte[] array, int begin, int end) {
@@ -345,11 +316,13 @@ public final class JOrphanUtils {
// N.B. Commons IO IOUtils has equivalent methods; these were added before IO was included
// TODO - perhaps deprecate these in favour of Commons IO?
+
/**
* Close a Closeable with no error thrown
+ *
* @param cl - Closeable (may be null)
*/
- public static void closeQuietly(Closeable cl){
+ public static void closeQuietly(Closeable cl) {
try {
if (cl != null) {
cl.close();
@@ -361,11 +334,12 @@ public final class JOrphanUtils {
/**
* close a Socket with no error thrown
+ *
* @param sock - Socket (may be null)
*/
- public static void closeQuietly(Socket sock){
+ public static void closeQuietly(Socket sock) {
try {
- if (sock!= null) {
+ if (sock != null) {
sock.close();
}
} catch (IOException ignored) {
@@ -375,11 +349,12 @@ public final class JOrphanUtils {
/**
* close a Socket with no error thrown
+ *
* @param sock - ServerSocket (may be null)
*/
- public static void closeQuietly(ServerSocket sock){
+ public static void closeQuietly(ServerSocket sock) {
try {
- if (sock!= null) {
+ if (sock != null) {
sock.close();
}
} catch (IOException ignored) {
@@ -390,28 +365,27 @@ public final class JOrphanUtils {
/**
* Check if a byte array starts with the given byte array.
*
- * @see String#startsWith(String, int)
- *
* @param target array to scan
* @param search array to search for
* @param offset starting offset (≥0)
* @return true if the search array matches the target at the current offset
+ * @see String#startsWith(String, int)
*/
- public static boolean startsWith(byte [] target, byte [] search, int offset){
+ public static boolean startsWith(byte[] target, byte[] search, int offset) {
final int targetLength = target.length;
final int searchLength = search.length;
- if (offset < 0 || searchLength > targetLength+offset){
+ if (offset < 0 || searchLength > targetLength + offset) {
return false;
}
- for(int i=0;i < searchLength; i++){
- if (target[i+offset] != search[i]){
+ for (int i = 0; i < searchLength; i++) {
+ if (target[i + offset] != search[i]) {
return false;
}
}
return true;
}
- private static final byte[] XML_PFX = {'<','?','x','m','l'};// "<?xml "
+ private static final byte[] XML_PFX = {'<', '?', 'x', 'm', 'l'};// "<?xml "
/**
* Detects if some content starts with the standard XML prefix.
@@ -419,8 +393,8 @@ public final class JOrphanUtils {
* @param target the content to check
* @return true if the document starts with the standard XML prefix.
*/
- public static boolean isXML(byte [] target){
- return startsWith(target, XML_PFX,0);
+ public static boolean isXML(byte[] target) {
+ return startsWith(target, XML_PFX, 0);
}
/**
@@ -430,7 +404,7 @@ public final class JOrphanUtils {
* @return hex representation of binary input
*/
public static String baToHexString(byte[] ba) {
- StringBuilder sb = new StringBuilder(ba.length*2);
+ StringBuilder sb = new StringBuilder(ba.length * 2);
for (byte b : ba) {
int j = b & 0xff;
if (j < 16) {
@@ -444,12 +418,12 @@ public final class JOrphanUtils {
/**
* Convert binary byte array to hex string.
*
- * @param ba input binary byte array
+ * @param ba input binary byte array
* @param separator the separator to be added between pairs of hex digits
* @return hex representation of binary input
*/
public static String baToHexString(byte[] ba, char separator) {
- StringBuilder sb = new StringBuilder(ba.length*2);
+ StringBuilder sb = new StringBuilder(ba.length * 2);
for (int i = 0; i < ba.length; i++) {
if (i > 0 && separator != 0) {
sb.append(separator);
@@ -470,40 +444,39 @@ public final class JOrphanUtils {
* @return hex representation of binary input
*/
public static byte[] baToHexBytes(byte[] ba) {
- byte[] hb = new byte[ba.length*2];
+ byte[] hb = new byte[ba.length * 2];
for (int i = 0; i < ba.length; i++) {
byte upper = (byte) ((ba[i] & 0xf0) >> 4);
byte lower = (byte) (ba[i] & 0x0f);
- hb[2*i]=toHexChar(upper);
- hb[2*i+1]=toHexChar(lower);
+ hb[2 * i] = toHexChar(upper);
+ hb[2 * i + 1] = toHexChar(lower);
}
return hb;
}
- private static byte toHexChar(byte in){
+ private static byte toHexChar(byte in) {
if (in < 10) {
- return (byte) (in+'0');
+ return (byte) (in + '0');
}
- return (byte) ((in-10)+'a');
+ return (byte) ((in - 10) + 'a');
}
/**
* Read as much as possible into buffer.
*
- * @param is the stream to read from
+ * @param is the stream to read from
* @param buffer output buffer
* @param offset offset into buffer
* @param length number of bytes to read
- *
* @return the number of bytes actually read
* @throws IOException if some I/O errors occur
*/
public static int read(InputStream is, byte[] buffer, int offset, int length) throws IOException {
int remaining = length;
- while ( remaining > 0 ) {
+ while (remaining > 0) {
int location = length - remaining;
- int count = is.read( buffer, location, remaining );
- if ( -1 == count ) { // EOF
+ int count = is.read(buffer, location, remaining);
+ if (-1 == count) { // EOF
break;
}
remaining -= count;
@@ -521,24 +494,27 @@ public final class JOrphanUtils {
public static void displayThreads(boolean includeDaemons) {
Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();
String lineSeparator = System.getProperty("line.separator");
- StringBuilder builder = new StringBuilder();
- for(Map.Entry<Thread, StackTraceElement[]> e : m.entrySet()) {
+ for (Map.Entry<Thread, StackTraceElement[]> e : m.entrySet()) {
boolean daemon = e.getKey().isDaemon();
- if (includeDaemons || !daemon){
- builder.setLength(0);
+ if (includeDaemons || !daemon) {
+ StringBuilder builder = new StringBuilder();
StackTraceElement[] ste = e.getValue();
for (StackTraceElement stackTraceElement : ste) {
int lineNumber = stackTraceElement.getLineNumber();
- builder.append(stackTraceElement.getClassName()+"#"+stackTraceElement.getMethodName()+
- (lineNumber >=0 ? " at line:"+ stackTraceElement.getLineNumber() : "")+lineSeparator);
+ builder.append(stackTraceElement.getClassName())
+ .append("#")
+ .append(stackTraceElement.getMethodName())
+ .append(lineNumber >= 0 ? " at line:" + stackTraceElement.getLineNumber() : "")
+ .append(lineSeparator);
}
- System.out.println(e.getKey().toString()+(daemon ? " (daemon)" : "")+", stackTrace:"+ builder.toString());
+ System.out.println(e.getKey().toString() + (daemon ? " (daemon)" : "") + ", stackTrace:" + builder.toString());
}
}
}
/**
* Returns {@code null} if input is empty, {@code null} or contains spaces only
+ *
* @param input String
* @return trimmed input or {@code null}
*/
@@ -555,6 +531,7 @@ public final class JOrphanUtils {
/**
* Check that value is empty (""), {@code null} or whitespace only.
+ *
* @param value Value
* @return {@code true} if the String is not empty (""), not {@code null} and not whitespace only.
*/
@@ -567,7 +544,7 @@ public final class JOrphanUtils {
* This is to avoid OutOfMemory issues if the data buffer is very large
* and the JVM needs to copy the buffer for use by native code.
*
- * @param data the buffer to be written
+ * @param data the buffer to be written
* @param output the output stream to use
* @throws IOException if there is a problem writing the data
*/
@@ -575,7 +552,7 @@ public final class JOrphanUtils {
public static void write(byte[] data, OutputStream output) throws IOException {
int bytes = data.length;
int offset = 0;
- while(bytes > 0) {
+ while (bytes > 0) {
int chunk = Math.min(bytes, DEFAULT_CHUNK_SIZE);
output.write(data, offset, chunk);
bytes -= chunk;
@@ -602,6 +579,7 @@ public final class JOrphanUtils {
* <li>Because it exists but is not empty</li>
* <li>Because it does not exist but cannot be created</li>
* </ul>
+ *
* @param folder to check
* @throws IllegalArgumentException when folder can't be written to
*/
@@ -619,8 +597,9 @@ public final class JOrphanUtils {
* <li>Because it exists but is not empty using folder.listFiles(exporterFileFilter)</li>
* <li>Because it does not exist but cannot be created</li>
* </ul>
- * @param folder to check
- * @param fileFilter used to filter listing of folder
+ *
+ * @param folder to check
+ * @param fileFilter used to filter listing of folder
* @throws IllegalArgumentException when folder can't be written to
*/
public static void canSafelyWriteToFolder(File folder, FileFilter fileFilter) {
@@ -630,10 +609,11 @@ public final class JOrphanUtils {
/**
* Check whether we can write to a folder. If {@code deleteFolderContent} is {@code true} the folder or file with
* the same name will be emptied or deleted.
- * @param folder to check
+ *
+ * @param folder to check
* @param deleteFolderContent flag whether the folder should be emptied or a file with the same name deleted
* @throws IllegalArgumentException when folder can't be written to
- * Throw IllegalArgumentException if folder cannot be written
+ * Throw IllegalArgumentException if folder cannot be written
*/
public static void canSafelyWriteToFolder(File folder, boolean deleteFolderContent) {
canSafelyWriteToFolder(folder, deleteFolderContent, file -> true);
@@ -643,35 +623,35 @@ public final class JOrphanUtils {
/**
* Check whether we can write to a folder.
*
- * @param folder which should be checked for writability and emptiness
+ * @param folder which should be checked for writability and emptiness
* @param deleteFolderIfExists flag whether the folder should be emptied or a file with the same name deleted
- * @param exporterFileFilter used for filtering listing of the folder
+ * @param exporterFileFilter used for filtering listing of the folder
* @throws IllegalArgumentException when folder can't be written to. That could have the following reasons:
- * <ul>
- * <li>it exists but is not a folder</li>
- * <li>it exists but is not empty</li>
- * <li>it does not exist but cannot be created</li>
- * </ul>
+ * <ul>
+ * <li>it exists but is not a folder</li>
+ * <li>it exists but is not empty</li>
+ * <li>it does not exist but cannot be created</li>
+ * </ul>
*/
public static void canSafelyWriteToFolder(File folder, boolean deleteFolderIfExists, FileFilter exporterFileFilter) {
- if(folder.exists()) {
+ if (folder.exists()) {
if (folder.isFile()) {
- if(deleteFolderIfExists) {
- if(!folder.delete()) {
+ if (deleteFolderIfExists) {
+ if (!folder.delete()) {
throw new IllegalArgumentException("Cannot write to '"
- +folder.getAbsolutePath()+"' as it is an existing file and delete failed");
+ + folder.getAbsolutePath() + "' as it is an existing file and delete failed");
}
} else {
throw new IllegalArgumentException("Cannot write to '"
- +folder.getAbsolutePath()+"' as it is an existing file");
+ + folder.getAbsolutePath() + "' as it is an existing file");
}
} else {
File[] listedFiles = folder.listFiles(exporterFileFilter);
- if(listedFiles != null && listedFiles.length > 0) {
- if(deleteFolderIfExists) {
+ if (listedFiles != null && listedFiles.length > 0) {
+ if (deleteFolderIfExists) {
try {
FileUtils.deleteDirectory(folder);
- } catch(IOException ex) {
+ } catch (IOException ex) {
throw new IllegalArgumentException("Cannot write to '" + folder.getAbsolutePath()
+ "' as folder is not empty and cleanup failed with error:" + ex.getMessage(), ex);
}
@@ -680,15 +660,15 @@ public final class JOrphanUtils {
}
} else {
throw new IllegalArgumentException("Cannot write to '"
- +folder.getAbsolutePath()+"' as folder is not empty");
+ + folder.getAbsolutePath() + "' as folder is not empty");
}
}
}
} else {
// check we can create it
- if(!folder.getAbsoluteFile().getParentFile().canWrite()) {
+ if (!folder.getAbsoluteFile().getParentFile().canWrite()) {
throw new IllegalArgumentException("Cannot write to '"
- +folder.getAbsolutePath()+"' as folder does not exist and parent folder is not writable");
+ + folder.getAbsolutePath() + "' as folder does not exist and parent folder is not writable");
}
}
}
@@ -696,9 +676,10 @@ public final class JOrphanUtils {
/**
* Replace in source all matches of regex by replacement taking
* into account case if caseSensitive is true
- * @param source Source text
- * @param regex Regular expression
- * @param replacement Replacement text to which function applies a quoting
+ *
+ * @param source Source text
+ * @param regex Regular expression
+ * @param replacement Replacement text to which function applies a quoting
* @param caseSensitive is case taken into account
* @return array of Object where first row is the replaced text, second row is the number of replacement that occurred
*/
@@ -711,7 +692,7 @@ public final class JOrphanUtils {
Matcher matcher = pattern.matcher(source);
int totalReplaced = 0;
StringBuffer result = new StringBuffer(); // NOSONAR Matcher#appendReplacement needs a StringBuffer
- while(matcher.find()) {
+ while (matcher.find()) {
matcher.appendReplacement(result, replacementQuoted);
totalReplaced++;
}
@@ -727,11 +708,11 @@ public final class JOrphanUtils {
* Replace all occurrences of {@code regex} in {@code value} by {@code replaceBy} if {@code value} is not blank.
* The replaced text is fed into the {@code setter}.
*
- * @param regex Regular expression that is used for the search
- * @param replaceBy value that is used for replacement
+ * @param regex Regular expression that is used for the search
+ * @param replaceBy value that is used for replacement
* @param caseSensitive flag whether the regex should be applied case sensitive
- * @param value in which the replacement takes place
- * @param setter that gets called with the replaced value
+ * @param value in which the replacement takes place
+ * @param setter that gets called with the replaced value
* @return number of matches that were replaced
*/
public static int replaceValue(String regex, String replaceBy, boolean caseSensitive, String value, Consumer<String> setter) {
@@ -752,10 +733,8 @@ public final class JOrphanUtils {
* of all the strings concatenated with the tokenizer string in between each
* one.
*
- * @param splittee
- * Array of Objects to be concatenated.
- * @param splitChar
- * Object to unsplit the strings with.
+ * @param splittee Array of Objects to be concatenated.
+ * @param splitChar Object to unsplit the strings with.
* @return Array of all the tokens.
*/
public static String unsplit(Object[] splittee, Object splitChar) {
@@ -777,7 +756,7 @@ public final class JOrphanUtils {
* @return String random password
*/
public static String generateRandomAlphanumericPassword(int length) {
- char[][] pairs = {{'a','z'}, {'A','Z'}, {'0','9'}};
+ char[][] pairs = {{'a', 'z'}, {'A', 'Z'}, {'0', '9'}};
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder()
.usingRandom(LazySecureRandom.INSTANCE::nextInt)
.withinRange(pairs)
diff --git a/src/jorphan/src/test/java/org/apache/commons/cli/avalon/ClutilTestCase.java b/src/jorphan/src/test/java/org/apache/commons/cli/avalon/ClutilTestCase.java
index 1b2f403..f323349 100644
--- a/src/jorphan/src/test/java/org/apache/commons/cli/avalon/ClutilTestCase.java
+++ b/src/jorphan/src/test/java/org/apache/commons/cli/avalon/ClutilTestCase.java
@@ -26,44 +26,31 @@ import java.util.List;
import org.junit.Test;
-/**
- *
- */
public final class ClutilTestCase {
private static final String[] ARGLIST1 = new String[] { "--you", "are", "--all", "-cler", "kid" };
private static final String[] ARGLIST2 = new String[] { "-Dstupid=idiot", "are", "--all", "here", "-d" };
- private static final String[] ARGLIST3 = new String[] {
// duplicates
+ private static final String[] ARGLIST3 = new String[] {
"-Dstupid=idiot", "are", "--all", "--all", "here" };
- private static final String[] ARGLIST4 = new String[] {
// incompatible (blee/all)
+ private static final String[] ARGLIST4 = new String[] {
"-Dstupid", "idiot", "are", "--all", "--blee", "here" };
private static final String[] ARGLIST5 = new String[] { "-f", "myfile.txt" };
private static final int DEFINE_OPT = 'D';
-
private static final int CASE_CHECK_OPT = 'd';
-
private static final int YOU_OPT = 'y';
-
private static final int ALL_OPT = 'a';
-
private static final int CLEAR1_OPT = 'c';
-
private static final int CLEAR2_OPT = 'l';
-
private static final int CLEAR3_OPT = 'e';
-
private static final int CLEAR5_OPT = 'r';
-
private static final int BLEE_OPT = 'b';
-
private static final int FILE_OPT = 'f';
-
private static final int TAINT_OPT = 'T';
private static final CLOptionDescriptor DEFINE = new CLOptionDescriptor("define",
@@ -380,11 +367,8 @@ public final class ClutilTestCase {
public void testSingleArg2() {
final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE };
- final CLArgsParser parser = new CLArgsParser(new String[] { "-f-=,=-" } // Check
- // delimiters
- // are
- // allowed
- , options);
+ // Check delimiters are allowed
+ final CLArgsParser parser = new CLArgsParser(new String[] { "-f-=,=-" }, options);
assertNull(parser.getErrorString(), parser.getErrorString());
@@ -400,11 +384,8 @@ public final class ClutilTestCase {
public void testSingleArg3() {
final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE };
- final CLArgsParser parser = new CLArgsParser(new String[] { "--file=-=,-" } // Check
- // delimiters
- // are
- // allowed
- , options);
+ // Check delimiters are allowed
+ final CLArgsParser parser = new CLArgsParser(new String[] { "--file=-=,-" }, options);
assertNull(parser.getErrorString(), parser.getErrorString());
@@ -534,12 +515,8 @@ public final class ClutilTestCase {
public void testCombinedArgs3() {
final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT, FILE };
- final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "--", "-fa" }// Should
- // not
- // detect
- // trailing
- // option
- , options);
+ // Should not detect trailing option
+ final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "--", "-fa" }, options);
assertNull(parser.getErrorString(), parser.getErrorString());
@@ -556,11 +533,8 @@ public final class ClutilTestCase {
public void testCombinedArgs4() {
final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT, FILE };
- final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "rest", "-fa" } // should
- // detect
- // trailing
- // option
- , options);
+ // should detect trailing option
+ final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "rest", "-fa" }, options);
assertNull(parser.getErrorString(), parser.getErrorString());
@@ -603,13 +577,8 @@ public final class ClutilTestCase {
public void test2ArgsParse2() {
final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE };
- final CLArgsParser parser = new CLArgsParser(new String[] { "--define", "a-b,c=d-e,f" }, // Check
- // "-"
- // is
- // allowed
- // in
- // arg2
- options);
+ // Check "-" is allowed in arg2
+ final CLArgsParser parser = new CLArgsParser(new String[] { "--define", "a-b,c=d-e,f" }, options);
assertNull(parser.getErrorString(), parser.getErrorString());
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/collections/PackageTest.java b/src/jorphan/src/test/java/org/apache/jorphan/collections/PackageTest.java
index d131195..72dfc84 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/collections/PackageTest.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/collections/PackageTest.java
@@ -35,147 +35,144 @@ public class PackageTest {
private static Logger log = LoggerFactory.getLogger(PackageTest.class);
- @Test
- public void testAdd1() throws Exception {
- Collection<String> treePath = Arrays.asList(new String[] { "1", "2", "3", "4" });
- HashTree tree = new HashTree();
- log.debug("treePath = {}", treePath);
- tree.add(treePath, "value");
- log.debug("Now treePath = {}, tree = {}", treePath, tree);
- assertEquals(1, tree.list(treePath).size());
- assertEquals("value", tree.getArray(treePath)[0]);
+ @Test
+ public void testAdd1() throws Exception {
+ Collection<String> treePath = Arrays.asList(new String[]{"1", "2", "3", "4"});
+ HashTree tree = new HashTree();
+ log.debug("treePath = {}", treePath);
+ tree.add(treePath, "value");
+ log.debug("Now treePath = {}, tree = {}", treePath, tree);
+ assertEquals(1, tree.list(treePath).size());
+ assertEquals("value", tree.getArray(treePath)[0]);
+ }
+
+ @Test
+ public void testEqualsAndHashCode1() throws Exception {
+ HashTree tree1 = new HashTree("abcd");
+ HashTree tree2 = new HashTree("abcd");
+ HashTree tree3 = new HashTree("abcde");
+ HashTree tree4 = new HashTree("abcde");
+
+ assertTrue(tree1.equals(tree1));
+ assertTrue(tree1.equals(tree2));
+ assertTrue(tree2.equals(tree1));
+ assertTrue(tree2.equals(tree2));
+ assertEquals(tree1.hashCode(), tree2.hashCode());
+
+ assertTrue(tree3.equals(tree3));
+ assertTrue(tree3.equals(tree4));
+ assertTrue(tree4.equals(tree3));
+ assertTrue(tree4.equals(tree4));
+ assertEquals(tree3.hashCode(), tree4.hashCode());
+
+ assertNotSame(tree1, tree2);
+ assertNotSame(tree1, tree3);
+ assertNotSame(tree1, tree4);
+ assertNotSame(tree2, tree3);
+ assertNotSame(tree2, tree4);
+
+ assertFalse(tree1.equals(tree3));
+ assertFalse(tree1.equals(tree4));
+ assertFalse(tree2.equals(tree3));
+ assertFalse(tree2.equals(tree4));
+
+ assertNotNull(tree1);
+ assertNotNull(tree2);
+
+ tree1.add("abcd", tree3);
+ assertFalse(tree1.equals(tree2));
+ assertFalse(tree2.equals(tree1));// Check reflexive
+ if (tree1.hashCode() == tree2.hashCode()) {
+ // This is not a requirement
+ System.out.println("WARN: unequal HashTrees should not have equal hashCodes");
}
-
- @Test
- public void testEqualsAndHashCode1() throws Exception {
- HashTree tree1 = new HashTree("abcd");
- HashTree tree2 = new HashTree("abcd");
- HashTree tree3 = new HashTree("abcde");
- HashTree tree4 = new HashTree("abcde");
-
- assertTrue(tree1.equals(tree1));
- assertTrue(tree1.equals(tree2));
- assertTrue(tree2.equals(tree1));
- assertTrue(tree2.equals(tree2));
- assertEquals(tree1.hashCode(), tree2.hashCode());
-
- assertTrue(tree3.equals(tree3));
- assertTrue(tree3.equals(tree4));
- assertTrue(tree4.equals(tree3));
- assertTrue(tree4.equals(tree4));
- assertEquals(tree3.hashCode(), tree4.hashCode());
-
- assertNotSame(tree1, tree2);
- assertNotSame(tree1, tree3);
- assertNotSame(tree1, tree4);
- assertNotSame(tree2, tree3);
- assertNotSame(tree2, tree4);
-
- assertFalse(tree1.equals(tree3));
- assertFalse(tree1.equals(tree4));
- assertFalse(tree2.equals(tree3));
- assertFalse(tree2.equals(tree4));
-
- assertNotNull(tree1);
- assertNotNull(tree2);
-
- tree1.add("abcd", tree3);
- assertFalse(tree1.equals(tree2));
- assertFalse(tree2.equals(tree1));// Check reflexive
- if (tree1.hashCode() == tree2.hashCode()) {
- // This is not a requirement
- System.out.println("WARN: unequal HashTrees should not have equal hashCodes");
- }
- tree2.add("abcd", tree4);
- assertTrue(tree1.equals(tree2));
- assertTrue(tree2.equals(tree1));
- assertEquals(tree1.hashCode(), tree2.hashCode());
- }
-
-
- @Test
- public void testAddObjectAndTree() throws Exception {
- ListedHashTree tree = new ListedHashTree("key");
- ListedHashTree newTree = new ListedHashTree("value");
- tree.add("key", newTree);
- assertEquals(tree.list().size(), 1);
- assertEquals("key", tree.getArray()[0]);
- assertEquals(1, tree.getTree("key").list().size());
- assertEquals(0, tree.getTree("key").getTree("value").size());
- assertEquals(tree.getTree("key").getArray()[0], "value");
- assertNotNull(tree.getTree("key").get("value"));
- }
-
- @Test
- public void testEqualsAndHashCode2() throws Exception {
- ListedHashTree tree1 = new ListedHashTree("abcd");
- ListedHashTree tree2 = new ListedHashTree("abcd");
- ListedHashTree tree3 = new ListedHashTree("abcde");
- ListedHashTree tree4 = new ListedHashTree("abcde");
-
- assertTrue(tree1.equals(tree1));
- assertTrue(tree1.equals(tree2));
- assertTrue(tree2.equals(tree1));
- assertTrue(tree2.equals(tree2));
- assertEquals(tree1.hashCode(), tree2.hashCode());
-
- assertTrue(tree3.equals(tree3));
- assertTrue(tree3.equals(tree4));
- assertTrue(tree4.equals(tree3));
- assertTrue(tree4.equals(tree4));
- assertEquals(tree3.hashCode(), tree4.hashCode());
-
- assertNotSame(tree1, tree2);
- assertNotSame(tree1, tree3);
- assertFalse(tree1.equals(tree3));
- assertFalse(tree3.equals(tree1));
- assertFalse(tree1.equals(tree4));
- assertFalse(tree4.equals(tree1));
-
- assertFalse(tree2.equals(tree3));
- assertFalse(tree3.equals(tree2));
- assertFalse(tree2.equals(tree4));
- assertFalse(tree4.equals(tree2));
-
- tree1.add("abcd", tree3);
- assertFalse(tree1.equals(tree2));
- assertFalse(tree2.equals(tree1));
-
- tree2.add("abcd", tree4);
- assertTrue(tree1.equals(tree2));
- assertTrue(tree2.equals(tree1));
- assertEquals(tree1.hashCode(), tree2.hashCode());
-
- tree1.add("a1");
- tree1.add("a2");
- tree2.add("a2");
- tree2.add("a1");
-
- assertFalse(tree1.equals(tree2));
- assertFalse(tree2.equals(tree1));
- if (tree1.hashCode() == tree2.hashCode()) {
- // This is not a requirement
- System.out.println("WARN: unequal ListedHashTrees should not have equal hashcodes");
-
- }
-
- tree4.add("abcdef");
- assertFalse(tree3.equals(tree4));
- assertFalse(tree4.equals(tree3));
- }
-
-
- @Test
- public void testSearch() throws Exception {
- ListedHashTree tree = new ListedHashTree();
- SearchByClass<Integer> searcher = new SearchByClass<>(Integer.class);
- String one = "one";
- String two = "two";
- Integer o = Integer.valueOf(1);
- tree.add(one, o);
- tree.getTree(one).add(o, two);
- tree.traverse(searcher);
- assertEquals(1, searcher.getSearchResults().size());
+ tree2.add("abcd", tree4);
+ assertTrue(tree1.equals(tree2));
+ assertTrue(tree2.equals(tree1));
+ assertEquals(tree1.hashCode(), tree2.hashCode());
+ }
+
+
+ @Test
+ public void testAddObjectAndTree() throws Exception {
+ ListedHashTree tree = new ListedHashTree("key");
+ ListedHashTree newTree = new ListedHashTree("value");
+ tree.add("key", newTree);
+ assertEquals(tree.list().size(), 1);
+ assertEquals("key", tree.getArray()[0]);
+ assertEquals(1, tree.getTree("key").list().size());
+ assertEquals(0, tree.getTree("key").getTree("value").size());
+ assertEquals(tree.getTree("key").getArray()[0], "value");
+ assertNotNull(tree.getTree("key").get("value"));
+ }
+
+ @Test
+ public void testEqualsAndHashCode2() throws Exception {
+ ListedHashTree tree1 = new ListedHashTree("abcd");
+ ListedHashTree tree2 = new ListedHashTree("abcd");
+ ListedHashTree tree3 = new ListedHashTree("abcde");
+ ListedHashTree tree4 = new ListedHashTree("abcde");
+
+ assertTrue(tree1.equals(tree1));
+ assertTrue(tree1.equals(tree2));
+ assertTrue(tree2.equals(tree1));
+ assertTrue(tree2.equals(tree2));
+ assertEquals(tree1.hashCode(), tree2.hashCode());
+
+ assertTrue(tree3.equals(tree3));
+ assertTrue(tree3.equals(tree4));
+ assertTrue(tree4.equals(tree3));
+ assertTrue(tree4.equals(tree4));
+ assertEquals(tree3.hashCode(), tree4.hashCode());
+
+ assertNotSame(tree1, tree2);
+ assertNotSame(tree1, tree3);
+ assertFalse(tree1.equals(tree3));
+ assertFalse(tree3.equals(tree1));
+ assertFalse(tree1.equals(tree4));
+ assertFalse(tree4.equals(tree1));
+
+ assertFalse(tree2.equals(tree3));
+ assertFalse(tree3.equals(tree2));
+ assertFalse(tree2.equals(tree4));
+ assertFalse(tree4.equals(tree2));
+
+ tree1.add("abcd", tree3);
+ assertFalse(tree1.equals(tree2));
+ assertFalse(tree2.equals(tree1));
+
+ tree2.add("abcd", tree4);
+ assertTrue(tree1.equals(tree2));
+ assertTrue(tree2.equals(tree1));
+ assertEquals(tree1.hashCode(), tree2.hashCode());
+
+ tree1.add("a1");
+ tree1.add("a2");
+ tree2.add("a2");
+ tree2.add("a1");
+
+ assertFalse(tree1.equals(tree2));
+ assertFalse(tree2.equals(tree1));
+ if (tree1.hashCode() == tree2.hashCode()) {
+ // This is not a requirement
+ System.out.println("WARN: unequal ListedHashTrees should not have equal hashcodes");
}
+ tree4.add("abcdef");
+ assertFalse(tree3.equals(tree4));
+ assertFalse(tree4.equals(tree3));
+ }
+
+ @Test
+ public void testSearch() throws Exception {
+ ListedHashTree tree = new ListedHashTree();
+ SearchByClass<Integer> searcher = new SearchByClass<>(Integer.class);
+ String one = "one";
+ String two = "two";
+ Integer o = Integer.valueOf(1);
+ tree.add(one, o);
+ tree.getTree(one).add(o, two);
+ tree.traverse(searcher);
+ assertEquals(1, searcher.getSearchResults().size());
+ }
}
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/exec/TestKeyToolUtils.java b/src/jorphan/src/test/java/org/apache/jorphan/exec/TestKeyToolUtils.java
index d180f3b..725688a 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/exec/TestKeyToolUtils.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/exec/TestKeyToolUtils.java
@@ -45,13 +45,12 @@ public class TestKeyToolUtils {
public static void setup(@TempDir Path keystoreDir) throws IOException {
keystore = keystoreDir.resolve("dummy-keystore.jks").toFile();
password = JOrphanUtils.generateRandomAlphanumericPassword(32);
- KeyToolUtils.generateProxyCA(keystore, password, validity );
+ KeyToolUtils.generateProxyCA(keystore, password, validity);
}
/*
* Check the assumption that a missing executable will generate
* either an IOException or status which is neither 0 nor 1
- *
*/
@Test
public void testCheckKeytool() throws Exception {
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableModelTest.java b/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableModelTest.java
index 2bec77d..7a1476d 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableModelTest.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableModelTest.java
@@ -115,7 +115,6 @@ public class ObjectTableModelTest {
// Assert
assertModelRanges();
-
events.assertEvents(
events.assertEvent()
.source(model)
@@ -154,8 +153,6 @@ public class ObjectTableModelTest {
.firstRow(1)
.lastRow(1)
);
-
-
}
@Test
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableSorterTest.java b/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableSorterTest.java
index a628561..32e9f4e 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableSorterTest.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/gui/ObjectTableSorterTest.java
@@ -56,8 +56,7 @@ import org.junit.rules.ErrorCollector;
import org.junit.rules.ExpectedException;
public class ObjectTableSorterTest {
- ObjectTableModel model;
- ObjectTableSorter sorter;
+ private ObjectTableSorter sorter;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@@ -66,77 +65,68 @@ public class ObjectTableSorterTest {
@Before
public void createModelAndSorter() {
- String[] headers = { "key", "value", "object" };
- Functor[] readFunctors = { new Functor("getKey"), new Functor("getValue"), new Functor("getValue") };
- Functor[] writeFunctors = { null, null, null };
- Class<?>[] editorClasses = { String.class, Integer.class, Object.class };
- model = new ObjectTableModel(headers, readFunctors, writeFunctors, editorClasses);
- sorter = new ObjectTableSorter(model);
- List<Entry<String,Integer>> data = asList(b2(), a3(), d4(), c1());
+ String[] headers = {"key", "value", "object"};
+ Functor[] readFunctors = {new Functor("getKey"), new Functor("getValue"), new Functor("getValue")};
+ Functor[] writeFunctors = {null, null, null};
+ Class<?>[] editorClasses = {String.class, Integer.class, Object.class};
+ ObjectTableModel model = new ObjectTableModel(headers, readFunctors, writeFunctors, editorClasses);
+ sorter = new ObjectTableSorter(model);
+ List<Entry<String, Integer>> data = asList(b2(), a3(), d4(), c1());
data.forEach(model::addRow);
}
@Test
public void noSorting() {
- List<SimpleImmutableEntry<String, Integer>> expected = asList(b2(), a3(), d4(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(b2(), a3(), d4(), c1()));
}
@Test
public void sortKeyAscending() {
sorter.setSortKey(new SortKey(0, SortOrder.ASCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(a3(), b2(), c1(), d4());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(a3(), b2(), c1(), d4()));
}
@Test
public void sortKeyDescending() {
sorter.setSortKey(new SortKey(0, SortOrder.DESCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(d4(), c1(), b2(), a3());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(d4(), c1(), b2(), a3()));
}
@Test
public void sortValueAscending() {
sorter.setSortKey(new SortKey(1, SortOrder.ASCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(c1(), b2(), a3(), d4());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(c1(), b2(), a3(), d4()));
}
@Test
public void sortValueDescending() {
sorter.setSortKey(new SortKey(1, SortOrder.DESCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(d4(), a3(), b2(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(d4(), a3(), b2(), c1()));
}
@Test
public void fixLastRowWithAscendingKey() {
sorter.fixLastRow().setSortKey(new SortKey(0, SortOrder.ASCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(a3(), b2(), d4(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(a3(), b2(), d4(), c1()));
}
@Test
public void fixLastRowWithDescendingKey() {
sorter.fixLastRow().setSortKey(new SortKey(0, SortOrder.DESCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(d4(), b2(), a3(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(d4(), b2(), a3(), c1()));
}
@Test
public void fixLastRowWithAscendingValue() {
sorter.fixLastRow().setSortKey(new SortKey(1, SortOrder.ASCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(b2(), a3(), d4(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(b2(), a3(), d4(), c1()));
}
@Test
public void fixLastRowWithDescendingValue() {
sorter.fixLastRow().setSortKey(new SortKey(1, SortOrder.DESCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(d4(), a3(), b2(), c1());
- assertRowOrderAndIndexes(expected);
+ assertRowOrderAndIndexes(asList(d4(), a3(), b2(), c1()));
}
@Test
@@ -146,44 +136,40 @@ public class ObjectTableSorterTest {
map.put(key, map.size());
return map;
}, (a, b) -> a);
- Comparator<String> customKeyComparator = (a,b) -> customKeyOrder.get(a).compareTo(customKeyOrder.get(b));
- sorter.setValueComparator(0, customKeyComparator).setSortKey(new SortKey(0, SortOrder.ASCENDING));
- List<SimpleImmutableEntry<String, Integer>> expected = asList(a3(), c1(), b2(), d4());
- assertRowOrderAndIndexes(expected);
+ Comparator<String> customKeyComparator = Comparator.comparing(customKeyOrder::get);
+ sorter.setValueComparator(0, customKeyComparator)
+ .setSortKey(new SortKey(0, SortOrder.ASCENDING));
+ assertRowOrderAndIndexes(asList(a3(), c1(), b2(), d4()));
}
- private ObjectTableModel createTableModel(final String name,
- final Class<?> klass) {
- return new ObjectTableModel(new String[] { name },
- new Functor[] { null }, new Functor[] { null },
- new Class<?>[] { klass });
+ private ObjectTableModel createTableModel(
+ final String name, final Class<?> klass) {
+ return new ObjectTableModel(new String[]{name},
+ new Functor[]{null}, new Functor[]{null},
+ new Class<?>[]{klass});
}
@Test
public void getDefaultComparatorForNullClass() {
ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("null", null));
-
assertThat(sorter.getValueComparator(0), is(nullValue()));
}
@Test
public void getDefaultComparatorForStringClass() {
ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("string", String.class));
-
assertThat(sorter.getValueComparator(0), is(CoreMatchers.notNullValue()));
}
@Test
public void getDefaultComparatorForIntegerClass() {
ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("integer", Integer.class));
-
assertThat(sorter.getValueComparator(0), is(CoreMatchers.notNullValue()));
}
@Test
public void getDefaultComparatorForObjectClass() {
ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("object", Object.class));
-
assertThat(sorter.getValueComparator(0), is(nullValue()));
}
@@ -250,7 +236,7 @@ public class ObjectTableSorterTest {
public void setSortKeys_single() {
List<SortKey> keys = singletonList(new SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(keys);
- assertThat(sorter.getSortKeys(), allOf( is(not(sameInstance(keys))), is(equalTo(keys)) ));
+ assertThat(sorter.getSortKeys(), allOf(is(not(sameInstance(keys))), is(equalTo(keys))));
}
@Test
@@ -267,31 +253,30 @@ public class ObjectTableSorterTest {
sorter.setSortKeys(Collections.singletonList(new SortKey(2, SortOrder.ASCENDING)));
}
-
@SuppressWarnings("unchecked")
- protected List<Entry<String,Integer>> actual() {
+ protected List<Entry<String, Integer>> actual() {
return IntStream
.range(0, sorter.getViewRowCount())
.map(sorter::convertRowIndexToModel)
- .mapToObj(modelIndex -> (Entry<String,Integer>) sorter.getModel().getObjectListAsList().get(modelIndex))
+ .mapToObj(modelIndex -> (Entry<String, Integer>) sorter.getModel().getObjectListAsList().get(modelIndex))
.collect(Collectors.toList())
;
}
protected SimpleImmutableEntry<String, Integer> d4() {
- return new AbstractMap.SimpleImmutableEntry<>("d", 4);
+ return new AbstractMap.SimpleImmutableEntry<>("d", 4);
}
protected SimpleImmutableEntry<String, Integer> c1() {
- return new AbstractMap.SimpleImmutableEntry<>("c", 1);
+ return new AbstractMap.SimpleImmutableEntry<>("c", 1);
}
protected SimpleImmutableEntry<String, Integer> b2() {
- return new AbstractMap.SimpleImmutableEntry<>("b", 2);
+ return new AbstractMap.SimpleImmutableEntry<>("b", 2);
}
protected SimpleImmutableEntry<String, Integer> a3() {
- return new AbstractMap.SimpleImmutableEntry<>("a", 3);
+ return new AbstractMap.SimpleImmutableEntry<>("a", 3);
}
protected void assertRowOrderAndIndexes(List<SimpleImmutableEntry<String, Integer>> expected) {
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/math/TestStatCalculator.java b/src/jorphan/src/test/java/org/apache/jorphan/math/TestStatCalculator.java
index a71c4ef..706ce55 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/math/TestStatCalculator.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/math/TestStatCalculator.java
@@ -63,7 +63,6 @@ public class TestStatCalculator {
statistics.addValue(l);
}
assertEquals(9, calc.getPercentPoint(0.8999999).intValue());
- //
assertEquals(Math.round(statistics.getPercentile(90)),
calc.getPercentPoint(0.9).intValue());
}
@@ -106,36 +105,36 @@ public class TestStatCalculator {
}
@Test
- public void testLong(){
+ public void testLong() {
calc.addValue(0L);
calc.addValue(2L);
calc.addValue(2L);
final Long long0 = Long.valueOf(0);
final Long long2 = Long.valueOf(2);
- assertEquals(long2,calc.getMax());
- assertEquals(long0,calc.getMin());
+ assertEquals(long2, calc.getMax());
+ assertEquals(long0, calc.getMin());
Map<Number, Number[]> map = calc.getDistribution();
assertTrue(map.containsKey(long0));
assertTrue(map.containsKey(long2));
}
@Test
- public void testInteger(){
+ public void testInteger() {
StatCalculatorInteger calci = new StatCalculatorInteger();
assertEquals(Integer.MIN_VALUE, calci.getMax().intValue());
assertEquals(Integer.MAX_VALUE, calci.getMin().intValue());
calci.addValue(0);
calci.addValue(2);
calci.addValue(2);
- assertEquals(Integer.valueOf(2),calci.getMax());
- assertEquals(Integer.valueOf(0),calci.getMin());
+ assertEquals(Integer.valueOf(2), calci.getMax());
+ assertEquals(Integer.valueOf(0), calci.getMin());
Map<Number, Number[]> map = calci.getDistribution();
assertTrue(map.containsKey(Integer.valueOf(0)));
assertTrue(map.containsKey(Integer.valueOf(2)));
}
@Test
- public void testBug52125_1(){ // No duplicates when adding
+ public void testBug52125_1() { // No duplicates when adding
calc.addValue(1L);
calc.addValue(2L);
calc.addValue(3L);
@@ -149,7 +148,7 @@ public class TestStatCalculator {
@Test
@SuppressWarnings("boxing")
- public void testBug52125_2(){ // add duplicates
+ public void testBug52125_2() { // add duplicates
calc.addValue(1L);
calc.addValue(2L);
calc.addValue(3L);
@@ -160,7 +159,7 @@ public class TestStatCalculator {
}
@Test
- public void testBug52125_2A(){ // as above, but with aggregate sample instead
+ public void testBug52125_2A() { // as above, but with aggregate sample instead
calc.addValue(1L);
calc.addValue(2L);
calc.addValue(3L);
@@ -171,7 +170,7 @@ public class TestStatCalculator {
}
@Test
- public void testBug52125_3(){ // add duplicates as per bug
+ public void testBug52125_3() { // add duplicates as per bug
calc.addValue(1L);
calc.addValue(2L);
calc.addValue(3L);
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/reflect/TestClassTools.java b/src/jorphan/src/test/java/org/apache/jorphan/reflect/TestClassTools.java
index 93faee0..d756ba8 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/reflect/TestClassTools.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/reflect/TestClassTools.java
@@ -25,17 +25,8 @@ import static org.junit.Assert.assertTrue;
import org.apache.jorphan.util.JMeterException;
import org.junit.Test;
-/**
- * Test various aspects of the {@link ClassTools} class
- */
public class TestClassTools {
- /**
- * Test that a class can be constructed using the default constructor
- *
- * @throws JMeterException
- * when something fails during object construction
- */
@Test
public void testConstructString() throws JMeterException {
String dummy = (String) ClassTools.construct("java.lang.String");
@@ -43,27 +34,13 @@ public class TestClassTools {
assertEquals("", dummy);
}
- /**
- * Test that a class can be constructed using an constructor with an integer
- * parameter
- *
- * @throws JMeterException
- * when something fails during object construction
- */
@Test
- public void testConstructStringInt() throws JMeterException {
+ public void testConstructInt() throws JMeterException {
Integer dummy = (Integer) ClassTools.construct("java.lang.Integer", 23);
assertNotNull(dummy);
assertEquals(Integer.valueOf(23), dummy);
}
- /**
- * Test that a class can be constructed using an constructor with an string
- * parameter
- *
- * @throws JMeterException
- * when something fails during object construction
- */
@Test
public void testConstructStringString() throws JMeterException {
String dummy = (String) ClassTools.construct("java.lang.String",
@@ -72,28 +49,13 @@ public class TestClassTools {
assertEquals("hello", dummy);
}
- /**
- * Test that a simple method can be invoked on an object
- *
- * @throws SecurityException
- * when the method can not be used because of security concerns
- * @throws IllegalArgumentException
- * when the method parameters does not match the given ones
- * @throws JMeterException
- * when something fails while invoking the method
- */
@Test
- public void testInvoke() throws SecurityException,
- IllegalArgumentException, JMeterException {
+ public void testInvoke() throws Exception {
Dummy dummy = new Dummy();
ClassTools.invoke(dummy, "callMe");
assertTrue(dummy.wasCalled());
}
- /**
- * Dummy class to be used for construction and invocation tests
- *
- */
public static class Dummy {
private boolean called = false;
@@ -105,12 +67,9 @@ public class TestClassTools {
return this.called;
}
- /**
- * Simple method to be called on void invocation
- */
+ /** Simple method to be called on void invocation */
public void callMe() {
this.called = true;
}
}
-
}
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/util/TestConverter.java b/src/jorphan/src/test/java/org/apache/jorphan/util/TestConverter.java
index eb3de3f..5ee1a5c 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/util/TestConverter.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/util/TestConverter.java
@@ -28,16 +28,9 @@ import java.util.GregorianCalendar;
import org.junit.Test;
-/**
- * Tests for {@link Converter}
- *
- */
+/** Tests for {@link Converter} */
public class TestConverter {
- /**
- * Test {@link Converter#getCalendar(Object, Calendar)} with a given Date
- * and null as default value
- */
@Test
public void testGetCalendarObjectCalendarWithTimeAndNullDefault() {
Calendar cal = new GregorianCalendar();
@@ -45,20 +38,12 @@ public class TestConverter {
assertEquals(cal, Converter.getCalendar(time, null));
}
- /**
- * Test {@link Converter#getCalendar(Object, Calendar)} with null as Date
- * and a sensible default value
- */
@Test
public void testGetCalendarObjectCalendarWithNullAndCalendarAsDefault() {
Calendar cal = new GregorianCalendar();
assertEquals(cal, Converter.getCalendar(null, cal));
}
- /**
- * Test {@link Converter#getCalendar(Object, Calendar)} with correctly
- * formatted strings and <code>null</code> as default value
- */
@Test
public void testGetCalendarObjectCalendarWithValidStringAndNullDefault() {
Calendar cal = new GregorianCalendar();
@@ -75,39 +60,23 @@ public class TestConverter {
}
}
- /**
- * Test {@link Converter#getCalendar(Object, Calendar)} with an invalid
- * string and <code>null</code> as default value
- */
@Test
public void testGetCalendarObjectCalendarWithInvalidStringAndNullDefault() {
assertNull(Converter.getCalendar("invalid date", null));
}
- /**
- * Test {@link Converter#getDate(Object, Date)} with a given Date
- * and null as default value
- */
@Test
public void testGetDateObjectDateWithTimeAndNullDefault() {
Date time = new Date();
assertEquals(time, Converter.getDate(time, null));
}
- /**
- * Test {@link Converter#getDate(Object, Date)} with null as Date
- * and a sensible default value
- */
@Test
public void testGetDateObjectDateWithNullAndDateAsDefault() {
Date date = new Date();
assertEquals(date, Converter.getDate(null, date));
}
- /**
- * Test {@link Converter#getDate(Object, Date)} with correctly
- * formatted strings and <code>null</code> as default value
- */
@Test
public void testGetDateObjectDateWithValidStringAndNullDefault() {
Calendar cal = new GregorianCalendar();
@@ -124,13 +93,8 @@ public class TestConverter {
}
}
- /**
- * Test {@link Converter#getDate(Object, Date)} with an invalid
- * string and <code>null</code> as default value
- */
@Test
public void testGetDateObjectDateWithInvalidStringAndNullDefault() {
assertNull(Converter.getDate("invalid date", null));
}
-
}
diff --git a/src/jorphan/src/test/java/org/apache/jorphan/util/TestJorphanUtils.java b/src/jorphan/src/test/java/org/apache/jorphan/util/TestJorphanUtils.java
index 86cc3a9..2864229 100644
--- a/src/jorphan/src/test/java/org/apache/jorphan/util/TestJorphanUtils.java
+++ b/src/jorphan/src/test/java/org/apache/jorphan/util/TestJorphanUtils.java
@@ -80,84 +80,79 @@ public class TestJorphanUtils {
// Test ignore trailing split characters
// Ignore adjacent delimiters
assertThat("Ignore trailing split chars", JOrphanUtils.split("a,bc,,", ",", true),
- CoreMatchers.equalTo(new String[] { "a", "bc" }));
+ CoreMatchers.equalTo(new String[]{"a", "bc"}));
}
@Test
public void testSplitStringStringFalseWithTrailingSplitChars() {
- // Test ignore trailing split characters
+ // Test ignore trailing split characters
assertThat("Include the trailing split chars", JOrphanUtils.split("a,bc,,", ",", false),
- CoreMatchers.equalTo(new String[] { "a", "bc", "", "" }));
+ CoreMatchers.equalTo(new String[]{"a", "bc", "", ""}));
}
@Test
public void testSplitStringStringTrueWithLeadingSplitChars() {
// Test leading split characters
assertThat("Ignore leading split chars", JOrphanUtils.split(",,a,bc", ",", true),
- CoreMatchers.equalTo(new String[] { "a", "bc" }));
+ CoreMatchers.equalTo(new String[]{"a", "bc"}));
}
@Test
public void testSplitStringStringFalseWithLeadingSplitChars() {
// Test leading split characters
assertThat("Include leading split chars", JOrphanUtils.split(",,a,bc", ",", false),
- CoreMatchers.equalTo(new String[] { "", "", "a", "bc" }));
+ CoreMatchers.equalTo(new String[]{"", "", "a", "bc"}));
}
@Test
public void testSplit3() {
String in = "a,bc,,"; // Test ignore trailing split characters
- String[] out = JOrphanUtils.split(in, ",",true);// Ignore adjacent delimiters
- assertThat(out, CoreMatchers.equalTo(new String[] { "a", "bc" }));
- out = JOrphanUtils.split(in, ",",false);
- assertThat(out, CoreMatchers.equalTo(new String[] { "a", "bc", "", "" }));
+ String[] out = JOrphanUtils.split(in, ",", true);// Ignore adjacent delimiters
+ assertThat(out, CoreMatchers.equalTo(new String[]{"a", "bc"}));
+ out = JOrphanUtils.split(in, ",", false);
+ assertThat(out, CoreMatchers.equalTo(new String[]{"a", "bc", "", ""}));
}
@Test
public void testSplitStringStringTrueWithLeadingComplexSplitCharacters() {
// Test leading split characters
- assertThat(JOrphanUtils.split(" , ,a ,bc", " ,", true), CoreMatchers.equalTo(new String[] { "a", "bc" }));
+ assertThat(JOrphanUtils.split(" , ,a ,bc", " ,", true), CoreMatchers.equalTo(new String[]{"a", "bc"}));
}
@Test
public void testSplitStringStringFalseWithLeadingComplexSplitCharacters() {
// Test leading split characters
assertThat(JOrphanUtils.split(" , ,a ,bc", " ,", false),
- CoreMatchers.equalTo(new String[] { "", "", "a", "bc" }));
+ CoreMatchers.equalTo(new String[]{"", "", "a", "bc"}));
}
@Test
- public void testSplitStringStringTrueTruncate() throws Exception
- {
+ public void testSplitStringStringTrueTruncate() throws Exception {
assertThat(JOrphanUtils.split("a;,b;,;,;,d;,e;,;,f", ";,", true),
- CoreMatchers.equalTo(new String[] { "a", "b", "d", "e", "f" }));
+ CoreMatchers.equalTo(new String[]{"a", "b", "d", "e", "f"}));
}
@Test
- public void testSplitStringStringFalseTruncate() throws Exception
- {
+ public void testSplitStringStringFalseTruncate() throws Exception {
assertThat(JOrphanUtils.split("a;,b;,;,;,d;,e;,;,f", ";,", false),
- CoreMatchers.equalTo(new String[] { "a", "b", "", "", "d", "e", "", "f" }));
+ CoreMatchers.equalTo(new String[]{"a", "b", "", "", "d", "e", "", "f"}));
}
@Test
- public void testSplitStringStringTrueDoubledSplitChar() throws Exception
- {
+ public void testSplitStringStringTrueDoubledSplitChar() throws Exception {
assertThat(JOrphanUtils.split("a;;b;;;;;;d;;e;;;;f", ";;", true),
- CoreMatchers.equalTo(new String[] { "a", "b", "d", "e", "f" }));
+ CoreMatchers.equalTo(new String[]{"a", "b", "d", "e", "f"}));
}
@Test
- public void testSplitStringStringFalseDoubledSplitChar() throws Exception
- {
+ public void testSplitStringStringFalseDoubledSplitChar() throws Exception {
assertThat(JOrphanUtils.split("a;;b;;;;;;d;;e;;;;f", ";;", false),
- CoreMatchers.equalTo(new String[] { "a", "b", "", "", "d", "e", "", "f" }));
-
+ CoreMatchers.equalTo(new String[]{"a", "b", "", "", "d", "e", "", "f"}));
}
// Empty string
@Test
- public void testEmpty(){
+ public void testEmpty() {
String[] out = JOrphanUtils.split("", ",", false);
assertEquals(0, out.length);
}
@@ -166,37 +161,37 @@ public class TestJorphanUtils {
@Test
public void testSplitSSSSingleDelimiterWithDefaultValue() {
// Test non-empty parameters
- assertThat(JOrphanUtils.split("a,bc,,", ",", "?"), CoreMatchers.equalTo(new String[] { "a", "bc", "?", "?" }));
+ assertThat(JOrphanUtils.split("a,bc,,", ",", "?"), CoreMatchers.equalTo(new String[]{"a", "bc", "?", "?"}));
}
@Test
public void testSplitSSSSingleDelimiterWithEmptyValue() {
// Empty default
- assertThat(JOrphanUtils.split("a,bc,,", ",", ""), CoreMatchers.equalTo(new String[] { "a", "bc", "", "" }));
+ assertThat(JOrphanUtils.split("a,bc,,", ",", ""), CoreMatchers.equalTo(new String[]{"a", "bc", "", ""}));
}
@Test
public void testSplitSSSEmptyDelimiter() {
String in = "a,bc,,"; // Empty delimiter
- assertThat(JOrphanUtils.split(in, "", "?"), CoreMatchers.equalTo(new String[] { in }));
+ assertThat(JOrphanUtils.split(in, "", "?"), CoreMatchers.equalTo(new String[]{in}));
}
@Test
public void testSplitSSSMultipleDelimCharsWithDefaultValue() {
// Multiple delimiters
assertThat(JOrphanUtils.split("a,b;c,,", ",;", "?"),
- CoreMatchers.equalTo(new String [] { "a", "b", "c", "?", "?" }));
+ CoreMatchers.equalTo(new String[]{"a", "b", "c", "?", "?"}));
}
@Test
public void testSplitSSSMultipleDelimCharsWithEmptyValue() {
// Multiple delimiters
- assertThat(JOrphanUtils.split("a,b;c,,", ",;", ""), CoreMatchers.equalTo(new String[] { "a", "b", "c", "", "" }));
+ assertThat(JOrphanUtils.split("a,b;c,,", ",;", ""), CoreMatchers.equalTo(new String[]{"a", "b", "c", "", ""}));
}
@Test
public void testSplitSSSSameDelimiterAsDefaultValue() {
- assertThat(JOrphanUtils.split("a,bc,,", ",", ","), CoreMatchers.equalTo(new String[] { "a", "bc", ",", "," }));
+ assertThat(JOrphanUtils.split("a,bc,,", ",", ","), CoreMatchers.equalTo(new String[]{"a", "bc", ",", ","}));
}
@Test(expected=NullPointerException.class)
@@ -211,79 +206,79 @@ public class TestJorphanUtils {
@Test
public void testSplitStringStringNullWithSingleDelimiter() {
- assertThat(JOrphanUtils.split("a,bc,,", ",", null), CoreMatchers.equalTo(new String[] { "a", "bc" }));
+ assertThat(JOrphanUtils.split("a,bc,,", ",", null), CoreMatchers.equalTo(new String[]{"a", "bc"}));
}
@Test
public void testSplitStringStringNullWithMultipleDelimiter() {
- assertThat(JOrphanUtils.split("a,;bc,;,", ",;", null), CoreMatchers.equalTo(new String[] { "a", "bc" }));
+ assertThat(JOrphanUtils.split("a,;bc,;,", ",;", null), CoreMatchers.equalTo(new String[]{"a", "bc"}));
}
@Test
public void testSplitSSSWithEmptyInput() {
- String[] out = JOrphanUtils.split("", "," ,"x");
+ String[] out = JOrphanUtils.split("", ",", "x");
assertEquals(0, out.length);
}
@Test
public void testSplitSSSWithEmptyDelimiter() {
final String in = "a,;bc,;,";
- assertThat(JOrphanUtils.split(in, "", "x"), CoreMatchers.equalTo(new String[] { in }));
+ assertThat(JOrphanUtils.split(in, "", "x"), CoreMatchers.equalTo(new String[]{in}));
}
@Test
- public void testreplaceAllChars(){
- assertEquals("", JOrphanUtils.replaceAllChars("",' ', "+"));
- assertEquals("source", JOrphanUtils.replaceAllChars("source",' ', "+"));
- assertEquals("so+rce", JOrphanUtils.replaceAllChars("source",'u', "+"));
- assertEquals("+so+urc+", JOrphanUtils.replaceAllChars("esoeurce",'e', "+"));
- assertEquals("AZAZsoAZurcAZ", JOrphanUtils.replaceAllChars("eesoeurce",'e', "AZ"));
- assertEquals("A+B++C+", JOrphanUtils.replaceAllChars("A B C ",' ', "+"));
- assertEquals("A%20B%20%20C%20", JOrphanUtils.replaceAllChars("A B C ",' ', "%20"));
+ public void testreplaceAllChars() {
+ assertEquals("", JOrphanUtils.replaceAllChars("", ' ', "+"));
+ assertEquals("source", JOrphanUtils.replaceAllChars("source", ' ', "+"));
+ assertEquals("so+rce", JOrphanUtils.replaceAllChars("source", 'u', "+"));
+ assertEquals("+so+urc+", JOrphanUtils.replaceAllChars("esoeurce", 'e', "+"));
+ assertEquals("AZAZsoAZurcAZ", JOrphanUtils.replaceAllChars("eesoeurce", 'e', "AZ"));
+ assertEquals("A+B++C+", JOrphanUtils.replaceAllChars("A B C ", ' ', "+"));
+ assertEquals("A%20B%20%20C%20", JOrphanUtils.replaceAllChars("A B C ", ' ', "%20"));
}
@Test
- public void testTrim(){
- assertEquals("",JOrphanUtils.trim("", " ;"));
- assertEquals("",JOrphanUtils.trim(" ", " ;"));
- assertEquals("",JOrphanUtils.trim("; ", " ;"));
- assertEquals("",JOrphanUtils.trim(";;", " ;"));
- assertEquals("",JOrphanUtils.trim(" ", " ;"));
- assertEquals("abc",JOrphanUtils.trim("abc ;", " ;"));
+ public void testTrim() {
+ assertEquals("", JOrphanUtils.trim("", " ;"));
+ assertEquals("", JOrphanUtils.trim(" ", " ;"));
+ assertEquals("", JOrphanUtils.trim("; ", " ;"));
+ assertEquals("", JOrphanUtils.trim(";;", " ;"));
+ assertEquals("", JOrphanUtils.trim(" ", " ;"));
+ assertEquals("abc", JOrphanUtils.trim("abc ;", " ;"));
}
@Test
public void testGetByteArraySlice() throws Exception {
- Assert.assertArrayEquals(new byte[] {1, 2},
- JOrphanUtils.getByteArraySlice(new byte[]{0, 1, 2, 3}, 1, 2));
+ Assert.assertArrayEquals(new byte[]{1, 2},
+ JOrphanUtils.getByteArraySlice(new byte[]{0, 1, 2, 3}, 1, 2));
}
@Test
- public void testbaToHexString(){
- assertEquals("",JOrphanUtils.baToHexString(new byte[]{}));
- assertEquals("00",JOrphanUtils.baToHexString(new byte[]{0}));
- assertEquals("0f107f8081ff",JOrphanUtils.baToHexString(new byte[]{15,16,127,-128,-127,-1}));
+ public void testbaToHexString() {
+ assertEquals("", JOrphanUtils.baToHexString(new byte[]{}));
+ assertEquals("00", JOrphanUtils.baToHexString(new byte[]{0}));
+ assertEquals("0f107f8081ff", JOrphanUtils.baToHexString(new byte[]{15, 16, 127, -128, -127, -1}));
}
@Test
- public void testBaToHexStringSeparator(){
+ public void testBaToHexStringSeparator() {
assertEquals("", JOrphanUtils.baToHexString(new byte[]{}, '-'));
assertEquals("00", JOrphanUtils.baToHexString(new byte[]{0}, '-'));
- assertEquals("0f-10-7f-80-81-ff", JOrphanUtils.baToHexString(new byte[]{15,16,127,-128,-127,-1}, '-'));
+ assertEquals("0f-10-7f-80-81-ff", JOrphanUtils.baToHexString(new byte[]{15, 16, 127, -128, -127, -1}, '-'));
}
@Test
- public void testbaToByte() throws Exception{
- assertEqualsArray(new byte[]{},JOrphanUtils.baToHexBytes(new byte[]{}));
- assertEqualsArray(new byte[]{'0','0'},JOrphanUtils.baToHexBytes(new byte[]{0}));
+ public void testbaToByte() throws Exception {
+ assertEqualsArray(new byte[]{}, JOrphanUtils.baToHexBytes(new byte[]{}));
+ assertEqualsArray(new byte[]{'0', '0'}, JOrphanUtils.baToHexBytes(new byte[]{0}));
assertEqualsArray("0f107f8081ff".getBytes(StandardCharsets.UTF_8),
- JOrphanUtils.baToHexBytes(new byte[] { 15, 16, 127, -128, -127, -1 }));
+ JOrphanUtils.baToHexBytes(new byte[]{15, 16, 127, -128, -127, -1}));
}
- private void assertEqualsArray(byte[] expected, byte[] actual){
- assertEquals("arrays must be same length",expected.length, actual.length);
- for(int i=0; i < expected.length; i++){
- assertEquals("values must be the same for index: "+i,expected[i],actual[i]);
+ private void assertEqualsArray(byte[] expected, byte[] actual) {
+ assertEquals("arrays must be same length", expected.length, actual.length);
+ for (int i = 0; i < expected.length; i++) {
+ assertEquals("values must be the same for index: " + i, expected[i], actual[i]);
}
}
@@ -313,17 +308,17 @@ public class TestJorphanUtils {
in = new StringBuilder("A");
assertEquals(" A", JOrphanUtils.rightAlign(in, 8).toString());
assertEquals(" foo",
- JOrphanUtils.rightAlign(new StringBuilder("foo"), 39).toString());
+ JOrphanUtils.rightAlign(new StringBuilder("foo"), 39).toString());
}
@Test
public void testLeftAlign() {
- assertEquals("foo ",
- JOrphanUtils.leftAlign(new StringBuilder("foo"), 5).toString());
- assertEquals("foo",
- JOrphanUtils.leftAlign(new StringBuilder("foo"), 2).toString());
- assertEquals("foo ",
- JOrphanUtils.leftAlign(new StringBuilder("foo"), 39).toString());
+ assertEquals("foo ",
+ JOrphanUtils.leftAlign(new StringBuilder("foo"), 5).toString());
+ assertEquals("foo",
+ JOrphanUtils.leftAlign(new StringBuilder("foo"), 2).toString());
+ assertEquals("foo ",
+ JOrphanUtils.leftAlign(new StringBuilder("foo"), 39).toString());
}
@Test
@@ -335,39 +330,38 @@ public class TestJorphanUtils {
@Test
public void testReplaceAllWithRegexWithSearchValueContainedInReplaceValue() {
// Bug 61054
- Assert.assertArrayEquals(new Object[] { "abcd", 1 },
+ Assert.assertArrayEquals(new Object[]{"abcd", 1},
JOrphanUtils.replaceAllWithRegex("abc", "abc", "abcd", true));
}
@Test
public void testReplaceAllWithRegex() {
- Assert.assertArrayEquals(new Object[] {"toto", 0},
- JOrphanUtils.replaceAllWithRegex("toto","ti", "ta", true));
- Assert.assertArrayEquals(new Object[] {"toto", 0},
- JOrphanUtils.replaceAllWithRegex("toto","TO", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TITI", 2},
- JOrphanUtils.replaceAllWithRegex("toto","TO", "TI", false));
- Assert.assertArrayEquals(new Object[] {"TITI", 2},
- JOrphanUtils.replaceAllWithRegex("toto","to", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TITIti", 2},
- JOrphanUtils.replaceAllWithRegex("tototi","to", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TOTIti", 1},
- JOrphanUtils.replaceAllWithRegex("TOtoti","to", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TOTI", 1},
- JOrphanUtils.replaceAllWithRegex("TOtoti","to.*", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TOTI", 1},
- JOrphanUtils.replaceAllWithRegex("TOtoti","to.*ti", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TOTITITITIaTITITIti", 7},
- JOrphanUtils.replaceAllWithRegex("TO1232a123ti","[0-9]", "TI", true));
- Assert.assertArrayEquals(new Object[] {"TOTIaTIti", 2},
- JOrphanUtils.replaceAllWithRegex("TO1232a123ti","[0-9]+", "TI", true));
-
- Assert.assertArrayEquals(new Object[] {"TO${var}2a${var}ti", 2},
- JOrphanUtils.replaceAllWithRegex("TO1232a123ti","123", "${var}", true));
-
- Assert.assertArrayEquals(new Object[] {"TO${var}2a${var}ti${var2}", 2},
- JOrphanUtils.replaceAllWithRegex("TO1232a123ti${var2}","123", "${var}", true));
-
+ Assert.assertArrayEquals(new Object[]{"toto", 0},
+ JOrphanUtils.replaceAllWithRegex("toto", "ti", "ta", true));
+ Assert.assertArrayEquals(new Object[]{"toto", 0},
+ JOrphanUtils.replaceAllWithRegex("toto", "TO", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TITI", 2},
+ JOrphanUtils.replaceAllWithRegex("toto", "TO", "TI", false));
+ Assert.assertArrayEquals(new Object[]{"TITI", 2},
+ JOrphanUtils.replaceAllWithRegex("toto", "to", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TITIti", 2},
+ JOrphanUtils.replaceAllWithRegex("tototi", "to", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TOTIti", 1},
+ JOrphanUtils.replaceAllWithRegex("TOtoti", "to", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TOTI", 1},
+ JOrphanUtils.replaceAllWithRegex("TOtoti", "to.*", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TOTI", 1},
+ JOrphanUtils.replaceAllWithRegex("TOtoti", "to.*ti", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TOTITITITIaTITITIti", 7},
+ JOrphanUtils.replaceAllWithRegex("TO1232a123ti", "[0-9]", "TI", true));
+ Assert.assertArrayEquals(new Object[]{"TOTIaTIti", 2},
+ JOrphanUtils.replaceAllWithRegex("TO1232a123ti", "[0-9]+", "TI", true));
+
+ Assert.assertArrayEquals(new Object[]{"TO${var}2a${var}ti", 2},
+ JOrphanUtils.replaceAllWithRegex("TO1232a123ti", "123", "${var}", true));
+
+ Assert.assertArrayEquals(new Object[]{"TO${var}2a${var}ti${var2}", 2},
+ JOrphanUtils.replaceAllWithRegex("TO1232a123ti${var2}", "123", "${var}", true));
}
@Test
@@ -395,9 +389,9 @@ public class TestJorphanUtils {
@Test
public void testUnsplit() {
- assertEquals("", JOrphanUtils.unsplit(new Object[] {null, null}, 0));
- assertEquals("11", JOrphanUtils.unsplit(new Object[] {null, 1}, 1));
- assertEquals("-26738698", JOrphanUtils.unsplit(new Object[] {-26_738_698}, 1));
+ assertEquals("", JOrphanUtils.unsplit(new Object[]{null, null}, 0));
+ assertEquals("11", JOrphanUtils.unsplit(new Object[]{null, 1}, 1));
+ assertEquals("-26738698", JOrphanUtils.unsplit(new Object[]{-26_738_698}, 1));
}
@Test
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/curl/BasicCurlParserTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/curl/BasicCurlParserTest.java
index 2b3ae8b..df7a3a7 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/curl/BasicCurlParserTest.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/curl/BasicCurlParserTest.java
@@ -21,7 +21,6 @@ package org.apache.jmeter.curl;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -33,16 +32,11 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-/**
- * @since 5.1
- */
public class BasicCurlParserTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
- /**
- *
- */
+
public BasicCurlParserTest() {
super();
}
@@ -314,6 +308,7 @@ public class BasicCurlParserTest {
Assert.assertEquals("With method 'parser',the parameters need to reserve '\n' and '\r' ", "name=test",
request.getPostData());
}
+
@Test(expected = IllegalArgumentException.class)
public void testDataReadFromNonexistentFile() {
String cmdLine = "curl 'https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit/action_page.php' "
@@ -322,6 +317,7 @@ public class BasicCurlParserTest {
basicCurlParser.parse(cmdLine);
Assert.fail("The method 'translateCommandline shouldn't run when the path of file is incorrect");
}
+
@Test
public void testDataUrlEncodeOneParameterWithoutName() {
String cmdLine = "curl 'https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit/action_page.php' "
@@ -331,6 +327,7 @@ public class BasicCurlParserTest {
Assert.assertEquals("With method 'parser',the parameters need to be encoded' ", "%C3%A9",
request.getPostData());
}
+
@Test
public void testDataUrlEncodeOneParameterWithName() {
String cmdLine = "curl -s 'https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit/action_page.php' "
@@ -364,6 +361,7 @@ public class BasicCurlParserTest {
Assert.assertEquals("With method 'parser',the parameters in the file need to be encoded' ", "name=test",
request.getPostData());
}
+
@Test
public void testDataUrlEncodeWith2AtSymbol() throws IOException {
String encoding = StandardCharsets.UTF_8.name();
@@ -512,12 +510,12 @@ public class BasicCurlParserTest {
String url = "api.imgur.com/3/upload";
BasicCurlParser.stringToCookie(cookieStr, url);
}
+
@Test
public void testCookie() {
String cmdLine = "curl -X POST \"https://api.imgur.com/3/upload\" -b 'name=Tom;password=123456'";
BasicCurlParser basicCurlParser = new BasicCurlParser();
BasicCurlParser.Request request = basicCurlParser.parse(cmdLine);
- List<Cookie>cookies=new ArrayList<>();
Cookie c1=new Cookie();
c1.setDomain("api.imgur.com");
c1.setName("name");
@@ -528,8 +526,6 @@ public class BasicCurlParserTest {
c2.setName("password");
c2.setValue("123456");
c2.setPath("/3/upload");
- cookies.add(c1);
- cookies.add(c2);
Assert.assertTrue("With method 'parser', the cookie should be set in CookieManager",
request.getCookies("https://api.imgur.com/3/upload").contains(c1));
Assert.assertTrue("With method 'parser', the cookie should be set in CookieManager",
@@ -537,6 +533,7 @@ public class BasicCurlParserTest {
Assert.assertEquals("With method 'parser', the cookie should be set in CookieManager", 2,
request.getCookies("https://api.imgur.com/3/upload").size());
}
+
@Test
public void testCookieFromFile() throws IOException {
File file = tempFolder.newFile("test.txt");
@@ -545,7 +542,9 @@ public class BasicCurlParserTest {
BasicCurlParser basicCurlParser = new BasicCurlParser();
BasicCurlParser.Request request = basicCurlParser.parse(cmdLine);
Assert.assertEquals("With method 'parser', the file of cookie should be uploaded in CookieManager",
- file.getAbsolutePath(), request.getFilepathCookie());}
+ file.getAbsolutePath(), request.getFilepathCookie());
+ }
+
@Test
public void testCookieInHeader() {
String cmdLine = "curl 'http://jmeter.apache.org/' -H 'cookie: PHPSESSID=testphpsessid;a=b' --compressed";
@@ -560,6 +559,7 @@ public class BasicCurlParserTest {
Assert.assertEquals("Just static cookie in header can be added in CookieManager", c1, cookies.get(0));
Assert.assertEquals("Just static cookie in header can be added in CookieManager", 1, cookies.size());
}
+
@Test
public void testIgnoreOptions() {
String cmdLine = "curl 'http://jmeter.apache.org/' --include --keepalive-time '20'";
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/MultipartUrlConfigTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/MultipartUrlConfigTest.java
index 9633ea0..cf3aeab 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/MultipartUrlConfigTest.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/MultipartUrlConfigTest.java
@@ -28,7 +28,6 @@ import org.junit.Test;
public class MultipartUrlConfigTest {
-
@Test
@SuppressWarnings("deprecation")
public void testConstructors() {
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/UrlConfigTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/UrlConfigTest.java
index e640a6f..a6a6b11 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/UrlConfigTest.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/config/UrlConfigTest.java
@@ -33,10 +33,9 @@ import org.junit.Before;
import org.junit.Test;
public class UrlConfigTest extends JMeterTestCase {
- private HTTPSamplerBase config;
+ private HTTPSamplerBase config;
private HTTPSamplerBase defaultConfig;
-
private HTTPSamplerBase partialConfig;
@Before
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManager.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManager.java
index 0273e47..57e5e59 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManager.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManager.java
@@ -33,89 +33,89 @@ import org.junit.Test;
public class TestAuthManager extends JMeterTestCase {
- @Test
- public void testHttp() throws Exception {
- assertTrue(AuthManager.isSupportedProtocol(new URL("http:")));
- }
+ @Test
+ public void testHttp() throws Exception {
+ assertTrue(AuthManager.isSupportedProtocol(new URL("http:")));
+ }
- @Test
- public void testHttps() throws Exception {
- assertTrue(AuthManager.isSupportedProtocol(new URL("https:")));
- }
+ @Test
+ public void testHttps() throws Exception {
+ assertTrue(AuthManager.isSupportedProtocol(new URL("https:")));
+ }
- @Test
- public void testFile() throws Exception {
- AuthManager am = new AuthManager();
- CollectionProperty ao = am.getAuthObjects();
- assertEquals(0, ao.size());
- am.addFile(findTestPath("testfiles/TestAuth.txt"));
- assertEquals(9, ao.size());
- Authorization at;
- at = am.getAuthForURL(new URL("http://a.b.c/"));
- assertEquals("login", at.getUser());
- assertEquals("password", at.getPass());
- at = am.getAuthForURL(new URL("http://a.b.c:80/")); // same as above
- assertEquals("login", at.getUser());
- assertEquals("password", at.getPass());
- at = am.getAuthForURL(new URL("http://a.b.c:443/"));// not same
- assertNull(at);
- at = am.getAuthForURL(new URL("http://a.b.c/1"));
- assertEquals("login1", at.getUser());
- assertEquals("password1", at.getPass());
- assertEquals("", at.getDomain());
- assertEquals("", at.getRealm());
- at = am.getAuthForURL(new URL("http://d.e.f/"));
- assertEquals("user", at.getUser());
- assertEquals("pass", at.getPass());
- assertEquals("domain", at.getDomain());
- assertEquals("realm", at.getRealm());
- at = am.getAuthForURL(new URL("https://j.k.l/"));
- assertEquals("jkl", at.getUser());
- assertEquals("pass", at.getPass());
- at = am.getAuthForURL(new URL("https://j.k.l:443/"));
- assertEquals("jkl", at.getUser());
- assertEquals("pass", at.getPass());
- at = am.getAuthForURL(new URL("https://l.m.n/"));
- assertEquals("lmn443", at.getUser());
- assertEquals("pass", at.getPass());
- at = am.getAuthForURL(new URL("https://l.m.n:443/"));
- assertEquals("lmn443", at.getUser());
- assertEquals("pass", at.getPass());
- at = am.getAuthForURL(new URL("https://l.m.n:8443/"));
- assertEquals("lmn8443", at.getUser());
- assertEquals("pass", at.getPass());
- }
+ @Test
+ public void testFile() throws Exception {
+ AuthManager am = new AuthManager();
+ CollectionProperty ao = am.getAuthObjects();
+ assertEquals(0, ao.size());
+ am.addFile(findTestPath("testfiles/TestAuth.txt"));
+ assertEquals(9, ao.size());
+ Authorization at;
+ at = am.getAuthForURL(new URL("http://a.b.c/"));
+ assertEquals("login", at.getUser());
+ assertEquals("password", at.getPass());
+ at = am.getAuthForURL(new URL("http://a.b.c:80/")); // same as above
+ assertEquals("login", at.getUser());
+ assertEquals("password", at.getPass());
+ at = am.getAuthForURL(new URL("http://a.b.c:443/"));// not same
+ assertNull(at);
+ at = am.getAuthForURL(new URL("http://a.b.c/1"));
+ assertEquals("login1", at.getUser());
+ assertEquals("password1", at.getPass());
+ assertEquals("", at.getDomain());
+ assertEquals("", at.getRealm());
+ at = am.getAuthForURL(new URL("http://d.e.f/"));
+ assertEquals("user", at.getUser());
+ assertEquals("pass", at.getPass());
+ assertEquals("domain", at.getDomain());
+ assertEquals("realm", at.getRealm());
+ at = am.getAuthForURL(new URL("https://j.k.l/"));
+ assertEquals("jkl", at.getUser());
+ assertEquals("pass", at.getPass());
+ at = am.getAuthForURL(new URL("https://j.k.l:443/"));
+ assertEquals("jkl", at.getUser());
+ assertEquals("pass", at.getPass());
+ at = am.getAuthForURL(new URL("https://l.m.n/"));
+ assertEquals("lmn443", at.getUser());
+ assertEquals("pass", at.getPass());
+ at = am.getAuthForURL(new URL("https://l.m.n:443/"));
+ assertEquals("lmn443", at.getUser());
+ assertEquals("pass", at.getPass());
+ at = am.getAuthForURL(new URL("https://l.m.n:8443/"));
+ assertEquals("lmn8443", at.getUser());
+ assertEquals("pass", at.getPass());
+ }
- @Test
- public void testAddFileWithoutDomainAndRealmWithMechanism() throws IOException {
- File authFile = File.createTempFile("auth", ".txt");
- Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\t\t\tBASIC_DIGEST".getBytes());
- AuthManager manager = new AuthManager();
- manager.addFile(authFile.getAbsolutePath());
- Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
- assertEquals("password", authForURL.getPass());
- }
+ @Test
+ public void testAddFileWithoutDomainAndRealmWithMechanism() throws IOException {
+ File authFile = File.createTempFile("auth", ".txt");
+ Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\t\t\tBASIC_DIGEST".getBytes());
+ AuthManager manager = new AuthManager();
+ manager.addFile(authFile.getAbsolutePath());
+ Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
+ assertEquals("password", authForURL.getPass());
+ }
- @Test
- public void testAddFileWithDomainAndRealmAndDefaultMechanism() throws IOException {
- File authFile = File.createTempFile("auth", ".txt");
- Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\tdomain\tEXAMPLE.COM\tBASIC_DIGEST".getBytes());
- AuthManager manager = new AuthManager();
- manager.addFile(authFile.getAbsolutePath());
- Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
- assertEquals("password", authForURL.getPass());
- assertEquals("domain", authForURL.getDomain());
- }
+ @Test
+ public void testAddFileWithDomainAndRealmAndDefaultMechanism() throws IOException {
+ File authFile = File.createTempFile("auth", ".txt");
+ Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\tdomain\tEXAMPLE.COM\tBASIC_DIGEST".getBytes());
+ AuthManager manager = new AuthManager();
+ manager.addFile(authFile.getAbsolutePath());
+ Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
+ assertEquals("password", authForURL.getPass());
+ assertEquals("domain", authForURL.getDomain());
+ }
- @Test
- public void testAddFileWithDomainAndRealmAndMechanism() throws IOException {
- File authFile = File.createTempFile("auth", ".txt");
- Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\tdomain\tEXAMPLE.COM\tKERBEROS".getBytes());
- AuthManager manager = new AuthManager();
- manager.addFile(authFile.getAbsolutePath());
- Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
- assertEquals("password", authForURL.getPass());
- assertEquals("domain", authForURL.getDomain());
- assertEquals(AuthManager.Mechanism.KERBEROS, authForURL.getMechanism());
- }
+ @Test
+ public void testAddFileWithDomainAndRealmAndMechanism() throws IOException {
+ File authFile = File.createTempFile("auth", ".txt");
+ Files.write(authFile.toPath(), "http://example.com\tuser\tpassword\tdomain\tEXAMPLE.COM\tKERBEROS".getBytes());
+ AuthManager manager = new AuthManager();
+ manager.addFile(authFile.getAbsolutePath());
+ Authorization authForURL = manager.getAuthForURL(new URL("http://example.com"));
+ assertEquals("password", authForURL.getPass());
+ assertEquals("domain", authForURL.getDomain());
+ assertEquals(AuthManager.Mechanism.KERBEROS, authForURL.getMechanism());
+ }
}
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManagerThreadIteration.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManagerThreadIteration.java
index e9705fe..155d5c9 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManagerThreadIteration.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestAuthManagerThreadIteration.java
@@ -22,7 +22,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.lang.reflect.Field;
-import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
@@ -44,12 +43,7 @@ public class TestAuthManagerThreadIteration {
public KerberosManager initKerberosManager() throws IllegalAccessException, NoSuchFieldException {
KerberosManager kerberosManager = new KerberosManager();
- Future<Subject> future = Executors.newSingleThreadExecutor().submit(new Callable<Subject>() {
- @Override
- public Subject call() throws Exception {
- return new Subject();
- }
- });
+ Future<Subject> future = Executors.newSingleThreadExecutor().submit(() -> new Subject());
subjects.put("test", future);
Field privateField = kerberosManager.getClass().getDeclaredField("subjects");
privateField.setAccessible(true);
diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestHC4CookieManager.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestHC4CookieManager.java
index bb8d2b8..043d04b 100644
--- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestHC4CookieManager.java
+++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/control/TestHC4CookieManager.java
@@ -44,601 +44,582 @@ import org.junit.Test;
* HC4CookieHandler tests
*/
public class TestHC4CookieManager extends JMeterTestCase {
- private CookieManager man = null;
-
- private JMeterContext jmctx = null;
-
- @Before
- public void setUp() throws Exception {
- jmctx = JMeterContextService.getContext();
- man = new CookieManager();
- // Ensure we use the new GUI defaults
- man.setImplementation(HC4CookieHandler.class.getName());
- man.setCookiePolicy(HC4CookieHandler.DEFAULT_POLICY_NAME);
- man.setThreadContext(jmctx);
- man.testStarted();// This is needed in order to set up the cookie policy
- }
-
- @Test
- public void testRemoveCookie() throws Exception {
- man.setThreadContext(jmctx);
- Cookie c = new Cookie("id", "me", "127.0.0.1", "/", false, 0);
- man.add(c);
- assertEquals(1, man.getCookieCount());
- // This should be ignored, as there is no value
- Cookie d = new Cookie("id", "", "127.0.0.1", "/", false, 0);
- man.add(d);
- assertEquals(0, man.getCookieCount());
- man.add(c);
- man.add(c);
- assertEquals(1, man.getCookieCount());
- Cookie e = new Cookie("id", "me2", "127.0.0.1", "/", false, 0);
- man.add(e);
- assertEquals(1, man.getCookieCount());
- }
-
- @Test
- public void testSendCookie() throws Exception {
- man.add(new Cookie("id", "value", "jakarta.apache.org", "/", false, 9999999999L));
- HTTPSamplerBase sampler = new HTTPNullSampler();
- sampler.setDomain("jakarta.apache.org");
- sampler.setPath("/index.html");
- sampler.setMethod(HTTPConstants.GET);
- assertNotNull(man.getCookieHeaderForURL(sampler.getUrl()));
- }
-
- @Test
- public void testSendCookie2() throws Exception {
- man.add(new Cookie("id", "value", ".apache.org", "/", false, 9999999999L));
- HTTPSamplerBase sampler = new HTTPNullSampler();
- sampler.setDomain("jakarta.apache.org");
-
- sampler.setPath("/index.html");
- sampler.setMethod(HTTPConstants.GET);
- assertNotNull(man.getCookieHeaderForURL(sampler.getUrl()));
- }
-
- /**
- * Test that the cookie domain field is actually handled as browsers do
- * (i.e.: host X matches domain .X):
- *
- * @throws Exception if something fails
- */
- @Test
- public void testDomainHandling() throws Exception {
- URL url = new URL("http://jakarta.apache.org/");
- man.addCookieFromHeader("test=1;domain=.jakarta.apache.org", url);
- assertNotNull(man.getCookieHeaderForURL(url));
- }
-
- /**
- * @throws Exception when anything goes wrong in the test
- */
- @Test
- public void testAddCookieFromHeaderWithWildcard() throws Exception {
- URL url = new URL("https://subdomain.bt.com/page");
- String headerLine = "SMTRYNO=1; path=/; domain=.bt.com";
- man.addCookieFromHeader(headerLine, url);
- Assert.assertEquals(1, man.getCookieCount());
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- List<org.apache.http.cookie.Cookie> cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
-
- for (org.apache.http.cookie.Cookie cookie : cookies) {
- // See http://tools.ietf.org/html/rfc6265#section-5.2.3
- Assert.assertEquals("bt.com", cookie.getDomain());
- Assert.assertTrue( ((BasicClientCookie)cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
- }
-
- // we check that CookieManager returns the cookies for the main domain
- URL urlMainDomain = new URL("https://www.bt.com/page");
- cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), urlMainDomain,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- Assert.assertEquals(1, cookies.size());
- for (org.apache.http.cookie.Cookie cookie : cookies) {
- // See http://tools.ietf.org/html/rfc6265#section-5.2.3
- Assert.assertEquals("bt.com", cookie.getDomain());
- Assert.assertTrue( ((BasicClientCookie)cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
- }
- }
-
- /**
- * @throws Exception when anything goes wrong in the test
- */
- @Test
- public void testAddCookieFromHeaderWithNoWildcard() throws Exception {
- URL url = new URL("https://subdomain.bt.com/page");
- String headerLine = "SMTRYNO=1; path=/";
- man.addCookieFromHeader(headerLine, url);
- Assert.assertEquals(1, man.getCookieCount());
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- List<org.apache.http.cookie.Cookie> cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- Assert.assertEquals(1, cookies.size());
- for (org.apache.http.cookie.Cookie cookie : cookies) {
- // See http://tools.ietf.org/html/rfc6265#section-5.2.3
- Assert.assertEquals("subdomain.bt.com", cookie.getDomain());
- Assert.assertFalse( ((BasicClientCookie)cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
- }
-
- // we check that CookieManager returns the cookies for the main domain
- URL urlMainDomain = new URL("https://www.bt.com/page");
- cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), urlMainDomain,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- Assert.assertEquals(0, cookies.size());
- }
-
- /**
- * @throws Exception when anything goes wrong in the test
- */
- @Test
- public void testAddCookieFromHeaderWithWildcard2() throws Exception {
- URL url = new URL("https://www.bt.com/page");
- String headerLine = "SMTRYNO=1; path=/; domain=.bt.com";
- man.addCookieFromHeader(headerLine, url);
-
- Assert.assertEquals(1, man.getCookieCount());
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- URL urlSubDomain = new URL("https://subdomain.bt.com/page");
-
- List<org.apache.http.cookie.Cookie> cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), urlSubDomain,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- Assert.assertEquals(1, cookies.size());
- for (org.apache.http.cookie.Cookie cookie : cookies) {
- // See http://tools.ietf.org/html/rfc6265#section-5.2.3
- Assert.assertEquals("bt.com", cookie.getDomain());
- Assert.assertTrue( ((BasicClientCookie)cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
- }
- }
-
- /**
- * @throws Exception when anything goes wrong in the test
- */
- @Test
- public void testBug56358() throws Exception {
- URL url = new URL("http://remote.com:10008/get/cookie");
- String headerLine = "test=value;Max-age=120;path=/;Version=1";
- man.setCookiePolicy(CookieSpecs.STANDARD);
- man.addCookieFromHeader(headerLine, url);
-
- Assert.assertEquals(1, man.getCookieCount());
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- URL urlSameDomainDifferentPort = new URL("http://remote.com:10001/test/me");
-
- List<org.apache.http.cookie.Cookie> cookies =
- cookieHandler.getCookiesForUrl(man.getCookies(), urlSameDomainDifferentPort,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- Assert.assertEquals(1, cookies.size());
- for (org.apache.http.cookie.Cookie cookie : cookies) {
- // See http://tools.ietf.org/html/rfc6265#section-5.2.3
- Assert.assertEquals("remote.com", cookie.getDomain());
- Assert.assertEquals("test", cookie.getName());
- }
- }
-
- @Test
- public void testCrossDomainHandling() throws Exception {
- URL url = new URL("http://jakarta.apache.org/");
- assertEquals(0,man.getCookieCount()); // starts empty
- man.addCookieFromHeader("test=2;domain=.hc.apache.org", url);
- assertEquals(0,man.getCookieCount()); // should not be stored
- man.addCookieFromHeader("test=1;domain=.jakarta.apache.org", url);
- assertEquals(1,man.getCookieCount()); // OK
- }
-
- /**
- * Test that we won't be tricked by similar host names (this was a past
- * bug, although it never got reported in the bug database):
- *
- * @throws Exception if something fails
- */
- @Test
- public void testSimilarHostNames() throws Exception {
- URL url = new URL("http://ache.org/");
- man.addCookieFromHeader("test=1", url);
- url = new URL("http://jakarta.apache.org/");
- assertNull(man.getCookieHeaderForURL(url));
- }
-
- // Test session cookie is returned
- @Test
- public void testSessionCookie() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("test=1", url);
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test=1", s);
- }
-
- // Bug 2063
- @Test
- public void testCookieWithEquals() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("NSCP_USER_LOGIN1_NEW=SHA=xxxxx", url);
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("NSCP_USER_LOGIN1_NEW=SHA=xxxxx", s);
- Cookie c=man.get(0);
- assertEquals("NSCP_USER_LOGIN1_NEW",c.getName());
- assertEquals("SHA=xxxxx",c.getValue());
- }
-
- // Test Old cookie is not returned
- @Test
- public void testOldCookie() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("test=1; expires=Mon, 01-Jan-1990 00:00:00 GMT", url);
- String s = man.getCookieHeaderForURL(url);
- assertNull(s);
- }
-
- // Test New cookie is returned
- @Test
- public void testNewCookie() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("test=1; expires=Mon, 01-Jan-2990 00:00:00 GMT", url);
- assertEquals(1,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test=1", s);
- }
-
- // Test HttpOnly cookie is parsed correctly
- @Test
- public void testHttpOnlyCookie() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader(
- "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
- + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly",
- url);
- assertEquals(1,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI", s);
- }
-
- // Test Secure cookie is parsed correctly and not transmitted for HTTP
- @Test
- public void testSecureCookieWithHttp() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader(
- "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
- + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly; secure",
- url);
- assertEquals(1,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNull(s);
- }
- // Test Secure cookie is parsed correctly and transmitted for HTTPS
- @Test
- public void testSecureCookieWithHttps() throws Exception {
- URL url = new URL("https://a.b.c/");
- man.addCookieFromHeader(
- "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
- + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly; secure",
- url);
- assertEquals(1,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI", s);
- }
-
- // Test multi-cookie header handling
- @Test
- public void testCookies1() throws Exception {
- man.setCookiePolicy(CookieSpecs.DEFAULT);
- man.testStarted(); // ensure policy is picked up
- URL url = new URL("http://a.b.c.d/testCookies1");
- man.addCookieFromHeader("test1=1; comment=\"how,now\", test2=2; version=1", url);
- assertEquals(2,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test1=1; test2=2", s);
- }
-
- @Test
- public void testCookies2() throws Exception {
- URL url = new URL("https://a.b.c.d/testCookies2");
- //The cookie in question does not have a version attribute mandatory for
- //standard (RFC 2109 and RFC 2965) cookies. Therefore it is parsed as
- //Netscape style cookie in which case comma is not considered a valid
- //header element delimiter and is treated as normal character.
-
- man.addCookieFromHeader("test1=1;secure, test2=2;secure", url);
- assertEquals(1,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test1=1", s);
- }
-
- @Test
- public void testCookies3() throws Exception {
- man.setCookiePolicy(CookieSpecs.DEFAULT);
- man.testStarted(); // ensure policy is picked up
- URL url = new URL("https://a.b.c.d/testCookies2");
- man.addCookieFromHeader("test1=1;secure, test2=2;secure; version=1", url);
- assertEquals(2,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test1=1; test2=2", s);
- }
-
- // Test duplicate cookie handling
- @Test
- public void testDuplicateCookie() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("test=1", url);
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test=1", s);
- man.addCookieFromHeader("test=2", url);
- s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test=2", s);
- }
- @Test
- public void testDuplicateCookie2() throws Exception {
- URL url = new URL("http://a.b.c/");
- man.addCookieFromHeader("test=1", url);
- man.addCookieFromHeader("test2=a", url);
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test=1; test2=a", s); // Assumes some kind of list is used
- man.addCookieFromHeader("test=2", url);
- man.addCookieFromHeader("test3=b", url);
- s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("test2=a; test=2; test3=b", s);// Assumes some kind of list is use
- // If not using a list that retains the order, then the asserts would need to change
- }
-
-
- /** Tests missing cookie path for a trivial URL fetch from the domain
- * Note that this fails prior to a fix for BUG 38256
- *
- * @throws Exception if something fails
- */
- @Test
- public void testMissingPath0() throws Exception {
- URL url = new URL("http://d.e.f/goo.html");
- man.addCookieFromHeader("test=moo", url);
- String s = man.getCookieHeaderForURL(new URL("http://d.e.f/"));
- assertNotNull(s);
- assertEquals("test=moo", s);
- }
-
- /** Tests missing cookie path for a non-trivial URL fetch from the
- * domain. Note that this fails prior to a fix for BUG 38256
- *
- * @throws Exception if something fails
- */
- @Test
- public void testMissingPath1() throws Exception {
- URL url = new URL("http://d.e.f/moo.html");
- man.addCookieFromHeader("test=moo", url);
- String s = man.getCookieHeaderForURL(new URL("http://d.e.f/goo.html"));
- assertNotNull(s);
- assertEquals("test=moo", s);
- }
-
- /** Tests explicit root path with a trivial URL fetch from the domain
- *
- * @throws Exception if something fails
- */
- @Test
- public void testRootPath0() throws Exception {
- URL url = new URL("http://d.e.f/goo.html");
- man.addCookieFromHeader("test=moo;path=/", url);
- String s = man.getCookieHeaderForURL(new URL("http://d.e.f/"));
- assertNotNull(s);
- assertEquals("test=moo", s);
- }
-
- /** Tests explicit root path with a non-trivial URL fetch from the domain
- *
- * @throws Exception if something fails
- */
- @Test
- public void testRootPath1() throws Exception {
- URL url = new URL("http://d.e.f/moo.html");
- man.addCookieFromHeader("test=moo;path=/", url);
- String s = man.getCookieHeaderForURL(new URL("http://d.e.f/goo.html"));
- assertNotNull(s);
- assertEquals("test=moo", s);
- }
-
- // Test cookie matching
- @Test
- public void testCookieMatching() throws Exception {
- URL url = new URL("http://a.b.c:8080/TopDir/fred.jsp");
- man.addCookieFromHeader("ID=abcd; Path=/TopDir", url);
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- assertEquals("ID=abcd", s);
-
- url = new URL("http://a.b.c:8080/other.jsp");
- s=man.getCookieHeaderForURL(url);
- assertNull(s);
-
- url = new URL("http://a.b.c:8080/TopDir/suub/another.jsp");
- s=man.getCookieHeaderForURL(url);
- assertNotNull(s);
-
- url = new URL("http://a.b.c:8080/TopDir");
- s=man.getCookieHeaderForURL(url);
- assertNotNull(s);
-
- url = new URL("http://a.b.d/");
- s=man.getCookieHeaderForURL(url);
- assertNull(s);
- }
-
- @Test
- public void testCookieOrdering1() throws Exception {
- URL url = new URL("http://order.now/sub1/moo.html");
- man.addCookieFromHeader("test1=moo1;path=/", url);
- // Waiting for https://issues.apache.org/jira/browse/HTTPCLIENT-1705
- man.addCookieFromHeader("test2=moo2;path=/sub1", url);
- man.addCookieFromHeader("test2=moo3;path=/", url);
- assertEquals(3,man.getCookieCount());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- //Cookies like "test1=moo1;path=/" are invalid from the standpoint of RFC 2109 and RFC 2965 as they lack mandatory version attribute.
- // The default policy treats such cookies as Netscape draft compatible. And the Netscape draft does not define any particular order
- // for cookies in the cookie header.
- // see https://issues.apache.org/jira/browse/HTTPCLIENT-1705
- // assertEquals("test2=moo2; test1=moo1; test2=moo3", s);
- }
-
- @Test
- public void testCookieOrdering2() throws Exception {
- URL url = new URL("http://order.now/sub1/moo.html");
- man.addCookieFromHeader("test1=moo1;", url);
- man.addCookieFromHeader("test2=moo2;path=/sub1", url);
- man.addCookieFromHeader("test2=moo3;path=/", url);
- assertEquals(3,man.getCookieCount());
- assertEquals("/sub1",man.get(0).getPath()); // Defaults to caller URL
- assertEquals("/sub1",man.get(1).getPath());
- assertEquals("/",man.get(2).getPath());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- List<org.apache.http.cookie.Cookie> c =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- assertEquals("/sub1",c.get(0).getPath());
- assertFalse(((BasicClientCookie)c.get(0)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/sub1",c.get(1).getPath());
- assertTrue(((BasicClientCookie)c.get(1)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/",c.get(2).getPath());
- assertEquals("test1=moo1; test2=moo2; test2=moo3", s);
- }
-
- @SuppressWarnings("deprecation") // test of deprecated item
- @Test
- public void testCookiePolicy2109() throws Exception {
- man.setCookiePolicy(org.apache.http.client.params.CookiePolicy.RFC_2109);
- man.testStarted(); // ensure policy is picked up
- URL url = new URL("http://order.now/sub1/moo.html");
- man.addCookieFromHeader("test1=moo1;", url);
- man.addCookieFromHeader("test2=moo2;path=/sub1", url);
- man.addCookieFromHeader("test2=moo3;path=/", url);
- assertEquals(3,man.getCookieCount());
- assertEquals("/sub1",man.get(0).getPath());
- assertEquals("/sub1",man.get(1).getPath());
- assertEquals("/",man.get(2).getPath());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- List<org.apache.http.cookie.Cookie> c =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- assertEquals("/sub1",c.get(0).getPath());
- assertFalse(((BasicClientCookie)c.get(0)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/sub1",c.get(1).getPath());
- assertTrue(((BasicClientCookie)c.get(1)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/",c.get(2).getPath());
- assertTrue(((BasicClientCookie)c.get(2)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("$Version=0; test1=moo1; test2=moo2; $Path=/sub1; test2=moo3; $Path=/", s);
- }
-
- @Test
- public void testCookiePolicyNetscape() throws Exception {
- man.setCookiePolicy(CookieSpecs.NETSCAPE);
- man.testStarted(); // ensure policy is picked up
- URL url = new URL("http://www.order.now/sub1/moo.html");
- man.addCookieFromHeader("test1=moo1;", url);
- man.addCookieFromHeader("test2=moo2;path=/sub1", url);
- man.addCookieFromHeader("test2=moo3;path=/", url);
- assertEquals(3,man.getCookieCount());
- assertEquals("/sub1",man.get(0).getPath());
- assertEquals("/sub1",man.get(1).getPath());
- assertEquals("/",man.get(2).getPath());
- String s = man.getCookieHeaderForURL(url);
- assertNotNull(s);
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
-
- List<org.apache.http.cookie.Cookie> c =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- assertEquals("/sub1",c.get(0).getPath());
- assertFalse(((BasicClientCookie)c.get(0)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/sub1",c.get(1).getPath());
- assertTrue(((BasicClientCookie)c.get(1)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("/",c.get(2).getPath());
- assertTrue(((BasicClientCookie)c.get(2)).containsAttribute(ClientCookie.PATH_ATTR));
- assertEquals("test1=moo1; test2=moo2; test2=moo3", s);
- }
-
- @Test
- public void testCookiePolicyIgnore() throws Exception {
- man.setCookiePolicy(CookieSpecs.IGNORE_COOKIES);
- man.testStarted(); // ensure policy is picked up
- URL url = new URL("http://order.now/sub1/moo.html");
- man.addCookieFromHeader("test1=moo1;", url);
- man.addCookieFromHeader("test2=moo2;path=/sub1", url);
- man.addCookieFromHeader("test2=moo3;path=/", url);
- assertEquals(0,man.getCookieCount());// Cookies are ignored
- Cookie cc;
- cc=new Cookie("test1","moo1",null,"/sub1",false,0,false,false);
- man.add(cc);
- cc=new Cookie("test2","moo2",null,"/sub1",false,0,true,false);
- man.add(cc);
- cc=new Cookie("test3","moo3",null,"/",false,0,false,false);
- man.add(cc);
- assertEquals(3,man.getCookieCount());
- assertEquals("/sub1",man.get(0).getPath());
- assertEquals("/sub1",man.get(1).getPath());
- assertEquals("/",man.get(2).getPath());
- String s = man.getCookieHeaderForURL(url);
-
- // With ignore policy, s is null as no match will occur,
- // getCookieHeaderForURL will return null
- assertNull(s);
-
- HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
- List<org.apache.http.cookie.Cookie> c =
- cookieHandler.getCookiesForUrl(man.getCookies(), url,
- CookieManager.ALLOW_VARIABLE_COOKIES);
- assertNotNull(c); // Make sure variable is used
- // see https://issues.apache.org/jira/browse/HTTPCLIENT-1704
- assertEquals(0,c.size()); // Cookies again ignored
- }
-
- @Test
- public void testLoad() throws Exception{
- assertEquals(0,man.getCookieCount());
- man.addFile(findTestPath("testfiles/cookies.txt"));
- assertEquals(3,man.getCookieCount());
-
- int num = 0;
- assertEquals("name",man.get(num).getName());
- assertEquals("value",man.get(num).getValue());
- assertEquals("path",man.get(num).getPath());
- assertEquals("domain",man.get(num).getDomain());
- assertTrue(man.get(num).getSecure());
- assertEquals(num,man.get(num).getExpires());
-
- num++;
- assertEquals("name2",man.get(num).getName());
- assertEquals("value2",man.get(num).getValue());
- assertEquals("/",man.get(num).getPath());
- assertEquals("",man.get(num).getDomain());
- assertFalse(man.get(num).getSecure());
- assertEquals(0,man.get(num).getExpires());
-
- num++;
- assertEquals("a",man.get(num).getName());
- assertEquals("b",man.get(num).getValue());
- assertEquals("d",man.get(num).getPath());
- assertEquals("c",man.get(num).getDomain());
- assertTrue(man.get(num).getSecure());
- assertEquals(0,man.get(num).getExpires()); // Show that maxlong now saved as 0
- }
+ private CookieManager man = null;
+ private JMeterContext jmctx = null;
+
+ @Before
+ public void setUp() throws Exception {
+ jmctx = JMeterContextService.getContext();
+ man = new CookieManager();
+ // Ensure we use the new GUI defaults
+ man.setImplementation(HC4CookieHandler.class.getName());
+ man.setCookiePolicy(HC4CookieHandler.DEFAULT_POLICY_NAME);
+ man.setThreadContext(jmctx);
+ man.testStarted();// This is needed in order to set up the cookie policy
+ }
+
+ @Test
+ public void testRemoveCookie() throws Exception {
+ man.setThreadContext(jmctx);
+ Cookie c = new Cookie("id", "me", "127.0.0.1", "/", false, 0);
+ man.add(c);
+ assertEquals(1, man.getCookieCount());
+ // This should be ignored, as there is no value
+ Cookie d = new Cookie("id", "", "127.0.0.1", "/", false, 0);
+ man.add(d);
+ assertEquals(0, man.getCookieCount());
+ man.add(c);
+ man.add(c);
+ assertEquals(1, man.getCookieCount());
+ Cookie e = new Cookie("id", "me2", "127.0.0.1", "/", false, 0);
+ man.add(e);
+ assertEquals(1, man.getCookieCount());
+ }
+
+ @Test
+ public void testSendCookie() throws Exception {
+ man.add(new Cookie("id", "value", "jakarta.apache.org", "/", false, 9999999999L));
+ HTTPSamplerBase sampler = new HTTPNullSampler();
+ sampler.setDomain("jakarta.apache.org");
+ sampler.setPath("/index.html");
+ sampler.setMethod(HTTPConstants.GET);
+ assertNotNull(man.getCookieHeaderForURL(sampler.getUrl()));
+ }
+
+ @Test
+ public void testSendCookie2() throws Exception {
+ man.add(new Cookie("id", "value", ".apache.org", "/", false, 9999999999L));
+ HTTPSamplerBase sampler = new HTTPNullSampler();
+ sampler.setDomain("jakarta.apache.org");
+
+ sampler.setPath("/index.html");
+ sampler.setMethod(HTTPConstants.GET);
+ assertNotNull(man.getCookieHeaderForURL(sampler.getUrl()));
+ }
+
+ /**
+ * Test that the cookie domain field is actually handled as browsers do
+ * (i.e.: host X matches domain .X):
+ */
+ @Test
+ public void testDomainHandling() throws Exception {
+ URL url = new URL("http://jakarta.apache.org/");
+ man.addCookieFromHeader("test=1;domain=.jakarta.apache.org", url);
+ assertNotNull(man.getCookieHeaderForURL(url));
+ }
+
+ @Test
+ public void testAddCookieFromHeaderWithWildcard() throws Exception {
+ URL url = new URL("https://subdomain.bt.com/page");
+ String headerLine = "SMTRYNO=1; path=/; domain=.bt.com";
+ man.addCookieFromHeader(headerLine, url);
+ Assert.assertEquals(1, man.getCookieCount());
+ HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
+ List<org.apache.http.cookie.Cookie> cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), url,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+
+ for (org.apache.http.cookie.Cookie cookie : cookies) {
+ // See http://tools.ietf.org/html/rfc6265#section-5.2.3
+ Assert.assertEquals("bt.com", cookie.getDomain());
+ Assert.assertTrue(((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
+ }
+
+ // we check that CookieManager returns the cookies for the main domain
+ URL urlMainDomain = new URL("https://www.bt.com/page");
+ cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), urlMainDomain,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+ Assert.assertEquals(1, cookies.size());
+ for (org.apache.http.cookie.Cookie cookie : cookies) {
+ // See http://tools.ietf.org/html/rfc6265#section-5.2.3
+ Assert.assertEquals("bt.com", cookie.getDomain());
+ Assert.assertTrue(((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
+ }
+ }
+
+ @Test
+ public void testAddCookieFromHeaderWithNoWildcard() throws Exception {
+ URL url = new URL("https://subdomain.bt.com/page");
+ String headerLine = "SMTRYNO=1; path=/";
+ man.addCookieFromHeader(headerLine, url);
+ Assert.assertEquals(1, man.getCookieCount());
+ HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
+ List<org.apache.http.cookie.Cookie> cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), url,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+ Assert.assertEquals(1, cookies.size());
+ for (org.apache.http.cookie.Cookie cookie : cookies) {
+ // See http://tools.ietf.org/html/rfc6265#section-5.2.3
+ Assert.assertEquals("subdomain.bt.com", cookie.getDomain());
+ Assert.assertFalse(((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
+ }
+
+ // we check that CookieManager returns the cookies for the main domain
+ URL urlMainDomain = new URL("https://www.bt.com/page");
+ cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), urlMainDomain,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+ Assert.assertEquals(0, cookies.size());
+ }
+
+ @Test
+ public void testAddCookieFromHeaderWithWildcard2() throws Exception {
+ URL url = new URL("https://www.bt.com/page");
+ String headerLine = "SMTRYNO=1; path=/; domain=.bt.com";
+ man.addCookieFromHeader(headerLine, url);
+
+ Assert.assertEquals(1, man.getCookieCount());
+ HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
+ URL urlSubDomain = new URL("https://subdomain.bt.com/page");
+
+ List<org.apache.http.cookie.Cookie> cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), urlSubDomain,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+ Assert.assertEquals(1, cookies.size());
+ for (org.apache.http.cookie.Cookie cookie : cookies) {
+ // See http://tools.ietf.org/html/rfc6265#section-5.2.3
+ Assert.assertEquals("bt.com", cookie.getDomain());
+ Assert.assertTrue(((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
+ }
+ }
+
+ @Test
+ public void testBug56358() throws Exception {
+ URL url = new URL("http://remote.com:10008/get/cookie");
+ String headerLine = "test=value;Max-age=120;path=/;Version=1";
+ man.setCookiePolicy(CookieSpecs.STANDARD);
+ man.addCookieFromHeader(headerLine, url);
+
+ Assert.assertEquals(1, man.getCookieCount());
+ HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
+ URL urlSameDomainDifferentPort = new URL("http://remote.com:10001/test/me");
+
+ List<org.apache.http.cookie.Cookie> cookies =
+ cookieHandler.getCookiesForUrl(man.getCookies(), urlSameDomainDifferentPort,
+ CookieManager.ALLOW_VARIABLE_COOKIES);
+ Assert.assertEquals(1, cookies.size());
+ for (org.apache.http.cookie.Cookie cookie : cookies) {
+ // See http://tools.ietf.org/html/rfc6265#section-5.2.3
+ Assert.assertEquals("remote.com", cookie.getDomain());
+ Assert.assertEquals("test", cookie.getName());
+ }
+ }
+
+ @Test
+ public void testCrossDomainHandling() throws Exception {
+ URL url = new URL("http://jakarta.apache.org/");
+ assertEquals(0, man.getCookieCount()); // starts empty
+ man.addCookieFromHeader("test=2;domain=.hc.apache.org", url);
+ assertEquals(0, man.getCookieCount()); // should not be stored
+ man.addCookieFromHeader("test=1;domain=.jakarta.apache.org", url);
+ assertEquals(1, man.getCookieCount()); // OK
+ }
+
+ /**
+ * Test that we won't be tricked by similar host names (this was a past
+ * bug, although it never got reported in the bug database):
+ */
+ @Test
+ public void testSimilarHostNames() throws Exception {
+ URL url = new URL("http://ache.org/");
+ man.addCookieFromHeader("test=1", url);
+ url = new URL("http://jakarta.apache.org/");
+ assertNull(man.getCookieHeaderForURL(url));
+ }
+
+ // Test session cookie is returned
+ @Test
+ public void testSessionCookie() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("test=1", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test=1", s);
+ }
+
+ // Bug 2063
+ @Test
+ public void testCookieWithEquals() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("NSCP_USER_LOGIN1_NEW=SHA=xxxxx", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("NSCP_USER_LOGIN1_NEW=SHA=xxxxx", s);
+ Cookie c = man.get(0);
+ assertEquals("NSCP_USER_LOGIN1_NEW", c.getName());
+ assertEquals("SHA=xxxxx", c.getValue());
+ }
+
+ // Test Old cookie is not returned
+ @Test
+ public void testOldCookie() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("test=1; expires=Mon, 01-Jan-1990 00:00:00 GMT", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNull(s);
+ }
+
+ // Test New cookie is returned
+ @Test
+ public void testNewCookie() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("test=1; expires=Mon, 01-Jan-2990 00:00:00 GMT", url);
+ assertEquals(1, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test=1", s);
+ }
+
+ // Test HttpOnly cookie is parsed correctly
+ @Test
+ public void testHttpOnlyCookie() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader(
+ "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
+ + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly",
+ url);
+ assertEquals(1, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI", s);
+ }
+
+ // Test Secure cookie is parsed correctly and not transmitted for HTTP
+ @Test
+ public void testSecureCookieWithHttp() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader(
+ "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
+ + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly; secure",
+ url);
+ assertEquals(1, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNull(s);
+ }
+
+ // Test Secure cookie is parsed correctly and transmitted for HTTPS
+ @Test
+ public void testSecureCookieWithHttps() throws Exception {
+ URL url = new URL("https://a.b.c/");
+ man.addCookieFromHeader(
+ "mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI; Path=/;"
+ + " Expires=Tue, 07 Feb 2990 09:13:14 GMT; HttpOnly; secure",
+ url);
+ assertEquals(1, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("mySASession=s%3AcafPSGf6UJguyhddGFFeLdHBy9CYbzIS.NhYyA26LGTAVoLxhCQUK%2F2Bs34MW5kGHmErKzG6r3XI", s);
+ }
+
+ // Test multi-cookie header handling
+ @Test
+ public void testCookies1() throws Exception {
+ man.setCookiePolicy(CookieSpecs.DEFAULT);
+ man.testStarted(); // ensure policy is picked up
+ URL url = new URL("http://a.b.c.d/testCookies1");
+ man.addCookieFromHeader("test1=1; comment=\"how,now\", test2=2; version=1", url);
+ assertEquals(2, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test1=1; test2=2", s);
+ }
+
+ @Test
+ public void testCookies2() throws Exception {
+ URL url = new URL("https://a.b.c.d/testCookies2");
+ //The cookie in question does not have a version attribute mandatory for
+ //standard (RFC 2109 and RFC 2965) cookies. Therefore it is parsed as
+ //Netscape style cookie in which case comma is not considered a valid
+ //header element delimiter and is treated as normal character.
+
+ man.addCookieFromHeader("test1=1;secure, test2=2;secure", url);
+ assertEquals(1, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test1=1", s);
+ }
+
+ @Test
+ public void testCookies3() throws Exception {
+ man.setCookiePolicy(CookieSpecs.DEFAULT);
+ man.testStarted(); // ensure policy is picked up
+ URL url = new URL("https://a.b.c.d/testCookies2");
+ man.addCookieFromHeader("test1=1;secure, test2=2;secure; version=1", url);
+ assertEquals(2, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test1=1; test2=2", s);
+ }
+
+ // Test duplicate cookie handling
+ @Test
+ public void testDuplicateCookie() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("test=1", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test=1", s);
+ man.addCookieFromHeader("test=2", url);
+ s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test=2", s);
+ }
+
+ @Test
+ public void testDuplicateCookie2() throws Exception {
+ URL url = new URL("http://a.b.c/");
+ man.addCookieFromHeader("test=1", url);
+ man.addCookieFromHeader("test2=a", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test=1; test2=a", s); // Assumes some kind of list is used
+ man.addCookieFromHeader("test=2", url);
+ man.addCookieFromHeader("test3=b", url);
+ s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("test2=a; test=2; test3=b", s);// Assumes some kind of list is use
+ // If not using a list that retains the order, then the asserts would need to change
+ }
+
+
+ /**
+ * Tests missing cookie path for a trivial URL fetch from the domain
+ * Note that this fails prior to a fix for BUG 38256
+ */
+ @Test
+ public void testMissingPath0() throws Exception {
+ URL url = new URL("http://d.e.f/goo.html");
+ man.addCookieFromHeader("test=moo", url);
+ String s = man.getCookieHeaderForURL(new URL("http://d.e.f/"));
+ assertNotNull(s);
+ assertEquals("test=moo", s);
+ }
+
+ /**
+ * Tests missing cookie path for a non-trivial URL fetch from the
+ * domain. Note that this fails prior to a fix for BUG 38256
+ */
+ @Test
+ public void testMissingPath1() throws Exception {
+ URL url = new URL("http://d.e.f/moo.html");
+ man.addCookieFromHeader("test=moo", url);
+ String s = man.getCookieHeaderForURL(new URL("http://d.e.f/goo.html"));
+ assertNotNull(s);
+ assertEquals("test=moo", s);
+ }
+
+ /**
+ * Tests explicit root path with a trivial URL fetch from the domain
+ */
+ @Test
+ public void testRootPath0() throws Exception {
+ URL url = new URL("http://d.e.f/goo.html");
+ man.addCookieFromHeader("test=moo;path=/", url);
+ String s = man.getCookieHeaderForURL(new URL("http://d.e.f/"));
+ assertNotNull(s);
+ assertEquals("test=moo", s);
+ }
+
+ /**
+ * Tests explicit root path with a non-trivial URL fetch from the domain
+ */
+ @Test
+ public void testRootPath1() throws Exception {
+ URL url = new URL("http://d.e.f/moo.html");
+ man.addCookieFromHeader("test=moo;path=/", url);
+ String s = man.getCookieHeaderForURL(new URL("http://d.e.f/goo.html"));
+ assertNotNull(s);
+ assertEquals("test=moo", s);
+ }
+
+ // Test cookie matching
+ @Test
+ public void testCookieMatching() throws Exception {
+ URL url = new URL("http://a.b.c:8080/TopDir/fred.jsp");
+ man.addCookieFromHeader("ID=abcd; Path=/TopDir", url);
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+ assertEquals("ID=abcd", s);
+
+ url = new URL("http://a.b.c:8080/other.jsp");
+ s = man.getCookieHeaderForURL(url);
+ assertNull(s);
+
+ url = new URL("http://a.b.c:8080/TopDir/suub/another.jsp");
+ s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+
+ url = new URL("http://a.b.c:8080/TopDir");
+ s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
+
+ url = new URL("http://a.b.d/");
+ s = man.getCookieHeaderForURL(url);
+ assertNull(s);
+ }
+
+ @Test
+ public void testCookieOrdering1() throws Exception {
+ URL url = new URL("http://order.now/sub1/moo.html");
+ man.addCookieFromHeader("test1=moo1;path=/", url);
+ // Waiting for https://issues.apache.org/jira/browse/HTTPCLIENT-1705
+ man.addCookieFromHeader("test2=moo2;path=/sub1", url);
+ man.addCookieFromHeader("test2=moo3;path=/", url);
+ assertEquals(3, man.getCookieCount());
+ String s = man.getCookieHeaderForURL(url);
+ assertNotNull(s);
... 2989 lines suppressed ...