.sendKeys method problems in WebDriver Sampler JMeter - java

I'm making WebDriver Selenium scripts and trying to run them with JMeter.
I have an issue I don't understand. My code will crash at line 17 with this error in JMeter:
ERROR c.g.j.p.w.s.WebDriverSampler: Sourced file: inline evaluation of:
import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' : Error in method invocation: Method sendKeys( java.lang.String ) not found in class'org.openqa.selenium.remote.RemoteWebElement' : at Line: 17 : in file: inline evaluation of: ``import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' : .sendKeys ( "value" )
in inline evaluation of: ``import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' at line number 17
This is my code in WebDriver Sampler in JMeter:
code with .sendKeys method
What is the problem? Am I just blind?
I tried to import org.openqa.selenium.remote.RemoteWebElement directly to the script and I also tried to change syntax because I learned it was necessary to put an Array instead of a String behind .sendKeys method, but it didn't work for me.
I am using apache-jmeter-5.5 and Script Language in WebDriver Sampler is set to java.

You're just violating JMeter Best Practices, using Beanshell is not recommended since JMeter 3.1
The reason is that WebElement.sendKeys() function expects a CharSequence and you're trying to pass a String there and Beanshell interpreter doesn't like it.
Switch the language to groovy and the issue will go away. See Apache Groovy: What Is Groovy Used For? article for more information on Groovy scripting in JMeter

Related

Splitting a cookie string and saving the split cookie value in a external csv file in Apache JMeter Selenium Webdriver Sampler

Objective : I wanna "split" the extracted cookie from ";" and save the cookie value in a iterative manner for each user in a csv file, column wise, for my Apache JMeter code in Selenium Webdriver Sampler in java language.
I am using a CSV Dataset config to fetch the username & password and would like to save the cookie value in a separate column.
I am unable to spilt the cookie and save using the following code snippet.
My code Snippet
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.*;
import org.junit.Assert;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import java.io.*;
import java.util.Arrays;
import java.io.FileWriter;
import java.util.List;
import java.io.Writer;
import java.lang.String;
// Login
String title = driver.getTitle();
System.out.println(title);
Assert.assertEquals("Sign in to your account", title);
WebElement username = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath(".//input[#type='email']")));
driver.findElement(By.xpath(".//input[#type='email']")).click();
driver.findElement(By.xpath(".//input[#type='email']")).sendKeys(new String[] {WDS.vars.get("username")});
driver.findElement(By.xpath(".//input[#type='submit']")).click();
WebElement username = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath(".//input[#type='password']")));
driver.findElement(By.xpath(".//input[#type='password']")).click();
driver.findElement(By.xpath(".//input[#type='password']")).sendKeys(new String[] {WDS.vars.get("password")});
driver.findElement(By.xpath(".//input[#type='submit']")).click();
Thread.sleep(3000L);
driver.findElement(By.xpath(".//input[#type='button']")).click();
Thread.sleep(3000L);
// Generating the cookie
String rawValue = driver.manage().getCookieNamed(".sampleCookie");
System.out.println(rawValue);
WDS.log.info(WDS.vars.get("rawValue"));
System.out.println("Login Successful");
WDS.log.info("Login Successful");
I am able to use the above code snippet to generate the cookie, but unable to print in JMeter Log console using
WDS.log.info(WDS.vars.get("rawValue"));
Info: 2023-02-03 14:34:08,656 INFO c.g.j.p.w.s.WebDriverSampler: null
I am unable to split the cookie via below mentioned code.
//Splitting the cookie
//Split cookie string from semicolon
String[] cookie = rawValue.split(";");
Error:
2023-02-03 15:38:44,557 ERROR c.g.j.p.w.s.WebDriverSampler: Sourced file: inline evaluation of: import org.openqa.selenium.*; import org.openqa.selenium.support.ui.*; import or . . . '' : Typed variable declaration : Error in method invocation: Method split( java.lang.String ) not found in class'org.openqa.selenium.Cookie' : at Line: 53 : in file: inline evaluation of: import org.openqa.selenium.; import org.openqa.selenium.support.ui.; import or . . . '' : rawValue.split ( ";" )
in inline evaluation of: ``import org.openqa.selenium.; import org.openqa.selenium.support.ui.;
I am unable to save the split cookie value or the raw cookie Value in that case via below mentioned code.
//Write the cookie value to a csv file
FileWriter fstream = new FileWriter("C:\\Users\\Scripts\\TestData\\Cookie.csv",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(WDS.vars.get("rawValue"));
out.write(System.getProperty("line.separator"));
out.close();
fstream.close();
Error: 2023-02-03 15:45:13,652 ERROR c.g.j.p.w.s.WebDriverSampler:
Sourced file: inline evaluation of: import org.openqa.selenium.*; import org.openqa.selenium.support.ui.*; import or . . . '' : Method Invocation out.write : at Line: 54 : in file: inline evaluation of: import org.openqa.selenium.; import
org.openqa.selenium.support.ui.; import or . . . '' : out .write (
WDS .vars .get ( "rawValue" ) )
Target exception: java.lang.NullPointerException: Cannot invoke
"String.length()" because "str" is null in inline evaluation of:
``import org.openqa.selenium.; import
org.openqa.selenium.support.ui.;
I have imported the required classes and have tried executing this code snippets individually with the login code, did'nt worked out.
I would really appreciate if anyone can aid me with the solutions.
raw cookie Value = .sampleCookie=eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjEiLCJoyA;
split cookie value = eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjEiLCJoyA
driver.manage().getCookieNamed function gives you an instance of org.openqa.selenium.Cookie which doesn't have split() function
If you want to continue with this approach you need to cast it to String first:
String[] cookie = rawValue.toString().split(";");
Alternatively you can use Cookie class functions instead of "splitting", i.e.
rawValue.getName()
rawValue.getValue()
rawValue.getDomain()
rawValue.getExpiry()
rawValue.isSecure()
rawValue.isHttpOnly()
The same is for printing it to the log file, you cannot put a Cookie object there, you need to change it to be a String:
WDS.log.info(rawValue.toString());
Also your approach of writing the variables into the file won't work if you intend to run your script with 2 or more users, the target file will have corrupt data due to race conditions so consider switching to Sample Variables and Flexible File Writer instead.

getting syntax error from nifi ExecuteScript processor inspite of correct python code

I am getting below error inspite of correct python code don't know how to resolve this error. Any help is much appreciated
org.apache.nifi.processor.exception.ProcessException: javax.script.ScriptException: SyntaxError: no viable alternative at input '*' in <script> at line number 35 at column number 26
python code
def get_match_list(regEx, line):
match = re.search(regEx, line)
print(match)
if match:
match_list = [*match.groups()] # this is the line exception is pointed
return match_list
else:
return []
It looks like jython use python 2.7 and as Unpacking Generalizations is a feature that introduced in python 3.5 you can not use this syntax in jython, so an alternative way to convert a tuple to a list is that use list ( match.groups) it works fine in older versions of python and current version of jython (2.7.2)

Method showString([class java.lang.Integer, class java.lang.Integer, class java.lang.Boolean]) does not exist in PySpark

This is the snippet:
from pyspark import SparkContext
from pyspark.sql.session import SparkSession
sc = SparkContext()
spark = SparkSession(sc)
d = spark.read.format("csv").option("header", True).option("inferSchema", True).load('file.csv')
d.show()
After this runs into the error:
An error occurred while calling o163.showString. Trace:
py4j.Py4JException: Method showString([class java.lang.Integer, class java.lang.Integer, class java.lang.Boolean]) does not exist
All the other methods work well. Tried researching alot but in vain. Any lead will be highly appreciated
This is an indicator of a Spark version mismatch. Before Spark 2.3 show method took only two arguments:
def show(self, n=20, truncate=True):
since 2.3 it takes three arguments:
def show(self, n=20, truncate=True, vertical=False):
In your case Python client seems to invoke the latter one, while the JVM backend uses the older version.
Since SparkContext initialization undergone significant changes in 2.4, which would cause failure on SparkContext.__init__, you're likely using:
2.3.x Python library.
2.2.x JARs.
You can confirm that by checking versions directly from your session, Python:
sc.version
vs. JVM:
sc._jsc.version()
Problems like this, are usually a result of misconfigured PYTHONPATH (either directly, or by using pip installed PySpark on top per-existing Spark binaries) or SPARK_HOME.
On spark-shell console, enter the variable name and see the data type.
As an alternative, you can tab twice after variable named. and it will show necessary function which could be applied.
Example of a DataFrame object.
res23: org.apache.spark.sql.DataFrame = [order_id: string, book_name: string ... 1 more field]

Did Matlab 2017a change how it imports external java classes?

I'm calling PDFBox from Matlab to figure out how many pages there are in a PDF. Everything works great with Matlba 2016b and prior. I can import the library and load a PDF without a problem:
import org.apache.pdfbox.pdmodel.PDDocument;
pdfFile = PDDocument.load(filename);
When I run the same thing in 2017a, I get the following error:
No method 'load' with matching signature found for class
'org.apache.pdfbox.pdmodel.PDDocument'.
I can change the line after the import so that the function signature matches:
jFilename = java.lang.String(filename);
pdfFile = PDDocument.load(jFilename.getBytes());
However, this causes PDFBox to have problems when I call load:
Java exception occurred:
java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1111)
at org.apache.pdfbox.pdfparser.COSParser.parseHeader(COSParser.java:1874)
at org.apache.pdfbox.pdfparser.COSParser.parsePDFHeader(COSParser.java:1853)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:242)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1093)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1071)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1053)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1038)
This error seems to occur regardless of the PDF I'm trying to load. I'm getting the same exception with PDFBox 1.8.10 and 2.0.6.
I'm left with 2 questions:
Did Matlab 2017a change how it passes strings to Java? I didn't see anything in the release notes about this.
What could be causing the PDFBox error? Matlab is still on Java 1.7 in 2017a so I wouldn't think there should be any difference in how PDFBox works.
It seems like the method you are calling is from PDDocument version 1.8.11
In the latest version, PDDocument version 2.0.2 the method signature for accepting a file name no longer exists.
Change your code to the following, and it should work.
pdfFile = PDDocument.load(java.io.File(filename));

Using a functional java construct (Predicate) from jython

So, I'm attempting to use the selenium java libraries from jython (yes, I know selenium has a python interface, but for good reasons of corporate teamwork accessing the pure java libraries makes more sense if it can be done well).
I'm just trying to do the example script here: http://seleniumhq.org/docs/03_webdriver.html#introducing-the-selenium-webdriver-api-by-example
Which I've implemented with the following jython code:
from org.openqa.selenium.firefox import FirefoxDriver
from org.openqa.selenium import By
from org.openqa.selenium import WebDriver
from org.openqa.selenium import WebElement
from org.openqa.selenium.support.ui import ExpectedCondition
from org.openqa.selenium.support.ui import WebDriverWait
driver = FirefoxDriver()
driver.get('http://www.google.com')
element = driver.findElement(By.name('q'))
# The array wrapper around the string is the only weird thing I encountered
element.sendKeys(["Cheese!"])
print "Page title is: " + driver.getTitle()
class ExpectedConditionTitle(ExpectedCondition):
def apply(d):
print(type(d))
return d.title.toLowerCase().startsWith(["cheese!"])
def equals(d):
pass
print(type(driver))
WebDriverWait(driver, 10).until(ExpectedConditionTitle().apply())
print driver.getTitle()
driver.quit()
And it's puking on the ExpectedCondition bit. I can't figure out how to make a subclass for the variety desired by until. I've gotten the following errors with variations in my code:
last
Traceback (innermost last):
File "Example.py", line 24, in ?
File "Example.py", line 19, in apply
AttributeError: 'instance' object has no attribute 'title'
and
Traceback (innermost last):
File "Example.py", line 24, in ?
File "Example.py", line 19, in apply
AttributeError: getTitle
and
Traceback (innermost last):
File "Example.py", line 22, in ?
TypeError: until(): 1st arg can't be coerced to com.google.common.base.Function or com.google.common.base.Predicate
The selenium ExpectedCondition interface is basically just a front for the Guava Predicate interface.
I'm not well versed enough in python or java to figure this out. Anyone have any ideas how I might accomplish this?

Categories

Resources