How to continue test execution after assertion failed? - selenium

I know that this question is duplicate one. But I am searching for the result from yesterday. I didn't got any solution for that..
I am using Selenium Webdriver 2.47.1 & TestNG for automation. In my automation script I have 12 set of tests & I am using TestNG Assert method to compare Expected Result & Actual Result. My code format is given below...
#Test(priority = 6)
public void TestingeNote1() {
cd.switchTo().frame("RTop");
cd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
String TesteNote1 = cd.findElement(By.xpath("//table/tbody/tr[2]/td[5]")).getText();
StringBuffer object1 = new StringBuffer(TesteNote1);
String ActeNote1 = object1.substring(108);
String ExpeNote1 = ex.getExcelValue(scenarioName, 75, 4);
try {
Assert.assertEquals(ExpeNote1, ActeNote1);
ex.setExcelValue(scenarioName, 75, 8, "PASSED");
}
catch(Exception e) {
ex.setExcelValue(scenarioName, 75, 8, "FAILED");
}
cd.switchTo().defaultContent();
}
Execution of test script stops once assertion got failed. I want to continue the execution after assertion fail also. I have used Verify() also, It just gives the verify result as passed. But the above test result is Failed one.

I'd recommend using a try/finally block.
.
.
.
try {
//use IF condition to match Strings (ExpeNote1, ActeNote1)are equal
ex.setExcelValue(scenarioName, 75, 8, "PASSED");
}
catch(Exception e)
{ ex.setExcelValue(scenarioName, 75, 8, "FAILED");}
finally { cd.switchTo().defaultContent();}

Use try catch block with proper exception catcher. For example when you try to catch a normal exception use exception in the catch block, if the element is not present in the DOM then use NoSuchElementException etc... In your case catch the exception that you are getting in your error console. Here's how -
try {
Assert.assertEquals(ExpeNote1, ActeNote1);
ex.setExcelValue(scenarioName, 75, 8, "PASSED");
}
catch(AssertionError e) {
ex.setExcelValue(scenarioName, 75, 8, "FAILED");
}
Your execution stops because you are not catching the proper exception that your assert statement throws. I guess you are getting an AssertionError, if not replace the exception type you get from your code above. Hope this helps.

Use soft asserts. It will continue test even after one assertion failed.
SoftAssert softAssert = new SoftAssert();
String ActualErrorMEssage = firstNameerrorXpath.getText;
String ActualErrorMEssage2 = secondNameNameerrorXpath.getText;
softAssert.assertEquals(ActualErrorMEssage,ExpectedErrorMEssage);
softAssert.assertEquals(ActualErrorMEssage2,ExpectedErrorMEssage);
softAssert.assertAll();

Related

Convert response body of a Quarkus Test

I'm trying to test my Quarkus application. I want to check that a response is greater than 0, the problem is that the endpoint I'm calling return a String and not a number. How can I convert the response to a number and check that it is greater than 0?
#Test
void getAdminListSize() {
given()
.when()
.header("Authorization", token_admin)
.get(PATH + "/get?listSize=true")
.then()
.statusCode(200)
.body(greaterThan(0))
;
}
This is the response I receive: "28357".
This is the error I get:
java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: a value greater than <0>
Actual: 28357
Just extract the body to a variable and work with it
#Test
void getAdminListSize() {
String s = given()
.when()
.header("Authorization", token_admin)
.get(PATH + "/get?listSize=true")
.then()
.assertThat()
.statusCode(200)
.extract()
.body()
.asString();
convert s into a integer and do the assert
}
Other option is use .as(Clazz.class) and work with your dto if you have one

PLC4X:Exception during scraping of Job

I'm actually developing a project that read data from 19 PLCs Siemens S1500 and 1 modicon. I have used the scraper tool following this tutorial:
PLC4x scraper tutorial
but when the scraper is working for a little amount of time I get the following exception:
I have changed the scheduled time between 1 to 100 and I always get the same exception when the scraper reach the same number of received messages.
I have tested if using PlcDriverManager instead of PooledPlcDriverManager could be a solution but the same problem persists.
In my pom.xml I use the following dependency:
<dependency>
<groupId>org.apache.plc4x</groupId>
<artifactId>plc4j-scraper</artifactId>
<version>0.7.0</version>
</dependency>
I have tried to change the version to an older one like 0.6.0 or 0.5.0 but the problem still persists.
If I use the modicon (Modbus TCP) I also get this exception after a little amount of time.
Anyone knows why is happening this error? Thanks in advance.
Edit: With the scraper version 0.8.0-SNAPSHOT I continue having this problem.
Edit2: This is my code, I think the problem can be that in my scraper I am opening a lot of connections and when it reaches 65526 messages it fails. But since all the processing is happenning inside the lambda function and I'm using a PooledPlcDriverManager, I think the scraper is using only one connection so I dont know where is the mistake.
try {
// Create a new PooledPlcDriverManager
PlcDriverManager S7_plcDriverManager = new PooledPlcDriverManager();
// Trigger Collector
TriggerCollector S7_triggerCollector = new TriggerCollectorImpl(S7_plcDriverManager);
// Messages counter
AtomicInteger messagesCounter = new AtomicInteger();
// Configure the scraper, by binding a Scraper Configuration, a ResultHandler and a TriggerCollector together
TriggeredScraperImpl S7_scraper = new TriggeredScraperImpl(S7_scraperConfig, (jobName, sourceName, results) -> {
LinkedList<Object> S7_results = new LinkedList<>();
messagesCounter.getAndIncrement();
S7_results.add(jobName);
S7_results.add(sourceName);
S7_results.add(results);
logger.info("Array: " + String.valueOf(S7_results));
logger.info("MESSAGE number: " + messagesCounter);
// Producer topics routing
String topic = "s7" + S7_results.get(1).toString().substring(S7_results.get(1).toString().indexOf("S7_SourcePLC") + 9 , S7_results.get(1).toString().length());
String key = parseKey_S7("s7");
String value = parseValue_S7(S7_results.getLast().toString(),S7_results.get(1).toString());
logger.info("------- PARSED VALUE -------------------------------- " + value);
// Create my own Kafka Producer
ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, key, value);
// Send Data to Kafka - asynchronous
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
// executes every time a record is successfully sent or an exception is thrown
if (e == null) {
// the record was successfully sent
logger.info("Received new metadata. \n" +
"Topic:" + recordMetadata.topic() + "\n" +
"Partition: " + recordMetadata.partition() + "\n" +
"Offset: " + recordMetadata.offset() + "\n" +
"Timestamp: " + recordMetadata.timestamp());
} else {
logger.error("Error while producing", e);
}
}
});
}, S7_triggerCollector);
S7_scraper.start();
S7_triggerCollector.start();
} catch (ScraperException e) {
logger.error("Error starting the scraper (S7_scrapper)", e);
}
So in the end indeed it was the PLC that was simply hanging up the connection randomly. However the NiFi integration should have handled this situation more gracefully. I implemented a fix for this particular error ... could you please give version 0.8.0-SNAPSHOT a try (or use 0.8.0 if we happen to have released it already)

Plc4x addressing system

I am discovering the Plc4x java implementation which seems to be of great interest in our field. But the youth of the project and the documentation makes us hesitate. I have been able to implement the basic hello world for reading out of our PLCs, but I was unable to write. I could not find how the addresses are handled and what the maskwrite, andMask and orMask fields mean.
Please can somebody explain to me the following example and detail how the addresses should be used?
#Test
void testWriteToPlc() {
// Establish a connection to the plc using the url provided as first argument
try( PlcConnection plcConnection = new PlcDriverManager().getConnection( "modbus:tcp://1.1.2.1" ) ){
// Create a new read request:
// - Give the single item requested the alias name "value"
var builder = plcConnection.writeRequestBuilder();
builder.addItem( "value-" + 1, "maskwrite:1[1]/2/3", 2 );
var writeRequest = builder.build();
LOGGER.info( "Synchronous request ..." );
var syncResponse = writeRequest.execute().get();
}catch(Exception e){
e.printStackTrace();
}
}
I have used PLC4x for writing using the modbus driver with success. Here is some sample code I am using:
public static void writePlc4x(ProtocolConnection connection, String registerName, byte[] writeRegister, int offset)
throws InterruptedException {
// modbus write works ok writing one record per request/item
int size = 1;
PlcWriteRequest.Builder writeBuilder = connection.writeRequestBuilder();
if (writeRegister.length == 2) {
writeBuilder.addItem(registerName, "register:" + offset + "[" + size + "]", writeRegister);
}
...
PlcWriteRequest request = writeBuilder.build();
request.execute().whenComplete((writeResponse, error) -> {
assertNotNull(writeResponse);
});
Thread.sleep((long) (sleepWait4Write * writeRegister.length * 1000));
}
In the case of modbus writing there is an issue regarding the return of the writer Future, but the write is done. In the modbus use case I don't need any mask stuff.

Selenium RC PHPUnit test

My testcase crashes with the following error:
$this->open("/en");
$this->type("id=LoginForm_username", "seleniumfree");
$this->type("id=LoginForm_password", "seleniumfree");
$this->click("name=login");
$this->waitForPageToLoad("30000");
$this->click("link=Calendar");
$this->waitForPageToLoad("30000");
$this->click("link=Add to agenda");
$this->type("id=UserAgenda_date", "2013-10-10");
$this->select("id=UserAgenda_time", "label=01:00");
$note = $this->getEval("Math.floor(Math.random()*1000)").':note';
$this->type("id=UserAgenda_note", $note);
$this->click("name=yt0");
sleep(5);
try { //also tried with integer
$this->assertEquals("2", $this->getXpathCount("//input[#value='"+ $note + "']"));
} catch (PHPUnit_Framework_AssertionFailedError $e) {
array_push($this->verificationErrors, $e->toString());
}
Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/':
ERROR: Command execution failure. Please search the user group at https://groups.google.com/forum/#!forum/selenium-users for error details from the log window.
The error message is: The expression cannot be converted to return the specified type.
In firefox IDE, playing the test runs fine.Is there another way I can count the inputs by value?

Detail Hudson test reports

Is there any way to force Hudson to give me more detailed test results - e.g. I'm comparing two strings and I want to know where they differ.
Is there any way to do this?
Thank you for help.
You should not hope Hudson give the detail information, it just shows the testing messages generated by junit.
You could show the expected string and actual string when failing asserting equals between those two strings.
For example,
protected void compareFiles(File newFile, String referenceLocation, boolean lineNumberMatters) {
BufferedReader reader = null;
BufferedReader referenceReader = null;
List<String> expectedLines = new ArrayList<String>();
try {
referenceReader = new BufferedReader(new InputStreamReader(FileLocator.openStream(Activator.getDefault().getBundle(), new Path("data/regression/" + referenceLocation), false))); //$NON-NLS-1$
expectedLines = getLinesFromReader(referenceReader);
} catch (Exception e) {
assertFalse("Exception occured during reading reference data: " + e, true); //$NON-NLS-1$
}
List<String>foundLines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(newFile));
foundLines = getLinesFromReader(reader);
} catch (Exception e) {
assertFalse("Exception occured during reading file: " + e, true); //$NON-NLS-1$
}
boolean throwException = expectedLines.size() != foundLines.size();
if (throwException) {
StringBuffer buffer = new StringBuffer("\n" + newFile.toString()); //$NON-NLS-1$
for (String line: foundLines)
buffer.append(line + "\n"); //$NON-NLS-1$
assertEquals("The number of lines in the reference(" + referenceLocation + ") and new output(" + newFile.getAbsolutePath()+ ") did not match!" + buffer, expectedLines.size(), foundLines.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (!lineNumberMatters) {
Collections.sort(expectedLines);
Collections.sort(foundLines);
}
/** Either the line matches character by character or it matches regex-wise, in that order */
for (int i=0;i<expectedLines.size(); i++)
assertTrue("Found errors in file (" + newFile + ")! " + foundLines.get(i) + " vs. " + expectedLines.get(i), foundLines.get(i).equals(expectedLines.get(i)) || foundLines.get(i).matches(expectedLines.get(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
Hudson supports JUnit directly. On your job configuration page, near the end, should be an option to "Publish JUnit test results report".
I'm not too familiar with JUnit itself, but I guess it produces (or has the ability to produce) and put results in an xml file. You just need to put the path of to the xml file (relative to the workspace) in the text box.
Once you do that, and create a build, you'll have a detailed report on your project page. You should then be able to click your way through the results for each test.