I am using following code to create issue on Jira which is hosted on my local machine.
But i am getting error code 400. I am not able to find out what went wrong and things are working perfectley fine when making the API call from post man.
I am using the API documentation available on below location for this -
https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
public static void main(String[] args) throws MalformedURLException, FileNotFoundException {
RestAssured.baseURI = "http://localhost:8080";
String headerKey=null;
String headerValue = null;
String body = "{\r\n" +
" \"fields\": {\r\n" +
" \"project\":\r\n" +
" {\r\n" +
" \"key\": \"GOOG\"\r\n" +
" },\r\n" +
" \"summary\": \"REST ye mereeery gentlemen.\",\r\n" +
" \"description\": \"Creating of an eeissue using project keys and issue type names using the REST API\",\r\n" +
" \"issuetype\": {\r\n" +
" \"name\": \"Bug\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
Map<String,String> authInfo = AuthenticateUser.getSessionInfo();
for(String key:authInfo.keySet()) {
System.out.println(key+":"+authInfo.get(key));
headerKey = key;
headerValue = authInfo.get(key);
}
given().header(headerKey,headerValue).body(body).contentType(ContentType.JSON).
when().post("/rest/api/2/issue/").
then().statusCode(201);
}
}
Exception in thread "main" java.lang.AssertionError: 1 expectation failed.
Expected status code <201> but was <400>.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:59)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:238)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:250)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:483)
at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:655)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
at io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:123)
at io.restassured.specification.ResponseSpecification$statusCode$0.callCurrent(Unknown Source)
at io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:131)
at io.restassured.internal.ValidatableResponseOptionsImpl.statusCode(ValidatableResponseOptionsImpl.java:119)
at com.local.jira.Demo.main(Demo.java:46)
Looking at your postman screenshot I can see that you've only passed headers and a body but your rest assured code seems a bit over populated with other references, Code 400 is BAD_REQUEST
I've framed a sample code which should help, If you still need assistance then revert
{
RequestSpecification req = RestAssured.given();
req.header("Content-Type", "application/json");
req.header("JSESSIONID", "9533");
req.body("{\n" +
" \"fields\": {\n" +
" \"project\":\n" +
" {\n" +
" \"key\": \"TEST\"\n" +
" },\n" +
" \"summary\": \"REST ye merry gentlemen.\",\n" +
" \"description\": \"Creating of an issue using project keys and issue type names using the REST API\",\n" +
" \"issuetype\": {\n" +
" \"name\": \"Bug\"\n" +
" }\n" +
" }\n" +
"}");
Response resp = req.post("http://localhost:8080/rest/api/2/issue");
int code = resp.getStatusCode();
System.out.println("Status Code is : " + code);
String body = resp.asString();
System.out.println("Body is : " + body);
Assert.assertEquals(code, 201);
}
Related
I am using a content provider with a multi-table sqlite database. Some of the tables have a relationship to one another of one to many. One table lists the entities and the second table lists the activities, with a reference to the entity by way of the "foreign key" which is the ID of the entity. I don't use an actual "foreign key" but this is how I keep track.
Here are my database tables:
private static final String CREATE_TABLE_ENTITY = "CREATE TABLE " + TABLE_ENTITY + " ( " + ENTITY_KEY_ID + " INTEGER PRIMARY KEY, " + NAME + " TEXT, " + DATE_OBTAINED + " TEXT, " + PROFILE_IMAGE + " TEXT, " + QUALITY1 + " TEXT, " + QUALITY2 + " TEXT, " + QUALITY3 + " TEXT, " + " )" ;
private static final String CREATE_TABLE_ACTIVE_ENTITIES = "CREATE TABLE " + TABLE_ACTIVE_ENTITIES + " ( " + ACTIVE_ENTITY_KEY_ID + " INTEGER PRIMARY KEY, " + TABLE_ENTITY_KEY_ID + " INTEGER, " + NAME + " TEXT, " + DATE + " TEXT, " + ACTIVITY1 + " TEXT, " + ACTIVITY2 + " TEXT, " + ACTIVITY3 + " TEXT, " + ACTIVITY4 + ... + " )" ;
So I want to query the results of a particular Entity and get the most recent Activities. I attempted an inner join on the ENTITY_KEY_ID which is equivalent to the TABLE_ENTITY_KEY_ID in the Activities Table.
This is my content provider query:
#Nullable
#Override
public Cursor query(Uri uri, String[] strings, String selection, String[] selectionArgs, String sortOrder) {
db = hdb.getWritableDatabase();
int uriType = uriMatcher.match(uri);
Cursor cursor = null
case TABLE_ENTITY_JOIN_TABLE_ACTIVE_ENTITIES_ID:
if (uri != null) {
String[] args = {uri.getLastPathSegment()
cursor = db.rawQuery("SELECT table_entity.NAME, date_obtained, profile_image, quality1, quality2, quality3, table_active_entities.activity1, table_active_entities.activity2 " + " FROM table_entity, table_active_entities " + " ON ENTITY_KEY_ID = table_entity_key_id " + " WHERE ENTITY_KEY_ID=?", args);
}
break;
default:
throw new IllegalArgumentException("Unknown Uri");
}
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(), uri);
}
return cursor;
}
This is where I call the query from my activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hermit_page);
getInfoIntent = getIntent();
uri = getInfoIntent.getParcelableExtra(MyProvider.CONTENT_ITEM_TYPE);
getSupportLoaderManager().initLoader(0,null,this);
action = Intent.ACTION_ATTACH_DATA;
EntityDataFilter = MyDatabaseHelper.ENTITY_KEY_ID + " = " + uri.getLastPathSegment();
long id = Long.parseLong(uri.getLastPathSegment());
Cursor cursor = getContentResolver().query(ContentUris.withAppendedId(MyProvider.CONTENT_URI_TABLE_ENTITY_JOIN_TABLE_ACTIVE_ENTITIES, id),null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
name = cursor.getString(cursor.getColumnIndex(MyDatabaseHelper.NAME));
hImage = cursor.getString(cursor.getColumnIndex(MyDatabaseHelper.PROFILE_IMAGE));
...
cursor.close();
}
The issue I am having is the WHERE clause which selects the ID is not pulling up the rows. I am either getting the result of the first ID of the ENTITY table if I put cursor.moveToFirst() or I am getting the last ID of the ENTITY table if I put cursor.moveToLast(). I am not getting the info from the join only from the ENTITY TABLE. It does not correlate to which ENTITY_ID is actually selected. So it seems the WHERE clause is not filtering by ID. I tried adding parameters to the query statement within the activity(using the EntityDataFilter string) , but this did not produce any difference in results. I also tried writing the select query as a string initially then plugging the string in the content provider query like : cursor.db.RawQuery(MyStringQuery,args) but this did not work either. I am tracking the output by looking at the TextView results in my activity. Your help is greatly appreciated if you understand why it is giving these results and how I can better write the statement to get the results that I want. Thank you very much in advance!
i want to fetch the text from shadow element of Dom
http://prntscr.com/e9smzg
I have tried below code but its not working..
public String ShadowRootElement(String str) {
WebElement ele = (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot",getElementByXpath(str));
return ele.findElement(By.xpath("//div[#id='inner-editor']")).getText().toString();
}
Please refer attached screenshot link for html code.
public String getEmailId(String str){
return ShadowRootElement(Repo.get("ipEmailId"));
}
First of all, the way you call ele.findElement(By.xpath("//div[#id='inner-editor']")).getText().toString(); is troublesome.
To locate elements under shadow root node,By.xpath() won't work. Only By.id() & By.cssSelector() will work as valid locators. Please refer to this post for more details.
Secondly (and unfortunately), I found even if you can locate the node under shadow root, element.getText() method would return an empty string.. Simply put it doesn't work for me either :-(
you will not be able to use xpath with shadowroots, since xpath is applied to DOM
Here, you can pull back all the elements, then use css or other to check if text exists, eg (use driver instead of session, since I wrap my driver):
public static String getAllShadowRootsText(DriverSessions session, String rootNode)
{
String elsText = "";
try {
List<SearchContext> sroots = getAllShadowRoots(session, rootNode);
for(SearchContext sroot : sroots){
// we have to specify the elements with shadowroot children, we cant just get all *
List<WebElement> els = sroot.findElements(By.cssSelector(validDomTypes));
for(WebElement el : els) {
elsText = elsText + el.getText();
}
}
}
catch (Exception e) {} // we might want to loop this, pages change and shadow roots move / go stale
return elsText;
}
public static List<SearchContext> getAllShadowRoots(DriverSessions session, String rootNode)
{
String script = ""
+ "function getShadowRoots (node, sroots, func) { "
+ "var done = func(node); "
+ "if (done) {return true;} "
+ "if ('shadowRoot' in node && node.shadowRoot) { "
+ "sroots.push(node.shadowRoot); "
+ "var done = getShadowRoots(node.shadowRoot, sroots, func); "
+ "if (done) {return true;} "
+ "} "
+ "node = node.firstChild; "
+ "while (node) { "
+ "var done = getShadowRoots(node, sroots, func); "
+ "if (done) {return true;} "
+ "node = node.nextSibling; "
+ "} "
+ "} "
+ "try { "
+ "sroots = new Array(); "
+ "getShadowRoots("+rootNode+", sroots, function (node, sroots) {}); "
+ "return sroots;"
+ "} "
+ "catch(err){return null};";
JavascriptExecutor js = (JavascriptExecutor)session.getDriver();
#SuppressWarnings("unchecked")
List<SearchContext> els = (List<SearchContext>) js.executeScript(script);
return els;
}
I was trying to run a simple Cql3 query with Astyanax and I keep on getting an error.
The aim is to create a simple table via Astyanax using cql3.
public class SomeTest {
private AstyanaxContext<Keyspace> astyanaxContext;
private Keyspace keyspace;
private static String CREATE_TABLE_QUERY = "CREATE TABLE top_items (\n" +
" categoryName varchar,\n" +
" type varchar,\n" +
" baseItemId int,\n" +
" margin float,\n" +
" ds timestamp,\n" +
" PRIMARY KEY (categoryName, ds)\n" +
");";
#Before
public void setUp() {
try {
this.astyanaxContext = new AstyanaxContext.Builder()
.forCluster("ClusterName")
.forKeyspace("new_examples")
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl().setDiscoveryType(NodeDiscoveryType.NONE).setCqlVersion("3.0.0"))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl("MyConnectionPool").setMaxConnsPerHost(1).setPort(9160)
.setSeeds("localhost:9160")).withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
this.astyanaxContext.start();
this.keyspace = this.astyanaxContext.getEntity();
// Using simple strategy
keyspace.createKeyspace(ImmutableMap.<String, Object>builder()
.put("strategy_options", ImmutableMap.<String, Object>builder()
.put("replication_factor", "1")
.build())
.put("strategy_class", "SimpleStrategy")
.build()
);
// test the connection
this.keyspace.describeKeyspace();
} catch (Throwable e) {
throw new RuntimeException("Failed to prepare CassandraBolt", e);
}
}
#Test
public void testWrite() throws ConnectionException {
ColumnFamily<String, String> CQL3_CF = ColumnFamily.newColumnFamily(
"Cql3CF",
StringSerializer.get(),
StringSerializer.get());
OperationResult<CqlResult<String, String>> result;
result = keyspace
.prepareQuery(CQL3_CF)
.withCql(CREATE_TABLE_QUERY)
.execute();
}
}
When I run the test I get this stack trace
java.lang.NoSuchMethodError: org.apache.thrift.meta_data.FieldValueMetaData.<init>(BZ)V
at org.apache.cassandra.thrift.Cassandra$execute_cql_query_args.<clinit>(Cassandra.java:32588)
at org.apache.cassandra.thrift.Cassandra$Client.send_execute_cql_query(Cassandra.java:1393)
at org.apache.cassandra.thrift.Cassandra$Client.execute_cql_query(Cassandra.java:1387)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6$1.internalExecute(ThriftColumnFamilyQueryImpl.java:699)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6$1.internalExecute(ThriftColumnFamilyQueryImpl.java:696)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:55)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:27)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$1.execute(ThriftSyncConnectionFactoryImpl.java:136)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:69)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:248)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6.execute(ThriftColumnFamilyQueryImpl.java:694)
at storage.cassandra.daos.SomeTest.testWrite(SomeTest.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:76)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
I'm using "com.netflix.astyanax" % "astyanax" % "1.56.18" .
Please help.
It looks like Astyanax is not properly supporting Cassandra 1.2 or 1.2.1 (not even 1.56.24, released 7 days ago...). You may try java-driver instead. It is not yet released but it works fine, as far as I have tested.
https://github.com/datastax/java-driver
In web application [asp.net], i write the code to redirect to other page with in the solution, but it is giving exception.
Response.Redirect("abc.aspx");
can you help me, thank you.
WeeklyAttendanceMailStatusBE obj = new WeeklyAttendanceMailStatusBE();
obj.CreatedBy = Session["xxx"].ToString();
obj.Sesssionid = Session.SessionID.ToString();
obj.StatusDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());
obj.Types = "Insert";
if (radLastWeek.Checked == true)
{
obj.Flags = 1;
obj.LastWeekStatus = 1;
int result = new WeeklyAttendanceMailStatusBL().InsertWeeklyAttendanceMailStatus(obj);
if (result > 0)
{
Response.Redirect("abc.html");
}
else
{
DateTime dt = DateTime.Now;
ScriptManager.RegisterStartupScript(this, GetType(), "message", "<script> alert('Not Submited Mail Status')</status>", false);
}
}
else
{
}
May be this is because of "thread is being aborted" exception, handle exception with try catch statements or specific catch class called ThreadAbortException
Please refer this for more information.
Try this :
Response.Redirect("abc.aspx",false);
Add a second argument (boolean value) that indicates whether to stop running the current page.
Reference :
HOW TO: Use Response.Redirect in ASP.NET with Visual Basic .NET
Is it possible to return a WebElement's xpath?
Not directly from WebDriver, but you can fake it if you really need to:
public String getElementXPath(WebDriver driver, WebElement element) {
return (String)((JavascriptExecutor)driver).executeScript("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element);
}
The Javascript is from this post, minified to fit on one line. It may not be perfect, but could give you an idea of where to go. Most drivers implement the JavascriptExecutor interface and have the capability of executing Javascript in the browser. executeScript can return any primitive JavaScript type, an HTML element, or non-nested list of any of the preceding.
Not all browsers support xpath the same way, so be careful if using these xpaths to select elements. Also, not all browsers have native xpath support (cough IE cough), so it was faked in that case.
If WebElement was found by By.xpath:
on Java:
public static String GetWebElementXpath(WebElement El) throws AssertionError{
if ((El instanceof WebElement)){
Object o = El;
String text = o.toString();
/* text is smth like this
[[FirefoxDriver: firefox on WINDOWS (9170d4a5-1554-4018-adac-f3f6385370c0)] -> xpath: //div[contains(#class,'forum-topic-preview')]//div[contains(#class,'small-human')]]
*/
text = text.substring( text.indexOf("xpath: ")+7,text.length()-1);
return text;
}else { Assert.fail("Argument is not an WebElement, his actual class is:"+El.getClass()); }
return "";
}
Both of the above answers suffer from the same problem. By returning the completed XPath with the .toLowerCase() function called, any XPath containing an id with a capital letter will not work.
Example: //div[#id="deviceblock-1111"] will not work on tag <div id="deviceBlock-1111">
You could however just remove the .toLowerCase() call off the return but you'll end up with XPath's looking like this: //DIV[#id="deviceBlock-1111"]/DIV[2]/SELECT[1]/OPTION[5]
To solve this use the function below.
public String GetElementXPath(WebElement element, WebDriver driver)
{
return (String) ((JavascriptExecutor) driver).executeScript(
"getXPath=function(node)" +
"{" +
"if (node.id !== '')" +
"{" +
"return '//' + node.tagName.toLowerCase() + '[#id=\"' + node.id + '\"]'" +
"}" +
"if (node === document.body)" +
"{" +
"return node.tagName.toLowerCase()" +
"}" +
"var nodeCount = 0;" +
"var childNodes = node.parentNode.childNodes;" +
"for (var i=0; i<childNodes.length; i++)" +
"{" +
"var currentNode = childNodes[i];" +
"if (currentNode === node)" +
"{" +
"return getXPath(node.parentNode) +
'/' + node.tagName.toLowerCase() +
'[' + (nodeCount+1) + ']'" +
"}" +
"if (currentNode.nodeType === 1 && " +
"currentNode.tagName.toLowerCase() === node.tagName.toLowerCase())" +
"{" +
"nodeCount++" +
"}" +
"}" +
"};" +
"return getXPath(arguments[0]);", element);
}
This will return a correctly formatted, unique XPath from your WebElement.
//div[#id="deviceBlock-1111"]/div[2]/select[1]/option[5]
I would comment directly on dflems' answer, but I do not have the reputation to do so.
Converting the entire xpath to lower case is fine unless the xpath contains an id value that is not all lower-case. Below is a modified version of dflems' Javascript, but in Python instead of Java:
def get_xpath_from_element(driver, element):
return driver.execute_script("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName.toLowerCase()+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]);", element)
xpath selenium python javascript
public String getElementXPath(WebDriver driver, WebElement element) {
String javaScript = "function getElementXPath(elt){" +
"var path = \"\";" +
"for (; elt && elt.nodeType == 1; elt = elt.parentNode){" +
"idx = getElementIdx(elt);" +
"xname = elt.tagName;" +
"if (idx > 1){" +
"xname += \"[\" + idx + \"]\";" +
"}" +
"path = \"/\" + xname + path;" +
"}" +
"return path;" +
"}" +
"function getElementIdx(elt){" +
"var count = 1;" +
"for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling){" +
"if(sib.nodeType == 1 && sib.tagName == elt.tagName){" +
"count++;" +
"}" +
"}" +
"return count;" +
"}" +
"return getElementXPath(arguments[0]).toLowerCase();";
return (String)((JavascriptExecutor)driver).executeScript(javaScript, element);
}
There is a way to get the elements XPath without the use of JavaScript.
Define starting point of outer XPath, for example body tag.
Check all possible inward tags with selenium for NoSuchElementException.
Check getText for the lists of XPaths generated.
win
public static String getXPathFromElement(WebElement element) {
String elementDescription = element.toString();
return elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]"));
}
Web element toString() looks like this:
'[[FirefoxDriver: firefox on WINDOWS (ceb69f9f-bef4-455d-b626-ab439f195be6)] -> id: pageBeanfundDescription]'
I just extract the id/xpath.
/**
* This method return By reference for the WebElement passed to it as a parameter.
* #param element
* #return
*/
public static By convertWebElementToByReference(WebElement element)
{
By byLocator = null;
String elementDescription = element.toString();
String elementTypeAndValue[] = (elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]"))).split(":");
switch (elementTypeAndValue[0].trim())
{
case "id": byLocator = By.id(elementTypeAndValue[1].trim());
break;
case "xpath": byLocator = By.xpath(elementTypeAndValue[1].trim());
break;
case "link text": byLocator = By.linkText(elementTypeAndValue[1].trim());
break;
case "tag name": byLocator = By.tagName(elementTypeAndValue[1].trim());
break;
case "class name": byLocator = By.className(elementTypeAndValue[1].trim());
break;
case "partial link text": byLocator = By.partialLinkText(elementTypeAndValue[1].trim());
break;
case "name": byLocator = By.name(elementTypeAndValue[1].trim());
break;
case "css selector": byLocator = By.cssSelector(elementTypeAndValue[1].trim());
break;
default:
throw new RuntimeException("Invalid locator type: " + elementTypeAndValue[0].trim());
}
return byLocator;
}