Soft assert with multiple conditions in selenium - selenium

I am trying to get the title of the page, and sometimes they change, but the name is only between 3 names, using the if function below I can get it in selenium.
but I am converting it into soft assert for my test script. basically it should pass the test if the title is between student profile or test or test2.
if(contr0l.getTitle().contentEquals("Student Profile") || contr0l.getTitle().contentEquals("Experiential Learning") || contr0l.getTitle().contentEquals("")){
System.out.println("CV Link is Correct!"+ '\n' + "Title is " + contr0l.getTitle() + '\n');
}else{
System.out.println("Title is incorrect, Current Title" + contr0l.getTitle() + '\n');
}
Softfail.assertEquals(contr0l.getTitle(), ("Student Profile") , ("test")); // << this line
contr0l.navigate().back();
// Softfail.assertAll();

You can you hamcrest library to simplify your assertions. This is your dependency:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
</dependency>
This is the example of your test:
package click.webelement.so;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;
public class TestTitle {
#Test
public void testTitle() {
String observed = "Title that you have received from driver";
String[] expectedTitles = {
"Test 1",
"Title that you have received from driver",
"Test 2"
};
assertThat(observed, is(in(expectedTitles)));
}
}
UPD: Using no hamcrest:
package click.webelement.so;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Arrays;
public class Main {
#Test
public void testTitle() {
String observed = "Title that you have received from driver";
String[] expectedTitles = {
"Test 1",
"Title that you have received from driver",
"Test 2"
};
Assert.assertTrue(Arrays.asList(expectedTitles).contains(observed));
}
}

Related

Liferay 7.2 api json url 404

I have:
Eclispse
Version: 2019-06 (4.12.0)
Build id: 20190614-1200
Liferay 7.2.0 CE GA1.
I use Gradle.
I followed this tutorial:
https://www.liferaystack.com/2017/11/rest-extender-and-jax-rs-restful-web-service-in-liferay-7-dxp.html
I created a rest module.
I created two file of configuration inside the folder "src/main/resources/configuration":
com.liferay.portal.remote.cxf.common.configuration.CXFEndpointPublisherConfiguration-cxf.properties
Code:
contextPath=/my-rest-service
authVerifierProperties=auth.verifier.BasicAuthHeaderAuthVerifier.urls.includes=*
com.liferay.portal.remote.rest.extender.configuration.RestExtenderConfiguration-rest.properties
Code:
contextPaths=/my-rest-service
jaxRsServiceFilterStrings=(component.name=com.liferaystack.application.MyRestServiceApplication)
This is the MyRestWebserviceApplication.java:
package com.liferaystack.application;
import java.util.Collections;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
/**
* #author pinoteam
*/
#ApplicationPath("/my-rest-service")
#Component(immediate = true, service = Application.class)
public class MyRestWebserviceApplication extends Application {
public Set<Object> getSingletons() {
return Collections.<Object>singleton(this);
}
#GET
#Produces("text/plain")
public String working() {
return "It works!";
}
#GET
#Path("/morning")
#Produces("text/plain")
public String hello() {
return "Good morning!";
}
#GET
#Path("/mattina")
#Produces("text/plain")
public String helloGa() {
return "Good morning!";
}
#GET
#Path("/morning/{name}")
#Produces("text/plain")
public String morning(
#PathParam("name") String name,
#QueryParam("drink") String drink) {
String greeting = "Good Morning " + name;
if (drink != null) {
greeting += ". Would you like some " + drink + "?";
}
return greeting;
}
}
I run build and deploy.
The app is active, but nothing work.
In control panel i have not any Rest Extender Configuration and i have not api at any url.
what am i missing? any idea?
The tutorial you link is for Liferay 7.0 - the package/path names of the configuration files might have changed, and I've seen a context path being declared in bnd.bnd, rather than those property files - things might have changed since then.
An alternative starting point might be the blade sample, which is written for 7.2, and provides a Whiteboard-properties in the Java class:
#Component(
property = {
JaxrsWhiteboardConstants.JAX_RS_APPLICATION_BASE + "=/users",
JaxrsWhiteboardConstants.JAX_RS_NAME + "=Users"
},
service = Application.class
)
public class UsersRestService extends Application {
#GET
#Path("/list")
#Produces("text/plain")
public String getUsers() {
...
}
...
That plugin's configuration file is rather trivial (looks optional on first glance, but don't take my word for it)

Expected Condition interface error in WebDriver sampler in JMeter

I want to use Expected Condition interface and implement apply method as follows in WebDriver sampler. This script for loading multiple charts on single page but it give me error
javax.script.ScriptException: In file: inline evaluation of:
import java.io.File; import org.apache.commons.io.FileUtils;
import openqa.selen . . . '' Encountered "( new ExpectedCondition <"
at line 22, column 19.in inline evaluation of: ``
import java.io.File; import org.apache.commons.io.FileUtils;
import openqa.selen . . . '' at line number 22.”
Environment:
JMeter : version 5
Java : java version "1.8.0_181"
Can anyone please help? This is my code:
WDS.sampleResult.sampleStart();
List loading =WDS.browser.findElements(By.xpath("//img[#class='loading']"));
WDS.log.info("Total "+loading.size());
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver WDS.browser) {
Iterator eleIterator =WDS.browser.findElements(By.xpath("//img[#class='loading']")).iterator();
while (eleIterator.hasNext()) {
boolean displayed = false;
try {
displayed = eleIterator.next().isDisplayed();
// System.out.println("TEST = "+displayed);
}
catch (NoSuchElementException e)
{
displayed = false;
}
catch (StaleElementReferenceException e)
{
displayed = false;
}
if (displayed) {
// return false even if one of them is displayed.
return false;
}
}
//this means all are not displayed/invisible
return true;
}
});
WDS.sampleResult.sampleEnd();

Geb cannot see my class as content page

When i try to run my test i get this Exception:
groovy.lang.MissingPropertyException: Unable to resolve code as content for pages FactIndexPage, or as a property on its Navigator context. Is code a class you forgot to import?
Here my test class
import geb.spock.GebReportingSpec
import pages.*
import spock.lang.Stepwise
#Stepwise
class FactControllerSpec extends GebReportingSpec {
def "test de la presence du code dans la page d'acceuil"() {
given: "test que le champ code de facture est bien present"
when:
to IndexFactPage
then: $("form", name: code).find("input", type: "button")
}
}
And below the class who describe my page content
import geb.Page
class IndexFactPage extends Page {
static url = "/fact/mmapay"
static at = {
$("h2").text() == "Pour régler votre facture, veuillez saisir:" }
static content = {
codeField { $("input[name = code]") }
nomField { $("input[name = nom]") }
prenomField { $("input[name = prenom]") }
montantField { $("input[name = montant]") }
chercher1 { $("input", type: "button") }
abandonner1 { $("input", type: "button") }
}
}
Please help me to resolve my class IndexFactPage as a content page..
Thank you in advance..
The part causing you problems is this $("form", name: code).
$("form", name: "code") will find you a form named code, this may not be what you're after though based on your page and spec snippets.
Without seeing the page source there's no way to provide a proper solution but here's some observations from your IndexFactPage
static content = {
codeField { $("input[name = code]") }
nomField { $("input[name = nom]") }
prenomField { $("input[name = prenom]") }
montantField { $("input[name = montant]") }
chercher1 { $("input", type: "button") }
abandonner1 { $("input", type: "button") }
}
These fields codeField, nomField, prenomField, and montantField all look like they map to individual fields but chercher1 and abandonner1 will select the same button.
Based on what your spec states for it's purpose to be then possibly your spec should look like this -
import geb.spock.GebReportingSpec
import pages.*
import spock.lang.Stepwise
#Stepwise
class FactControllerSpec extends GebReportingSpec {
def "test the presence of the code field on the home page"() {
when: "we are on the home page"
to IndexFactPage
then: "the code field is present"
codeField.present
}
}

Getting error while running Geb test using spock and maven

I'm getting the following error while running groovy scripts with maven:
Signup Test Happy Path(SignUpPageSpec): The required page content
'usernamefield - SimplePageContent (owner: JiraSignupPage, args: [],
value: null') is not present.
Can anybody help me to resolve this error. Following are scripts:
JiraSignUpPage.groovy
package test.groovy.script
import geb.Page;
//import main.groovy.script.*;
class JiraSignupPage extends Page
{
static url = "/vcty-jira"
static at = { title == "System Dashboard - Velocity Jira" }
static content = {
usernamefield { $("input#login-form-username") }
passwordfield { $('input#login-form-password') }
submitButton(to: JiraSignUpResultPage) { $('button#login-form-submit') }
}
}
JiraSignUpResultPage.groovy
package test.groovy.script
import geb.Page;
public class JiraSignUpResultPage extends Page
{
static url = "/jira/secure/Dashboard.jspa"
static at = { title == "Amit - Jira Tracker" }
}
SignUpPageSpec.groovy
import spock.lang.Stepwise;
import geb.spock.GebReportingSpec;
import geb.Page;
//import main.groovy.script.*;
import test.groovy.script.*;
#Stepwise
public class SignUpPageSpec extends GebReportingSpec {
def "Signup Test Happy Path"() {
given: "I'm at the sign up form"
to JiraSignupPage
when: "I signup as a valid user"
usernamefield = "xyz"
passwordfield = "xyz"
submitButton.click()
then: "I'm at the result page"
at JiraSignUpResultPage
}
}
GebConfig.groovy
import org.openqa.selenium.firefox.FirefoxDriver
import geb.waiting.*;
driver = { new FirefoxDriver() }
baseUrl = "http://172.17.48.65:8080/"
reportsDir = new File("target/geb-reports")
reportOnTestFailureOnly = true
waiting {
timeout = 20
retryInterval = 0.5
}
I'm running mvn.test to run these test. It causes browser to open but ends up with error.
The error tells you that your usernamefield content definition returned an empty navigator - an input with id login-form-username has not been found on the page you navigated to.
Probably your page is not fully loaded.
Try adding usernamefield.displayed to 'at' block
or add 'wait' to page element
usernamefield(wait: true) { $("input#login-form-username") }

SQLite >1 Column Table errorcode = 1

I have a problem creating a database with 2 columns.
In the first one there should be a name and in the second one a number.
Creating the name database is no problem, but when I try to add the second column I get the error message "I/Database(13531): sqlite returned: error code = 1, msg = no such column: zahl"
my code is here
first the Manager
package my.studienarbeit.bestimmung.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatenbankManager extends SQLiteOpenHelper {
private static final String DB_NAME = "carbohydrates.db";
private static final int DB_VERSION = 1;
private static final String WEIGHT_CREATE =
"CREATE TABLE weight ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL, " +
// + "zahl INTEGER" +
")";
public DatenbankManager(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(WEIGHT_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatenbankManager.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
and my database:
package my.studienarbeit.bestimmung.database;
import my.studienarbeit.bestimmung.R;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class Datenbanken extends ListActivity {
private SQLiteDatabase mDatenbank;
private DatenbankManager mHelper;
/*/ private static final String WEIGHT_SELECT_RAW =
"SELECT _id, name, zahl FROM weight" ; //*/
//*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daten_datenbanken);
mHelper = new DatenbankManager(this);
mHelper.getWritableDatabase();
}
#Override
protected void onPause() {
super.onPause();
mDatenbank.close();
Toast.makeText(this,
getResources().getString(R.string.tx_daten_datenbanken_db_geschlossen),
Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
mDatenbank = mHelper.getWritableDatabase();
Toast.makeText(
this,
getResources().getString(
R.string.tx_daten_datenbanken_db_geoeffnet
),
Toast.LENGTH_SHORT)
.show();
ladeDaten();
}
private void ladeDaten() {
// Cursor weightCursor = mDatenbank.rawQuery(WEIGHT_SELECT_RAW, null);
Cursor weightCursor = mDatenbank.query("weight",
new String [] {
"_id",
"name",
// "zahl",
},
null, null, null, null, null
);
startManagingCursor(weightCursor);
SimpleCursorAdapter weightAdapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
weightCursor,
new String [] {
"name",
// "zahl"
},
new int[] {
android.R.id.text1
}
);
setListAdapter(weightAdapter);
}
public void onNavButtonClick(View view) {
EditText et_c =
(EditText) findViewById(R.id.editText_name_c);
// EditText et_w =
// (EditText) findViewById(R.id.editText_weight_c);
ContentValues werte = new ContentValues();
werte.put("name", et_c.getText().toString());
// werte.put("zahl", et_w.getText().toString());
mDatenbank.insert("weight", null, werte);
ladeDaten();
et_c.setText("");
// et_w.setText("");
The 2nd column is not active right now for debug functions.
If you first created your table without the "zahl" column, then added the "zahl" column and rerun your application, the OpenHelper did not do the "onCreate" again with the new values. My suggestion is that you first drop the table (on emulator, go to Settings > Applications > Yourapp > Click "Clear Data" button), then uncomment the "zahl" lines (especially in DatenbankManager.java), then recompile + run. Running your app again, with an empty database, will recreate the table with column "zahl".