How can I call the Weblement to the other class - oop

public class LoginPagePages {
#FindBy(how=How.XPATH,using="//div[#class='validation-summary-errors text-danger']/ul/li")
WebElement incorrect_username;
}
How can I pass the WebElement incorrect_username; to the class LoginPageTestCase, so that I can get its text into String errorsign and use it for my Assertion
public class LoginPageTestCase {
#Test(priority=1)
public void IncorrectPassword() {
String errorsign = I NEED TO CALL HERE THE "WebElement incorrect_username".getText();
Assert.assertEquals(errorsign, "Username is incorrect");
Add_Log.info("Login Failed");
}

You can create an instance of LoginPagePages in your test and use getter to get it
public class LoginPagePages {
#FindBy(how=How.XPATH,using="//div[#class='validation-summary-errors text-danger']/ul/li")
private WebElement incorrect_username;
public WebElement getIncorrectUsername {
return incorrect_username;
}
}
public class LoginPageTestCase {
#Test(priority=1)
public void IncorrectPassword() {
LoginPagePages loginPage = new LoginPagePages();
String errorsign = loginPage.getIncorrectUsername().getText();
Assert.assertEquals(errorsign, "Username is incorrect");
Add_Log.info("Login Failed");
}
}

Related

How to use the TempData attribute to pass data to a Razor view

I have:
namespace Test
{
public interface ITest
{
public string Test1(string s);
}
public class Test : ITest
{
[Microsoft.AspNetCore.Mvc.TempData]
public string Message
{
get; set;
}
public string Test1(string s)
{
Message = "Test " + s;
return "Test has run";
}
}
}
And in Startup.cs:
services.AddScoped<Test.ITest, Test.Test>();
Then in a Razor view:
#inject Test.ITest Test
<p>Result is #Test.Test1("Hello World!")</p>
<p>TempData["Message"] is #TempData["Message"]</p>
The output is:
Result is Test has run
TempData["Message"] is
Where have I done incorrectly? How can I pass a TempData["Message"] from some code (that is not in a Controller) to a Razor page?
How can I pass a TempData["Message"] from some code (that is not in a Controller) to a Razor page?
If you'd like to retain and pass value via TempData inside your custom service, you can try the following code snippet.
public interface ITest
{
public string Test1(string s);
public string Test2();
}
public class Test : ITest
{
private readonly IHttpContextAccessor _httpContextAccessor;
public Test(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string Message
{
get {
var tempDataDictionaryFactory = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<ITempDataDictionaryFactory>();
var tempDataDictionary = tempDataDictionaryFactory.GetTempData(_httpContextAccessor.HttpContext);
if (tempDataDictionary.TryGetValue("Message", out object value))
{
return (string)value;
};
return "";
}
set
{
var tempDataDictionaryFactory = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<ITempDataDictionaryFactory>();
var tempDataDictionary = tempDataDictionaryFactory.GetTempData(_httpContextAccessor.HttpContext);
tempDataDictionary.Remove("Message");
tempDataDictionary.TryAdd("Message", value);
}
}
public string Test1(string s)
{
Message = "Test " + s;
return "Test has run";
}
public string Test2()
{
return Message;
}
}
In Razor Page
<p>Result is #Test.Test1("Hello World!")</p>
<p>TempData["Message"] is #TempData.Peek("Message")</p>
<p>#Test.Test2()</p>
Test Result

How to use Extent Report logs in Page Objects?

I am getting Null Pointer Exception when using the test.log() method into Page Objects.
My Extent Report test is defined in the "#BeforeMethod" at the TestBase class. Hence, I need to access the test.log(); into the Page Object e.g. LoginPage.java. It's works fine at the test case level i.e. LoginPageTest.java
#BeforeMethod
public void beforeMethod(Method method) {
String testMethodName = method.getName();
test = extent.createTest(testMethodName);
String testReslt = method.getName();
test.info(MarkupHelper.createLabel(testReslt, ExtentColor.BLUE));
log.info("**************" + method.getName() + "Started***************");
}
public static void logExtentReport(String str) {
test.log(Status.INFO, str);
}
Below is the LoginPage.java (which is a page-object class)
public class LoginPage {
private WebDriver driver;
private final Logger log = LoggerHelper.getLogger(LoginPage.class);
VerificationHelper verificationHelper;
WaitHelper waitHelper;
#FindBy(css = "#email")
WebElement loginEmail;
#FindBy(css = "#password")
WebElement loginPassword;
#FindBy(css = "#loginbutton")
WebElement loginBtn;
#FindBy(css = "#loginerrormsg")
WebElement authenticationFailureMessage;
#FindBy(css = "#soflow-color")
WebElement userProfileDrpDwn;
#FindBy(xpath = "//option[#value='string:logout']")
WebElement logout;
#FindBy(tagName = "a")
List<WebElement> allLinks;
String urls[] = null;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
waitHelper = new WaitHelper(driver);
waitHelper.waitForElement(loginBtn,
ObjectReader.reader.getExplicitWait());
}
public void enterEmailAddress(String emailAddress) {
log.info("entering email address...." + emailAddress);
this.loginEmail.clear();
this.loginEmail.sendKeys(emailAddress);
}
public void enterPassword(String password) {
log.info("entering password...." + password);
this.loginPassword.clear();
this.loginPassword.sendKeys(password);
}
public ProspectorPage clickOnSubmitButton(String isValidCredentials) {
log.info("clicking on submit button...");
loginBtn.click();
if (isValidCredentials.equalsIgnoreCase("yes")) {
return new ProspectorPage(driver);
}
return null;
}
public boolean verifySuccessLoginMsg() {
return new VerificationHelper(driver).isDisplayed(userProfileDrpDwn);
}
public boolean verifyAuthenticationFailureMsg() {
return new
VerificationHelper(driver).isDisplayed(authenticationFailureMessage);
}
public void loginToApplication(String emailAddress, String password,
String isValidCredentials) {
enterEmailAddress(emailAddress);
loginBtn.click();
enterPassword(password);
new TestBase().captureScreen("Login Page_1", driver);
clickOnSubmitButton(isValidCredentials);
}
public void logout() {
userProfileDrpDwn.click();
new TestBase().captureScreen("Logout", driver);
waitHelper.waitForElement(logout,
ObjectReader.reader.getExplicitWait());
logout.click();
log.info("clicked on logout link");
TestBase.logExtentReport("clicked on logout link");
waitHelper.waitForElement(loginBtn,
ObjectReader.reader.getExplicitWait());
}
}
}
As you can see in the LoginPage class, I have used TestBase.logExtentReport() method, which is showing NullPointerException, and I cannot initialize the TestBase reference in the PageObject class. Hence, How can I use the logExtentReport method there?
Helper Class is also getting NPE, even after changing the scope of logger from final to static. Below is the code:
import com.uiFramework.engie.prospector.helper.logger.LoggerHelper;
import com.uiFramework.engie.prospector.testbase.TestBase;
public class VerificationHelper {
private WebDriver driver;
private static Logger log =
LoggerHelper.getLogger(VerificationHelper.class);
public VerificationHelper(WebDriver driver){
this.driver = driver;
}
public boolean isDisplayed(WebElement element){
try{
element.isDisplayed();
log.info("element is Displayed.."+element.getText());
TestBase.logExtentReport("element is
Displayed.."+element.getText());
return true;
}
catch(Exception e){
log.error("element is not Displayed..", e.getCause());
TestBase.logExtentReport("element is not
Displayed.."+e.getMessage());
return false;
}
}
public boolean isNotDisplayed(WebElement element){
try{
element.isDisplayed();
log.info("element is present.."+element.getText());
TestBase.logExtentReport("element is
present.."+element.getText());
return false;
}
catch(Exception e){
log.error("element is not present..");
return true;
}
}
public String readValueFromElement(WebElement element){
if(null == element){
log.info("WebElement is null..");
return null;
}
boolean status = isDisplayed(element);
if(status){
log.info("element text is .."+element.getText());
return element.getText();
}
else{
return null;
}
}
public String getText(WebElement element){
if(null == element){
log.info("WebElement is null..");
return null;
}
boolean status = isDisplayed(element);
if(status){
log.info("element text is .."+element.getText());
return element.getText();
}
else{
return null;
}
}
}
Just change
private final Logger log = LoggerHelper.getLogger(LoginPage.class);
to
private static final Logger log = LoggerHelper.getLogger(LoginPage.class);

Can I execute multiple test cases in same browser using Selenium

I have multiple usernames and passwords. I need to validate all that test data in one Chrome window. And I need to check whether it's working fine or not. Is it possible? Thanks in advance.
public class Wrappers extends GenericWrappers {
public String browserName;
public String dataSheetName;
protected static WebDriver Browser_Session;
#BeforeSuite
public void beforeSuite() {
startResult();
}
#BeforeTest
public void beforeTest() {
loadObjects();
}
#BeforeMethod
public void beforeMethod() {
test = startTestCase(testCaseName, testDescription);
test.assignCategory(category);
invokeApp("Chrome");
}
#AfterSuite
public void afterSuite() {
endResult();
}
#AfterTest
public void afterTest() {
unloadObjects();
}
#AfterMethod
public void afterMethod() {
endTestcase();
}
#DataProvider(name = "fetchData")
public Object[][] getData() {
return DataInputProvider.getSheet(dataSheetName);
}
}
public class Login extends PEFWrappers {
#Parameters("browser")
#BeforeClass()
public void setValues(String browser) {
browserName = browser;
testCaseName = "TC001 - Login";
testDescription = "Login and Submit a form";
category = "smoke";
dataSheetName = "TC_001";
}
#Test(dataProvider = "fetchData")
public void loginPEF(String LoginId, String Password) throws InterruptedException
{
new LoginPage(driver, test)
.enterLoginID(LoginId)
.enterPassword(Password)
.clickLogin();
}
}
You can specify the set of credentials in the DataProvider method
For eg
#DataProvider(name="fetchData")
public Object[][] getData()
{
Object [][] myData = {{"user1","pwd1"},
{"user2","pwd2"}};
return myData;
}
Here I have given 2 sets of username/Password So the test will be executed 2 times with 2 different sets of credentials.
Here you are taking values from external file. So just enter username and password in rows. Test will repeat as many times as the number of rows available in the datasheet

Opening different URLs in one Serenity task class?

In Serenity BDD I have a Task which opens the login page of an application. I'd like to use this class to not only open the login page but other pages as well.
public class StartWith implements Task {
LoginPage loginPage;
#Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Open.browserOn(loginPage)
);
}
public static Task theLoginPage() {
return instrumented(StartWith.class);
}
// Is this possible???
public static Task theContactPage() {
return instrumented(StartWith.class);
}
}
Is it possible to add another static method e.g. theContactPage so that my actor could call one of these:
StartWith.theLoginPage()
StartWith.theContactPage()
You can use url as string param.
public class StartWith implements Task {
private final String url;
public StartWith(String url) {
this.url = url;
}
#Override
#Step("{0} start portal at \\{#url\\}")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Open.url(url)
);
}
public static Task theLoginPage() {
String url = "http://example.com/login";
return instrumented(StartWith.class, url);
}
public static Task theContactPage() {
String url = "http://example.com/contact";
return instrumented(StartWith.class);
}
}

how to make custom error feedback messages in SignInPanel in Wicket

I am implementing a LoginPage with Wicket, and I am not getting it, how to write the custom Feedback messages, for ex, "Password is wrong", "Username is wrong" or "Accound is locked out" (the last example should be a bit more difficult because it is related to Ldap/Ldap error messages I think.. But I think there is an easier way for the second two, with the properties file of my LoginPage or something like that.. I tried to change the default Wicket "login failed" message, and this through the properties' file of my page, I just added "signFailed=Sign in failed TEST", and it got changed.. but didn't got it how to tell the user why! Pass or username is wrong!
here the implementation:
public class LoginPage extends SampleManagementPage {
private static final long serialVersionUID = -8585718500226951823L;
private SignInPanel signIn;
public LoginPage() {
signIn = new SignInPanel("signInPanel");
add(signIn);
}
}
and my SampleManagementPage extends WebPage!
here the properties' file of LoginPage:
page.title=Login for Sample Management
signInFailed=Sign in failed TEST
The reason why you are able to change only the signFailed error message, is that wicket SignInPanel throws only this particular error in case it's sign-in form fails to authenticate. To see that, you can open the source code of SignInPanel.java.
One way to overcome the problem and produce your own error messages, is write your own sign-in panel. I m not saying it is the only way but it worked for me :)
public class LoginPanel extends Panel {
private static final long serialVersionUID = -1662154893824849377L;
private static final String SIGN_IN_FORM = "signInForm";
private boolean includeRememberMe = true;
private boolean rememberMe = true;
private String password;
private String username;
public LoginPanel(final String id, final boolean includeRememberMe) {
super(id);
this.includeRememberMe = includeRememberMe;
add(new FeedbackPanel("feedback"));
add(new SignInForm(SIGN_IN_FORM));
}
#Override
protected void onConfigure() {
if (isSignedIn() == false) {
IAuthenticationStrategy authenticationStrategy = getApplication().getSecuritySettings().getAuthenticationStrategy();
String[] data = authenticationStrategy.load();
if ((data != null) && (data.length > 1)) {
if (signIn(data[0], data[1])) {
username = data[0];
password = data[1];
onSignInRemembered();
} else {
authenticationStrategy.remove();
}
}
}
super.onConfigure();
}
private boolean signIn(String username, String password) {
return AuthenticatedWebSession.get().signIn(username, password);
}
private boolean userExists(String username) {
return ((MyWebSession) AuthenticatedWebSession.get()).userExists(username);
}
private boolean isSignedIn() {
return AuthenticatedWebSession.get().isSignedIn();
}
protected void onSignInFailed() {
error(getLocalizer().getString("signInFailed", this, "Wrong password"));
}
private void onUserExistsFailed() {
error(getLocalizer().getString("userExistsFailed", this, "User does not exist"));
}
protected void onSignInSucceeded() {
continueToOriginalDestination();
setResponsePage(getApplication().getHomePage());
}
protected void onSignInRemembered() {
continueToOriginalDestination();
throw new RestartResponseException(getApplication().getHomePage());
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public LoginPanel(final String id) {
this(id, true);
}
public final class SignInForm extends StatelessForm<LoginPanel> {
private static final long serialVersionUID = 1L;
public SignInForm(final String id) {
super(id);
setModel(new CompoundPropertyModel<LoginPanel>(LoginPanel.this));
add(new TextField<String>("username"));
add(new PasswordTextField("password"));
WebMarkupContainer rememberMeRow = new WebMarkupContainer("rememberMeRow");
add(rememberMeRow);
rememberMeRow.add(new CheckBox("rememberMe"));
rememberMeRow.setVisible(includeRememberMe);
}
#Override
public final void onSubmit() {
IAuthenticationStrategy strategy = getApplication().getSecuritySettings().getAuthenticationStrategy();
if (!userExists(username)) {
onUserExistsFailed();
strategy.remove();
return;
}
if (signIn(getUsername(), getPassword())) {
if (rememberMe == true) {
strategy.save(username, password);
} else {
strategy.remove();
}
onSignInSucceeded();
} else {
onSignInFailed();
strategy.remove();
}
}
}
}
public class MyWebSession extends AuthenticatedWebSession {
private static final long serialVersionUID = -401924496527311251L;
public MyWebSession(Request request) {
super(request);
}
public boolean userExists(String username) {
// business login
}
#Override
public boolean authenticate(String username, String password) {
// business login
}
#Override
public Roles getRoles() {
Roles roles = new Roles();
roles.add(Roles.USER);
return roles;
}
}