Keeping same session, 1 single browser - selenium-webdriver

The title of the question may be irrelevant to what I am trying to find out. My goal is to write a test that will
A) login to Hotmail
B) Delete the junk mail in my junk folder.
Design wise I have created 2 separate test classes. TestSignInPage1.class is only testing the user login part which is working and passed.
TestJunkFolderDelete.class will go to junk mail folder and do the deletion. I understand I simply can’t use the junk delete test on its own, a user 1st needs to login to the account so I called the TestSignInPage1 class in the junk folder.
#Test
public void testJunk(){
//The part below will get my login credential from TestSignPage class
TestSignInPage1 t= new TestSignInPage1();
t.testPage1();
//The following part will handle junk folder clean operation
WebDriver driver=br.openBrowser("firefox", "https://outlook.live.com/owa/?realm=hotmail.com&path=/mail/junkemail");
JunkMail jm= PageFactory.initElements(driver, JunkMail.class);
jm.doJunkClean();
Problem: Once the login part has been executed, the junk folder delete test opens up another new browser and again asks for login information.
Question: In professional world how would you tackle this (i.e.: you will have 1 test only, is there a way to keep the same session 1 browser) etc?

Related

Exception in Site.createExternalUser in Apex RESTclass: Site.ExternalUserCreateException: [That operation is only allowed from within an active site.]

I have a Non-Salesforce Auth System which holds usernames and passwords for a few thousand users. I am willing to migrate these users to Salesforce and give access to these users to my Experience Cloud site. I am developing an apex REST Resource which will take username and password as arguments and create a user with that username and password with a community profile. I am planning to call this API from my Non-Salesforce system and migrate all these users. I am using Site.createExternalUser method in this API. I am getting the exception
Site.ExternalUserCreateException: [That operation is only allowed from within an active site.]
The reason I am using Site.createExternalUser is because I don't want to send the welcome email/reset password email to my users since they already have signed up successfully long ago.
I am open to any alternatives for achiving this.
Below is my code:
#RestResource(urlMapping='/createUser/*')
global with sharing class createUserRestResource {
#HttpPost
global static String doPost(){
Contact con=new Contact();
con.Firstname="First";
con.LastName= "Last";
con.Email="first.last#example.com";
con.AccountId='/Add an account Id here./';
insert con;
usr.Username= "usernameFromRequest#example.com";
usr.Alias= "alias123";
usr.Email= "first.last#example.com";
usr.FirstName= "First";
usr.IsActive= true;
usr.LastName= "Last";
usr.ProfileId='/Community User Profile Id/';
usr.EmailEncodingKey= 'ISO-8859-1';
usr.TimeZoneSidKey= 'America/Los_Angeles';
usr.LocaleSidKey= 'en_US';
usr.LanguageLocaleKey= 'en_US';
usr.ContactId = con.Id;
String userId = Site.createExternalUser(usr, con.AccountId, 'Password#1234', false);
return userId;
}
}
You can suppress sending emails out in whole org (Setup -> Deliverability) or in the Community config there will be way to not send welcome emails (your community -> Workspaces -> Administration -> Emails).
Without running on actual Site I don't think you can pull it off in one go. In theory it's simple, insert contact, then insert user. In practice depends which fields you set on the user. If it's Partner community you might be setting UserRoleId too and that's forbidden. See MIXED DML error. In Customer community you might be safe... until you decide to assign them some permission sets too.
You might need 2 separate endpoints, 1 to create contact, 1 to make user out of it. Or save the contact and then offload user creation to #future/Queueable/something else like that.

How do I run specific scenario in cucumber

How to run specific scenario in cucumber out of multiple scenario?
Feature file
Feature: Test Test Smoke scenario
Scenario: Test login with valid credentials
Given open firefox and start application
jhbhhjhj
When I click on Login
And enter valid "kumar.rakesh#yopmail.com" and valid "admin#123"
Then Click on login and User should be able to login successfully
Scenario: Test shop for cart
Given Click on shop for carts
And select plates
When Click on Add to cart
Then product should be added in the cart successfully
And verify the product
Scenario: Test login with valid credentials1
Given open firefox and start application
When I click on Login
And enter valid "kumar.rakesh#yopmail.com" and valid "admin#123"
Then Click on login and User should be able to login successfully
Scenario: Test shop for cart1
Given Click on shop for carts
And select plates
When Click on Add to cart
Then product should be added in the cart successfully
And verify the product
Test Runner
package runner;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#Cucumber.Options(features="features",glue={"steps"},format = {"pretty", "html:target/Destination"})
public class TestRunnr {
}
Use tags future in the cucumber like below.
Feature: Test Milacron Smoke scenario
#Test1
Scenario: Test login with valid credentials
Given open firefox and start application
When I click on Login
And enter valid "kumar.rakesh#thoughtfocus.com" and valid "Thought#123"
Then Click on login and User should be able to login successfully
#Test2
Scenario: Test shop for cart
Given Click on shop for carts
And select plates
When Click on Add to cart
Then product should be added in the cart successfully
And verify the product
#Test3
Scenario: Test login with valid credentials1
Given open firefox and start application
When I click on Login
And enter valid "kumar.rakesh#thoughtfocus.com" and valid "Thought#123"
Then Click on login and User should be able to login successfully
#Test4
Scenario: Test shop for cart1
Given Click on shop for carts
And select plates
When Click on Add to cart
Then product should be added in the cart successfully
And verify the product
If you want to run only Test1 scenario update runner file like below.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="features",glue={"steps"},format = {"pretty", "html:target/Destination"},tags={"#Test1"})
public class TestRunner {
}
If you want to execute multiple scenarios keep comma sepearated tags as mentioned below.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="features",glue={"steps"},format = {"pretty", "html:target/Destination"},tags={"#Test1,#Test2"})
public class TestRunner {
}
Like the other answers suggest, use tags. If you use maven, you don't have to change the runner file - just add this to your maven call
-Dcucumber.options="--tags #Test1"
The thing I like about this method is that I don't risk committing the tags in the runner file.
Also, here is an example on running multiple tags in maven.
You can either use selective feature file or selective scenarios in the feature using tags. Please try with this solution.
Lets consider the you have n number of feature files and you need to run only selective feature from that. Then name each feature file with #tag name.
eg.: Under this folder, if you are having n number of features - "src/main/resources/publish"
1st Feature file name:
Login.feature
//Inside the file start with feature tag name
#Login
Feature: To Login to Email
//Then feature name followed with scenario tag name
#User1
#Scenario1:
Scenario Outline: Navigate and logon to gmail application
Given User launches gmail application
When User updates emailID <emailID>
And User updates pwd <pwd>
Then User clicks on Login Button
Examples:
| emailID | pwd |
| a#gmail.com| 123 |
#User2
#Scenario2:
Scenario Outline: Navigate and logon to facebook application
//Write the code for scenario 2 as similar to above
2nd Feature File name:
CreateEmail.feature
#Createmail
Feature: Create email
Scenario: Blah blah blah...
//Write all Given when And Then
3rd Feature File name:
SendEmail.feature
#Sendemail
Feature: Send email
Scenario: Blah blah blah...
//Write all Given when And Then
So From the above Test files. Lets consider you want to test 1st and 3rd feature alone, Then you can use code as below:
eg.:
//This is to run specific feature files, which is 1 and 3. Likewise you can use the tags for scenario as well if you have n number scenario in same feature file.
#CucumberOptions(features= "src/main/resources/publish", tags="#Login, #Sendemail", format = {"pretty"} )
// This is to run specific scenario in the feature file. If you have multiple scenario, then you can write your specify your scenario tags followed by comma.
#CucumberOptions(features= "src/main/resources/publish/Login.feature", tags="#User2", format = {"pretty"} )
You need to use tags to filter out the scenario. Put the tag on the feature file and add this to the cucumberoptions of the runner.
#RunScenarioExample
Scenario: Test login with valid credential
#Cucumber.Options(features="features",glue={"steps"},format = {"pretty", "html:target/Destination"}, tags={"#RunScenarioExample"})

RegOpenCurrentUser(KEY_WRITE) on newly created user

After i successfully create a new user, add user to built-in admins group, i would like to edit the newly created user's registry (this program is an elevated-as-admin program). I called NetUserAdd(), NetLocalGroupAddMembers(), LogonUser(), and then, finally LoadUserProfile() so the user's directory exists.
Excuse the sloppy code, but this is what I am doing after that:
DuplicateTokenEx(hToken,TOKEN_ALL_ACCESS,&sa,SecurityImpersonation,TokenPrimary,&hNewToken);
ImpersonateLoggedOnUser(hNewToken);
HKEY hKey;
LSTATUS stat = RegOpenCurrentUser(KEY_READ|KEY_WRITE, &hKey);
// stat is 5 (ACCESS_DENIED) when KEY_WRITE is added, it
// returns 0 (ERROR_SUCCESS) when it's just KEY_READ
RegCloseKey(hKey);
RevertToSelf();
CloseHandle(hNewToken);
The error is on the RegOpenCurrentUser() line. It errors out when I ask to write to that user's HKU registry. It works perfectly fine if I use just KEY_READ
Is this even possible what I am trying to do? Is the user's registry hive even created yet? Or does the user have to physically sign on to create it?
Ultimately what i would want to do is create GPO's for the new user.
If you already have the user profile loaded with LoadUserProfile(), you don't really need to use RegOpenCurrentUser() at all. You can instead use the hProfile field of the PROFILEINFO that LoadUserProfile() returns:
hProfile
Type: HANDLE
A handle to the HKEY_CURRENT_USER registry subtree.
...
When the LoadUserProfile call returns successfully, the hProfile member receives a registry key handle opened to the root of the user's subtree, opened with full access (KEY_ALL_ACCESS).

How to re-run the test with different data using TestNG

Currently we are re-running the test when a Test Fails using TestNG iRetryAnalyzer.
Problem that we are facing is:
We have a Test to 'Add a user'. For the first time after adding a user, in the process of checking the success message exception occurred (Timeout/NosuchElement) etc But the user is added in the database.
Now again when we re-run the test with same data, the Test Fails as user is already Added.
How can i overcome this??
As here the Data, the user email id unique field. Atleast I should be able to change the Email Id when im re-running it for the second time.
Please help me.
If you just need to create a unique, fake email address that you don't need to actually use, you can always append a date/time stamp to some base email you get from your DataProvider:
#Test(dataProvider = "dp")
public void emailTest(String userName, String emailShortname) {
//Get the current time
long time = System.currentTimeMillis();
//append it to the email from your DataProvider
StringBuilder emailBuilder= new StringBuilder();
emailBuilder.append(emailShortname).append("_").append(time).append("#gmail.com");
//do user creation code below using emailBuilder result...
I would say that if you are going to do these sorts of tests using Selenium, you're going to fill up your database with junk test IDs, so I'd suggest your team create a mechanism to clean these out either as part of the test run or after it.
Ideally, if there is a way to delete a user. You should use that in the #aftertest method and remove that user.
This way the next time you will be again able to use the same email id irrespective of the test is successful or not.
If not and if the email id is never verified ( I mean like some confirmation email which you use to confirm the user) you can create fake email id on the fly like xyz123#gmail.com. If the email id is verified then i guess you are in trouble.

Problems with accessing private files uploaded via file field in a webform with Varnish running on the server

I have a webform with a file field configured to private files. When I'm logged in as a superuser (uid=1) and trying to download the file, I get access denied.
I was trying to debug this, and this is what I noticed.
All private files served by the file_download() function that is called in the system.module. This function validates if the file exists and request the file headers using file_download_headers() function that triggers hook_file_download().
In the webform_file_download() function the module determines whether the file was a webform upload and grant or deny file access based on access to the submission. It validates access permission by calling webform_submission_access(). When I run dpm($account) in this function, I get an anonymous user when I'm trying to access the private file. When I browse recent log messages I have the entry below:
access denied 06/02/2015 - 11:23 system/files/webform/cv-uploads/cv.pdf Anonymous
When I change the URL to file that doesn't exist, I get this:
page not found 06/02/2015 - 11:26 system/files/webform/cv-uploads/cv.FDP admin
As you can see for some reasons when the module is trying to get access to the file that does exist, I get access denied and the user is anonymous. When the file doesn't exist, I get page not found and the user is a logged in user.
Any ideas why this happens?
UPDATE
I've added the following code to my index.php but I still get anonymous user when I'm trying to access the file.
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+ global $user;
+ watchdog('user', '<pre>'. print_r($user, TRUE) . '</pre>');
menu_execute_active_handler();
I've copied over the whole site including database and files to my local machine, and I'm not experiencing this issue. There's should be some settings that does this on the live site.
UPDATE 2
I've noticed that on the live site we have a list of disabled functions that I'm not aware of. Maybe it will help somehow.
disable_functions = apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, system, xmlrpc_entity_decode, parse_ini_file,show_source,shell_exec
The problem was caused by the Varnish on the server. Below is the settings for Varnish.
# Always cache the following file types for all users. This list of extensions
# appears twice, once here and again in vcl_fetch so make sure you edit both
# and keep them equal.
if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
unset req.http.Cookie;
}

Resources