user interface for selenium with specflow c# - c#

my end goal is to have my boss (not a technical person) use the testing software on her own.(without visual studio or any other 3rd party software) So, i need to build a user interface. here is what one of my scenarios look like. scentially have this scenario run in a console( I can figure out the UI later) or have the HTML report that specflows generates done without visual studio.
I also need the user to pick which scenario runs.
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
using static Aflutter3.Element_objects.Element;
using static Aflutter3.Element_objects;
using static Aflutter3.Other_Functions;
using static Aflutter3.Login_Class;
namespace Aflutter3
{
[Binding]
public class SigninSteps
{
[Given(#"I open google chrome")]
public void GivenIOpenGoogleChrome()
{
if (Driver != null)
Console.WriteLine("Opened");
else
Console.WriteLine("Unsuccessfully Opened");
}
[Given(#"I go to aflutter sign in page")]
public void GivenIGoToAflutterSignInPage()
{
if (Go_To_LoginPage() == true)
Console.WriteLine("Website successfully Accessed");
else
Console.WriteLine("Website unsuccessfully Accessed");
}
[Given(#"I enter the username and password")]
public void GivenIEnterTheUsernameAndPassword()
{
Enter_Credentials();
Console.WriteLine("Username and password successfully entered");
}
[When(#"i click sign in")]
public void WhenIClickSignIn()
{
Click_Sign_in();
Console.WriteLine("Login To Aflutter Button Successfully Clicked");
}
[Then(#"I should be in the homepage")]
public void ThenIShouldBeInTheHomepage()
{
if (Check_If_Homepage_Loaded())
Console.WriteLine("Homepage was succesfully loaded");
else
Console.WriteLine("Homepage was unsuccesfully loaded");
}
}
}

Better to create a one file, which will go through the all flow - start tests, generate report, maybe open report. It can be cmd file or power-shell script. When this script is executed, all happens and you boss needs only to check report.

Related

Unity SendKeys to launch Google Assistant via Win+Shift+A

So I've done some coding with unity previously but trying to do traditional coding and am having trouble figuring it out.
After downloading Google Assistant on my Windows 10 computer, it does not listen to "Ok google". So I decided that a simple project was to make a program that would listen for a keyword and would stimulate the keys: Win+Shift+A to open Google Assistant.
The current code I have is here:
using NUnit.Framework;
using WindowsInput;
namespace Ok_Google
{
public class Tests
{
[SetUp]
public void Setup()
{
}
string keyWord1 = "Ok Google";
string keyWord2 = "Hey Google";
private object SendKeys;
public void Start()
{
}
public void ListeForKeyWord()
{
}
public void EnterShortCut()
{
SendKeys.Send("{LWin}");
SendKeys.Send("{Shift}");
SendKeys.Send("{A}");
}
[Test]
public void Test1()
{
Assert.Pass();
}
}
}
It's not recognizing the Object Send, following the command SendKeys
Can anyone find a potential solution for this and show the process of correcting these errors?

Troubles with [After*] Fixtures in Steps

The Problem:
I have two features (I'm just getting started with SpecFlow)
In each of the feature steps, I create a global WebDriver so that I can use it for all of the steps. If I run just the steps, everything runs correctly in both features. They do, however, leave the browser window open because I never close the WebDriver. So my thought was to put an AfterFeature fixture in each of the Step files do close the driver.
[AfterFeature]
public static void ShutDown()
{
Driver.Close();
}
When I run each feature, everything is fine and the driver closes at the end of the run. However, if I run more than one feature like this, the driver will close after the first feature and a new one will not open when the next feature starts. I find this odd since each feature steps file has it's own instantiated driver.
I have learned that if I use [AfterTestRun], the tests will run correctly and both browsers will remain open until all features are complete. At which point they will both close. This is ok for now when I only have two features, but when I get a bunch, I would rather not have a bunch of random browser windows sticking around until all the tests are completed.
I think this might be somehow related to my inability to use [AfterScenario] without breaking my tests. I was trying to use [AfterScenario] to logout after each scenario/test, but when I do I see a random blank driver/browser window pop up at the end of my first test (regardless of which test I run first).
I have this feeling that I'm just missing some sort of paradigm with this whole BDD methodology here, and that things are actually working as designed. But I am at a loss as to what changes I should make. Here is an example of my login tests.. Is there something fundamental that I'm missing here?
The Code:
Login.feature
Feature: Login
In order to be able to use Laserfiche
As a legitimate user
I want to be able to log into the repository
#SmokeTest
Scenario: Login with correct credentials
Given I am on the Login page
And I have a good username/password combination
And I select a repository
When I fill out the form and submit
Then I am taken to the repo page
---------------
LoginSteps.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Selenium_C_Sharp_POC.Page_Object_Files.Pages;
using Selenium_C_Sharp_POC.Page_Object_Files.Test_Tools;
using TechTalk.SpecFlow;
namespace Selenium_C_Sharp_POC.StepDefinitions
{
[Binding]
public class LoginSteps
{
private static readonly IWebDriver Driver = new ChromeDriver();
private static LoginPage _loginPage;
private static string _username;
private static string _password;
private static string _repo;
[AfterTestRun]
public static void ShutDown()
{
Driver?.Close();
}
[Given(#"I am on the Login page")]
public void GivenIAmOnTheLoginPage()
{
_loginPage = new LoginPage(Driver);
}
[Given(#"I have a good username/password combination")]
public void GivenIHaveAGoodUsernamePasswordCombination()
{
_username = Nomenclature.WebClientPersonalUsername;
_password = Nomenclature.WebClientPersonalPassword;
}
[Given(#"I select a repository")]
public void GivenISelectARepository()
{
_repo = Nomenclature.RepoUnderTest;
}
[When(#"I fill out the form and submit")]
public void WhenIFillOutTheFormAndSubmit()
{
_loginPage.Login(
username: _username,
password: _password,
repo: _repo);
}
[Then(#"I am taken to the repo page")]
public void ThenIAmTakenToTheRepoPage()
{
Assert.AreEqual(
expected: _repo,
actual: Driver.Title);
HelperMethods.Logout(Driver);
}
}
}
Edit: Added Login Page Class code
using System;
using OpenQA.Selenium;
using System.Threading;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using Selenium_C_Sharp_POC.Page_Object_Files.Test_Tools;
namespace Selenium_C_Sharp_POC.Page_Object_Files.Pages
{
class LoginPage
{
private readonly IWebElement _repoDropDown;
private readonly IWebElement _usernameTextBox;
private readonly IWebElement _passwordTextBox;
private readonly IWebElement _submitButton;
private readonly IWebDriver _driver;
private readonly IWebElement _warningBox;
public LoginPage(IWebDriver driver)
{
_driver = driver;
HelperMethods.OpenWebPage(
domain: Nomenclature.Domain,
driver: _driver,
subPage: Nomenclature.LoginPageFilename
);
_repoDropDown = _driver.FindElement(By.Id("SelectedRepo"));
_passwordTextBox = _driver.FindElement(By.Name("password"));
_usernameTextBox = _driver.FindElement(By.Name("username"));
_submitButton = _driver.FindElement(By.Id("LoginButton"));
_warningBox = _driver.FindElement(By.ClassName("alert-danger"));
}
public void Login(string username, string password, string repo)
{
SelectRepo(repo);
_usernameTextBox.SendKeys(username);
_passwordTextBox.SendKeys(password);
_submitButton.Click();
WaitForLoginToComplete();
}
public void SelectRepo(string repo)
{
_repoDropDown.Click();
var options = _repoDropDown.FindElements(By.XPath(".//option"));
foreach (var option in options)
{
if(option.Text.Equals(repo))
option.Click();
}
}
public bool WarningDisplayed_UsernamePassword()
{
Thread.Sleep(500);
return _warningBox.Displayed &&
_warningBox.Text.Equals(Nomenclature.BadUsernameOrPasswordText, StringComparison.OrdinalIgnoreCase);
}
internal bool OpenedRepoPage(string expectedRepo)
{
return _driver.Title.Equals(expectedRepo);
}
internal void WaitForLoginToComplete()
{
try
{
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("alert-danger")));
}
catch (Exception)
{
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(45));
wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[#ng-model='searchQuery']")));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("entryListLoadingSpinner")));
}
}
}
}
LatestInfo:
I believe I know why this is happening. I just don't know the proper way to fix it. As an experiment, I changed the WebDriver for my search tests to Firefox and left the WebDriver for my login tests as Chrome. No matter what test(s) I ran, I always saw 2 browsers open; one Chrome and one Firefox.
When I moved all of the steps from my SearchTestSteps.cs file into the LoginTestSteps.cs file, the problem disappeared.
So, yeah, this solves the immediate issue, but it is sub-optimal to have all of my steps in a single file. That can quickly become unwieldy.
Since each set of steps needs to have its own WebDriver, I'm at a loss.
Might this have something to do with folder structure and where things are stored? Here is what mine looks like.
Root
|-Page Object Files
|- Page Components
|- Pages
|- Test Tools
|- Step Definitions
|- <*Steps.cs>
|- TESTS
|- BDD Tests
|-<*.feature>
|- *standard selenium test files*
After investigating some more, I realized that the problem is NOT what I thought it was, and therefore the title and contents were inaccurate. I am closing this question and creating a new question with more accurate Title and information.
Having Multiple Step Files Opens Multiple Browsers

Testing local project in Visual Studio using selenium web driver

I am trying to set up a visual studio project with acceptance tests using NUnit and Selenium Web Driver, I would like to be able to "run tests" and this to start my web site, use selenium to run the tests and quit.
I have this basic setup so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
namespace FrontEndTests.AcceptanceTests
{
[TestFixture]
class Phantom
{
private PhantomJSDriver _driver;
[SetUp]
public void WhenOpeningANewWebPage()
{
_driver = new PhantomJSDriver();
_driver.Navigate().GoToUrl(#"localhost");
}
[Test]
public void ThenICanFindAClass()
{
Assert.NotNull(_driver.FindElement(By.ClassName("featured")));
}
[TearDown]
public void Finally()
{
_driver.Quit();
}
}
}
If I set the URL to 'www.google.com' the tests pass fine (with the correct class set) but localhost returns elementnotfoundexception in selenium.
How do I get it to work locally?
Thanks
Based on this:
"When I run the project in visual studio it points to localhost:31106 I have tried to using this as the URL but this gives the same error - Gregg_1987"
IIS must be running your application. When you click run it starts the application in IIS express for the time that the application is running. Visual Studio then attaches to this for execution purposes.
If you are trying to execute Selenium on this you would have to install regular IIS and register the application through IIS so that it will be accessible. Then your tests can hit this through the URL registered in IIS. Otherwise you would have to try to programmatically execute the app using IIS express which there is some guidance on here: Automatically start ASP.MVC project when running test project
Once the site is accessible through IIS you can then hit it with your Selenium tests.
Well, you need to start you site before all tests or you can start it once in SetUp and kill it in TearDown (or if you are going to run your tests on some CI then run once before all tests and kill after all). To start it you can choose either webdev or iisexpress (on your choice), below sample of using WebDev.WebHost.dll
public class Phantom
{
private PhantomJSDriver _driver;
//Move this field to base class if you need to start site before each test
//e.g. you can move setup and teardown to base class, it's all up to you
public DevServer WebDevServer { get; private set; }
[SetUp]
public void WhenOpeningANewWebPage()
{
WebDevServer = new DevServer();
WebDevServer.Start();
_driver = new PhantomJSDriver();
_driver.Navigate().GoToUrl(#"localhost");
}
[Test]
public void ThenICanFindAClass()
{
Assert.NotNull(_driver.FindElement(By.ClassName("featured")));
}
[TearDown]
public void Finally()
{
_driver.Quit();
WebDevServer.Stop();
}
}
public class DevServer
{
private Server _webServer;
public DirectoryInfo SourcePath { get; set; }
public string VirtualPath { get; set; }
public int Port { get; set; }
public DevServer()
{
//Port
Port = Settings.WebDevPort;
//Path to your site folde
SourcePath = Settings.WebDevSourcePath;
//Virt path can be ~
VirtualPath = Settings.WebDevVirtualPath;
}
public void Start()
{
Stop();
try
{
_webServer = new Server(Port, VirtualPath, SourcePath.FullName);
_webServer.Start();
}
catch (Exception e)
{
Trace.TraceError("Process cannot be started." + Environment.NewLine + e);
throw;
}
}
public void Stop()
{
if (_webServer != null)
{
_webServer.Stop();
_webServer = null;
}
}
}

Exchange Server 2007 Transport Agent Issue

This is the first time i am working on Exchange Server Development. Below is a simple Transport Agent that i am using, this agent should simply update the email Subjects as shown below in the code.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Transport.Smtp;
namespace MyAgents
{
public sealed class MyAgentFactory : SmtpReceiveAgentFactory
{
public override SmtpReceiveAgent CreateAgent(SmtpServer server)
{
return new MyAgent();
}
}
public class MyAgent : SmtpReceiveAgent
{
public MyAgent()
{
this.OnEndOfData += new EndOfDataEventHandler(MyEndOfDataHandler);
}
private void MyEndOfDataHandler(ReceiveMessageEventSource source, EndOfDataEventArgs e)
{
e.MailItem.Message.Subject = "This message passed through my agent: " + e.MailItem.Message.Subject;
}
}
}
Below is the Powershell script i am using to install the Agent.
Net Stop MSExchangeTransport
Install-TransportAgent -Name MyAgent -AssemblyPath EmailLogger.dll -TransportAgentFactory MyAgents.MyAgentFactory
Enable-TransportAgent -Identity MyAgent
Net Start MSExchangeTransport
Agent installed successfully using Exchange Management Shell.
Now when i send/receive emails in exchange, Email subjects are not modified. Emails have their original subjects. I don't know why?
I also performed the steps mentioned in below links to debug the Agent but breakpoints are not being hit by Visual Studio Debugger.
http://www.sf-tools.net/Messaging/tabid/55/EntryId/163/Exchange-2010-Transport-Agent.aspx
Debugging MS Exchange 2007 Transport Agent
http://omarjames.com/blog/index.php/debugging-exchange-transport-agent/
My System Configuration
I am using the Exchange Server 2007 Virtual Machine provided by Microsoft from link below
http://www.microsoft.com/en-pk/download/details.aspx?id=14901
I also installed the Visual Studio 2008 on the VM for debugging.
Please help me in resolving the issue?
Problem Solved. :)
I must use Routing Agent instead of SmtpReceive Agent because only Routing Agents are guaranteed to see all the Emails passing through Exchange Server.
Below is the modified working code, Everything else remains same
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Transport.Routing;
namespace MyAgents
{
public sealed class MyAgentFactory : RoutingAgentFactory
{
public override RoutingAgent CreateAgent(SmtpServer server)
{
return new MyAgent();
}
}
public class MyAgent : RoutingAgent
{
public MyAgent()
{
this.OnSubmittedMessage += new SubmittedMessageEventHandler(this.MySubmittedMessageHandler);
}
public void MySubmittedMessageHandler(SubmittedMessageEventSource source, QueuedMessageEventArgs e)
{
e.MailItem.Message.Subject = "This message passed through my agent: " + e.MailItem.Message.Subject;
}
}
}

How does one use ManagementEventWatcher to keep track of suspend/resume?

I am trying to use ManagementEventWatcher in a service to keep track of when a computer goes in and out of sleep mode. I am new to .NET and C# so I am struggling quite a bit to come up with syntax to make this work.
I have found a blog post that details how he used ManagementEventWatcher to keep track of this status, but he did not post up his entire code. I am trying to go through and make a simple service that creates a .txt log file stating that the computer has been suspended/resumed but am running into problems with the namespaces and types.
Here is the code to the service.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
}
public void Resume()
{
}
}
}
Again, this is the first time that I am programming with .NET and C# so I apologize for my ignorance.
I am getting namespace errors such as:
The type or namespace name
'ManagementEventWatcher' could not be
found (are you missing a using
directive or an assembly reference?)
Thanks,
Tomek
You need the System.Management namespace, which is included in the code sample provided by you. I believe you need to reference the System.Management library in your project settings. Follow the following steps to do this( I am assuming you are suing Visual Studio):
Go to the Solution Explorer, and expand your project, right click on the References folder/option and select Add References from the context menu. Now select the .Net tab and select the System.Management from the list and click OK.

Categories