Skip to content

Commit

Permalink
add NotepadCalculatorTest sample (#903)
Browse files Browse the repository at this point in the history
  • Loading branch information
fforjan authored and hassanuz committed Dec 10, 2019
1 parent 3a08341 commit d775629
Show file tree
Hide file tree
Showing 9 changed files with 561 additions and 0 deletions.
85 changes: 85 additions & 0 deletions Samples/C#/NotepadAndCalculatorTest/CalculatorSession.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//******************************************************************************
//
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
using System;
using System.Threading;

namespace NotepadCalculatorTest
{
public class CalculatorSession : IDisposable
{
// Note: append /wd/hub to the URL if you're directing the test at Appium
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
private const string CalculatorAppId = "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App";

public WindowsDriver<WindowsElement> Session { get; private set; }
public WindowsElement CalculatorHeader { get; private set; }
public WindowsElement CalculatorResult { get; private set; }

public CalculatorSession()
{
// Create a new session to bring up an instance of the Calculator application
// Note: Multiple calculator windows (instances) share the same process Id
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", CalculatorAppId);
appCapabilities.SetCapability("deviceName", "WindowsPC");
this.Session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(Session);

// Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
Session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1.5);

// Identify calculator mode by locating the calculator header
try
{
CalculatorHeader = Session.FindElementByAccessibilityId("Header");
}
catch
{
CalculatorHeader = Session.FindElementByAccessibilityId("ContentPresenter");
}

// Ensure that calculator is in standard mode
if (!CalculatorHeader.Text.Equals("Standard", StringComparison.OrdinalIgnoreCase))
{
Session.FindElementByAccessibilityId("TogglePaneButton").Click();
Thread.Sleep(TimeSpan.FromSeconds(1));
var splitViewPane = Session.FindElementByClassName("SplitViewPane");
splitViewPane.FindElementByName("Standard Calculator").Click();
Thread.Sleep(TimeSpan.FromSeconds(1));
Assert.IsTrue(CalculatorHeader.Text.Equals("Standard", StringComparison.OrdinalIgnoreCase));
}

// Locate the CalculatorResult element
CalculatorResult = Session.FindElementByAccessibilityId("CalculatorResults");
}

public void Dispose()
{
// Close the application and delete the session
if (Session != null)
{
Session.Quit();
Session = null;
CalculatorHeader = null;
CalculatorResult = null;
}
}
}
}
74 changes: 74 additions & 0 deletions Samples/C#/NotepadAndCalculatorTest/MultiSession.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//******************************************************************************
//
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using System.Threading;
using System;
using System.Runtime.CompilerServices;

namespace NotepadCalculatorTest
{
[TestClass]
public class MultiSession
{
private NotepadSession notepadSession;
private CalculatorSession calculatorSession;

[TestMethod]
[DataRow("One", "Plus", "Seven")]
[DataRow("Nine", "Minus", "One")]
[DataRow("Eight", "Divide by", "Eight")]
public void Templatized(string input1, string operation, string input2)
{
// we (re) start with our notepad session
notepadSession.Session.SwitchTo();
notepadSession.NotepadMainEditBox.SendKeys($"{input1} {operation} {input2} = ");

// now let's switch to calculator
calculatorSession.Session.SwitchTo();

// Run sequence of button presses specified above and validate the results
calculatorSession.Session.FindElementByName(input1).Click();
calculatorSession.Session.FindElementByName(operation).Click();
calculatorSession.Session.FindElementByName(input2).Click();
calculatorSession.Session.FindElementByName("Equals").Click();

// and back to notepad for the result
notepadSession.Session.SwitchTo();
notepadSession.NotepadMainEditBox.SendKeys($"{GetCalculatorResultText()}\n");
}

[TestInitialize]
public void TestInitialize()
{
notepadSession = new NotepadSession();
calculatorSession = new CalculatorSession();
}

[TestCleanup]
public void TestCleanup()
{
calculatorSession.Dispose();
notepadSession.Dispose();
}

private string GetCalculatorResultText()
{
return calculatorSession.CalculatorResult.Text.Replace("Display is", string.Empty).Trim();
}
}
}
120 changes: 120 additions & 0 deletions Samples/C#/NotepadAndCalculatorTest/NotepadCalculatorTest.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props" Condition="Exists('packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NotepadCalculatorTest</RootNamespace>
<AssemblyName>NotepadCalculatorTest</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="appium-dotnet-driver, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.WinAppDriver.Appium.WebDriver.1.0.1-Preview\lib\net45\appium-dotnet-driver.dll</HintPath>
</Reference>
<Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Drawing" />
<Reference Include="WebDriver, Version=3.8.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\Selenium.WebDriver.3.8.0\lib\net45\WebDriver.dll</HintPath>
</Reference>
<Reference Include="WebDriver.Support, Version=3.8.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\Selenium.Support.3.8.0\lib\net45\WebDriver.Support.dll</HintPath>
</Reference>
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise />
</Choose>
<ItemGroup>
<Compile Include="NotepadSession.cs" />
<Compile Include="MultiSession.cs" />
<Compile Include="SingleSession.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="CalculatorSession.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="README.md" />
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets" Condition="Exists('packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
25 changes: 25 additions & 0 deletions Samples/C#/NotepadAndCalculatorTest/NotepadCalculatorTest.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29326.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NotepadCalculatorTest", "NotepadCalculatorTest.csproj", "{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2C5ADFF-D6B5-48C1-BB8C-571BFD583D7F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {993F4E37-F1F7-434A-BFF8-F767326C7654}
EndGlobalSection
EndGlobal
82 changes: 82 additions & 0 deletions Samples/C#/NotepadAndCalculatorTest/NotepadSession.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//******************************************************************************
//
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium;
using System;

namespace NotepadCalculatorTest
{
public class NotepadSession :IDisposable
{
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
private const string NotepadAppId = @"C:\Windows\System32\notepad.exe";

public WindowsElement NotepadMainEditBox { get; private set; }

public NotepadSession()
{

// Create a new session to launch Notepad application
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", NotepadAppId);
this.Session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(Session);
Assert.IsNotNull(Session.SessionId);

// Verify that Notepad is started with untitled new file
Assert.AreEqual("Untitled - Notepad", Session.Title);

// Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
Session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1.5);

NotepadMainEditBox = Session.FindElementByClassName("Edit");
}


public void Cleanup()
{
// Select all text and delete to clear the edit box
NotepadMainEditBox.SendKeys(Keys.Control + "a" + Keys.Control);
NotepadMainEditBox.SendKeys(Keys.Delete);
Assert.AreEqual(string.Empty, NotepadMainEditBox.Text);
}

public WindowsDriver<WindowsElement> Session { get; }

public void Dispose()
{
// Close the application and delete the session
if (Session != null)
{
NotepadMainEditBox = null;

Session.Close();

try
{
// Dismiss Save dialog if it is blocking the exit
Session.FindElementByName("Don't Save").Click();
}
catch { }

Session.Quit();
}
}
}
}
Loading

2 comments on commit d775629

@ecchioni
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.Session = new WindowsDriver(new Uri(WindowsApplicationDriverUrl), appCapabilities); produces an error:Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'System.Uri' to 'OpenQA.Selenium.Appium.AppiumOptions' UnitTestProject3

@carson-cq
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.Session = new WindowsDriver(new Uri(WindowsApplicationDriverUrl), appCapabilities); produces an error:Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'System.Uri' to 'OpenQA.Selenium.Appium.AppiumOptions' UnitTestProject3

Update Appium.WebDriver to lower version(maybe 3.0.0.2).

Please sign in to comment.