[Settings] Unit Tests Migration Feature Branch Merge (#5754)

* added MSTest project

* enabled settings tests run in the build pipeline

* re-added settings test project

* re-added test project and sample test

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* updated settings test output path

* updated output path for release config

* added xunit test project

* removed xunit test project

* fix build

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-ci.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-ci.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml

* Update build-powertoys-steps.yml
This commit is contained in:
Nkateko
2020-08-13 13:51:01 -07:00
committed by GitHub
parent d1ee9ebbd9
commit ebd1a6406b
29 changed files with 226 additions and 2219 deletions

View File

@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class SampleTest
{
[TestInitialize]
public void Setup()
{
}
[TestCleanup]
public void CleanUp()
{
}
[TestMethod]
public void SampleTest_For_Settings()
{
}
}
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutputPath>..\..\..\x64\Debug\SettingsTests\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutputPath>..\..\..\x64\Release\SettingsTest\</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.0" />
<PackageReference Include="coverlet.collector" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.PowerToys.Settings.UI.Lib\Microsoft.PowerToys.Settings.UI.Lib.csproj" />
</ItemGroup>
</Project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -1,253 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="..\..\Version.props" />
<!-- We don't have GenerateAssemblyInfo task until we use .net core, so we generate it with WriteLinesToFile -->
<PropertyGroup>
<AssemblyTitle>Microsoft.PowerToys.Settings.UnitTest</AssemblyTitle>
<AssemblyDescription>PowerToys Settings UnitTest</AssemblyDescription>
<AssemblyCompany>Microsoft Corp.</AssemblyCompany>
<AssemblyCopyright>Copyright (C) 2020 Microsoft Corp.</AssemblyCopyright>
<AssemblyProduct>PowerToys</AssemblyProduct>
</PropertyGroup>
<ItemGroup>
<AssemblyVersionFiles Include="Generated Files\AssemblyInfo.cs" />
</ItemGroup>
<Target Name="GenerateAssemblyInfo" BeforeTargets="PrepareForBuild">
<ItemGroup>
<HeaderLines Include="// Copyright (c) Microsoft Corporation" />
<HeaderLines Include="// The Microsoft Corporation licenses this file to you under the MIT license." />
<HeaderLines Include="// See the LICENSE file in the project root for more information." />
<HeaderLines Include="#pragma warning disable SA1516" />
<HeaderLines Include="using System.Reflection%3b" />
<HeaderLines Include="using System.Resources%3b" />
<HeaderLines Include="using System.Runtime.InteropServices%3b" />
<HeaderLines Include="using System.Windows%3b" />
<HeaderLines Include="[assembly: AssemblyTitle(&quot;$(AssemblyTitle)&quot;)]" />
<HeaderLines Include="[assembly: AssemblyDescription(&quot;$(AssemblyDescription)&quot;)]" />
<HeaderLines Include="[assembly: AssemblyConfiguration(&quot;&quot;)]" />
<HeaderLines Include="[assembly: AssemblyCompany(&quot;$(AssemblyCompany)&quot;)]" />
<HeaderLines Include="[assembly: AssemblyCopyright(&quot;$(AssemblyCopyright)&quot;)]" />
<HeaderLines Include="[assembly: AssemblyProduct(&quot;$(AssemblyProduct)&quot;)]" />
<HeaderLines Include="[assembly: AssemblyTrademark(&quot;&quot;)]" />
<HeaderLines Include="[assembly: AssemblyCulture(&quot;&quot;)]" />
<HeaderLines Include="[assembly: ComVisible(false)]" />
<HeaderLines Include="[assembly: NeutralResourcesLanguage(&quot;en-US&quot;)]" />
<HeaderLines Include="[assembly: AssemblyVersion(&quot;$(Version).0&quot;)]" />
<HeaderLines Include="[assembly: AssemblyFileVersion(&quot;$(Version).0&quot;)]" />
</ItemGroup>
<WriteLinesToFile File="Generated Files\AssemblyInfo.cs" Lines="@(HeaderLines)" Overwrite="true" Encoding="Unicode" WriteOnlyWhenDifferent="true" />
</Target>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{A80355C2-780D-4245-BD80-25B8DE698EE3}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.PowerToys.Settings.UnitTest</RootNamespace>
<AssemblyName>Microsoft.PowerToys.Settings.UnitTest</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.18362.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<UnitTestPlatformVersion Condition="'$(UnitTestPlatformVersion)' == ''">$(VisualStudioVersion)</UnitTestPlatformVersion>
<AppxPackageSigningEnabled>false</AppxPackageSigningEnabled>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\Test\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>false</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup>
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>
<ItemGroup>
<SDKReference Include="TestPlatform.Universal, Version=$(UnitTestPlatformVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="Generated Files\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ViewModelTests\ColorPicker.cs" />
<Compile Include="ViewModelTests\FancyZones.cs" />
<Compile Include="ViewModelTests\General.cs" />
<Compile Include="ModelsTests\HelperTest.cs" />
<Compile Include="ViewModelTests\ImageResizer.cs" />
<Compile Include="ModelsTests\BasePTModuleSettingsTest.cs" />
<Compile Include="ModelsTests\BasePTSettingsTest.cs" />
<Compile Include="ModelsTests\SettingsUtilsTests.cs" />
<Compile Include="UnitTestApp.xaml.cs">
<DependentUpon>UnitTestApp.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModelTests\KeyboardManager.cs" />
<Compile Include="ViewModelTests\PowerRename.cs" />
<Compile Include="ViewModelTests\PowerPreview.cs" />
<Compile Include="ViewModelTests\ShortcutGuide.cs" />
<Compile Include="ViewModelTests\PowerLauncherViewModelTest.cs" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="UnitTestApp.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<Content Include="Assets\LockScreenLogo.scale-200.png" />
<Content Include="Assets\SplashScreen.scale-200.png" />
<Content Include="Assets\Square150x150Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
<Content Include="Assets\StoreLogo.png" />
<Content Include="Assets\Wide310x150Logo.scale-200.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>6.2.10</Version>
</PackageReference>
<PackageReference Include="MSTest.TestAdapter">
<Version>2.1.2</Version>
</PackageReference>
<PackageReference Include="MSTest.TestFramework">
<Version>2.1.2</Version>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk">
<Version>16.6.1</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\codeAnalysis\GlobalSuppressions.cs">
<Link>GlobalSuppressions.cs</Link>
</Compile>
<AdditionalFiles Include="..\..\codeAnalysis\StyleCop.json">
<Link>StyleCop.json</Link>
</AdditionalFiles>
</ItemGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers">
<Version>1.1.118</Version>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\common\ManagedTelemetry\Telemetry\Telemetry.csproj">
<Project>{5d00d290-4016-4cfe-9e41-1e7c724509ba}</Project>
<Name>Telemetry</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.PowerToys.Settings.UI.Lib\Microsoft.PowerToys.Settings.UI.Lib.csproj">
<Project>{b1bcc8c6-46b5-4bfa-8f22-20f32d99ec6a}</Project>
<Name>Microsoft.PowerToys.Settings.UI.Lib</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.PowerToys.Settings.UI\Microsoft.PowerToys.Settings.UI.csproj">
<Project>{a7d5099e-f0fd-4bf3-8522-5a682759f915}</Project>
<Name>Microsoft.PowerToys.Settings.UI</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.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>

View File

@@ -1,53 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UnitTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
namespace CommonLibTest
{
[TestClass]
public class BasePTModuleSettingsTest
{
// Work around for System.JSON required properties:
// https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to.
// Test also fails when the attributes are not initialized i.e they have null values.
[TestMethod]
[Obsolete]
public void ToJsonString_ShouldReturnValidJSONOfModel_WhenSuccessful()
{
// Arrange
string file_name = "test\\BasePTModuleSettingsTest";
string expectedSchemaText = @"
{
'$schema': 'http://json-schema.org/draft-04/schema#',
'type': 'object',
'properties': {
'name': {
'type': 'string'
},
'version': {
'type': 'string'
}
},
'additionalProperties': false
}";
string testSettingsConfigs = new BasePTSettingsTest().ToJsonString();
SettingsUtils.SaveSettings(testSettingsConfigs, file_name);
JsonSchema expectedSchema = JsonSchema.Parse(expectedSchemaText);
// Act
JObject actualSchema = JObject.Parse(SettingsUtils.GetSettings<BasePTSettingsTest>(file_name).ToJsonString());
bool valid = actualSchema.IsValid(expectedSchema);
// Assert
Assert.IsTrue(valid);
}
}
}

View File

@@ -1,17 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.PowerToys.Settings.UI.Lib;
namespace Microsoft.PowerToys.Settings.UnitTest
{
public class BasePTSettingsTest : BasePTModuleSettings
{
public BasePTSettingsTest()
{
Name = string.Empty;
Version = string.Empty;
}
}
}

View File

@@ -1,76 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CommonLibTest
{
[TestClass]
public class HelperTest
{
public static void TestStringIsSmaller(string v1, string v2)
{
var res = Helper.CompareVersions(v1, v2);
Assert.IsTrue(res < 0);
}
public static void TestStringsAreEqual(string v1, string v2)
{
var res = Helper.CompareVersions(v1, v2);
Assert.IsTrue(res == 0);
}
[TestMethod]
public void Helper_CompareVersions_ShouldBeEqual_WhenSuccessful()
{
TestStringsAreEqual("v0.0.0", "v0.0.0");
TestStringsAreEqual("v0.1.1", "v0.1.1");
TestStringsAreEqual("v1.1.1", "v1.1.1");
TestStringsAreEqual("v1.999.99", "v1.999.99");
}
[TestMethod]
public void Helper_CompareVersions_ShouldBeSmaller_WhenSuccessful()
{
TestStringIsSmaller("v0.0.0", "v0.0.1");
TestStringIsSmaller("v0.0.0", "v0.1.0");
TestStringIsSmaller("v0.0.0", "v1.0.0");
TestStringIsSmaller("v1.0.1", "v1.0.2");
TestStringIsSmaller("v1.1.1", "v1.1.2");
TestStringIsSmaller("v1.1.1", "v1.2.0");
TestStringIsSmaller("v1.999.99", "v2.0.0");
TestStringIsSmaller("v1.0.99", "v1.2.0");
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Helper_CompareVersions_ShouldThrowBadFormat_WhenNoVersionString()
{
Helper.CompareVersions("v0.0.1", string.Empty);
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Helper_CompareVersions_ShouldThrowBadFormat_WhenShortVersionString()
{
Helper.CompareVersions("v0.0.1", "v0.1");
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Helper_CompareVersions_ShouldThrowBadFormat_WhenLongVersionString()
{
Helper.CompareVersions("v0.0.1", "v0.0.0.1");
}
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Helper_CompareVersions_ShouldThrowBadFormat_WhenItIsNotAVersionString()
{
Helper.CompareVersions("v0.0.1", "HelloWorld");
}
}
}

View File

@@ -1,123 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UnitTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CommonLibTest
{
[TestClass]
public class SettingsUtilsTests
{
public SettingsUtilsTests()
{
string file_name = "\\test";
if (SettingsUtils.SettingsFolderExists(file_name))
{
DeleteFolder(file_name);
}
}
[TestCleanup]
public void Cleanup()
{
string file_name = "\\test";
if (SettingsUtils.SettingsFolderExists(file_name))
{
DeleteFolder(file_name);
}
}
[TestMethod]
public void SaveSettings_SaveSettingsToFile_WhenFilePathExists()
{
// Arrange
string file_name = "\\test";
string file_contents_correct_json_content = "{\"name\":\"powertoy module name\",\"version\":\"powertoy version\"}";
BasePTSettingsTest expected_json = JsonSerializer.Deserialize<BasePTSettingsTest>(file_contents_correct_json_content);
// Act
SettingsUtils.SaveSettings(file_contents_correct_json_content, file_name);
BasePTSettingsTest actual_json = SettingsUtils.GetSettings<BasePTSettingsTest>(file_name);
// Assert
Assert.IsTrue(actual_json.Equals(actual_json));
}
[TestMethod]
public void SaveSettings_ShouldCreateFile_WhenFilePathIsNotFound()
{
// Arrange
string file_name = "test\\Test Folder";
string file_contents_correct_json_content = "{\"name\":\"powertoy module name\",\"version\":\"powertoy version\"}";
BasePTSettingsTest expected_json = JsonSerializer.Deserialize<BasePTSettingsTest>(file_contents_correct_json_content);
// Act
if (SettingsUtils.SettingsFolderExists(file_name))
{
DeleteFolder(file_name);
}
SettingsUtils.SaveSettings(file_contents_correct_json_content, file_name);
BasePTSettingsTest actual_json = SettingsUtils.GetSettings<BasePTSettingsTest>(file_name);
// Assert
Assert.IsTrue(actual_json.Equals(actual_json));
}
[TestMethod]
public void SettingsFolderExists_ShouldReturnFalse_WhenFilePathIsNotFound()
{
// Arrange
string file_name_random = "test\\" + RandomString();
string file_name_exists = "test\\exists";
string file_contents_correct_json_content = "{\"name\":\"powertoy module name\",\"version\":\"powertoy version\"}";
// Act
bool pathNotFound = SettingsUtils.SettingsFolderExists(file_name_random);
SettingsUtils.SaveSettings(file_contents_correct_json_content, file_name_exists);
bool pathFound = SettingsUtils.SettingsFolderExists(file_name_exists);
// Assert
Assert.IsFalse(pathNotFound);
Assert.IsTrue(pathFound);
}
[TestMethod]
public void CreateSettingsFolder_ShouldCreateFolder_WhenSuccessful()
{
// Arrange
string file_name = "test\\" + RandomString();
// Act
SettingsUtils.CreateSettingsFolder(file_name);
// Assert
Assert.IsTrue(SettingsUtils.SettingsFolderExists(file_name));
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
public static string RandomString()
{
Random random = new Random();
int length = 20;
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
}
}

View File

@@ -1,46 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp">
<Identity Name="08e1807b-8b6d-4bfa-adc4-79c64aae8e78"
Publisher="CN=lamotile"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="08e1807b-8b6d-4bfa-adc4-79c64aae8e78" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>Microsoft.PowerToys.Settings.UnitTest</DisplayName>
<PublisherDisplayName>lamotile</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="vstest.executionengine.universal.App"
Executable="$targetnametoken$.exe"
EntryPoint="Microsoft.PowerToys.Settings.UnitTest.App">
<uap:VisualElements
DisplayName="Microsoft.PowerToys.Settings.UnitTest"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="Microsoft.PowerToys.Settings.UnitTest"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClientServer" />
<Capability Name="privateNetworkClientServer" />
</Capabilities>
</Package>

View File

@@ -1,7 +0,0 @@
<Application
x:Class="Microsoft.PowerToys.Settings.UnitTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Microsoft.PowerToys.Settings.UnitTest">
</Application>

View File

@@ -1,97 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Microsoft.PowerToys.Settings.UnitTest
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
/// <summary>
/// Initializes a new instance of the <see cref="App"/> class.
/// This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeComponent();
Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI();
// Ensure the current window is active
Window.Current.Activate();
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments);
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}

View File

@@ -1,65 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class ColorPicker
{
private const string ModuleName = "ColorPicker";
[TestInitialize]
public void Setup()
{
var generalSettings = new GeneralSettings();
var colorPickerSettings = new ColorPickerSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(colorPickerSettings.ToJsonString(), colorPickerSettings.Name, ModuleName + ".json");
}
[TestCleanup]
public void CleanUp()
{
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(ModuleName))
{
DeleteFolder(ModuleName);
}
ShellPage.DefaultSndMSGCallback = null;
}
[TestMethod]
public void ColorPickerIsEnabledByDefault()
{
var viewModel = new ColorPickerViewModel();
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.Enabled.ColorPicker);
};
Assert.IsTrue(viewModel.IsEnabled);
}
private static void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
}
}

View File

@@ -1,382 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.UI;
namespace ViewModelTests
{
[TestClass]
public class FancyZones
{
public const string ModuleName = "FancyZones";
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
GeneralSettings generalSettings = new GeneralSettings();
FZConfigProperties fZConfigProperties = new FZConfigProperties();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(fZConfigProperties.ToJsonString(), ModuleName);
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(ModuleName))
{
DeleteFolder(ModuleName);
}
ShellPage.DefaultSndMSGCallback = null;
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
[TestMethod]
public void IsEnabled_ShouldDisableModule_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsTrue(viewModel.IsEnabled); // check if the module is enabled.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsFalse(snd.GeneralSettings.Enabled.FancyZones);
};
// act
viewModel.IsEnabled = false;
}
[TestMethod]
public void ShiftDrag_ShouldSetValue2False_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsTrue(viewModel.ShiftDrag); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsFalse(snd.Powertoys.FancyZones.Properties.FancyzonesShiftDrag.Value);
};
// act
viewModel.ShiftDrag = false;
}
[TestMethod]
public void OverrideSnapHotkeys_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.OverrideSnapHotkeys); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesOverrideSnapHotkeys.Value);
};
// act
viewModel.OverrideSnapHotkeys = true;
}
[TestMethod]
public void ZoneSetChangeFlashZones_ShouldSetValue2False_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.MakeDraggedWindowsTransparent); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesMakeDraggedWindowTransparent.Value);
};
// act
viewModel.MakeDraggedWindowsTransparent = true;
}
[TestMethod]
public void MouseSwitch_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.MouseSwitch); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesMouseSwitch.Value);
};
// act
viewModel.MouseSwitch = true;
}
[TestMethod]
public void DisplayChangeMoveWindows_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.DisplayChangeMoveWindows); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesDisplayChangeMoveWindows.Value);
};
// act
viewModel.DisplayChangeMoveWindows = true;
}
[TestMethod]
public void ZoneSetChangeMoveWindows_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.ZoneSetChangeMoveWindows); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesZoneSetChangeMoveWindows.Value);
};
// act
viewModel.ZoneSetChangeMoveWindows = true;
}
[TestMethod]
public void AppLastZoneMoveWindows_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.AppLastZoneMoveWindows); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesAppLastZoneMoveWindows.Value);
};
// act
viewModel.AppLastZoneMoveWindows = true;
}
public void OpenWindowOnActiveMonitor_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.OpenWindowOnActiveMonitor); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesOpenWindowOnActiveMonitor.Value);
};
// act
viewModel.OpenWindowOnActiveMonitor = true;
}
[TestMethod]
public void RestoreSize_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.RestoreSize); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesRestoreSize.Value);
};
// act
viewModel.RestoreSize = true;
}
[TestMethod]
public void UseCursorPosEditorStartupScreen_ShouldSetValue2False_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsTrue(viewModel.UseCursorPosEditorStartupScreen); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.UseCursorposEditorStartupscreen.Value);
};
// act
viewModel.UseCursorPosEditorStartupScreen = true;
}
[TestMethod]
public void ShowOnAllMonitors_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.ShowOnAllMonitors); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesShowOnAllMonitors.Value);
};
// act
viewModel.ShowOnAllMonitors = true;
}
[TestMethod]
public void SpanZonesAcrossMonitors_ShouldSetValue2True_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.IsFalse(viewModel.SpanZonesAcrossMonitors); // check if value was initialized to false.
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.FancyZones.Properties.FancyzonesSpanZonesAcrossMonitors.Value);
};
// act
viewModel.SpanZonesAcrossMonitors = true;
}
[TestMethod]
public void ZoneHighlightColor_ShouldSetColorValue2White_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.AreEqual(ConfigDefaults.DefaultFancyZonesZoneHighlightColor, ToRGBHex(viewModel.ZoneHighlightColor));
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.AreEqual("#E1E1E1", snd.Powertoys.FancyZones.Properties.FancyzonesZoneHighlightColor.Value);
};
// act
viewModel.ZoneHighlightColor = Color.FromArgb(0, 225, 225, 225);
}
[TestMethod]
public void ZoneBorderColor_ShouldSetColorValue2White_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.AreEqual(ConfigDefaults.DefaultFancyzonesBorderColor, ToRGBHex(viewModel.ZoneBorderColor));
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.AreEqual("#E1E1E1", snd.Powertoys.FancyZones.Properties.FancyzonesBorderColor.Value);
};
// act
viewModel.ZoneBorderColor = Color.FromArgb(0, 225, 225, 225);
}
[TestMethod]
public void ZoneInActiveColor_ShouldSetColorValue2White_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.AreEqual(ConfigDefaults.DefaultFancyZonesInActiveColor, ToRGBHex(viewModel.ZoneInActiveColor));
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.AreEqual("#E1E1E1", snd.Powertoys.FancyZones.Properties.FancyzonesInActiveColor.Value);
};
// act
viewModel.ZoneInActiveColor = Color.FromArgb(0, 225, 225, 225);
}
[TestMethod]
public void ExcludedApps_ShouldSetColorValue2White_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.AreEqual(string.Empty, viewModel.ExcludedApps);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.AreEqual("Sample", snd.Powertoys.FancyZones.Properties.FancyzonesExcludedApps.Value);
};
// act
viewModel.ExcludedApps = "Sample";
}
[TestMethod]
public void HighlightOpacity_ShouldSetOpacityValueTo60_WhenSuccessful()
{
// arrange
FancyZonesViewModel viewModel = new FancyZonesViewModel();
Assert.AreEqual(50, viewModel.HighlightOpacity);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
FancyZonesSettingsIPCMessage snd = JsonSerializer.Deserialize<FancyZonesSettingsIPCMessage>(msg);
Assert.AreEqual(60, snd.Powertoys.FancyZones.Properties.FancyzonesHighlightOpacity.Value);
};
// act
viewModel.HighlightOpacity = 60;
}
private string ToRGBHex(Color color)
{
return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}
}
}

View File

@@ -1,153 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class General
{
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
GeneralSettings generalSettings = new GeneralSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(string.Empty))
{
DeleteFolder(string.Empty);
}
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
[TestMethod]
public void IsElevated_ShouldUpdateRunasAdminStatusAttrs_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.AreEqual(viewModel.RunningAsUserDefaultText, viewModel.RunningAsText);
Assert.IsFalse(viewModel.IsElevated);
// Act
viewModel.IsElevated = true;
// Assert
Assert.AreEqual(viewModel.RunningAsAdminDefaultText, viewModel.RunningAsText);
Assert.IsTrue(viewModel.IsElevated);
}
[TestMethod]
public void Startup_ShouldEnableRunOnStartUp_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.IsFalse(viewModel.Startup);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.Startup);
};
// act
viewModel.Startup = true;
}
[TestMethod]
public void RunElevated_ShouldEnableAlwaysRunElevated_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.IsFalse(viewModel.RunElevated);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.RunElevated);
};
// act
viewModel.RunElevated = true;
}
[TestMethod]
public void AutoDownloadUpdates_ShouldEnableAutoDownloadUpdates_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.IsFalse(viewModel.AutoDownloadUpdates);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.AutoDownloadUpdates);
};
// act
viewModel.AutoDownloadUpdates = true;
}
[TestMethod]
public void IsLightThemeRadioButtonChecked_ShouldThemeToLight_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.IsFalse(viewModel.IsLightThemeRadioButtonChecked);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.AreEqual("light", snd.GeneralSettings.Theme);
};
// act
viewModel.IsLightThemeRadioButtonChecked = true;
}
[TestMethod]
public void IsDarkThemeRadioButtonChecked_ShouldThemeToDark_WhenSuccessful()
{
// Arrange
GeneralViewModel viewModel = new GeneralViewModel();
Assert.IsFalse(viewModel.IsDarkThemeRadioButtonChecked);
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.AreEqual("dark", snd.GeneralSettings.Theme);
};
// act
viewModel.IsDarkThemeRadioButtonChecked = true;
}
}
}

View File

@@ -1,221 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class ImageResizer
{
public const string Module = "ImageResizer";
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
// Test base path:
// C:\Users\<user name>\AppData\Local\Packages\08e1807b-8b6d-4bfa-adc4-79c64aae8e78_9abkseg265h2m\LocalState\Microsoft\PowerToys\
GeneralSettings generalSettings = new GeneralSettings();
ImageResizerSettings imageResizer = new ImageResizerSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(imageResizer.ToJsonString(), imageResizer.Name);
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(Module))
{
DeleteFolder(Module);
}
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
[TestMethod]
public void IsEnabled_ShouldEnableModule_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.Enabled.ImageResizer);
};
// act
viewModel.IsEnabled = true;
}
[TestMethod]
public void JPEGQualityLevel_ShouldSetValueToTen_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// act
viewModel.JPEGQualityLevel = 10;
// Assert
viewModel = new ImageResizerViewModel();
Assert.AreEqual(10, viewModel.JPEGQualityLevel);
}
[TestMethod]
public void PngInterlaceOption_ShouldSetValueToTen_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// act
viewModel.PngInterlaceOption = 10;
// Assert
viewModel = new ImageResizerViewModel();
Assert.AreEqual(10, viewModel.PngInterlaceOption);
}
[TestMethod]
public void TiffCompressOption_ShouldSetValueToTen_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// act
viewModel.TiffCompressOption = 10;
// Assert
viewModel = new ImageResizerViewModel();
Assert.AreEqual(10, viewModel.TiffCompressOption);
}
[TestMethod]
public void FileName_ShouldUpdateValue_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
string expectedValue = "%1 (%3)";
// act
viewModel.FileName = expectedValue;
// Assert
viewModel = new ImageResizerViewModel();
Assert.AreEqual(expectedValue, viewModel.FileName);
}
[TestMethod]
public void KeepDateModified_ShouldUpdateValue_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// act
viewModel.KeepDateModified = true;
// Assert
ImageResizerSettings settings = SettingsUtils.GetSettings<ImageResizerSettings>(Module);
Assert.AreEqual(true, settings.Properties.ImageresizerKeepDateModified.Value);
}
[TestMethod]
public void Encoder_ShouldUpdateValue_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
// act
viewModel.Encoder = 3;
// Assert
viewModel = new ImageResizerViewModel();
Assert.AreEqual("163bcc30-e2e9-4f0b-961d-a3e9fdb788a3", viewModel.GetEncoderGuid(viewModel.Encoder));
Assert.AreEqual(3, viewModel.Encoder);
}
[TestMethod]
public void AddRow_ShouldAddEmptyImageSize_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
int sizeOfOriginalArray = viewModel.Sizes.Count;
// act
viewModel.AddRow();
// Assert
Assert.AreEqual(viewModel.Sizes.Count, sizeOfOriginalArray + 1);
}
[TestMethod]
public void DeleteImageSize_ShouldDeleteImageSize_WhenSuccessful()
{
// arrange
ImageResizerViewModel viewModel = new ImageResizerViewModel();
int sizeOfOriginalArray = viewModel.Sizes.Count;
ImageSize deleteCandidate = viewModel.Sizes.Where<ImageSize>(x => x.Id == 0).First();
// act
viewModel.DeleteImageSize(0);
// Assert
Assert.AreEqual(viewModel.Sizes.Count, sizeOfOriginalArray - 1);
Assert.IsFalse(viewModel.Sizes.Contains(deleteCandidate));
}
[TestMethod]
public void UpdateWidthAndHeight_ShouldUpateSize_WhenCorrectValuesAreProvided()
{
// arrange
ImageSize imageSize = new ImageSize()
{
Id = 0,
Name = "Test",
Fit = (int)ResizeFit.Fit,
Width = 30,
Height = 30,
Unit = (int)ResizeUnit.Pixel,
};
double negativeWidth = -2.0;
double negativeHeight = -2.0;
// Act
imageSize.Width = negativeWidth;
imageSize.Height = negativeHeight;
// Assert
Assert.AreEqual(0, imageSize.Width);
Assert.AreEqual(0, imageSize.Height);
// Act
imageSize.Width = 50;
imageSize.Height = 50;
// Assert
Assert.AreEqual(50, imageSize.Width);
Assert.AreEqual(50, imageSize.Height);
}
}
}

View File

@@ -1,135 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.System;
namespace ViewModelTests
{
[TestClass]
public class KeyboardManager
{
public const string Module = "Keyboard Manager";
[TestInitialize]
public void Setup()
{
}
[TestCleanup]
public void CleanUp()
{
}
[TestMethod]
public void CombineShortcutLists_ShouldReturnEmptyList_WhenBothArgumentsAreEmptyLists()
{
// arrange
var firstList = new List<KeysDataModel>();
var secondList = new List<AppSpecificKeysDataModel>();
// act
var result = KeyboardManagerViewModel.CombineShortcutLists(firstList, secondList);
// Assert
var expectedResult = new List<AppSpecificKeysDataModel>();
Assert.AreEqual(expectedResult.Count(), result.Count());
}
[TestMethod]
public void CombineShortcutLists_ShouldReturnListWithOneAllAppsEntry_WhenFirstArgumentHasOneEntryAndSecondArgumentIsEmpty()
{
// arrange
var firstList = new List<KeysDataModel>();
var entry = new KeysDataModel();
entry.OriginalKeys = VirtualKey.Control + ";" + VirtualKey.A;
entry.NewRemapKeys = VirtualKey.Control + ";" + VirtualKey.V;
firstList.Add(entry);
var secondList = new List<AppSpecificKeysDataModel>();
// act
var result = KeyboardManagerViewModel.CombineShortcutLists(firstList, secondList);
// Assert
var expectedResult = new List<AppSpecificKeysDataModel>();
var expectedEntry = new AppSpecificKeysDataModel();
expectedEntry.OriginalKeys = entry.OriginalKeys;
expectedEntry.NewRemapKeys = entry.NewRemapKeys;
expectedEntry.TargetApp = "All Apps";
expectedResult.Add(expectedEntry);
var x = expectedResult[0].Equals(result[0]);
Assert.AreEqual(expectedResult.Count(), result.Count());
Assert.IsTrue(expectedResult[0].Compare(result[0]));
}
[TestMethod]
public void CombineShortcutLists_ShouldReturnListWithOneAppSpecificEntry_WhenFirstArgumentIsEmptyAndSecondArgumentHasOneEntry()
{
// arrange
var firstList = new List<KeysDataModel>();
var secondList = new List<AppSpecificKeysDataModel>();
var entry = new AppSpecificKeysDataModel();
entry.OriginalKeys = VirtualKey.Control + ";" + VirtualKey.A;
entry.NewRemapKeys = VirtualKey.Control + ";" + VirtualKey.V;
entry.TargetApp = "msedge";
secondList.Add(entry);
// act
var result = KeyboardManagerViewModel.CombineShortcutLists(firstList, secondList);
// Assert
var expectedResult = new List<AppSpecificKeysDataModel>();
var expectedEntry = new AppSpecificKeysDataModel();
expectedEntry.OriginalKeys = entry.OriginalKeys;
expectedEntry.NewRemapKeys = entry.NewRemapKeys;
expectedEntry.TargetApp = entry.TargetApp;
expectedResult.Add(expectedEntry);
Assert.AreEqual(expectedResult.Count(), result.Count());
Assert.IsTrue(expectedResult[0].Compare(result[0]));
}
[TestMethod]
public void CombineShortcutLists_ShouldReturnListWithOneAllAppsEntryAndOneAppSpecificEntry_WhenFirstArgumentHasOneEntryAndSecondArgumentHasOneEntry()
{
// arrange
var firstList = new List<KeysDataModel>();
var firstListEntry = new KeysDataModel();
firstListEntry.OriginalKeys = VirtualKey.Control + ";" + VirtualKey.A;
firstListEntry.NewRemapKeys = VirtualKey.Control + ";" + VirtualKey.V;
firstList.Add(firstListEntry);
var secondList = new List<AppSpecificKeysDataModel>();
var secondListEntry = new AppSpecificKeysDataModel();
secondListEntry.OriginalKeys = VirtualKey.Control + ";" + VirtualKey.B;
secondListEntry.NewRemapKeys = VirtualKey.Control + ";" + VirtualKey.W;
secondListEntry.TargetApp = "msedge";
secondList.Add(secondListEntry);
// act
var result = KeyboardManagerViewModel.CombineShortcutLists(firstList, secondList);
// Assert
var expectedResult = new List<AppSpecificKeysDataModel>();
var expectedFirstEntry = new AppSpecificKeysDataModel();
expectedFirstEntry.OriginalKeys = firstListEntry.OriginalKeys;
expectedFirstEntry.NewRemapKeys = firstListEntry.NewRemapKeys;
expectedFirstEntry.TargetApp = "All Apps";
expectedResult.Add(expectedFirstEntry);
var expectedSecondEntry = new AppSpecificKeysDataModel();
expectedSecondEntry.OriginalKeys = secondListEntry.OriginalKeys;
expectedSecondEntry.NewRemapKeys = secondListEntry.NewRemapKeys;
expectedSecondEntry.TargetApp = secondListEntry.TargetApp;
expectedResult.Add(expectedSecondEntry);
Assert.AreEqual(expectedResult.Count(), result.Count());
Assert.IsTrue(expectedResult[0].Compare(result[0]));
Assert.IsTrue(expectedResult[1].Compare(result[1]));
}
}
}

View File

@@ -1,138 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class PowerLauncherViewModelTest
{
private class SendCallbackMock
{
public int TimesSent { get; set; }
public void OnSend(PowerLauncherSettings settings)
{
TimesSent++;
}
}
private PowerLauncherViewModel viewModel;
private PowerLauncherSettings mockSettings;
private SendCallbackMock sendCallbackMock;
[TestInitialize]
public void Initialize()
{
mockSettings = new PowerLauncherSettings();
sendCallbackMock = new SendCallbackMock();
viewModel = new PowerLauncherViewModel(
mockSettings,
new PowerLauncherViewModel.SendCallback(sendCallbackMock.OnSend));
}
[TestMethod]
public void SearchPreference_ShouldUpdatePreferences()
{
viewModel.SearchResultPreference = "SearchOptionsAreNotValidated";
viewModel.SearchTypePreference = "SearchOptionsAreNotValidated";
Assert.AreEqual(sendCallbackMock.TimesSent, 2);
Assert.IsTrue(mockSettings.Properties.SearchResultPreference == "SearchOptionsAreNotValidated");
Assert.IsTrue(mockSettings.Properties.SearchTypePreference == "SearchOptionsAreNotValidated");
}
public void AssertHotkeySettings(HotkeySettings setting, bool win, bool ctrl, bool alt, bool shift, int code)
{
Assert.AreEqual(win, setting.Win);
Assert.AreEqual(ctrl, setting.Ctrl);
Assert.AreEqual(alt, setting.Alt);
Assert.AreEqual(shift, setting.Shift);
Assert.AreEqual(code, setting.Code);
}
[TestMethod]
public void Hotkeys_ShouldUpdateHotkeys()
{
var openPowerLauncher = new HotkeySettings();
openPowerLauncher.Win = true;
openPowerLauncher.Code = (int)Windows.System.VirtualKey.S;
var openFileLocation = new HotkeySettings();
openFileLocation.Ctrl = true;
openFileLocation.Code = (int)Windows.System.VirtualKey.A;
var openConsole = new HotkeySettings();
openConsole.Alt = true;
openConsole.Code = (int)Windows.System.VirtualKey.D;
var copyFileLocation = new HotkeySettings();
copyFileLocation.Shift = true;
copyFileLocation.Code = (int)Windows.System.VirtualKey.F;
viewModel.OpenPowerLauncher = openPowerLauncher;
viewModel.OpenFileLocation = openFileLocation;
viewModel.OpenConsole = openConsole;
viewModel.CopyPathLocation = copyFileLocation;
Assert.AreEqual(4, sendCallbackMock.TimesSent);
AssertHotkeySettings(
mockSettings.Properties.OpenPowerLauncher,
true,
false,
false,
false,
(int)Windows.System.VirtualKey.S);
AssertHotkeySettings(
mockSettings.Properties.OpenFileLocation,
false,
true,
false,
false,
(int)Windows.System.VirtualKey.A);
AssertHotkeySettings(
mockSettings.Properties.OpenConsole,
false,
false,
true,
false,
(int)Windows.System.VirtualKey.D);
AssertHotkeySettings(
mockSettings.Properties.CopyPathLocation,
false,
false,
false,
true,
(int)Windows.System.VirtualKey.F);
}
[TestMethod]
public void Override_ShouldUpdateOverrides()
{
viewModel.OverrideWinRKey = true;
viewModel.OverrideWinSKey = false;
Assert.AreEqual(1, sendCallbackMock.TimesSent);
Assert.IsTrue(mockSettings.Properties.OverrideWinkeyR);
Assert.IsFalse(mockSettings.Properties.OverrideWinkeyS);
}
[TestMethod]
public void DriveDetectionViewModel_WhenSet_MustUpdateOverrides()
{
// Act
viewModel.DisableDriveDetectionWarning = true;
// Assert
Assert.AreEqual(1, sendCallbackMock.TimesSent);
Assert.IsTrue(mockSettings.Properties.DisableDriveDetectionWarning);
}
}
}

View File

@@ -1,102 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class PowerPreview
{
public const string Module = "File Explorer";
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
GeneralSettings generalSettings = new GeneralSettings();
PowerPreviewSettings powerpreview = new PowerPreviewSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(powerpreview.ToJsonString(), powerpreview.Name);
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(Module))
{
DeleteFolder(Module);
}
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
[TestMethod]
public void SVGRenderIsEnabled_ShouldPrevHandler_WhenSuccessful()
{
// arrange
PowerPreviewViewModel viewModel = new PowerPreviewViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
SndModuleSettings<SndPowerPreviewSettings> snd = JsonSerializer.Deserialize<SndModuleSettings<SndPowerPreviewSettings>>(msg);
Assert.IsTrue(snd.powertoys.FileExplorerPreviewSettings.Properties.EnableSvgPreview);
};
// act
viewModel.SVGRenderIsEnabled = true;
}
[TestMethod]
public void SVGThumbnailIsEnabled_ShouldPrevHandler_WhenSuccessful()
{
// arrange
PowerPreviewViewModel viewModel = new PowerPreviewViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
SndModuleSettings<SndPowerPreviewSettings> snd = JsonSerializer.Deserialize<SndModuleSettings<SndPowerPreviewSettings>>(msg);
Assert.IsTrue(snd.powertoys.FileExplorerPreviewSettings.Properties.EnableSvgThumbnail);
};
// act
viewModel.SVGThumbnailIsEnabled = true;
}
[TestMethod]
public void MDRenderIsEnabled_ShouldPrevHandler_WhenSuccessful()
{
// arrange
PowerPreviewViewModel viewModel = new PowerPreviewViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
SndModuleSettings<SndPowerPreviewSettings> snd = JsonSerializer.Deserialize<SndModuleSettings<SndPowerPreviewSettings>>(msg);
Assert.IsTrue(snd.powertoys.FileExplorerPreviewSettings.Properties.EnableMdPreview);
};
// act
viewModel.MDRenderIsEnabled = true;
}
}
}

View File

@@ -1,202 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class PowerRename
{
public const string ModuleName = "PowerRename";
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
GeneralSettings generalSettings = new GeneralSettings();
PowerRenameSettings powerRename = new PowerRenameSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(powerRename.ToJsonString(), powerRename.Name, "power-rename-settings.json");
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
// delete folder created.
if (SettingsUtils.SettingsFolderExists(ModuleName))
{
DeleteFolder(ModuleName);
}
}
[TestMethod]
public void IsEnabled_ShouldEnableModule_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.Enabled.PowerRename);
};
// act
viewModel.IsEnabled = true;
}
[TestMethod]
public void MRUEnabled_ShouldSetValue2True_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
PowerRenameSettingsIPCMessage snd = JsonSerializer.Deserialize<PowerRenameSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.PowerRename.Properties.MRUEnabled.Value);
};
// act
viewModel.MRUEnabled = true;
}
[TestMethod]
public void WhenIsEnabledIsOffAndMRUEnabledIsOffGlobalAndMruShouldBeOff()
{
PowerRenameViewModel viewModel = new PowerRenameViewModel();
ShellPage.DefaultSndMSGCallback = msg => { };
viewModel.IsEnabled = false;
viewModel.MRUEnabled = false;
Assert.IsFalse(viewModel.GlobalAndMruEnabled);
}
[TestMethod]
public void WhenIsEnabledIsOffAndMRUEnabledIsOnGlobalAndMruShouldBeOff()
{
PowerRenameViewModel viewModel = new PowerRenameViewModel();
ShellPage.DefaultSndMSGCallback = msg => { };
viewModel.IsEnabled = false;
viewModel.MRUEnabled = true;
Assert.IsFalse(viewModel.GlobalAndMruEnabled);
}
[TestMethod]
public void WhenIsEnabledIsOnAndMRUEnabledIsOffGlobalAndMruShouldBeOff()
{
PowerRenameViewModel viewModel = new PowerRenameViewModel();
ShellPage.DefaultSndMSGCallback = msg => { };
viewModel.IsEnabled = true;
viewModel.MRUEnabled = false;
Assert.IsFalse(viewModel.GlobalAndMruEnabled);
}
[TestMethod]
public void WhenIsEnabledIsOnAndMRUEnabledIsOnGlobalAndMruShouldBeOn()
{
PowerRenameViewModel viewModel = new PowerRenameViewModel();
ShellPage.DefaultSndMSGCallback = msg => { };
viewModel.IsEnabled = true;
viewModel.MRUEnabled = true;
Assert.IsTrue(viewModel.GlobalAndMruEnabled);
}
[TestMethod]
public void EnabledOnContextMenu_ShouldSetValue2True_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
PowerRenameSettingsIPCMessage snd = JsonSerializer.Deserialize<PowerRenameSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.PowerRename.Properties.ShowIcon.Value);
};
// act
viewModel.EnabledOnContextMenu = true;
}
[TestMethod]
public void EnabledOnContextExtendedMenu_ShouldSetValue2True_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
PowerRenameSettingsIPCMessage snd = JsonSerializer.Deserialize<PowerRenameSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.PowerRename.Properties.ShowIcon.Value);
};
// act
viewModel.EnabledOnContextMenu = true;
}
[TestMethod]
public void RestoreFlagsOnLaunch_ShouldSetValue2True_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
PowerRenameSettingsIPCMessage snd = JsonSerializer.Deserialize<PowerRenameSettingsIPCMessage>(msg);
Assert.IsTrue(snd.Powertoys.PowerRename.Properties.PersistState.Value);
};
// act
viewModel.RestoreFlagsOnLaunch = true;
}
[TestMethod]
public void MaxDispListNum_ShouldSetMaxSuggListTo20_WhenSuccessful()
{
// arrange
PowerRenameViewModel viewModel = new PowerRenameViewModel();
// Assert
ShellPage.DefaultSndMSGCallback = msg =>
{
PowerRenameSettingsIPCMessage snd = JsonSerializer.Deserialize<PowerRenameSettingsIPCMessage>(msg);
Assert.AreEqual(20, snd.Powertoys.PowerRename.Properties.MaxMRUSize.Value);
};
// act
viewModel.MaxDispListNum = 20;
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
}
}

View File

@@ -1,130 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ViewModelTests
{
[TestClass]
public class ShortcutGuide
{
private const string ModuleName = "Shortcut Guide";
[TestInitialize]
public void Setup()
{
// initialize creation of test settings file.
// Test base path:
// C:\Users\<user name>\AppData\Local\Packages\08e1807b-8b6d-4bfa-adc4-79c64aae8e78_9abkseg265h2m\LocalState\Microsoft\PowerToys\
GeneralSettings generalSettings = new GeneralSettings();
ShortcutGuideSettings shortcutGuide = new ShortcutGuideSettings();
SettingsUtils.SaveSettings(generalSettings.ToJsonString());
SettingsUtils.SaveSettings(shortcutGuide.ToJsonString(), shortcutGuide.Name);
}
[TestCleanup]
public void CleanUp()
{
// delete folder created.
string generalSettings_file_name = string.Empty;
if (SettingsUtils.SettingsFolderExists(generalSettings_file_name))
{
DeleteFolder(generalSettings_file_name);
}
if (SettingsUtils.SettingsFolderExists(ModuleName))
{
DeleteFolder(ModuleName);
}
}
public void DeleteFolder(string powertoy)
{
Directory.Delete(Path.Combine(SettingsUtils.LocalApplicationDataFolder(), $"Microsoft\\PowerToys\\{powertoy}"), true);
}
[TestMethod]
public void IsEnabled_ShouldEnableModule_WhenSuccessful()
{
// Arrange
ShortcutGuideViewModel viewModel = new ShortcutGuideViewModel();
// Assert
// Initialize mock function of sending IPC message.
ShellPage.DefaultSndMSGCallback = msg =>
{
OutGoingGeneralSettings snd = JsonSerializer.Deserialize<OutGoingGeneralSettings>(msg);
Assert.IsTrue(snd.GeneralSettings.Enabled.ShortcutGuide);
};
// Act
viewModel.IsEnabled = true;
}
[TestMethod]
public void ThemeIndex_ShouldSetThemeToDark_WhenSuccessful()
{
// Arrange
ShortcutGuideViewModel viewModel = new ShortcutGuideViewModel();
Assert.AreEqual(1, viewModel.ThemeIndex);
// Assert
// Initialize mock function of sending IPC message.
ShellPage.DefaultSndMSGCallback = msg =>
{
ShortcutGuideSettingsIPCMessage snd = JsonSerializer.Deserialize<ShortcutGuideSettingsIPCMessage>(msg);
Assert.AreEqual("dark", snd.Powertoys.ShortcutGuide.Properties.Theme.Value);
};
// Act
viewModel.ThemeIndex = 0;
}
[TestMethod]
public void PressTime_ShouldSetPressTimeToOneHundred_WhenSuccessful()
{
// Arrange
ShortcutGuideViewModel viewModel = new ShortcutGuideViewModel();
Assert.AreEqual(900, viewModel.PressTime);
// Assert
// Initialize mock function of sending IPC message.
ShellPage.DefaultSndMSGCallback = msg =>
{
ShortcutGuideSettingsIPCMessage snd = JsonSerializer.Deserialize<ShortcutGuideSettingsIPCMessage>(msg);
Assert.AreEqual(100, snd.Powertoys.ShortcutGuide.Properties.PressTime.Value);
};
// Act
viewModel.PressTime = 100;
}
[TestMethod]
public void OverlayOpacity_ShouldSeOverlayOpacityToOneHundred_WhenSuccessful()
{
// Arrange
ShortcutGuideViewModel viewModel = new ShortcutGuideViewModel();
Assert.AreEqual(90, viewModel.OverlayOpacity);
// Assert
// Initialize mock function of sending IPC message.
ShellPage.DefaultSndMSGCallback = msg =>
{
ShortcutGuideSettingsIPCMessage snd = JsonSerializer.Deserialize<ShortcutGuideSettingsIPCMessage>(msg);
// Serialisation not working as expected in the test project:
Assert.AreEqual(100, snd.Powertoys.ShortcutGuide.Properties.OverlayOpacity.Value);
};
// Act
viewModel.OverlayOpacity = 100;
}
}
}