I am using Selenium (2.24) to generate unit tests (for the Visual Studio unit test framework). While using the C# WebDriver for FireFox, it appears that the browser which is fired up by the driver is not finding my website cookies via javascript (I have a javascript file included in the site that looks for cookies and lets me know if they are found). Also, it is not using the browsers image cache, and is always requesting new images from the server. This behavior does not happen when I run my site from the "normal" (not launched by Selenium) FireFox.
The strange thing is that calling the below code in my unit test DOES return my cookie (it just can't be found by my JavaScript)
driver.Manage().Cookies.GetCookieNamed("MyCookie");
How can I configure the driver to respect my cookies and use the browsers image cache? This functionality is key to testing my website.
By default the FirefoxDriver will create a new anonymous Profile each time it starts Firefox. If you want it to use an exiting profile you need to tell it to.
In Java you do it like so:
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("MyProfile");
WebDriver driver = new FirefoxDriver(profile);
I'm assuming there's something similar in C#
For cookies: if cookie is marked as "HTTP Only" JavaScript on a page will not be able to see it. As result any code that uses execution of JavaScript on the page will not see this particular cookie.
You can confirm it by using some HTTP debugger (i.e. Fiddler) to see if cookie is set with HttpOnly property. You also can check if running script on a page via dev tools or typing javascript:alert(...) in address bar can see the cookie (document.cookie)
Related
In my Winforms project, I can get a cookie of a site opened in IE by the following method :
InternetGetCookie("mysite.com", "mycookie", "something" , "something" )
As a new requirement coming, the site must be opened in Chrome. That means the method above doesn't work anymore.
After some research, I found out a solution to use Sqlite to read the cookies file stored in "Users\xx\AppData\Google\Chrome\User Data\Default\cookies", it works as expected. I can fetch the cookie by giving the name and URL.
BUT PROBLEM: The cookies file is not up-to-date and is updated 1-2 minutes laters. That means the cookies of the request shown in Chrome DevTool is not the same as in the cookies file.
Is there any way to fetch the cookie in Chrome from C# Winforms project similar to InternetGetCookie?
Hmm, there doesn't seem to be a chrome flag to flush this quicker so probably not going to be an easy option... You could maybe:
Grab it from memory (may be possible if you can search for the value somehow)
Write a Chrome extension which dumps it immediately
Use a headless browser instance to visit the site and send the cookie back instead
I am having a strange issue where I am unable to log into a site under test with the Selenium WebDriver, but am not having any issues logging in when running the project under test in Visual Studio, or in our QA environment.
I have broken the test down to the most simplistic example, where it allows me to manually enter the username, password, and click the login button while it waits for verification that it has moved on to the next screen (waits for an element on that page).
All that happens when running under Selenium is a page refresh.
The test:
driver.Navigate().GoToUrl(this._baseURL + "Account/Index");
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(drv => drv.FindElement(By.Id("element-on-next-page")));
The login button calls the jQuery $.ajax method to POST data to a service, and is correctly going into the success() method. The service returns a redirect URL.
This, in turn, attempts to redirect, which works when working with the site manually, but simply re-loads the login page when under a Selenium test:
window.location.replace(location.origin + result.RedirectTo);
I have verified that the result.RedirectTo is valid when the test is running (it is the page it should be redirecting to for successful login).
Tested with Chrome 71.0.3578.98, Firefox 64.0.2 and IE 11.472.17134.0. It works fine manually in all three.
I am unsure why this behavior is acting differently under automation.
UPDATE: The page it is attempting to redirect to has an [Authorize()] attribute on the controller. Removing this attribute allows the test to pass. The attribute only causes Selenium tests to fail, not manual testing.
have to try to perform login steps manually on the chrome browser launched by Selenium?
I am not sure but sometimes google redirects to authorization page or verify your identity page just to ensure you are not using automation scripts for creating multiple emails signup or scraping any website data.
Just try to run the same scenario manually on the browser launched by selenium.
I am trying to use selenium with .NET (C#) to pull Flash cookies from a particular URL (in this case, a game on kongregate). I know where the flash cookies are stored physically for the browser I use personally. I attempted to access the flash cookies using the physical location in google Chrome's directory (Google\Chrome\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot#SharedObjects), however this has no effect on the flash cookies a gather using selenium. How can I get access to the Shared Object files that are stored through my selenium instance?
Try loading a custom Chrome profile and see if that helps. Here's a quick example.
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=/path/to/your/custom/profile");
See here for more details.
Is there a way to redirect my application to a webpage after checking the browser version first?
I'm using C# to run my angular app and the index.html is loaded by default, but is there a way to control that ?
E.g : if my browser is IE load wrongBrowser.html otherwise load index.html (the default one)
Note that i dont want to redirect my page because i want to keep the orignal url : ex localhost/api/search=text. If i do a redirect, it will overide my url. So i just want to load the html content
Im using C# with visual Studio for the server side
The first page of your app will have to load as it needs to be able to determine the browser specs. Only then can you then redirect to another page based on that knowledge.
I have never used Angular JS neither Angular with C#, but from personal knowledge I know you can "redirect" without changing the url, using a XML request in vanilla javascript (maybe you can place this somewhere):
var request = new XMLHttpRequest();
request.addEventListener("load", function(evt){
document.write(evt.target.response);
}, false);
request.open('GET', 'a.html', true),
request.send();
Now what this does is simple, we set variable request which is a XMLHttpRequest object, then we set an event listener for when it loads, after it loads we replace the code in the page with the targets code, we then set the url and send the request.
I have only used this for testing, so there might be issues that I don't know of, but it does import the html code in.
In C# you can do the following using Request.Browser:
if(Request.Browser.Browser.IndexOf("InternetExplorer")){
return View("wrongBrowser");
}
You have to use IndexOf due to the fact that most, if not all browsers return their version in their name too.
Here's a list of possible browser strings:
IE <= 11: InternetExplorer <numeric version>
Edge: Edge <version>
Safari: Safari <version>
Chrome: Chrome <version>
Opera: Chrome <version>
There are more, most of them will come under Chrome though. I will not go into much detail as you specified IE11 which is listed above. The above method is not really reliable for other, less popular browsers so keep that in mind.
Short version:
I am looking to make sure that a URL (partial match) is requested (client-side).
Long Version:
I am looking to automate part of my testing. Currently I use Fiddler2 to manually verify.
Here's the scenario:
User navigates to Site A
My app redirects using a tracking URL (seen in Fiddler's HTTP traffic)
User ends up on Site A, parameters now applied.
I would like to verify, in C#, that step 2 happened by doing a partial match (contains {string} for example).
Question:
How should I go about this? I have started looking into HttpWebRequest class and FiddlerCore, but my love using the simplest code possible (so other team members to update if needed) lead me to ask what the users of StackOverflow would recommend.
Take a look at SharpPcap. It's based on pcap (WinPcap on Windows), which is the packet capture library that is used by the popular Wireshark.
There is a really great tutorial on CodeProject with lots of example code to get you started: http://www.codeproject.com/Articles/12458/SharpPcap-A-Packet-Capture-Framework-for-NET
Once you have a hold of the packets (SharpPcap does capture, not parsing), you can use Packet.Net to parse the packets into something usable (HTTP communications, in your case).
Edit: Didn't see #2 as an intermediate URL when I read the question, it looked like it was the (only) redirect action. Depending on your browser of choice, and the type of redirect performed, you can use Selenium to read the page referrer and get the redirect.
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
// Call any javascript
var referrer = js.executeScript("document.referrer");
I would recommend Selenium Webdriver for all your web site/app testing needs in C#. It integrates very nicely with NUnit, MSTest and other test frameworks - it's very easy to use.
With Selenium Webdriver, you will start an automated browser instance (Firefox, Chrome, Internet Explorer, PhantomJS and others) from your C# testing code. You will then control the browser with simple commands, like "go to url" or "enter text in input box" or "click button". See more in the API.
It doesn't require much from other developers either - they just run the test suite, and assuming they have the browser installed, it will work. I've used it successfully with hundreds of tests across a team of developers who each had different browser preferences (even for the testing, which we each tweaked) and on the team build server.
For this test, I would go to the url in step 1, then wait for a second, and read the url in step 3.
Here is some sample code, adapated from Introducing the Selenium-WebDriver API by Example. Since I don't know the URL nor {string} ("cheese" in this example) you are looking for, the sample hasn't changed much.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
// Requires reference to WebDriver.Support.dll
using OpenQA.Selenium.Support.UI;
class RedirectThenReadUrl
{
static void Main(string[] args)
{
// Create a new instance of the Firefox driver.
// Notice that the remainder of the code relies on the interface,
// not the implementation.
// Further note that other drivers (InternetExplorerDriver,
// ChromeDriver, etc.) will require further configuration
// before this example will work. See the wiki pages for the
// individual drivers at http://code.google.com/p/selenium/wiki
// for further information.
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
// Print the original URL
System.Console.WriteLine("Page url is: " + driver.Url);
// #kirbycope: In your case, the redirect happens here - you just have
// to wait for the new page to load before reading the new values
// Wait for the page to load, timeout after 10 seconds
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until((d) => { return d.Url.ToLower().Contains("cheese"); });
// Print the redirected URL
System.Console.WriteLine("Page url is: " + driver.Url);
//Close the browser
driver.Quit();
}
}
Sounds like you want to sniff HTTP traffic. You could use a packet capture driver like winpcap, import that DLL and test, or use SharpPcap that #SimpleCoder mentioned.
The path of minimum effort would be write a FiddlerScript Addon, to check the request and redirect if necessary.
Follow Up:
I ended up using Telerik's proxy to send HTTP Requests and parse the responces via C#. Here's the article that was used as a springboard:
https://docs.telerik.com/teststudio/advanced-topics/coded-samples/general/using-the-http-proxy