How to check page url with Selenide - selenide

How to check page url in selenide ?
For example I should check if url() is www.google.pl
Thanks

Selenide support checking urls from version 5.23.0. Enjoy
import static com.codeborne.selenide.WebDriverConditions.*;
webdriver().shouldHave(url("https://auth.google.com"));
webdriver().shouldHave(url("https://mastercard.ee"), Duration.ofSeconds(42));
webdriver().shouldNotHave(url("http://yandex.ru");
webdriver().shouldNotHave(urlStartingWith("ftp://"));
webdriver().shouldHave(currentFrameUrl(baseUrl + "/login.html"));
webdriver().shouldHave(currentFrameUrlStartingWith(baseUrl + "/logout.html"));```

You need to get browser address url. This is how to get current url by Selenide:
String currentUrl = WebDriverRunner.getWebDriver().getCurrentUrl();
Solution example with junit4 assertEquals() method:
String url = "http://www.google.pl";
Selenide.open(url);
String currentUrl = WebDriverRunner.getWebDriver().getCurrentUrl();
assertEquals(url, currentUrl);
with junit4 & Selenide imports:
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.WebDriverRunner;
import static org.junit.Assert.assertEquals;
Tested. Results:

Related

FastAPI links created by url_for in Jinja2 template use HTTP instead of HTTPS

I migrated an application in Flask served by waitress to FastAPI served by uvicorn, but I can't force the links (generated by url_for inside the index.html template) to use HTTPS instead of HTTP.
With waitress I used:
from waitress import serve
import flask_app
PORT=5000
HOST_IP_ADDRESS='0.0.0.0'
serve(flask_app.app, host=HOST_IP_ADDRESS, port=PORT, url_scheme="https")
with uvicorn I tried to use proxy_headers, but that didn't work. I used a workaround in the index.html
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
which correctly loaded the style.css from static files, but the links to another endpoint still use HTTP.
Is there an easy way to force all links created by url_for to use HTTPS?
I have also run into this issue before. One possible solution is to create a custom url_for function which changes the protocol, then add it to the Jinja environment. One possible implementation may look something like this:
template = Jinja2Templates("/path/to/templates")
def https_url_for(request: Request, name: str, **path_params: Any) -> str:
http_url = request.url_for(name, **path_params)
# Replace 'http' with 'https'
return http_url.replace("http", "https", 1)
template.env.globals["https_url_for"] = https_url_for
You will have to pass the request to the function so it knows how to generate the url_for, but the request should be passed in to your Jinja2 template either way.
You can then use it in your Jinja2 template like this:
https_url_for(request, "/https/path", search="hi")
The resulting url should look like https://<domain>/https/path?search=hi.
I had the same problems. On develop environment all links were with http.
I solved it this way.
from starlette.templating import Jinja2Templates
from sqladmin import Admin
from jinja2 import ChoiceLoader, FileSystemLoader, PackageLoader
import jinja2
if hasattr(jinja2, "pass_context"):
pass_context = jinja2.pass_context
else:
pass_context = jinja2.contextfunction
#pass_context
def https_url_for(context: dict, name: str, **path_params) -> str:
request = context["request"]
http_url = request.url_for(name, **path_params)
return http_url.replace("http", "https", 1)
class CustomAdmin(Admin):
def init_templating_engine(self) -> Jinja2Templates:
templates = Jinja2Templates("templates")
loaders = [
FileSystemLoader(self.templates_dir),
PackageLoader("sqladmin", "templates"),
]
templates.env.loader = ChoiceLoader(loaders)
templates.env.globals["min"] = min
templates.env.globals["zip"] = zip
templates.env.globals["admin"] = self
templates.env.globals["is_list"] = lambda x: isinstance(x, list)
templates.env.globals["url_for"] = https_url_for
return templates
After all just import this class in main file and init the admin class

how can I encode JWT with jmeter

this is my payload
field1=valueField1&field2=valueField2&request=jwtEncodedRequest
Where jwtEncodedRequest is indeed a request encoded via jwt.
currently I'm using jwt.io to create an encoded request.
is it possible automatize this with jmeter?
Yes you can:
Use a JSR223 PreProcessor with Groovy
Compute token using this java library
Add the above library to jmeter/lib folder
Add Apache Ivy jar to JMeter Classpath
Restart JMeter to pick the .jar up
Add JSR223 Sampler to your Test Plan
Put the following code to "Script" area:
#Grab(group='io.jsonwebtoken', module='jjwt', version='0.9.1')
import io.jsonwebtoken.*
import java.security.PrivateKey
import java.util.Base64
import java.util.Base64.Decoder
import java.nio.charset.StandardCharsets
import java.security.interfaces.ECPrivateKey
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.spec.PKCS8EncodedKeySpec
// Generating Tokens for API Requests
// https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests
def exp = (System.currentTimeMillis() / 1000 + 1200).intValue()
//20 minutes from now
//JWT Payload (update with your Issuer ID)
String jsonString = """{"iss":"57246542-96fe-1a63-e053-0824d011072a","exp":${exp},"aud":"appstoreconnect-v1"}""";
//Content of the AuthKey_2X9R4HXF34.p8
/*
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg74+aaeYnqEIewDn8
Xh0rQXaQqAHSLGDyL9fV0p1hhxGgCgYIKoZIzj0DAQehRANCHOTEUjCMi4Vt7JGZ
jsRP1zF765oerCqfvHZYGqSeJl8AmK0awchcqAaMlw7hROoA2MToqx+llo2p9lZC
QYbeerau
-----END PRIVATE KEY-----
*/
//Key concatenated in a single line
//You better not hard code this key
def base64EncodedPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg74+aaeYnqEIewDn8Xh0rQXaQqAHSLGDyL9fV0p1hhxGgCgYIKoZIzj0DAQehRANCHOTEUjCMi4Vt7JGZjsRP1zF765oerCqfvHZYGqSeJl8AmK0awchcqAaMlw7hROoA2MToqx+llo2p9lZCQYbeerau"
ECPrivateKey signingKey
Base64.Decoder dec= Base64.getDecoder();
keyBytes = dec.decode(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
signingKey = keyFactory.generatePrivate(keySpec);
//Notice you don't need to encode the header nor the payload
String jwtToken = Jwts.builder()
//JWT Header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","ES256")
.setHeaderParam("kid","2X9R4HXF34") //UPDATE with your Key Identifier
.setPayload(jsonString)
.signWith(SignatureAlgorithm.ES256, signingKey)
.compact();
log.info(jwtToken)
You should see JWT token printed to jmeter.log file:
More information:
JSON Web Token Quickstart
Apache Groovy - Why and How You Should Use It

Assert command for checking the url in selenium webdriver

As there is no xpath and id for the url on the webpage, how can i check if my actual url is matching with the expected url?
I have provided my code below, but it did not work.
String Actualtext = driver.findElement(By.linkText("http://localhost:8080/imdb/homepage")).getText();
Assert.assertEquals(Actualtext, "http://localhost:8080/imdb/homepage" );
System.out.println("URL matching --> Part executed");
You can validate it against the 'current url' as
String URL = driver.getCurrentUrl();
Assert.assertEquals(URL, "http://localhost:8080/imdb/homepage" );
In Python, it is not getCurrentUrl, but
driver.current_url
getText() is used to fetch the visible innertText, You can use the getAttribute method to fetch the url (for hyperlink), something like below
String Actualtext = driver.findElement("YourElementLocator").getAttribute("href")
Assert.assertEquals(Actualtext, "http://localhost:8080/imdb/homepage" );
System.out.println("URL matching --> Part executed");
In selenium webdriver C#
String URL = driver.Url;
Assert.AreEqual(URL, "http://localhost:8080/imdb/homepage");
In Selenium webdriver java
String URL = driver.getCurrentUrl();
Assert.assertEquals(URL, "http://localhost:8080/imdb/homepage" );

HTML Unit - login to secure website using form - can't connect to page after form

I'm a newbie to java htmlunit so any help would be greatly appreciated - Thanks in advance.
I'm trying to login to a webpage that is protected with username and password authentication by submitting a username and password to the form on the webpage using htmlunit to mirror the actions of a web browser. The website itself has form based authorisation.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.Set;
//Import htmlunit classes
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.util.Cookie;
//This Class attempts to submit user and password credentials
//and mirrors how a login button would be clicked on a webpage:
public class submitForm {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
// Get the first page
HtmlPage page1 = (HtmlPage) webClient.getPage("http://cmdbjr/frameset.php?ci_name=&ci_id=&ci_type=");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
HtmlForm form = page1.getFormByName("loginform");
// Enter login and passwd
form.getInputByName("user_id").setValueAttribute("#####");
form.getInputByName("password").setValueAttribute("#####");
// Click "Sign In" button/link
page1 = (HtmlPage) form.getInputByValue("Log In").click();
// I added the cookie section but this returns a null pointer exception
Set<Cookie> cookie = webClient.getCookieManager().getCookies();
if(cookie != null){
Iterator<Cookie> i = cookie.iterator();
while (i.hasNext()) {
webClient.getCookieManager().addCookie(i.next());
}
}
// Get page as Html
String htmlBody = page1.getWebResponse().getContentAsString();
// Save the response in a file
String filePath = "c:/temp/test_out.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(htmlBody);
bw.close();
// Change the value of the text field
// userField.setValueAttribute("alwalsh");
// passwordField.setValueAttribute("1REland6");
// Now submit the form by clicking the button and get back the second page.
// final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
}
If I run the code without the cookie section of code the page I am trying to reach which
is after the login page doesn't appear an error page appears saying I'm not connected to the internet.
If the code is run with the cookie section the error:
Exception in thread "main" >java.lang.NullPointerException at contentWeb.main(contentWeb.java:26)
is returned.
I'm new to java htmlunit so any help at all would be greatly appreciated.
Thanks in advance.
I replicated your example with my yahoo mail login credentials and it worked. However, I added : webClient.setThrowExceptionOnScriptError(false); to ignore exceptions on script errors.

Use HtmlUnit to search google

The following code is an attempt to search google, and return the results as text or html.
The code was almost entirely copied directly from code snippets online, and i see no reason for it to not return results from the search. How do you return google search results, using htmlunit to submit the search query, without a browser?
import com.gargoylesoftware.htmlunit.WebClient;
import java.io.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import java.net.*;
public class GoogleSearch {
public static void main(String[] args)throws IOException, MalformedURLException
{
final WebClient webClient = new WebClient();
HtmlPage page1 = webClient.getPage("http://www.google.com");
HtmlInput input1 = page1.getElementByName("q");
input1.setValueAttribute("yarn");
HtmlSubmitInput submit1 = page1.getElementByName("btnK");
page1=submit1.click();
System.out.println(page1.asXml());
webClient.closeAllWindows();
}
}
There must be some browser detection that changes the generated HTML, because when inspecting the HTML with page1.getWebResponse().getContentAsString(), the submit button is named btnG and not btnK (which is not what I observe in Firefox). Make this change, and the result will be the expected one.
I've just checked this. It's actually 2 ids for 2 google pages:
btnK: on the google home page (where there's 1 long textbox in the middle of the screen). This time the button's id = 'gbqfa'
btnG: on the google result page (where the main textbox is on top of the screen). This time the button's id = 'gbqfb'

Resources