IE driver browser not working using JSR223 sampler - jmeter - performance

I am using JSR223 Sampler to use IE browser and run some validation on UI.
code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.apache.jmeter.samplers.SampleResult;
File file = new File("webdriver.ie.driver","C:\Program Files\Internet Explorer\IEDriverServe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
//System.setProperty("webdriver.ie.driver","C:\Users\Downloads\apache-jmeter-5.3\apache-jmeter-5.3\bin\IEDriverServer");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
WebDriver driver = new InternetExplorerDriver(capabilities)
def wait = new WebDriverWait(driver, 20);
driver.get('https://google.com/');
WDS.sampleResult.sampleStart();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//input[#name='q']")));
WDS.sampleResult.sampleEnd();
error :
2020-10-08 11:43:08,472 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2020-10-08 11:43:08,472 INFO o.a.j.t.JMeterThread: Thread started: IE 1-1
2020-10-08 11:43:08,479 ERROR o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script iecONFIG, message: javax.script.ScriptException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script23.groovy: 8: Unexpected input: '"webdriver.ie.driver","' # line 8, column 44.
ew File("webdriver.ie.driver","C:\Progra
^
1 error
javax.script.ScriptException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script23.groovy: 8: Unexpected input: '"webdriver.ie.driver","' # line 8, column 44.

There are multiple problems with your script, i.e.:
File file = new File("webdriver.ie.driver","C:\Program Files\Internet Explorer\IEDriverServe"); this constructor doesn't make sense, see File javadoc for possible options
You declare WebDriver driver twice, on 2nd occurrence your script will fail
You need to add .exe to IEDriverServer
Suggested code change:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.apache.jmeter.samplers.SampleResult;
System.setProperty("webdriver.ie.driver", 'c:/full/path/to/IEDriverServer.exe');
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
WebDriver driver = new InternetExplorerDriver(capabilities)
def wait = new WebDriverWait(driver, 20);
driver.get('https://google.com/');
WDS.sampleResult.sampleStart();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//input[#name='q']")));
WDS.sampleResult.sampleEnd();
More information: Internet Explorer Driver
Is there any specific reason for not using WebDriver Sampler with InternetExplorer Driver Config? It will be way more easy given you're not too familiar with Selenium and JMeter

Related

How to pass a value/keyword/argument on search box of a website while creating Jmeter Script from the API using Java?

I already created a Jmeter Script from API using Java.
I want to emulate the action where we search a value/keyword/argument in a search box of an eCommerce website.
The below script consists of the following samplers:
Load Url(Invoke the sample ecommerce URL)
Login(Used AuthManager to use Login Credentials)
Search(Search a value/keyword/argument on the search box of the sample website)
Here is my code snippet:
package com.blazemeter.demo;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.AuthManager;
import org.apache.jmeter.protocol.http.control.Authorization;
import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
import org.apache.jmeter.protocol.http.gui.AuthPanel;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.FileOutputStream;
public class JMeterFromAPI {
public static void main(String[] args) throws Exception {
String jmeterHome = "Path of Jmeter Home";
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome(jmeterHome);
JMeterUtils.loadJMeterProperties("Path of Jmeter Properties Files");
JMeterUtils.initLocale();
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// HTTP Sampler - Load URL
HTTPSamplerProxy LoadUrl = new HTTPSamplerProxy();
LoadUrl.setDomain("www.samplewebsite.com");
LoadUrl.setPort(80);
LoadUrl.setPath("/");
LoadUrl.setMethod("GET");
LoadUrl.setName("Load Url");
LoadUrl.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
LoadUrl.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
// Create HTTP Authorization Manager
AuthManager manager = new AuthManager();
Authorization authorization = new Authorization();
authorization.setURL("https://www.samplewebsite.com");
authorization.setUser("sampleusername");
authorization.setPass("samepassword");
manager.addAuth(authorization);
manager.setName(JMeterUtils.getResString("auth_manager_title")); // $NON-NLS-1$
manager.setProperty(TestElement.TEST_CLASS, AuthManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, AuthPanel.class.getName());
// HTTP Sampler - Login
HTTPSamplerProxy Login = new HTTPSamplerProxy();
Login.setDomain("www.samplewebsite.com");
Login.setPort(80);
Login.setPath("/account/login");
Login.setMethod("GET");
Login.setName("Login");
Login.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
Login.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
// HTTP Sampler - Search
HTTPSamplerProxy Search = new HTTPSamplerProxy();
Search.setDomain("www.samplewebsite.com"");
Search.setPort(80);
Search.setPath("/search?q=mobiles");
Search.setMethod("GET");
Search.setName("Search");
Search.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
Search.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
loopController.initialize();
// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Thread Group");
threadGroup.setNumThreads(3);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
// Test Plan
TestPlan testPlan = new TestPlan("Ecommerce Website");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
// HTTP Request Sampler and Header Manager
HashTree httpRequestTree = new HashTree();
httpRequestTree.add(Login, manager);
// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(LoadUrl);
threadGroupHashTree.add(httpRequestTree);
threadGroupHashTree.add(Search);
SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterHome + "/bin/test.jmx"));
//Add Summarizer output
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// Store Execution Results into a .jtl file
String logFile = jmeterHome + "/bin/result.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
System.exit(0);
}
}
So, I want to use the Search Sampler to search a value/keyword/argument for the search box given on the sample website.
Most probably you won't be able to login using HTTP Authorization Manager as it is designed to deal with external authentication systems like Basic, NTLM and Kerberos. If you need to type your credentials into a HTML Form - most likely you need to use HTTP Request sampler and send a POST request with the credentials.
For example this code:
HTTPSamplerProxy loginSampler = new HTTPSamplerProxy();
loginSampler.setDomain("example.com");
loginSampler.setPort(80);
loginSampler.setPath("/login");
loginSampler.setMethod("POST");
loginSampler.setName("Perform Login");
loginSampler.addArgument("username", "johndoe");
loginSampler.addArgument("password", "secret");
loginSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
loginSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
will result into the following configuration:
With regards to search terms - my expectation is that you need to stick to the same approach.
In general creating JMeter test plans using API is not recommended/supported way so I would suggest the following alternative approach:
Record your Test Plan skeleton using JMeter's HTTP(S) Test Script Recorder
Perform correlation if required
Check if your test is doing what it is supposed to be doing by inspecting requests/responses using View Results Tree listener
Once your .jmx script is ready use JMeter API to generate exactly the same test plan programatically.
P.S. An easier way of creating JMeter scripts without the GUI is using Taurus tool where you can develop a test plan using declarative YAML-based syntax.

Error When trying to use XSSF on Jmeter

I am getting error when trying to create xlsx file using Jmeter. actually I already try using HSSF (for .xls) and it is works fine. But when I am trying to change it using xlsx, I am getting error. I already copy the jar file for poi and poi-ooxml on jmeter lib file. here is my simple script :
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.lang.String;
import java.lang.Object;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("HENCIN");
try {
FileOutputStream out = new FileOutputStream(new File("D:\\Jmeter\\testhencin.xlsx"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Actually when I am trying to find the error, the problem are getting from this line :
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample sheet");
Please someone help me to figure it out. it works on HSSF but on XSSF it is not working. I am getting error :Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval org/apache/xmlbeans/XmlObject
I would suggest:
Catching all the possible exceptions and printing the stacktrace to jmeter.log file as well
Re-throwing the exception to make sure you won't get false positive sampler result, something like:
} catch (Throwable e) {
e.printStackTrace();
log.info("Error in Beanshell", e);
throw e;
}
With regards to your question, most likely it is due to missing XMLBeans jar in JMeter classpath. I would suggest the following:
Get "clean" installation of the latest JMeter version
Download the latest version of tika-app.jar and drop it to JMeter's "lib" folder
Restart JMeter to pick the jar up
Using Tika you will get all the necessary libraries bundled, moreover, you JMeter will display content of the binary files in the View Results Tree listener. See How to Extract Data From Files With JMeter article for more details.

Unable to start a Session in Flask within a function

I'm running Flask Session and using Eve as an API. For the Session code I'm following the example here https://pythonhosted.org/Flask-Session/
from flask import Flask, session
from flask.ext.session import Session
app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
#app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')
I have an Eve API located under /api, and I want to avoid starting a new Session for those requests at least.
I want to start my flask Session only if the request.environ['PATH_INFO'] doesn't start with '/api/' but whenever I put Session() anywhere else it fails.
Following the example:
sess = Session()
sess.init_app(app)
When I try to do that in before_request or similar, then I get:
A setup function was called after the first request was handled.
and if I try to start a session in a normal content generator I get:
AttributeError: 'SecureCookieSession' object has no attribute 'sid'
How can I start a session conditionally, depending on the path/environment/etc?
My current code looks like this:
import flask
import xml.etree.ElementTree as ElementTree
from bson.objectid import ObjectId
from random import shuffle, choice as pick
from cgi import escape as escapehtml
from time import mktime
from urllib import quote as escapeurl, unquote_plus as unescapeurl
from flask import Flask, request, session, render_template, send_from_directory, jsonify, redirect, abort
from flask.ext.session import Session
from flask.ext.login import LoginManager, login_user, logout_user, current_user, UserMixin, user_logged_in, login_required, fresh_login_required
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired, URLSafeTimedSerializer
from flask_mail import Mail, Message
from wtforms import Form, BooleanField, PasswordField
from flask.ext.mongoengine import MongoEngine
from flask.ext.security import Security, MongoEngineUserDatastore, RoleMixin, UserMixin
from flask.ext.principal import Principal, Permission, RoleNeed
from flask_security.forms import RegisterForm, Required, StringField
from flask_images import Images
from eve import Eve
from eve.auth import TokenAuth
from flask.ext.moment import Moment
from eve.io.mongo import Validator
from flask.ext.cors import CORS, cross_origin
from app.admin.one1 import one1
from app.emails.emails import emails
from app.alligator.alligator import alligator
from app.data.ndm_feed.ndm_feed import ndm_feed
from flask.ext import excel
...
login_serializer = URLSafeTimedSerializer(app.secret_key)
login_manager = LoginManager()
app.config.from_object(__name__)
login_manager.init_app(app)
Session(app)
and to avoid starting sessions for API calls I am trying to do things like this:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
Session(app)
or the equivalent:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
sess = Session()
sess.init_app(app)
But I can't seem to find a way to do it without the errors above.
How can I start a Flask session conditionally, depending on the path/environment/etc?
Actually your app already created before you use this: #app.before_request so it means you are late to add new configuration or extension initialize. Bu you can do with Blueprint:
# api.py
from flask import Blueprint
from flask_session import Session
sess = Session()
api = Blueprint('api', __name__)
# yourapp.py
...
def create_app():
...
try:
from api import api, sess
sess.init_app(app)
app.register_blueprint(api)
# views.py
#api.route('/set/')
def set():
session['key'] = 'value'
return 'ok

How to generate response times graph from Jmeter programmatically

I have the following java code to run JMeter.
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.SetupThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
public class HCTGameDay {
public static void main(String[] args){
// Engine
StandardJMeterEngine jm = new StandardJMeterEngine();
// jmeter.properties
JMeterUtils.loadJMeterProperties("/Users/rokumar/Desktop/jmeter.properties");
HashTree hashTree = new HashTree();
// HTTP Sampler
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("www.linkedin.com");
httpSampler.setPort(80);
httpSampler.setPath("/");
httpSampler.setMethod("GET");
// Loop Controller
TestElement loopCtrl = new LoopController();
((LoopController)loopCtrl).setLoops(1);
((LoopController)loopCtrl).addTestElement(httpSampler);
((LoopController)loopCtrl).setFirst(true);
// Thread Group
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController((LoopController)loopCtrl);
// Test plan
TestPlan testPlan = new TestPlan("HCT TEST PLAN");
hashTree.add("testPlan", testPlan);
hashTree.add("loopCtrl", loopCtrl);
hashTree.add("threadGroup", threadGroup);
hashTree.add("httpSampler", httpSampler);
jm.configure(hashTree);
jm.run();
}
}
I do not get any results in the console output . Where are the response times etc. stored and how do I plot the graph of response times, number of connections, number of users programmatically.
Add the following code before jm.configure(hashTree) line
//add Summarizer output to get test progress in stdout like:
// summary = 2 in 1.3s = 1.5/s Avg: 631 Min: 290 Max: 973 Err: 0 (0.00%)
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// Store execution results into a .jtl file
String logFile = jmeterHome + System.getProperty("line.separator") + "example.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(hashTree.getArray()[0], logger);
It will generate example.jtl file in /bin folder of your JMeter installation which is the usual JMeter result file suitable for analysis, graphs generation, etc.
See chapter 4.3 of 5 Ways To Launch a JMeter Test without Using the JMeter GUI guide for details on how to run JMeter test from Java code in general and example class at https://bitbucket.org/blazemeter/jmeter-from-code/ in particular for reference.

Authenticating Multiple Scopes in Google API Oauth2.0

I need to insert multiple scopes into the http post request that creates the service object that permits authentication. However, simply putting in multiple scopes into the string doesn't seem to achieve this unfortunately, returning the error at the bottom.
import gflags
import apiclient
import oauth2client
import argparse
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from apiclient import discovery
from apiclient import sample_tools
import httplib2
import sys
import os
import pprint
from pprint import pprint
name = 'prediction'
scope = "https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/devstorage.full_control testing_data/training_data.csv testing_data/training_data.csv"
filename = '__file__'
client_secrets = os.path.join(os.path.dirname(filename),
'client_secrets.json')
flow = client.flow_from_clientsecrets(client_secrets,scope=scope)
storage = file.Storage(name+'.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run(flow, storage)
http = credentials.authorize(httplib2.Http())
service = discovery.build('prediction','v1.6',http=http)
papi = service.trainedmodels()
result = papi.list(maxResults=10,project='895092811023').execute()
body = {'id':'Universities','storageDataLocation':'testing_data/training_data.csv'}
start = papi.insert(body=body,project='895092811023').execute()
This is the error, which points out that the required scopes are missing. (It is recording some scope, because it is saving a result to result, but just not letting me insert a new model, which I believe is due to the fact that it isn't getting the scope to access the data for this model, which is in Google Cloud Storage?
Traceback (most recent call last):
File "filehere", line 42, in <module>
start = papi.insert(body=body,project='895092811023').execute()
File "build\bdist.win-amd64\egg\oauth2client\util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\site-packages\apiclient\http.py", line 680, in execute
raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 401 when requesting https://www.googleapis.com/prediction/v1.6/projects/895092811023/trainedmodels?alt=json returned "Required scope(s) missing.">
The only thing you need to pass in for scopes are the www.googleapis.com things such as: https://www.googleapis.com/auth/prediction, don't pass in "testing_data/training_data.csv testing_data/training_data.csv".
You can always visit https://accounts.google.com/b/0/IssuedAuthSubTokens and see the scopes that your application has been granted.

Resources