diff --git a/src/BuildTools.sln b/src/BuildTools.sln index 49cb0b4666..f6fd7339dd 100644 --- a/src/BuildTools.sln +++ b/src/BuildTools.sln @@ -4,8 +4,6 @@ VisualStudioVersion = 15.0.26730.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.Build.Tasks", "Microsoft.DotNet.Build.Tasks\Microsoft.DotNet.Build.Tasks.csproj", "{17C66BCE-EB35-44CA-893C-8AAFB67708E9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xunit.console.netcore", "xunit.console.netcore\xunit.console.netcore.csproj", "{83FC1994-BCE0-427A-803B-02F20233A2D1}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{8B5A7D0F-2BD5-4892-9662-8FDC3589D938}" ProjectSection(SolutionItems) = preProject .nuget\packages.Unix.config = .nuget\packages.Unix.config @@ -27,8 +25,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scripts", "scripts", "{DEEA Scripts\set-package-build.cmd = Scripts\set-package-build.cmd EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xunit.netcore.extensions", "xunit.netcore.extensions\xunit.netcore.extensions.csproj", "{BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Cci.Extensions", "Microsoft.Cci.Extensions\Microsoft.Cci.Extensions.csproj", "{2179F9B5-1DBA-4563-9402-A94DE75EA9FA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenAPI", "GenAPI\GenAPI.csproj", "{E5BBF3AB-61AF-48FB-B105-799868C410C3}" @@ -41,8 +37,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.Build.Clou EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.CodeAnalysis", "Microsoft.DotNet.CodeAnalysis\Microsoft.DotNet.CodeAnalysis.csproj", "{0847DEA9-C368-4C4D-BE57-EF4D244493C5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xunit.console.uwp", "xunit.console.uwp\xunit.console.uwp.csproj", "{36219AA4-D36A-4CB4-9C7B-FB48641D411A}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.VersionTools", "Microsoft.DotNet.VersionTools\Microsoft.DotNet.VersionTools.csproj", "{8D524FA5-A8C5-4EBD-BA8B-2A4FED03EE58}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.Build.VstsBuildsApi", "Microsoft.DotNet.Build.VSTSBuildsApi\Microsoft.DotNet.Build.VstsBuildsApi.csproj", "{DD658734-88B2-48AD-8ADC-69D5C5798D9B}" @@ -95,42 +89,6 @@ Global {17C66BCE-EB35-44CA-893C-8AAFB67708E9}.Release|x64.ActiveCfg = Release|Any CPU {17C66BCE-EB35-44CA-893C-8AAFB67708E9}.Release|x64.Build.0 = Release|Any CPU {17C66BCE-EB35-44CA-893C-8AAFB67708E9}.Release|x86.ActiveCfg = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|ARM.ActiveCfg = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|x64.ActiveCfg = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|x64.Build.0 = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Debug|x86.ActiveCfg = Debug|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|Any CPU.Build.0 = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|ARM.ActiveCfg = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|x64.ActiveCfg = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|x64.Build.0 = Release|Any CPU - {83FC1994-BCE0-427A-803B-02F20233A2D1}.Release|x86.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|ARM.ActiveCfg = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|ARM.Build.0 = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|x64.ActiveCfg = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|x64.Build.0 = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|x86.ActiveCfg = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Debug|x86.Build.0 = Debug|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|Any CPU.Build.0 = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|ARM.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|ARM.Build.0 = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|x64.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|x64.Build.0 = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|x86.ActiveCfg = Release|Any CPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A}.Release|x86.Build.0 = Release|Any CPU {2179F9B5-1DBA-4563-9402-A94DE75EA9FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2179F9B5-1DBA-4563-9402-A94DE75EA9FA}.Debug|Any CPU.Build.0 = Debug|Any CPU {2179F9B5-1DBA-4563-9402-A94DE75EA9FA}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -245,26 +203,6 @@ Global {0847DEA9-C368-4C4D-BE57-EF4D244493C5}.Release|x64.Build.0 = Release|Any CPU {0847DEA9-C368-4C4D-BE57-EF4D244493C5}.Release|x86.ActiveCfg = Release|Any CPU {0847DEA9-C368-4C4D-BE57-EF4D244493C5}.Release|x86.Build.0 = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|ARM.ActiveCfg = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|ARM.Build.0 = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|x64.ActiveCfg = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|x64.Build.0 = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|x86.ActiveCfg = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Debug|x86.Build.0 = Debug|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|Any CPU.Build.0 = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|ARM.ActiveCfg = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|ARM.Build.0 = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|x64.ActiveCfg = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|x64.Build.0 = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|x86.ActiveCfg = Release|Any CPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A}.Release|x86.Build.0 = Release|Any CPU {8D524FA5-A8C5-4EBD-BA8B-2A4FED03EE58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8D524FA5-A8C5-4EBD-BA8B-2A4FED03EE58}.Debug|Any CPU.Build.0 = Debug|Any CPU {8D524FA5-A8C5-4EBD-BA8B-2A4FED03EE58}.Debug|ARM.ActiveCfg = Debug|Any CPU diff --git a/src/Microsoft.xunit.extensibility.execution.netcore/Microsoft.xunit.extensibility.execution.netcore.depproj b/src/Microsoft.xunit.extensibility.execution.netcore/Microsoft.xunit.extensibility.execution.netcore.depproj deleted file mode 100644 index 900aab273c..0000000000 --- a/src/Microsoft.xunit.extensibility.execution.netcore/Microsoft.xunit.extensibility.execution.netcore.depproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - - 4.0.0.0 - Library - .NETStandard,Version=v1.3 - any - - - - - - - - - - \ No newline at end of file diff --git a/src/Microsoft.xunit.extensibility.execution.netcore/project.json b/src/Microsoft.xunit.extensibility.execution.netcore/project.json deleted file mode 100644 index 42c15c6102..0000000000 --- a/src/Microsoft.xunit.extensibility.execution.netcore/project.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "dependencies": { - "xunit.extensibility.execution": "2.1.0", - }, - "frameworks": { - "netstandard1.3": { - "imports": "portable-net45+win8" - } - }, - "runtimes": { - "any": {} - } -} diff --git a/src/WindowsStoreAppLauncher/App.h b/src/WindowsStoreAppLauncher/App.h deleted file mode 100644 index 807a2a7416..0000000000 --- a/src/WindowsStoreAppLauncher/App.h +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include -#include -using namespace std; - -class App -{ -public: - virtual ~App() - {} - virtual void Add() = 0; - virtual void Remove() = 0; - - virtual void Start(bool runInBackground, bool testApp, const wstring& executionArgs) = 0; - virtual void Start(bool runInBackground, bool testApp) = 0; - virtual void Stop() = 0; - virtual DWORD WaitForExit() = 0; - virtual DWORD WaitForExit(DWORD milliseconds, bool* result) = 0; - - virtual void EnableDebug(const wstring& debuggerCommandLine) = 0; - virtual void DisableDebug() = 0; - - virtual wstring GetAppStdOutContent() = 0; - virtual DWORD GetAppExitCode() = 0; - virtual wstring get_PackageFullName() const throw() = 0; -}; \ No newline at end of file diff --git a/src/WindowsStoreAppLauncher/AppxApp.cpp b/src/WindowsStoreAppLauncher/AppxApp.cpp deleted file mode 100644 index eafcc27adf..0000000000 --- a/src/WindowsStoreAppLauncher/AppxApp.cpp +++ /dev/null @@ -1,427 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" -#include "AppxApp.h" -#include "Support.h" -#include "Stream.h" - - -using namespace std; -using namespace ABI::Windows::ApplicationModel::Activation; -using namespace ABI::Windows::Management::Deployment; -using namespace ABI::Windows::Foundation; -using namespace Microsoft::WRL; - -typedef -unique_ptr -unique_char_array; - -void unique_char_deleter(wchar_t* arr) -{ - delete [] arr; -} - -AppxApp::AppxApp(const wstring& mainfestPath, const wstring& appId) -:m_manifestPath(mainfestPath), m_appId(appId), m_hProcess(nullptr) -{ - // Get the full path to the appx manifest file - unique_ptr manifestFullPath(reinterpret_cast(malloc(MAX_PATH * sizeof(wchar_t))), free); - IFT(GetFullPathName(m_manifestPath.c_str(), MAX_PATH, manifestFullPath.get(), nullptr) != 0 ? S_OK : HRESULT_FROM_WIN32(GetLastError())); - m_manifestPath = manifestFullPath.get(); - - // Create AppxFactory - dprintf("Creating AppxFactory...\n"); - ComPtr appxFactory; - IFT(CoCreateInstance(__uuidof(AppxFactory), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&appxFactory))); - - // Create IStream for Appx manifest file - dprintf("Creating Stream...\n"); - ComPtr appxManifestPathStream = Make(m_manifestPath); - - // Read the AppXManifest.xml file - dprintf("Creating Manifest Reader...\n"); - ComPtr appxManifestReader; - IFT(appxFactory->CreateManifestReader(appxManifestPathStream.Get(), &appxManifestReader)); - - dprintf("Creating PackageID...\n"); - // Get the AppxManifestPackageId - ComPtr appxManifestPackageId; - IFT(appxManifestReader->GetPackageId(&appxManifestPackageId)); - - dprintf("Getting Package Full Name...\n"); - // Get the package full name - LPWSTR packageId; - IFT(appxManifestPackageId->GetPackageFullName(&packageId)); - m_packageId = packageId; - dwprintf(L"%s\n", m_packageId.c_str()); - - dprintf("Getting Package Family Name...\n"); - // Get the package family name - LPWSTR packageFamilyName; - IFT(appxManifestPackageId->GetPackageFamilyName(&packageFamilyName)); - m_packageFamilyName = packageFamilyName; - dwprintf(L"%s\n", m_packageFamilyName.c_str()); - - if (m_appId.empty()) // If App Id is empty get it from the manifest file - { - ComPtr appxManifestApplicationsEnumerator; - ComPtr appxManifestApplication; - BOOL hasCurrent; - LPWSTR appUserModelId; - - dprintf("Getting Applications...\n"); - IFT(appxManifestReader->GetApplications(&appxManifestApplicationsEnumerator)); - IFT(appxManifestApplicationsEnumerator->GetHasCurrent(&hasCurrent)); - - // If the enumerator is empty can't choose a default app - if (!hasCurrent) - { - throw com_error(E_INVALIDARG); - } - - IFT(appxManifestApplicationsEnumerator->GetCurrent(&appxManifestApplication)); - IFT(appxManifestApplicationsEnumerator->MoveNext(&hasCurrent)); - - // If the enumerator has more than one item it is ambiguous what app to choose - if (hasCurrent) - { - throw com_error(E_INVALIDARG); - } - - dprintf("Getting UserModelId...\n"); - IFT(appxManifestApplication->GetAppUserModelId(&appUserModelId)); - m_appId = appUserModelId; - } - else // Else prepend the package family name to the supplied App Id - { - dprintf("Getting UserModelId...\n"); - m_appId = m_packageFamilyName + L"!" + m_appId; - } - dwprintf(L"%s\n", m_appId.c_str()); -} - -AppxApp::~AppxApp() -{ - if (m_hProcess != nullptr) - { - CloseHandle(m_hProcess); - } -} - -const wstring& AppxApp::get_ManifestPath() const throw() -{ - return m_manifestPath; -} - -const wstring& AppxApp::get_PackageId() const throw() -{ - return m_packageId; -} - -const wstring& AppxApp::get_PackageFamilyName() const throw() -{ - return m_packageFamilyName; -} - -wstring AppxApp::get_PackageFullName() const throw() -{ - return m_packageId; -} - -typedef BOOL(WINAPI *fn_AssignProcessToJobObject)(_In_ HANDLE hJob, _In_ HANDLE hProcess); -typedef HANDLE(WINAPI *fn_OpenJobObject)(_In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandles, _In_ LPCWSTR lpName); -typedef DWORD(WINAPI *fn_GetProcessImageFileName)(_In_ HANDLE hProcess, _Out_ LPWSTR lpImageFileName, _In_ DWORD nSize); -typedef DWORD(WINAPI *fn_GetEnvironmentVariable)(_In_opt_ LPCWSTR lpName, _Out_opt_ LPWSTR lpBuffer, _In_ DWORD nSize); - -fn_AssignProcessToJobObject p_AssignProcessToJobObject; -fn_OpenJobObject p_OpenJobObject; -fn_GetProcessImageFileName p_GetProcessImageFileName; -fn_GetEnvironmentVariable p_GetEnvironmentVariable; - - -void ProcessSmartyJob(HANDLE hProcess, const wchar_t* manifestPath) -{ - unique_ptr::type, decltype(&FreeLibrary)> kernel32(LoadLibraryEx(L"kernel32.dll", NULL, NULL), &FreeLibrary); - if (kernel32.get() == NULL) - return; - unique_ptr::type, decltype(&FreeLibrary)> psapi(LoadLibraryEx(L"api-ms-win-core-psapi-l1-1-0.dll", NULL, NULL), &FreeLibrary); - if (psapi.get() == NULL) - return; - unique_ptr::type, decltype(&FreeLibrary)> procEnv(LoadLibraryEx(L"api-ms-win-core-processenvironment-l1-2-0.dll", NULL, NULL), &FreeLibrary); - if (procEnv.get() == NULL) - return; - p_OpenJobObject = (fn_OpenJobObject) GetProcAddress(kernel32.get(), "OpenJobObject"); - p_AssignProcessToJobObject = (fn_AssignProcessToJobObject) GetProcAddress(kernel32.get(), "AssignProcessToJobObjectW"); - p_GetProcessImageFileName = (fn_GetProcessImageFileName) GetProcAddress(psapi.get(), "K32GetProcessImageFileNameW"); - p_GetEnvironmentVariable = (fn_GetEnvironmentVariable) GetProcAddress(procEnv.get(), "GetEnvironmentVariableW"); - auto varName = L"SMARTY_JOB_ID"; - DWORD sizeNeeded = (*p_GetEnvironmentVariable)(varName, nullptr, 0); - if (sizeNeeded == 0) - { - DWORD err = GetLastError(); - if (err == ERROR_ENVVAR_NOT_FOUND) - { - return; - } - else - { - auto msg = MessageForHR(HRESULT_FROM_WIN32(err)); - fwprintf(stderr, L"Error reading environment:\n%s\n", msg.c_str()); - throw runtime_error(string(msg.begin(), msg.end())); - } - } - unique_char_array smartyJobId(new wchar_t[sizeNeeded], unique_char_deleter); - DWORD size = (*p_GetEnvironmentVariable)(L"SMARTY_JOB_ID", smartyJobId.get(), sizeNeeded); - if (size == 0) - { - DWORD err = GetLastError(); - if (err == ERROR_ENVVAR_NOT_FOUND) - return; - else - { - fwprintf(stderr, L"Error reading environment:\n%s\n", MessageForHR(HRESULT_FROM_WIN32(err)).c_str()); - return; - } - } - unique_char_array appxProcessFileName(new wchar_t[MAX_PATH], unique_char_deleter); - if ((*p_GetProcessImageFileName)(hProcess, appxProcessFileName.get(), MAX_PATH) == 0) - { - fwprintf(stderr, L"Error getting process file name:\n%s\n", MessageForHR(HRESULT_FROM_WIN32(GetLastError())).c_str()); - return; - } - HRESULT hr = PathCchRemoveFileSpec(appxProcessFileName.get(), MAX_PATH); - if (FAILED(hr)) - { - fwprintf(stderr, L"Error processing path:\n%s\n", MessageForHR(hr).c_str()); - return; - } - unique_char_array manifestDirectory(new wchar_t[MAX_PATH], unique_char_deleter); - wcscpy_s(manifestDirectory.get(), MAX_PATH, manifestPath); - hr = PathCchRemoveFileSpec(manifestDirectory.get(), MAX_PATH); - if (FAILED(hr)) - { - fwprintf(stderr, L"Error processing path:\n%s\n", MessageForHR(hr).c_str()); - return; - } - if (wcscmp(appxProcessFileName.get(), manifestDirectory.get()) == 0) - { - // handle is the appx process handle - // and SMARTY_JOB_ID is set - HANDLE tmp = (*p_OpenJobObject)(JOB_OBJECT_ASSIGN_PROCESS, FALSE, smartyJobId.get()); - if (tmp == NULL) - { - fwprintf(stderr, L"Error opening job object %s:\n%s\n", smartyJobId.get(), MessageForHR(HRESULT_FROM_WIN32(GetLastError())).c_str()); - return; - } - unique_ptr < void, add_pointer::type> jobHandle(tmp, &CloseHandle); - BOOL ret = (*p_AssignProcessToJobObject)(jobHandle.get(), hProcess); - if (ret == 0) - { - fwprintf(stderr, L"Error assigning appx process to job:\n%s\n%s\n", smartyJobId.get(), MessageForHR(HRESULT_FROM_WIN32(GetLastError())).c_str()); - return; - } - } -} - -void AppxApp::InitStdoutFile(bool testApp) -{ - if (testApp) - { - wstring appContainerPath = GetAppContainerFolderPath(); - - WIN32_FILE_ATTRIBUTE_DATA stdoutFileAttributeData; - stdoutFile = appContainerPath + L"\\LocalState\\AC\\stdout.txt"; - - // Delete the stdout file if it exists - if (GetFileAttributesEx(stdoutFile.c_str(), ::GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &stdoutFileAttributeData)) - { - if (!DeleteFile(stdoutFile.c_str())) - { - throw com_error(HRESULT_FROM_WIN32(GetLastError())); - } - } - - // ExitCode.txt stores process Exit Code - WIN32_FILE_ATTRIBUTE_DATA exitCodeFileAttributeData; - exitCodeFile = appContainerPath + L"\\AC\\Temp\\exitcode.txt"; - if (GetFileAttributesEx(exitCodeFile.c_str(), ::GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &exitCodeFileAttributeData)) - { - if (!DeleteFile(exitCodeFile.c_str())) - { - throw com_error(HRESULT_FROM_WIN32(GetLastError())); - } - } - } -} - -void AppxApp::Start(bool runInBackground, bool testApp) -{ - Start(runInBackground, testApp, L""); -} - -void AppxApp::Start(bool runInBackground, bool testApp, const wstring& executionArgs) -{ - InitStdoutFile(testApp); - - ComPtr applicationActivationManager = GetApplicationActivationManager(); - DWORD dwProcessId; - - ACTIVATEOPTIONS options = ACTIVATEOPTIONS::AO_NOSPLASHSCREEN; - if (!runInBackground) - options = ACTIVATEOPTIONS::AO_NONE; - - IFT(applicationActivationManager->ActivateApplication(m_appId.c_str(), executionArgs.c_str(), options, &dwProcessId)); - dwprintf(L"Process started, pid: %d\n", dwProcessId); - // Get a process handle to the app - // PROCESS_SET_QUOTA is required for using AssignProcessToJobObject - m_hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_SET_QUOTA, FALSE, dwProcessId); - - if (m_hProcess == nullptr) - { - DWORD openProcessError = GetLastError(); - - // If the error is ERROR_INVALID_PARAMETER then the process exited before we could open a handle to it - if (openProcessError != ERROR_INVALID_PARAMETER) - { - throw com_error(HRESULT_FROM_WIN32(openProcessError)); - } - } - ProcessSmartyJob(m_hProcess, m_manifestPath.c_str()); -} - -void AppxApp::Stop() -{ - if (m_hProcess != nullptr) - { - if (!TerminateProcess(m_hProcess, (UINT) -1)) - { - throw com_error(HRESULT_FROM_WIN32(GetLastError())); - } - } -} - -DWORD AppxApp::WaitForExit() -{ - bool result; - return WaitForExit(INFINITE, &result); -} - -DWORD AppxApp::WaitForExit(DWORD milliseconds, bool* result) -{ - if (m_hProcess == nullptr) - { - throw com_error(E_POINTER); - } - - DWORD waitResult = WaitForSingleObjectEx(m_hProcess, milliseconds, FALSE); - - if (waitResult == WAIT_TIMEOUT) - { - *result = false; - return (DWORD) -1; - } - else if (waitResult != WAIT_FAILED) - { - *result = true; - DWORD exitCode = GetAppExitCode(); - return exitCode; - } - else - { - throw com_error(HRESULT_FROM_WIN32(GetLastError())); - } -} - -void AppxApp::EnableDebug(const wstring& debuggerCommandLine) -{ - if (packageDebugSettings == nullptr) - IFT(CoCreateInstance(CLSID_PackageDebugSettings, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&packageDebugSettings))); - wprintf(L"Package ID is %s\n", m_packageId.c_str()); - IFT(packageDebugSettings->EnableDebugging(m_packageId.c_str(), debuggerCommandLine.empty() ? nullptr : debuggerCommandLine.c_str(), nullptr)); -} - -void AppxApp::DisableDebug() -{ - if (packageDebugSettings == nullptr) - IFT(CoCreateInstance(CLSID_PackageDebugSettings, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&packageDebugSettings))); - IFT(packageDebugSettings->DisableDebugging(m_packageId.c_str())); -} - -// The package must be installed for this to succeed -HRESULT AppxApp::GetAppContainerFolderPathInternal(wchar_t** appContainerFolderPath) -{ - HRESULT hr; - - // Get the app container folder path - PSID tempsid; - IFR(DeriveAppContainerSidFromAppContainerName(m_packageFamilyName.c_str(), &tempsid)); - std::unique_ptr sid(tempsid, &FreeSid); - - wchar_t* tempSidString; - IFR(ConvertSidToStringSid(sid.get(), &tempSidString) ? S_OK : HRESULT_FROM_WIN32(GetLastError())); - std::unique_ptr sidString(tempSidString, LocalFree); - - wchar_t* tempfolderPath; - IFR(::GetAppContainerFolderPath(sidString.get(), &tempfolderPath)); - std::unique_ptr folderPath(tempfolderPath, CoTaskMemFree); - - // Remove the trailing \AC from the path - size_t pathLength = wcslen(folderPath.get()); - - if (pathLength < 3) - { - return E_FAIL; - } - - if (wcscmp(L"\\AC", folderPath.get() + (pathLength - 3)) != 0) - { - return E_FAIL; - } - - folderPath.get()[pathLength - 3] = '\0'; - - *appContainerFolderPath = folderPath.release(); - - return hr; -} - -wstring AppxApp::GetAppStdOutContent() -{ - try - { - wifstream file(stdoutFile); - return wstring((istreambuf_iterator(file)), istreambuf_iterator()); - } - catch (...) - { - return L"(null)"; - } -} - -// Some UI (or Jscript) app couldn't get its exit code directly -// So App itself are supposed to write a file("exitcode.txt") into %temp% folder -// then AppLauncher will fetch its vlaue if this file exists -DWORD AppxApp::GetAppExitCode() -{ - DWORD exitCode; - - // Check exitCode.txt file first - ifstream file(exitCodeFile); - if (file) - { - char content[256]; - memset(content, '\0', 256 * sizeof(char)); - file.getline(content, 256); - exitCode = atoi(content); - wprintf(L"Process exited with return code(from exitcode.txt) %d.\n", exitCode); - } - else - { - if (GetExitCodeProcess(m_hProcess, &exitCode) != 0) - wprintf(L"Process has just exited with return code %d.\n", exitCode); - } - - return exitCode; -} diff --git a/src/WindowsStoreAppLauncher/AppxApp.h b/src/WindowsStoreAppLauncher/AppxApp.h deleted file mode 100644 index c2af1298ae..0000000000 --- a/src/WindowsStoreAppLauncher/AppxApp.h +++ /dev/null @@ -1,94 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include "App.h" -#include "Support.h" -#include -#include -#include -#include -#include - -using namespace ABI::Windows::ApplicationModel::Activation; -using namespace ABI::Windows::Foundation::Internal; -using namespace ABI::Windows::Foundation; -using namespace Microsoft::WRL; -using namespace std; - -class AppxApp : public App -{ -private: - ComPtr packageDebugSettings; - wstring m_manifestPath, m_appId, m_packageId, m_packageFamilyName, stdoutFile, exitCodeFile; - HANDLE m_hProcess; - - - void InitStdoutFile(bool testApp); - HRESULT GetAppContainerFolderPathInternal(wchar_t** appContainerFolderPath); - -protected: - template - void Wait( - IAsyncOperationWithProgress* asyncOperation, - typename GetAbiType::TResult_complex>::type* result) - { - // Create an event so we can wait for the async operation to complete - Event completeEvent(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, WRITE_OWNER | EVENT_ALL_ACCESS)); - IFT(completeEvent.IsValid() ? S_OK : HRESULT_FROM_WIN32(GetLastError())); - - auto completeHandler = Callback> - ([&completeEvent]( - IAsyncOperationWithProgress* asyncOperationWithProgress, - AsyncStatus asyncStatus) - -> HRESULT - { - UNREFERENCED_PARAMETER(asyncOperationWithProgress); - UNREFERENCED_PARAMETER(asyncStatus); - SetEvent(completeEvent.Get()); - return S_OK; - }); - IFT(asyncOperation->put_Completed(completeHandler.Get())); - - // Wait for async operation to complete - IFT(WaitForSingleObjectEx(completeEvent.Get(), INFINITE, FALSE) != WAIT_FAILED ? S_OK : HRESULT_FROM_WIN32(GetLastError())); - - // Check for errors - ComPtr asyncInfo; - HRESULT errorCode; - - IFT(asyncOperation->QueryInterface(__uuidof(IAsyncInfo), &asyncInfo)); - IFT(asyncInfo->get_ErrorCode(&errorCode)); - - IFT(errorCode); - - // Get the result - if (result != nullptr) - { - IFT(asyncOperation->GetResults(result)); - } - } - - - const wstring& get_ManifestPath() const throw(); - const wstring& get_PackageId() const throw(); - const wstring& get_PackageFamilyName() const throw(); - virtual ComPtr GetApplicationActivationManager() = 0; - virtual wstring GetAppContainerFolderPath() const = 0; -public: - AppxApp(const wstring& manifestPath, const wstring& appId); - virtual ~AppxApp(void); - - virtual void Start(bool runInBackground, bool testApp, const wstring& executionArgs) override; - virtual void Start(bool runInBackground, bool testApp) override; - virtual void Stop() override; - virtual DWORD WaitForExit() override; - virtual DWORD WaitForExit(DWORD milliseconds, bool* result) override; - - virtual void EnableDebug(const wstring& debuggerCommandLine) override; - virtual void DisableDebug() override; - virtual wstring GetAppStdOutContent() override; - virtual wstring get_PackageFullName() const throw() override; - virtual DWORD GetAppExitCode() override; -}; diff --git a/src/WindowsStoreAppLauncher/Args.h b/src/WindowsStoreAppLauncher/Args.h deleted file mode 100644 index 1f2d7bb8b2..0000000000 --- a/src/WindowsStoreAppLauncher/Args.h +++ /dev/null @@ -1,509 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include -#include -#include - -using namespace std; - - -struct _Option -{ - virtual const vector& Strings() = 0; - virtual const wstring& Description() = 0; - virtual bool HasParam() = 0; - virtual const wstring& Param() = 0; - virtual void Call(const wstring& arg) = 0; - virtual void Call() = 0; -}; - -template -class Option : public _Option -{ - vector optStrings; - const Function& func; - wstring description; - - Option& operator=(const Option&) = delete; - -public: - Option(vector s, const Function& f, const wstring& desc) :optStrings(move(s)), func(f), description(desc) - { - } - - virtual const vector& Strings() override - { - return optStrings; - } - - virtual const wstring& Description() override - { - return description; - } - - virtual bool HasParam() - { - return false; - } - - virtual const wstring& Param() - { - // this function should never be called - static const wstring empty(L""); - return empty; - } - - virtual void Call(const wstring& arg) override - { - UNREFERENCED_PARAMETER(arg); - } - - virtual void Call() override - { - func(); - } -}; - -template -class ParamOption : public _Option -{ - vector optStrings; - const Function& func; - wstring description; - wstring paramName; - - ParamOption& operator=(const ParamOption&) = delete; - -public: - - ParamOption(vector s, const wstring& param, const Function& f, const wstring& desc) :optStrings(move(s)), func(f), description(desc), paramName(param) - { - } - - virtual const vector& Strings() override - { - return optStrings; - } - - virtual const wstring& Description() override - { - return description; - } - - virtual bool HasParam() - { - return true; - } - - virtual const wstring& Param() - { - return paramName; - } - - virtual void Call(const wstring& arg) override - { - func(arg); - } - - virtual void Call() override - { - } -}; - -template -_Option* make_option(vector s, const Function& f, const wstring& desc) -{ - return (_Option*)new Option(s, f, desc); -} - -template -_Option* make_option(vector s, const wstring& param, const Function& f, const wstring& desc) -{ - return (_Option*)new ParamOption(s, param, f, desc); -} - -class OptionList -{ - vector> options; - wstring exeName; - wstring positionalArgs; - wstring positionalArgInfo; - -public: - - OptionList(const wstring& exe, const wstring& positionalArgs, const wstring& positionalArgInfo) :exeName(exe), positionalArgs(positionalArgs), positionalArgInfo(positionalArgInfo) - { - } - - template - void Add(vector s, const Function& f, const wstring& desc) - { - Add(make_option(s, f, desc)); - } - - template - void Add(vector s, const wstring& param, const Function& f, const wstring& desc) - { - Add(make_option(s, param, f, desc)); - } - - void Add(_Option* option) - { - options.push_back(unique_ptr<_Option>(option)); - } - - wstring UsageShort() - { - wstringstream ret; - for (const unique_ptr<_Option>& option : options) - { - ret << L" ["; - bool first = true; - for (auto str : option->Strings()) - { - if (first) - first = false; - else - ret << L"|"; - ret << L"[-" << str << L"]"; - } - if (option->HasParam()) - ret << L" <" << option->Param() << L">"; - ret << L"]"; - } - return ret.str(); - } - - wstring UsageLong() - { - wstringstream ret; - for (const unique_ptr<_Option>& option : options) - { - ret << L"\t"; - bool first = true; - for (auto str : option->Strings()) - { - if (first) - first = false; - else - ret << L", "; - ret << L"-" << str; - } - if (option->HasParam()) - ret << L" <" << option->Param() << L">"; - ret << L"\n\t\t" << option->Description() << L"\n"; - } - return ret.str(); - } - - wstring Usage() - { - return exeName + L" " + UsageShort() + L" " + positionalArgs + L"\n\nOptions:\n" + UsageLong() + L"\nArguments:\n" + positionalArgInfo; - } - - template - wchar_t** Parse(int argc, wchar_t** argv, ErrorFunction onError) - { - if (argc == 0) - return argv; - if ((*argv)[0] != '-' && (*argv)[0] != '/') - return argv; - if (_Parse(&argc, &argv, onError)) - { - return Parse(argc, argv, onError); - } - else - { - return argv; - } - } - - void PrintUsage() - { - wprintf(L"%s", Usage().c_str()); - } -private: - template - bool _Parse(int* argc, wchar_t*** argv, ErrorFunction onError) - { - for (const unique_ptr<_Option>& option : options) - { - if (argc == 0) - return false; - wchar_t* curParam = **argv; - for (auto str : option->Strings()) - { - if (str.compare(curParam + 1) == 0) - { - if (option->HasParam()) - { - if (*argc < 2) - { - onError(str); - return false; - } - option->Call(*(*argv + 1)); - *argv += 2; - *argc -= 2; - return true; - } - else - { - option->Call(); - *argv += 1; - *argc -= 1; - return true; - } - } - } - } - return false; - } -}; - -/* -template -struct OptionWithParam -{ - OptionWithParam(vector s, const T& f) :optStrings(move(s)), func(f) - { - } - OptionWithParam& withDescription(wstring desc, wstring paramName) - { - description = desc; - this->paramName = paramName; - return *this; - } - vector optStrings; - const T& func; - wstring description; - wstring paramName; -};*/ - -/* -template -struct OptionList; - -wstring _Usage(OptionList<>* list); - -template <> -struct OptionList<> -{ - template - wchar_t** Parse(int argc, wchar_t** argv, err) - { - return argv; - } - wstring Usage() - { - return _Usage(this); - } - void PrintUsage() - { - wprintf(L"%s", Usage().c_str()); - } - OptionList<>& withInfo(const wstring& exeName, const wstring& positionalArgs, const wstring& positionalArgInfo) - { - this->exeName = exeName; - this->positionalArgs = positionalArgs; - this->positionalArgInfo = positionalArgInfo; - return *this; - } -protected: - template - bool _Parse(int& argc, wchar_t**& argv, err) - { - return false; - } - virtual wstring UsageLong() - { - return L""; - } - virtual wstring UsageShort() - { - return L""; - } - wstring exeName; - wstring positionalArgs; - wstring positionalArgInfo; - friend wstring _Usage(OptionList<>* list); -}; - - -template -struct OptionList, Tail...> : public OptionList -{ - OptionList(Option c, Tail... t) : OptionList(t...), curOpt(c) - {} - template - wchar_t** Parse(int argc, wchar_t** argv, err onError) - { - if (argc == 0) - return argv; - if ((*argv)[0] != '-' && (*argv)[0] != '/') - return argv; - if (_Parse(argc, argv, onError)) - { - return Parse(argc, argv, onError); - } - else - { - return argv; - } - } - OptionList, Tail...>& withInfo(const wstring& exeName, const wstring& positionalArgs, const wstring& positionalArgInfo) - { - this->exeName = exeName; - this->positionalArgs = positionalArgs; - this->positionalArgInfo = positionalArgInfo; - return *this; - } - wstring Usage() - { - return _Usage(this); - } - void PrintUsage() - { - wprintf(L"%s", Usage().c_str()); - } -protected: - template - bool _Parse(int& argc, wchar_t**& argv, err onError) - { - if (argc == 0) - return false; - wchar_t* curParam = *argv; - for (auto opt : curOpt.optStrings) - { - if (opt.compare(curParam + 1) == 0) - { - curOpt.func(); - argv += 1; - argc -= 1; - return true; - } - } - return __super::_Parse(argc, argv, onError); - } - virtual wstring UsageLong() override - { - wstring ret = L"\t"; - bool first = true; - for (auto opt : curOpt.optStrings) - { - if (first) - first = false; - else - ret += L", "; - ret += L"-" + opt; - } - ret += L"\n\t\t" + curOpt.description + L"\n"; - return ret + __super::UsageLong(); - } - virtual wstring UsageShort() override - { - wstring ret = L" ["; - bool first = true; - for (auto opt : curOpt.optStrings) - { - if (first) - first = false; - else - ret += L"|"; - ret += L"[-" + opt + L"]"; - } - return ret + L"]" + __super::UsageShort(); - } -private: - Option curOpt; -}; - -template -struct OptionList, Tail...> : public OptionList -{ - OptionList(OptionWithParam c, Tail... t) : OptionList(t...), curOpt(c) - {} - template - wchar_t** Parse(int argc, wchar_t** argv, err onError) - { - if (argc == 0) - return argv; - if ((*argv)[0] != '-' && (*argv)[0] != '/') - return argv; - if (_Parse(argc, argv, onError)) - { - return Parse(argc, argv, onError); - } - else - { - return argv; - } - } - OptionList, Tail...>& withInfo(const wstring& exeName, const wstring& positionalArgs, const wstring& positionalArgInfo) - { - this->exeName = exeName; - this->positionalArgs = positionalArgs; - this->positionalArgInfo = positionalArgInfo; - return *this; - } - wstring Usage() - { - return _Usage(this); - } - void PrintUsage() - { - wprintf(L"%s", Usage().c_str()); - } -protected: - template - bool _Parse(int& argc, wchar_t**& argv, err onError) - { - if (argc == 0) - return false; - wchar_t* curParam = *argv; - for (auto opt : curOpt.optStrings) - { - if (opt.compare(curParam + 1) == 0) - { - if (argc < 2) - { - onError(opt); - return false; - } - curOpt.func(*(argv + 1)); - argv += 2; - argc -= 2; - return true; - } - } - return __super::_Parse(argc, argv, onError); - } -private: - OptionWithParam curOpt; -}; - -template -OptionList option_list(List... opts) -{ - return OptionList(opts...); -} - -template -Option make_opt(vector s, const Func& f) -{ - return Option(s, f); -} - -template -OptionWithParam make_arg(vector s, const Func& f) -{ - return OptionWithParam(s, f); -} - -wstring _Usage(OptionList<>* list) -{ - return list->exeName + L" " + list->UsageShort() + L" " + list->positionalArgs + L"\n\nOptions:\n" + list->UsageLong() + L"\nArguments:\n" + list->positionalArgInfo; -}*/ diff --git a/src/WindowsStoreAppLauncher/Stream.cpp b/src/WindowsStoreAppLauncher/Stream.cpp deleted file mode 100644 index fbc5ebc3a9..0000000000 --- a/src/WindowsStoreAppLauncher/Stream.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" -#include "Stream.h" -#include "Support.h" - -#pragma warning(disable:4100) // unreferenced formal parameter - -Stream::Stream(const wstring& name) : name(name) -{ - file = shared_ptr(CreateFile(name.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), CloseHandle); -} - -Stream::Stream(shared_ptr f, const wstring& name) : name(name), file(f) -{ -} - -HRESULT STDMETHODCALLTYPE Stream::Read( - /* [annotation] */ - _Out_writes_bytes_to_(cb, *pcbRead) void *pv, - /* [annotation][in] */ - _In_ ULONG cb, - /* [annotation] */ - _Out_opt_ ULONG *pcbRead) -{ - dprintf("Read called...\n"); - ReadFile(file.get(), pv, cb, pcbRead, NULL); - return HRESULT_FROM_WIN32(GetLastError()); -} - -HRESULT STDMETHODCALLTYPE Stream::Write( - /* [annotation] */ - _In_reads_bytes_(cb) const void *pv, - /* [annotation][in] */ - _In_ ULONG cb, - /* [annotation] */ - _Out_opt_ ULONG *pcbWritten) -{ - dprintf("Write called...\n"); - return NTE_NOT_SUPPORTED; -} -HRESULT STDMETHODCALLTYPE Stream::Seek( - /* [in] */ LARGE_INTEGER dlibMove, - /* [in] */ DWORD dwOrigin, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *plibNewPosition) -{ - dprintf("Seek called... dlibMove: %lli dwOrigin: %u\n", dlibMove.QuadPart, dwOrigin); - LONG high = dlibMove.HighPart; - dprintf("Low : %u\n", dlibMove.LowPart); - dprintf("High : %i\n", high); - dprintf("Move method : %u\n", dwOrigin); - DWORD low = SetFilePointer(file.get(), dlibMove.LowPart, &high, dwOrigin); - HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); - if (SUCCEEDED(hr) && plibNewPosition) - { - plibNewPosition->HighPart = high; - plibNewPosition->LowPart = low; - } - if (FAILED(hr)) - { - dprintf("%S FAILED(0x%x) %S: %i\n%s\n", "SetFilePointer", hr, __FILE__, __LINE__, MessageForHR(hr).c_str()); \ - } - return hr; -} -HRESULT STDMETHODCALLTYPE Stream::SetSize( - /* [in] */ ULARGE_INTEGER libNewSize) -{ - dprintf("SetSize called...\n"); - return NTE_NOT_SUPPORTED; -} - -HRESULT STDMETHODCALLTYPE Stream::CopyTo( - /* [annotation][unique][in] */ - _In_ IStream *pstm, - /* [in] */ ULARGE_INTEGER cb, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *pcbRead, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *pcbWritten) -{ - dprintf("CopyTo called...\n"); - return NTE_NOT_SUPPORTED; -} - -HRESULT STDMETHODCALLTYPE Stream::Commit( - /* [in] */ DWORD grfCommitFlags) -{ - dprintf("Commit called...\n"); - return S_OK; -} - -HRESULT STDMETHODCALLTYPE Stream::Revert(void) -{ - dprintf("Revert called...\n"); - return S_OK; -} - -HRESULT STDMETHODCALLTYPE Stream::LockRegion( - /* [in] */ ULARGE_INTEGER libOffset, - /* [in] */ ULARGE_INTEGER cb, - /* [in] */ DWORD dwLockType) -{ - dprintf("LockRegion called...\n"); - return NTE_NOT_SUPPORTED; -} - -HRESULT STDMETHODCALLTYPE Stream::UnlockRegion( - /* [in] */ ULARGE_INTEGER libOffset, - /* [in] */ ULARGE_INTEGER cb, - /* [in] */ DWORD dwLockType) -{ - dprintf("UnlockRegion called...\n"); - return NTE_NOT_SUPPORTED; -} - -HRESULT STDMETHODCALLTYPE Stream::Stat( - /* [out] */ __RPC__out STATSTG *pstatstg, - /* [in] */ DWORD grfStatFlag) -{ - dprintf("Stat called... grdStatFlag : %u\n", grfStatFlag); - if (!pstatstg) - return E_POINTER; - if (grfStatFlag != STATFLAG_NONAME) - { - return NTE_NOT_SUPPORTED; - } - pstatstg->type = STGTY_STORAGE; - DWORD high; - DWORD low = GetFileSize(file.get(), &high); - if (low == INVALID_FILE_SIZE) - return HRESULT_FROM_WIN32(GetLastError()); - pstatstg->cbSize.LowPart = low; - pstatstg->cbSize.HighPart = high; - DWORD err = GetFileTime(file.get(), &pstatstg->ctime, &pstatstg->atime, &pstatstg->mtime); - if (err == 0) - return HRESULT_FROM_WIN32(GetLastError()); - pstatstg->grfMode = STGM_READ; - pstatstg->grfLocksSupported = 0; - pstatstg->clsid = CLSID_NULL; - pstatstg->grfStateBits = 0; - pstatstg->reserved = 0; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE Stream::Clone( - /* [out] */ __RPC__deref_out_opt IStream **ppstm) -{ - dprintf("Clone called...\n"); - if (ppstm) - { - *ppstm = Make(file, name).Detach(); - } - return S_OK; -} \ No newline at end of file diff --git a/src/WindowsStoreAppLauncher/Stream.h b/src/WindowsStoreAppLauncher/Stream.h deleted file mode 100644 index c7284dcb15..0000000000 --- a/src/WindowsStoreAppLauncher/Stream.h +++ /dev/null @@ -1,76 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include -#include -#include - -using namespace Microsoft::WRL; -using namespace std; - -class Stream : public RuntimeClass, IStream> -{ - shared_ptr file; - wstring name; -public: - Stream(shared_ptr f, const wstring& name); - - Stream(const wstring& name); - - virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read( - /* [annotation] */ - _Out_writes_bytes_to_(cb, *pcbRead) void *pv, - /* [annotation][in] */ - _In_ ULONG cb, - /* [annotation] */ - _Out_opt_ ULONG *pcbRead) override; - - virtual /* [local] */ HRESULT STDMETHODCALLTYPE Write( - /* [annotation] */ - _In_reads_bytes_(cb) const void *pv, - /* [annotation][in] */ - _In_ ULONG cb, - /* [annotation] */ - _Out_opt_ ULONG *pcbWritten) override; - virtual /* [local] */ HRESULT STDMETHODCALLTYPE Seek( - /* [in] */ LARGE_INTEGER dlibMove, - /* [in] */ DWORD dwOrigin, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *plibNewPosition) override; - - virtual HRESULT STDMETHODCALLTYPE SetSize( - /* [in] */ ULARGE_INTEGER libNewSize) override; - - virtual /* [local] */ HRESULT STDMETHODCALLTYPE CopyTo( - /* [annotation][unique][in] */ - _In_ IStream *pstm, - /* [in] */ ULARGE_INTEGER cb, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *pcbRead, - /* [annotation] */ - _Out_opt_ ULARGE_INTEGER *pcbWritten) override; - - virtual HRESULT STDMETHODCALLTYPE Commit( - /* [in] */ DWORD grfCommitFlags) override; - - virtual HRESULT STDMETHODCALLTYPE Revert(void) override; - - virtual HRESULT STDMETHODCALLTYPE LockRegion( - /* [in] */ ULARGE_INTEGER libOffset, - /* [in] */ ULARGE_INTEGER cb, - /* [in] */ DWORD dwLockType) override; - - virtual HRESULT STDMETHODCALLTYPE UnlockRegion( - /* [in] */ ULARGE_INTEGER libOffset, - /* [in] */ ULARGE_INTEGER cb, - /* [in] */ DWORD dwLockType) override; - - virtual HRESULT STDMETHODCALLTYPE Stat( - /* [out] */ __RPC__out STATSTG *pstatstg, - /* [in] */ DWORD grfStatFlag) override; - - virtual HRESULT STDMETHODCALLTYPE Clone( - /* [out] */ __RPC__deref_out_opt IStream **ppstm) override; -}; \ No newline at end of file diff --git a/src/WindowsStoreAppLauncher/Support.cpp b/src/WindowsStoreAppLauncher/Support.cpp deleted file mode 100644 index 7b705b65f0..0000000000 --- a/src/WindowsStoreAppLauncher/Support.cpp +++ /dev/null @@ -1,267 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" -#include "Support.h" - -string make_string(wstring w) -{ - return string(w.begin(), w.end()); -} - -FileLock::FileLock(const wchar_t* lockName) : handle(nullptr, CloseHandle) -{ - handle = safe_handle(CreateFile(lockName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL), CloseHandle); - while (handle.get() == INVALID_HANDLE_VALUE) - { - DWORD err = GetLastError(); - if (err == ERROR_FILE_EXISTS) - { - if (GetFileAccessDelta(lockName) > MAX_WAIT_TIME) - { - handle = safe_handle(CreateFile(lockName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL), CloseHandle); - } - else - { - Sleep(CHECK_INTERVAL); - handle = safe_handle(CreateFile(lockName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL), CloseHandle); - } - } - else - { - throw com_error(HRESULT_FROM_WIN32(err)); - } - } -} - -/*static*/ unsigned int FileLock::GetFileAccessDelta(const wchar_t* name) -{ - WIN32_FILE_ATTRIBUTE_DATA data; - if (!GetFileAttributesEx(name, GetFileExInfoStandard, &data)) - { - return (unsigned int) 0x7FFFFFFF; - } - FILETIME systemT; - GetSystemTimeAsFileTime(&systemT); - ULARGE_INTEGER creationTime = *(ULARGE_INTEGER*) &data.ftCreationTime; - ULARGE_INTEGER systemTime = *(ULARGE_INTEGER*) &systemT; - return (unsigned int) ((systemTime.QuadPart - creationTime.QuadPart) / 10000u); -} - -FileDisambiguator::FileDisambiguator(const wstring& prefix, const vector& files, bool copy, bool del) -:copy(copy), del(del) -{ - for (auto f : files) - { - this->disambiguatedFiles.push_back(DisambiguateFile(prefix, f)); - } -} - -wstring FileDisambiguator::DisambiguateFile(const wstring& prefix, const wstring& name) -{ - // calculate the source file name - auto seperatorIndex = name.rfind('\\'); - wstring src; - dwprintf(L"Seperator index: %lld\n", seperatorIndex); - if (seperatorIndex != wstring::npos) - { - wstring dir = name.substr(0, seperatorIndex); - wstring fname = name.substr(seperatorIndex + 1); - src = dir + L"\\" + prefix + L"_" + fname; - } - else - { - src = prefix + L"_" + name; - } - - - wprintf(L"copying %s -> %s\n", src.c_str(), name.c_str()); - BOOL cancel = false; - if (copy && !CopyFileEx(src.c_str(), name.c_str(), NULL, NULL, &cancel, COPY_FILE_FAIL_IF_EXISTS)) - { - DWORD err = GetLastError(); - wprintf(L"Error copying file:\n%s\n", MessageForHR(HRESULT_FROM_WIN32(err)).c_str()); - if (err == ERROR_FILE_EXISTS) - return name.c_str(); - return L""; - } - else - { - return name.c_str(); - } -} - -FileDisambiguator::~FileDisambiguator() -{ - for (auto f : this->disambiguatedFiles) - { - if (del && !f.empty()) - { - wprintf(L"deleting %s...\n", f.c_str()); - DeleteFile(f.c_str()); - } - } -} - -typedef DWORD(WINAPI *fn_FormatMessage)(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ LPWSTR lpBuffer, _In_ DWORD nSize, _In_opt_ va_list * Arguments); - -bool haveFormatMessage = true; -fn_FormatMessage p_FormatMessage = NULL; - -DWORD WINAPI _formatMessage(_In_ DWORD dwFlags, _In_opt_ LPCVOID lpSource, _In_ DWORD dwMessageId, _In_ DWORD dwLanguageId, _Out_ LPWSTR lpBuffer, _In_ DWORD nSize, _In_opt_ va_list * Arguments) -{ - if (p_FormatMessage == NULL && haveFormatMessage) - { - //this will be leaked, but we don't need to free this until process shutdown anyways - HMODULE locModule = LoadLibraryEx(L"api-ms-win-core-localization-l1-2-1.dll", NULL, NULL); - if (locModule == NULL) - { - haveFormatMessage = false; - return (DWORD) -1; - } - p_FormatMessage = (fn_FormatMessage) GetProcAddress(locModule, "FormatMessageW"); - return (*p_FormatMessage)(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); - } - else if (haveFormatMessage) - { - return (*p_FormatMessage)(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); - } - else - { - return (DWORD) -1; - } -} - -wstring MessageForHR(HRESULT hr) -{ - LPWSTR msg; - DWORD retval = _formatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - hr, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPWSTR) &msg, - 1, - NULL); - wstring ret; - if (retval != 0) - ret = wstring(msg); - else - { - wstringstream ss; - ss << L"0x" << hex << hr; - ret = ss.str(); - } - LocalFree((HLOCAL) msg); - return ret; -} - -wstring GetEnvironmentVariable(wstring name) -{ - LPWSTR buf = new wchar_t[_MAX_ENV]; - if (!GetEnvironmentVariableW(name.c_str(), buf, _MAX_ENV)) - { - wstring ret = L""; - delete [] buf; - return ret; - } - else - { - wstring ret = buf; - delete [] buf; - return ret; - } -} - -using namespace Reg; - -HKEY GetHKey(Key key) -{ - - switch (key) - { - case Key::HKCR: - return HKEY_CLASSES_ROOT; - case Key::HKCC: - return HKEY_CURRENT_CONFIG; - case Key::HKCU: - return HKEY_CURRENT_USER; - case Key::HKLM: - return HKEY_LOCAL_MACHINE; - case Key::HKU: - return HKEY_USERS; - default: - throw com_error(E_FAIL); - } -} - -REGSAM GetAccess(Access access) -{ - switch (access) - { - case Access::Read: - return KEY_READ; - case Access::Write: - return KEY_WRITE; - default: - throw com_error(E_FAIL); - } -} - -RegistryKey Reg::CreateKey(Key key, const wstring& subkey, Access access) -{ - HKEY tmpKey; - DWORD err = RegCreateKeyEx( - GetHKey(key), - subkey.c_str(), - 0, - NULL, - REG_OPTION_NON_VOLATILE, - GetAccess(access), - NULL, - &tmpKey, - NULL - ); - if (err != ERROR_SUCCESS) - { - throw com_error(HRESULT_FROM_WIN32(err)); - } - return RegistryKey(tmpKey, &RegCloseKey); -} - -DWORD Reg::GetValueOrDefault(const RegistryKey& key, const wstring& valueName, DWORD defaultValue) -{ - DWORD data; - DWORD cbData = sizeof(data); - DWORD err = RegGetValue(key.get(), NULL, valueName.c_str(), - RRF_RT_DWORD, - NULL, - &data, - &cbData); - if (err == ERROR_NOT_FOUND || err == ERROR_FILE_NOT_FOUND) - { - data = defaultValue; - } - else if (err != ERROR_SUCCESS) - { - throw com_error(HRESULT_FROM_WIN32(err)); - } - return data; -} - -void Reg::SetValue(const RegistryKey& key, const wstring& valueName, DWORD value) -{ - DWORD err = RegSetValueEx( - key.get(), - valueName.c_str(), - 0, - REG_DWORD, - reinterpret_cast(&value), - sizeof(DWORD)); - if (err != ERROR_SUCCESS) - { - throw com_error(HRESULT_FROM_WIN32(err)); - } -} - diff --git a/src/WindowsStoreAppLauncher/Support.h b/src/WindowsStoreAppLauncher/Support.h deleted file mode 100644 index 05db0cc8d7..0000000000 --- a/src/WindowsStoreAppLauncher/Support.h +++ /dev/null @@ -1,113 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include -#include -#include -#include -using namespace std; - -#define dprintf(...) -#define dwprintf(...) - -typedef unique_ptr < void, add_pointer < decltype(CloseHandle)>::type> safe_handle; - -#define MAX_WAIT_TIME (10 * 60 * 1000) -#define CHECK_INTERVAL (30 * 1000) - -wstring MessageForHR(HRESULT hr); - -#define IFR(function) if(FAILED(hr = function)) return hr; -#define IFER(function) if (function != 0) return E_FAIL; - -#define IFT(function) com_error::ThrowIfFailed(function) - -class FileLock -{ -public: - FileLock(const wchar_t* lockName); -private: - // gets the number of seconds since the file has been created - static unsigned int GetFileAccessDelta(const wchar_t* name); - safe_handle handle; -}; - -class FileDisambiguator -{ -public: - FileDisambiguator(const wstring& prefix, const vector& files, bool copy = true, bool del = true); - ~FileDisambiguator(); -private: - wstring DisambiguateFile(const wstring& prefix, const wstring& name); - vector disambiguatedFiles; - bool copy; - bool del; -}; - -string make_string(wstring w); - -class com_error : public exception -{ - string message; - HRESULT hr; -public: - com_error(HRESULT hr) - :hr(hr), message(make_string(MessageForHR(hr))) - { - } - - com_error(HRESULT hr, string function) - :hr(hr), message(function + ", " + make_string(MessageForHR(hr))) - { - - } - const char* what() const throw() - { - return message.c_str(); - } - - const HRESULT HR() const throw() - { - return hr; - } - static void ThrowIfFailed(HRESULT hr) - { - if (hr < 0) - throw com_error(hr); - } - static void ThrowIfFailed(HRESULT hr, string function) - { - if (hr < 0) - throw com_error(hr, function); - } -}; - -#undef GetEnvironmentVariable - -wstring GetEnvironmentVariable(wstring name); - - -namespace Reg -{ - typedef unique_ptr::type, decltype(&RegCloseKey)> RegistryKey; - enum struct Key - { - HKCR, - HKCC, - HKCU, - HKLM, - HKU - }; - enum struct Access - { - Read, - Write - }; - RegistryKey CreateKey(Key key, const wstring& subkey, Access access); - DWORD GetValueOrDefault(const RegistryKey& key, const wstring& valueName, DWORD fallbackValue); - void SetValue(const RegistryKey& key, const wstring& valueName, DWORD value); -} - - diff --git a/src/WindowsStoreAppLauncher/WindowsStoreApp.cpp b/src/WindowsStoreAppLauncher/WindowsStoreApp.cpp deleted file mode 100644 index 3a5b4de19d..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreApp.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" -#include "WindowsStoreApp.h" -#include "Stream.h" -#include "Support.h" - -using namespace ABI::Windows::Management::Deployment; -using namespace ABI::Windows::ApplicationModel::Activation; -using namespace ABI::Windows::ApplicationModel; -using namespace ABI::Windows::Foundation::Collections; -using namespace Microsoft::WRL; -using namespace Microsoft::WRL::Wrappers; -using namespace std; - -WindowsStoreApp::WindowsStoreApp(const wstring& manifestPath, const wstring& appId) -:AppxApp(manifestPath, appId) -{ -} - -WindowsStoreApp::~WindowsStoreApp() -{ -} - -ComPtr WindowsStoreApp::GetApplicationActivationManager() -{ - ComPtr applicationActivationManager; - IFT(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&applicationActivationManager))); - return applicationActivationManager; -} - -void WindowsStoreApp::Add() -{ - // Create the package Uri - ComPtr uriRuntimeClassFactory; - ComPtr packagerUri; - - dwprintf(L"GetActivationFactory...\n"); - IFT(RoGetActivationFactory(HStringReference(RuntimeClass_Windows_Foundation_Uri).Get(), __uuidof(IUriRuntimeClassFactory), &uriRuntimeClassFactory)); - dwprintf(L"CreateUri, path %s...\n", get_ManifestPath().c_str()); - HString manifestPath; - manifestPath.Set(get_ManifestPath().c_str(), (unsigned int)get_ManifestPath().length()); - IFT(uriRuntimeClassFactory->CreateUri(manifestPath.Get(), &packagerUri)); - - // Create the PackageManager - ComPtr packageMangerInspectable; - ComPtr packageManger; - - dwprintf(L"RoActivateInstance...\n"); - IFT(RoActivateInstance(HStringReference(RuntimeClass_Windows_Management_Deployment_PackageManager).Get(), &packageMangerInspectable)); - dwprintf(L"QueryInterface...\n"); - IFT(packageMangerInspectable.As(&packageManger)); - - // Register the package asynchronously - ComPtr> registerPackageAsyncOperation; - - dwprintf(L"RegisterPackageAsync...\n"); - IFT(packageManger->RegisterPackageAsync( - packagerUri.Get(), - nullptr, - ABI::Windows::Management::Deployment::DeploymentOptions::DeploymentOptions_DevelopmentMode, - ®isterPackageAsyncOperation)); - - // TODO: Get DeploymentResult::ErrorText - - dwprintf(L"Wait...\n"); - // Wait for the package to be registered and return the result - Wait(registerPackageAsyncOperation.Get(), nullptr); -} - -void WindowsStoreApp::Remove() -{ - // Create the PackageManager - ComPtr packageMangerInspectable; - ComPtr packageManger; - - IFT(RoActivateInstance(HStringReference(RuntimeClass_Windows_Management_Deployment_PackageManager).Get(), &packageMangerInspectable)); - IFT(packageMangerInspectable.As(&packageManger)); - - ComPtr> packageCollection; - IFT(packageManger->FindPackagesByUserSecurityIdPackageFamilyName(nullptr, HStringReference(get_PackageFamilyName().c_str()).Get(), &packageCollection)); - - ComPtr> packageIterator; - IFT(packageCollection->First(&packageIterator)); - - boolean hasCurrent; - for (packageIterator->get_HasCurrent(&hasCurrent); hasCurrent; packageIterator->MoveNext(&hasCurrent)) - { - ComPtr package; - IFT(packageIterator->get_Current(&package)); - - ComPtr packageId; - IFT(package->get_Id(&packageId)); - - HSTRING hstrPackageIdName; - IFT(packageId->get_FullName(&hstrPackageIdName)); - HString packageIdName; - packageIdName.Attach(hstrPackageIdName); - - // Remove the package asynchronously - ComPtr> removePackageAsyncOperation; - IFT(packageManger->RemovePackageAsync( - packageIdName.Get(), - &removePackageAsyncOperation)); - - // TODO: Get DeploymentResult::ErrorText - - // Wait for the package to be removed and return the result - Wait(removePackageAsyncOperation.Get(), nullptr); - } -} - -wstring WindowsStoreApp::GetAppContainerFolderPath() const -{ - wstring folderPath(GetEnvironmentVariable(L"USERPROFILE")); - folderPath += L"\\AppData\\Local\\Packages\\"; - folderPath += get_PackageFamilyName(); - folderPath += L"\\"; - wprintf(L"Resolved Folder Path: %s\n", folderPath.c_str()); - - return folderPath; -} diff --git a/src/WindowsStoreAppLauncher/WindowsStoreApp.h b/src/WindowsStoreAppLauncher/WindowsStoreApp.h deleted file mode 100644 index de49d40262..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreApp.h +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once -#include "AppxApp.h" -#include -#include - -#include -#include -#include - -using namespace ABI::Windows::Foundation; -using namespace Microsoft::WRL; -using namespace std; - -class WindowsStoreApp : public AppxApp -{ -protected: - virtual ComPtr GetApplicationActivationManager() override; - virtual wstring GetAppContainerFolderPath() const override; -public: - WindowsStoreApp(const wstring& manifestPath, const wstring& appId); - virtual ~WindowsStoreApp(); - - virtual void Add() override; - virtual void Remove() override; -}; - diff --git a/src/WindowsStoreAppLauncher/WindowsStoreApp.rc b/src/WindowsStoreAppLauncher/WindowsStoreApp.rc deleted file mode 100644 index f71168ac17..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreApp.rc +++ /dev/null @@ -1,34 +0,0 @@ -#include - -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -VS_VERSION_INFO VERSIONINFO -FILEVERSION 9,9,9,9 -PRODUCTVERSION 9,9,9,9 -FILEFLAGSMASK 0x3fL -FILEFLAGS 0x22L -FILEOS 0x40004L -FILETYPE 0x1L -FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - BEGIN - VALUE "CompanyName", "Microsoft Corporation" - VALUE "FileDescription", "WindowsStoreAppLauncher.exe" - VALUE "FileVersion", "9.9.9.9" - VALUE "InternalName", "WindowsStoreAppLauncher.exe" - VALUE "LegalCopyright", "Copyright (C) 2050" - VALUE "OriginalFilename", "WindowsStoreAppLauncher.exe" - VALUE "ProductName", "WindowsStoreAppLauncher" - VALUE "ProductVersion", "9.9.9.9" - END - END - - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - - END -END diff --git a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.cpp b/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.cpp deleted file mode 100644 index 8286ca5d2d..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.cpp +++ /dev/null @@ -1,393 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" -#include "WindowsStoreApp.h" -#include "Args.h" -#include "Support.h" -#include "dwmapi.h" - -//required by CRT -extern "C" BOOL __stdcall AreFileApisANSI(void) -#pragma warning(suppress:4273) // inconsistent dll linkage -{ - return TRUE; -} -extern "C" LONG __stdcall GetCurrentPackageId(_Inout_ UINT32 *bufferLength, _Out_opt_ BYTE *buffer) -{ - UNREFERENCED_PARAMETER(bufferLength); - UNREFERENCED_PARAMETER(buffer); - return APPMODEL_ERROR_NO_PACKAGE; -} - -using namespace std; -using namespace Microsoft::WRL; - -#define DEFAULT_TIMEOUT_MILLISECONDS 1000 * 60 * 2 - -struct ArgInfo -{ - wstring debuggerCommandLine; - unsigned int timeoutMilliseconds; - bool isTimeoutSpecified; - wstring manifestPath; - wstring appId; - bool isTestApp; - bool runInBackground; - bool installOnly; - bool uninstallOnly; - unsigned int delayLaunchMilliseconds; - wstring disambiguatePrefix; - vector filesToDisambiguate; - wstring executionArguments; -}; - -void Run(__in const ArgInfo& info, - __out DWORD& exitCode); - -int wmain(int argc, wchar_t* argv []) -{ - ArgInfo info; - info.debuggerCommandLine = L""; - info.timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS; - info.isTimeoutSpecified = false; - info.manifestPath = L""; - info.appId = L""; - info.isTestApp = false; - info.runInBackground = true; - info.installOnly = false; - info.uninstallOnly = false; - info.delayLaunchMilliseconds = 0; - info.disambiguatePrefix = L""; - info.filesToDisambiguate = vector(); - info.executionArguments = L""; - bool help = false; - - OptionList options(L"WindowsStoreAppLauncher.exe", L" []", L"\tAppx Manifest Path\n\t\tPath to the AppxManifest.xml file\n\texecution args\n\t\tThe arguments to pass the the application."); - - vector argInfoTmp; - - argInfoTmp.push_back(L"?"); - argInfoTmp.push_back(L"help"); - options.Add(argInfoTmp, [&]() { help = true; }, L"Display this help"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"d"); - argInfoTmp.push_back(L"debug"); - options.Add(argInfoTmp, L"debugger cmd line", [&](const wstring& arg) { info.debuggerCommandLine = arg; }, L"Launch the application under the specified debugger"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"t"); - argInfoTmp.push_back(L"timeout"); - options.Add(argInfoTmp, L"ms", [&](const wstring& arg) { info.isTimeoutSpecified = true; info.timeoutMilliseconds = stoi(arg); }, L"The time to wait for the app to exit(default: 120000)"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"test"); - options.Add(argInfoTmp, [&]() { info.isTestApp = true; }, L"The app is a test and will exit on its own"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"foreground"); - options.Add(argInfoTmp, [&]() { info.runInBackground = false; }, L"Run the application in the foreground"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"delaylaunch"); - options.Add(argInfoTmp, L"ms", [&](const wstring& arg) { info.delayLaunchMilliseconds = stoi(arg); }, L"Delay launching the app by the specified time"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"i"); - argInfoTmp.push_back(L"install"); - options.Add(argInfoTmp, [&]() { info.installOnly = true; }, L"Install the application and quit"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"u"); - argInfoTmp.push_back(L"uninstall"); - options.Add(argInfoTmp, [&]() { info.uninstallOnly = true; }, L"Uninstall the application and quit"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"disPrefix"); - options.Add(argInfoTmp, L"name", [&](const wstring& arg) { info.disambiguatePrefix = arg; }, L"The prefix used for file disambiguation"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"disFile"); - options.Add(argInfoTmp, L"name", [&](const wstring& arg) { - info.filesToDisambiguate.push_back(arg); - }, L"File that is disambiguated"); - argInfoTmp.clear(); - argInfoTmp.push_back(L"appId"); - options.Add(argInfoTmp, L"id", [&](const wstring& arg) { info.appId = arg; }, L"The application ID to start"); - argInfoTmp.clear(); - - wchar_t** endOfArgs = options.Parse(argc - 1, argv + 1, [&](const wstring& failedOpt) - { - wprintf(L"Error: Option %s missing argument\n", failedOpt.c_str()); - options.PrintUsage(); - exit(1); - }); - - if (argc == 1 || help) - { - options.PrintUsage(); - return 0; - } - - if (endOfArgs - argv < argc) - { - info.manifestPath = *(endOfArgs++); - wprintf(L"Got manifest file %s\n", info.manifestPath.c_str()); - } - else - { - fwprintf(stderr, L"Error: Missing appx manifest path\n"); - options.PrintUsage(); - return 1; - } - while (endOfArgs - argv < argc) - { - info.executionArguments += wstring(L" ") + (*(endOfArgs++)); - } - - DWORD exitCode = (DWORD) -1; - try - { - Run(info, exitCode); - wprintf(L"\n"); - wprintf(L"SUCCESS\n"); - wprintf(L"ExitCode %d\n", exitCode); - return exitCode; - } - catch (com_error e) - { - wprintf(L"\nFAILED 0x%X (%hs)\n", e.HR(), e.what()); - return 1; - } - catch (exception e) - { - wprintf(L"\nFAILED (%hs)\n", e.what()); - return 1; - } -} - -bool FileExists(const wstring& fname) -{ - _WIN32_FILE_ATTRIBUTE_DATA attributes; - if (!GetFileAttributesEx(fname.c_str(), ::GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &attributes)) - { - DWORD error = GetLastError(); - - if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) { - fwprintf(stderr, L"%s: does not exist\n", fname.c_str()); - return false; - } - else if (error == ERROR_INVALID_NAME) - { - wprintf(L"%s: is not a valid path\n", fname.c_str()); - return false; - } - else - { - wprintf(L"%s: could not be opened(%s)\n", fname.c_str(), MessageForHR(HRESULT_FROM_WIN32(error)).c_str()); - return false; - } - } - return true; -} - -void Install(const unique_ptr& app) -{ - // Install the application - wprintf(L"Removing any previous installation...\n"); - app->Remove(); - - wprintf(L"Installing the application...\n"); - app->Add(); -} - -void Uninstall(const unique_ptr& app) -{ - // Remove the application - wprintf(L"Removing the application...\n"); - app->Remove(); -} - -void Execute(const unique_ptr& app, const ArgInfo& info, DWORD& exitCode) -{ - try - { - // Enable the debugger - // This is necessary even if no debugger is specified because otherwise starting the app can time out - app->EnableDebug(info.debuggerCommandLine); - - if (info.delayLaunchMilliseconds > 0) - { - // Wait for the specified interval before launch - // These changes allow us to avoid a race condition between app launch and the app resolver cache. - // See DevDiv Bug # 779425 for more details. - wprintf(L"Waiting for %ims before launch...\n", info.delayLaunchMilliseconds); - Sleep(info.delayLaunchMilliseconds); - } - - // Start the application - wprintf(L"Starting the application...\n"); - app->Start(info.runInBackground, info.isTestApp, info.executionArguments); - - bool waitResult; - - if (info.debuggerCommandLine.empty() && info.isTimeoutSpecified) - { - wprintf(L"Waiting for %ims...\n", info.timeoutMilliseconds); - exitCode = app->WaitForExit(info.timeoutMilliseconds, &waitResult); - } - else - { - wprintf(L"Waiting for the application to exit...\n"); - waitResult = true; - exitCode = app->WaitForExit(); - } - - if (!waitResult) - { - if (info.isTestApp) - { - wprintf(L"The app did not exit within %ims - stopping the app...\n", info.timeoutMilliseconds); - } - else - { - wprintf(L"Stopping the app...\n"); - } - - app->Stop(); - } - - wprintf(L"Disabling the debugger...\n"); - app->DisableDebug(); - - if (info.isTestApp) - { - wprintf(L"\n\nSTDOUT & STDERR from immersive process:\n"); - wprintf(L"==================================================================================\n"); - wprintf(L"\n%s\n", app->GetAppStdOutContent().c_str()); - wprintf(L"==================================================================================\n"); - } - else if (waitResult) - { - wprintf(L"Error: The app exited before the timeout and most likely crashed\n"); - throw com_error(E_FAIL); - } - } - catch (com_error e) - { - wprintf(L"\nFAILED 0x%X (%hs)\n", e.HR(), e.what()); - Uninstall(app); - throw; - } -} - -unique_ptr CreateAppObject(__in const ArgInfo& info) -{ - return unique_ptr(new WindowsStoreApp(info.manifestPath, info.appId)); -} - - -typedef int(__stdcall *PROCDwmIsCompositionEnabled)(BOOL *pIsEnabled); -typedef int(__stdcall *PROCDwmEnableComposition)(UINT uCompositionAction); -HRESULT _DoSystemStateChecks() -{ - HRESULT hr = S_OK; - - HINSTANCE hinstLib = LoadLibraryW(L"Dwmapi.dll"); - if (hinstLib == NULL) - { - wprintf(L"Error: Dwmapi.dll could not be found!"); - return 0x8007007E; - } - - PROCDwmIsCompositionEnabled procDwmIsCompositionEnabled = (PROCDwmIsCompositionEnabled)GetProcAddress(hinstLib, "DwmIsCompositionEnabled"); - BOOL fEnabled; - hr = (procDwmIsCompositionEnabled)(&fEnabled); - if (SUCCEEDED(hr)) - { - if (!fEnabled) - { - // C4995: 'function': name was marked as #pragma deprecated - #pragma warning(disable : 4995) - PROCDwmEnableComposition procDwmEnableComposition = (PROCDwmEnableComposition)GetProcAddress(hinstLib, "DwmEnableComposition"); - hr = (*procDwmEnableComposition)(DWM_EC_ENABLECOMPOSITION); - - if (SUCCEEDED(hr)) - { - hr = (procDwmIsCompositionEnabled)(&fEnabled); - if (SUCCEEDED(hr) && fEnabled) - { - // Enable Successfully - return S_OK; - } - else if(!fEnabled) - { - const wchar_t szDWMMsg[] = - L"ERROR: 0x%X - The DWM is still disabled even after call DwmEnableComposition, but is required for running\r\n" - L"immersive applications. Please enable desktop composition and try again.\r\n"; - wprintf(szDWMMsg, hr); - } - else - { - const wchar_t szDWMMsg[] = L"ERROR: 0x%X - DwmIsCompositionEnabled return bad HResult.\r\n"; - wprintf(szDWMMsg, hr); - } - } - else - { - const wchar_t szDWMMsg[] = - L"ERROR: 0x%X - The DWM is currently disabled, but is required for running\r\n" - L"immersive applications. Please enable desktop composition and try again.\r\n"; - wprintf(szDWMMsg, hr); - } - } - } - else - { - const wchar_t szDWMMsg[] = L"ERROR: 0x%X - DwmIsCompositionEnabled return bad HResult.\r\n"; - wprintf(szDWMMsg, hr); - } - - FreeLibrary(hinstLib); - - return hr; -} - -void Run(__in const ArgInfo& info, __out DWORD& exitCode) -{ - Microsoft::WRL::Wrappers::RoInitializeWrapper roInitialize(RO_INIT_MULTITHREADED); - - if (FAILED(roInitialize)) - { - wprintf(L"FAILED to initialize the Windows Runtime(0x%x)\n%s\n", static_cast(roInitialize), MessageForHR(roInitialize).c_str()); - throw exception(); - } - - if (FAILED(_DoSystemStateChecks())) - { - throw exception(); - } - - setvbuf(stdout, NULL, _IONBF, 0); - setvbuf(stderr, NULL, _IONBF, 0); - - //Lock the directory - FileLock f(L"appxExecution.lock"); - //Copy disambigious files - FileDisambiguator files(info.disambiguatePrefix, info.filesToDisambiguate, info.installOnly || !info.uninstallOnly, info.uninstallOnly || !info.installOnly); - - if (!FileExists(info.manifestPath)) - throw exception(); - - auto app = CreateAppObject(info); - if (info.uninstallOnly) - { - exitCode = 100; - Uninstall(app); - } - else if (info.installOnly) - { - exitCode = 100; - Install(app); - wprintf(L"Package Full Name is %s\n", app->get_PackageFullName().c_str()); - } - else - { - Install(app); - Execute(app, info, exitCode); - Uninstall(app); - } -} diff --git a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.sln b/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.sln deleted file mode 100644 index 4de0f7aa45..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.sln +++ /dev/null @@ -1,27 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WindowsStoreAppLauncher", "WindowsStoreAppLauncher.vcxproj", "{177AA879-D233-4A16-8398-8BDF5D5E1ED8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Debug|x64.ActiveCfg = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Debug|x64.Build.0 = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Debug|x86.ActiveCfg = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Debug|x86.Build.0 = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Release|x64.ActiveCfg = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Release|x64.Build.0 = Release|x64 - {177AA879-D233-4A16-8398-8BDF5D5E1ED8}.Release|x86.ActiveCfg = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj b/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj deleted file mode 100644 index 27e7d7d029..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj +++ /dev/null @@ -1,79 +0,0 @@ - - - - Release - x64 - - - - - Release - x64 - - - - {177AA879-D233-4A16-8398-8BDF5D5E1ED8} - ManagedCProj - WindowsStoreAppLauncher - $(OutputPath) - - v120 - - - - Application - false - $(DefaultPlatformToolset) - false - Unicode - - - - - - - - - - false - - - - Level3 - NDEBUG;%(PreprocessorDefinitions) - Use - false - MultiThreaded - - - Advapi32.lib;Pathcch.lib;Userenv.lib;OleAut32.lib;runtimeobject.lib - - - - - - - - - - - - - - - Create - Create - Create - Create - - - - - - - - - - - - \ No newline at end of file diff --git a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj.filters b/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj.filters deleted file mode 100644 index bdab1c77ac..0000000000 --- a/src/WindowsStoreAppLauncher/WindowsStoreAppLauncher.vcxproj.filters +++ /dev/null @@ -1,59 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/src/WindowsStoreAppLauncher/stdafx.cpp b/src/WindowsStoreAppLauncher/stdafx.cpp deleted file mode 100644 index 6cafcfe3d9..0000000000 --- a/src/WindowsStoreAppLauncher/stdafx.cpp +++ /dev/null @@ -1,7 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#include "stdafx.h" - - diff --git a/src/WindowsStoreAppLauncher/stdafx.h b/src/WindowsStoreAppLauncher/stdafx.h deleted file mode 100644 index 0ae5a90d9b..0000000000 --- a/src/WindowsStoreAppLauncher/stdafx.h +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#define INITGUID -#include \ No newline at end of file diff --git a/src/common/AppxCommandLine.cs b/src/common/AppxCommandLine.cs deleted file mode 100644 index 7c237b7c4c..0000000000 --- a/src/common/AppxCommandLine.cs +++ /dev/null @@ -1,315 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Xunit.ConsoleClient; - -namespace Xunit.Shared -{ - internal class CommandLine - { - readonly Stack arguments = new Stack(); - - protected CommandLine(string[] args, Predicate fileExists = null) - { - if (fileExists == null) - fileExists = File.Exists; - - for (var i = args.Length - 1; i >= 0; i--) - arguments.Push(args[i]); - - Project = Parse(fileExists); - } - - public bool Debug { get; protected set; } - - public bool DiagnosticMessages { get; protected set; } - - public bool FailSkips { get; protected set; } - - public int? MaxParallelThreads { get; set; } - - public bool NoAppDomain { get; protected set; } - - public bool NoColor { get; protected set; } - - public bool NoLogo { get; protected set; } - - public XunitProject Project { get; protected set; } - - public bool? ParallelizeAssemblies { get; protected set; } - - public bool? ParallelizeTestCollections { get; set; } - - public bool Serialize { get; protected set; } - - public bool ShowProgress { get; protected set; } - - public bool Wait { get; protected set; } - public string InstallLocation { get; internal set; } - - protected virtual string GetFullPath(string fileName) - { - return Path.GetFullPath(fileName); - } - - XunitProject GetProjectFile(List> assemblies) - { - var result = new XunitProject(); - - foreach (var assembly in assemblies) - result.Add(new XunitProjectAssembly - { - AssemblyFilename = GetFullPath(assembly.Item1), - ConfigFilename = assembly.Item2 != null ? GetFullPath(assembly.Item2) : null, - }); - - return result; - } - - static void GuardNoOptionValue(KeyValuePair option) - { - if (option.Value != null) - throw new ArgumentException($"error: unknown command line option: {option.Value}"); - } - - static bool IsConfigFile(string fileName) - { - return fileName.EndsWith(".config", StringComparison.OrdinalIgnoreCase) - || fileName.EndsWith(".json", StringComparison.OrdinalIgnoreCase); - } - - public static CommandLine Parse(params string[] args) - { - return new CommandLine(args); - } - - protected XunitProject Parse(Predicate fileExists) - { - var assemblies = new List>(); - - while (arguments.Count > 0) - { - if (arguments.Peek().StartsWith("-", StringComparison.Ordinal)) - break; - - var assemblyFile = arguments.Pop(); - if (IsConfigFile(assemblyFile)) - throw new ArgumentException($"expecting assembly, got config file: {assemblyFile}"); - - if (!fileExists(assemblyFile)) - throw new ArgumentException($"file not found: {assemblyFile}"); - - string configFile = null; - if (arguments.Count > 0) - { - var value = arguments.Peek(); - if (!value.StartsWith("-", StringComparison.Ordinal) && IsConfigFile(value)) - { - configFile = arguments.Pop(); - if (!fileExists(configFile)) - throw new ArgumentException($"config file not found: {configFile}"); - } - } - - assemblies.Add(Tuple.Create(assemblyFile, configFile)); - } - - if (assemblies.Count == 0) - throw new ArgumentException("must specify at least one assembly"); - - var project = GetProjectFile(assemblies); - - while (arguments.Count > 0) - { - var option = PopOption(arguments); - var optionName = option.Key.ToLowerInvariant(); - - if (!optionName.StartsWith("-", StringComparison.Ordinal)) - throw new ArgumentException($"unknown command line option: {option.Key}"); - - optionName = optionName.Substring(1); - - if (optionName == "installlocation") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -installlocation"); - InstallLocation = option.Value; - } - else if (optionName == "nologo") - { - GuardNoOptionValue(option); - NoLogo = true; - } - else if (optionName == "failskips") - { - GuardNoOptionValue(option); - FailSkips = true; - } - else if (optionName == "nocolor") - { - GuardNoOptionValue(option); - NoColor = true; - } - else if (optionName == "noappdomain") - { - GuardNoOptionValue(option); - NoAppDomain = true; - } - else if (optionName == "debug") - { - GuardNoOptionValue(option); - Debug = true; - } - else if (optionName == "serialize") - { - GuardNoOptionValue(option); - Serialize = true; - } - else if (optionName == "showprogress") - { - GuardNoOptionValue(option); - ShowProgress = true; - } - else if (optionName == "wait") - { - GuardNoOptionValue(option); - Wait = true; - } - else if (optionName == "diagnostics") - { - GuardNoOptionValue(option); - DiagnosticMessages = true; - } - else if (optionName == "maxthreads") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -maxthreads"); - - switch (option.Value) - { - case "default": - MaxParallelThreads = 0; - break; - - case "unlimited": - MaxParallelThreads = -1; - break; - - default: - int threadValue; - if (!int.TryParse(option.Value, out threadValue) || threadValue < 1) - throw new ArgumentException("incorrect argument value for -maxthreads (must be 'default', 'unlimited', or a positive number)"); - - MaxParallelThreads = threadValue; - break; - } - } - else if (optionName == "parallel") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -parallel"); - - ParallelismOption parallelismOption; - if (!Enum.TryParse(option.Value, out parallelismOption)) - throw new ArgumentException("incorrect argument value for -parallel"); - - switch (parallelismOption) - { - case ParallelismOption.all: - ParallelizeAssemblies = true; - ParallelizeTestCollections = true; - break; - - case ParallelismOption.assemblies: - ParallelizeAssemblies = true; - ParallelizeTestCollections = false; - break; - - case ParallelismOption.collections: - ParallelizeAssemblies = false; - ParallelizeTestCollections = true; - break; - - default: - ParallelizeAssemblies = false; - ParallelizeTestCollections = false; - break; - } - } - else if (optionName == "noshadow") - { - GuardNoOptionValue(option); - foreach (var assembly in project.Assemblies) - assembly.Configuration.ShadowCopy = false; - } - else if (optionName == "trait") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -trait"); - - var pieces = option.Value.Split('='); - if (pieces.Length != 2 || string.IsNullOrEmpty(pieces[0]) || string.IsNullOrEmpty(pieces[1])) - throw new ArgumentException("incorrect argument format for -trait (should be \"name=value\")"); - - var name = pieces[0]; - var value = pieces[1]; - project.Filters.IncludedTraits.Add(name, value); - } - else if (optionName == "notrait") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -notrait"); - - var pieces = option.Value.Split('='); - if (pieces.Length != 2 || string.IsNullOrEmpty(pieces[0]) || string.IsNullOrEmpty(pieces[1])) - throw new ArgumentException("incorrect argument format for -notrait (should be \"name=value\")"); - - var name = pieces[0]; - var value = pieces[1]; - project.Filters.ExcludedTraits.Add(name, value); - } - else if (optionName == "class") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -class"); - - project.Filters.IncludedClasses.Add(option.Value); - } - else if (optionName == "method") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -method"); - - project.Filters.IncludedMethods.Add(option.Value); - } - else if (optionName == "namespace") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -namespace"); - - project.Filters.IncludedNameSpaces.Add(option.Value); - } - else if (optionName == "xml") - { - if (option.Value == null) - throw new ArgumentException($"missing filename for {option.Key}"); - - project.Output.Add(optionName, option.Value); - } - } - - return project; - } - - static KeyValuePair PopOption(Stack arguments) - { - var option = arguments.Pop(); - string value = null; - - if (arguments.Count > 0 && !arguments.Peek().StartsWith("-", StringComparison.Ordinal)) - value = arguments.Pop(); - - return new KeyValuePair(option, value); - } - } -} diff --git a/src/common/AssemblyExtensions.cs b/src/common/AssemblyExtensions.cs deleted file mode 100644 index db948c9476..0000000000 --- a/src/common/AssemblyExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -#if !ASPNETCORE50 && !NETCORE - -using System; -using System.IO; -using System.Reflection; - -internal static class AssemblyExtensions -{ - public static string GetLocalCodeBase(this Assembly assembly) - { - string codeBase = assembly.CodeBase; - if (codeBase == null) - return null; - - if (!codeBase.StartsWith("file:///")) - throw new ArgumentException(String.Format("Code base {0} in wrong format; must start with file:///", codeBase), "assembly"); - - codeBase = codeBase.Substring(8); - if (Path.DirectorySeparatorChar == '/') - return "/" + codeBase; - - return codeBase.Replace('/', Path.DirectorySeparatorChar); - } -} - -#endif diff --git a/src/common/AssemblyHelper_WPA81.cs b/src/common/AssemblyHelper_WPA81.cs deleted file mode 100644 index 0f7f5e7c59..0000000000 --- a/src/common/AssemblyHelper_WPA81.cs +++ /dev/null @@ -1,21 +0,0 @@ -#if !ASPNET50 - -using System; - -namespace Xunit -{ - /// - public class AssemblyHelper : IDisposable - { - /// - public static IDisposable SubscribeResolve() - { - return new AssemblyHelper(); - } - - /// - public void Dispose() { } - } -} - -#endif diff --git a/src/common/ConfigReader_XDocument.cs b/src/common/ConfigReader_XDocument.cs deleted file mode 100644 index cf1571d30c..0000000000 --- a/src/common/ConfigReader_XDocument.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Xml.Linq; - -namespace Xunit -{ - /// - /// This class is used to read configuration information for a test assembly. - /// -#if UNIT_TEST - public static class ConfigReader_XDocument -#else - public static class ConfigReader -#endif - { - /// - /// Loads the test assembly configuration for the given test assembly. - /// - /// The test assembly. - /// The test assembly configuration file. - /// The test assembly configuration. - public static TestAssemblyConfiguration Load(string assemblyFileName, string configFileName = null) - { - if (configFileName == null) - configFileName = assemblyFileName + ".config"; - - var result = new TestAssemblyConfiguration(); - - try - { - using (var stream = File.OpenRead(configFileName)) - { - var document = XDocument.Load(stream); - var appSettings = document.Root.Element("appSettings"); - - if (appSettings != null) - { - foreach (var add in appSettings.Elements("add")) - { - var key = add.Attribute("key"); - var value = add.Attribute("value"); - - if (key != null && value != null) - { - if (key.Value.Equals(TestOptionsNames.Configuration.DiagnosticMessages, StringComparison.OrdinalIgnoreCase)) - result.DiagnosticMessages = GetBoolean(value.Value, result.DiagnosticMessages); - else if (key.Value.Equals(TestOptionsNames.Configuration.MaxParallelThreads, StringComparison.OrdinalIgnoreCase)) - result.MaxParallelThreads = GetInt(value.Value, result.MaxParallelThreads); - else if (key.Value.Equals(TestOptionsNames.Configuration.MethodDisplay, StringComparison.OrdinalIgnoreCase)) - result.MethodDisplay = GetEnum(value.Value, result.MethodDisplay); - else if (key.Value.Equals(TestOptionsNames.Configuration.ParallelizeAssembly, StringComparison.OrdinalIgnoreCase)) - result.ParallelizeAssembly = GetBoolean(value.Value, result.ParallelizeAssembly); - else if (key.Value.Equals(TestOptionsNames.Configuration.ParallelizeTestCollections, StringComparison.OrdinalIgnoreCase)) - result.ParallelizeTestCollections = GetBoolean(value.Value, result.ParallelizeTestCollections); - else if (key.Value.Equals(TestOptionsNames.Configuration.PreEnumerateTheories, StringComparison.OrdinalIgnoreCase)) - result.PreEnumerateTheories = GetBoolean(value.Value, result.PreEnumerateTheories); - } - } - } - } - } - catch { } - - return result; - } - - static bool GetBoolean(string value, bool defaultValue) - { - switch (value.ToLowerInvariant()) - { - case "true": return true; - case "false": return false; - default: return defaultValue; - } - } - - static TValue GetEnum(string value, TValue defaultValue) - where TValue : struct - { - TValue result; - if (Enum.TryParse(value, ignoreCase: true, result: out result)) - return result; - return defaultValue; - } - - static int GetInt(string value, int defaultValue) - { - int result; - if (Int32.TryParse(value, out result)) - return result; - return defaultValue; - } - } -} diff --git a/src/common/DictionaryExtensions.cs b/src/common/DictionaryExtensions.cs deleted file mode 100644 index 7e65323a8c..0000000000 --- a/src/common/DictionaryExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -internal static class DictionaryExtensions -{ - public static void Add(this IDictionary> dictionary, TKey key, TValue value) - { - dictionary.GetOrAdd(key).Add(value); - } - - public static bool Contains(this IDictionary> dictionary, TKey key, TValue value, IEqualityComparer valueComparer) - { - List values; - - if (!dictionary.TryGetValue(key, out values)) - return false; - - return values.Contains(value, valueComparer); - } - - public static TValue GetOrAdd(this IDictionary dictionary, TKey key) - where TValue : new() - { - return dictionary.GetOrAdd(key, () => new TValue()); - } - - public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func newValue) - { - TValue result; - - if (!dictionary.TryGetValue(key, out result)) - { - result = newValue(); - dictionary[key] = result; - } - - return result; - } -} diff --git a/src/common/DisposableExtensions.cs b/src/common/DisposableExtensions.cs deleted file mode 100644 index 5e8c96e339..0000000000 --- a/src/common/DisposableExtensions.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -internal static class DisposableExtensions -{ - public static void SafeDispose(this IDisposable disposable) - { - if (disposable != null) - disposable.Dispose(); - } -} \ No newline at end of file diff --git a/src/common/ExceptionExtensions.cs b/src/common/ExceptionExtensions.cs deleted file mode 100644 index f09c2cd11c..0000000000 --- a/src/common/ExceptionExtensions.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Reflection; - -internal static class ExceptionExtensions -{ - const string RETHROW_MARKER = "$$RethrowMarker$$"; - - /// - /// Rethrows an exception object without losing the existing stack trace information - /// - /// The exception to re-throw. - /// - /// For more information on this technique, see - /// http://www.dotnetjunkies.com/WebLog/chris.taylor/archive/2004/03/03/8353.aspx. - /// The remote_stack_trace string is here to support Mono. - /// - public static void RethrowWithNoStackTraceLoss(this Exception ex) - { -#if XUNIT_CORE_DLL || WINDOWS_PHONE_APP || WINDOWS_PHONE || ASPNETCORE50 - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw(); -#else - FieldInfo remoteStackTraceString = - typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic) ?? - typeof(Exception).GetField("remote_stack_trace", BindingFlags.Instance | BindingFlags.NonPublic); - - remoteStackTraceString.SetValue(ex, ex.StackTrace + RETHROW_MARKER); - throw ex; -#endif - } - - /// - /// Unwraps an exception to remove any wrappers, like . - /// - /// The exception to unwrap. - /// The unwrapped exception. - public static Exception Unwrap(this Exception ex) - { - while (true) - { - var tiex = ex as TargetInvocationException; - if (tiex == null) - return ex; - - ex = tiex.InnerException; - } - } -} diff --git a/src/common/ExceptionUtility.cs b/src/common/ExceptionUtility.cs deleted file mode 100644 index 4a5dcb4de4..0000000000 --- a/src/common/ExceptionUtility.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Generic; -using Xunit.Abstractions; - -#if XUNIT_CORE_DLL -namespace Xunit.Sdk -#else -namespace Xunit -#endif -{ - /// - /// Utility classes for dealing with Exception objects. - /// - public static class ExceptionUtility - { - /// - /// Combines multiple levels of messages into a single message. - /// - /// The failure information from which to get the messages. - /// The combined string. - public static string CombineMessages(IFailureInformation failureInfo) - { - return GetMessage(failureInfo, 0, 0); - } - - /// - /// Combines multiple levels of stack traces into a single stack trace. - /// - /// The failure information from which to get the stack traces. - /// The combined string. - public static string CombineStackTraces(IFailureInformation failureInfo) - { - return GetStackTrace(failureInfo, 0); - } - - static bool ExcludeStackFrame(string stackFrame) - { - Guard.ArgumentNotNull("stackFrame", stackFrame); - - return stackFrame.StartsWith("at Xunit.", StringComparison.Ordinal); - } - - static string FilterStackTrace(string stack) - { - if (stack == null) - return null; - - var results = new List(); - - foreach (string line in SplitLines(stack)) - { - string trimmedLine = line.TrimStart(); - if (!ExcludeStackFrame(trimmedLine)) - results.Add(line); - } - - return string.Join(Environment.NewLine, results.ToArray()); - } - - static string GetMessage(IFailureInformation failureInfo, int index, int level) - { - string result = ""; - - if (level > 0) - { - for (int idx = 0; idx < level; idx++) - result += "----"; - - result += " "; - } - - var exceptionType = failureInfo.ExceptionTypes[index]; - if (GetNamespace(exceptionType) != "Xunit.Sdk") - result += exceptionType + " : "; - - result += failureInfo.Messages[index]; - - for (int subIndex = index + 1; subIndex < failureInfo.ExceptionParentIndices.Length; ++subIndex) - if (failureInfo.ExceptionParentIndices[subIndex] == index) - result += Environment.NewLine + GetMessage(failureInfo, subIndex, level + 1); - - return result; - } - - private static string GetNamespace(string exceptionType) - { - var nsIndex = exceptionType.LastIndexOf('.'); - if (nsIndex > 0) - return exceptionType.Substring(0, nsIndex); - - return ""; - } - - static string GetStackTrace(IFailureInformation failureInfo, int index) - { - string result = FilterStackTrace(failureInfo.StackTraces[index]); - - var children = new List(); - for (int subIndex = index + 1; subIndex < failureInfo.ExceptionParentIndices.Length; ++subIndex) - if (failureInfo.ExceptionParentIndices[subIndex] == index) - children.Add(subIndex); - - if (children.Count > 1) - { - for (int idx = 0; idx < children.Count; ++idx) - result += String.Format("{0}----- Inner Stack Trace #{1} ({2}) -----{0}{3}", - Environment.NewLine, - idx + 1, - failureInfo.ExceptionTypes[children[idx]], - GetStackTrace(failureInfo, children[idx])); - } - else if (children.Count == 1) - result += Environment.NewLine + - "----- Inner Stack Trace -----" + Environment.NewLine + - GetStackTrace(failureInfo, children[0]); - - return result; - } - - // Our own custom String.Split because Silverlight/CoreCLR doesn't support the version we were using - static IEnumerable SplitLines(string input) - { - while (true) - { - int idx = input.IndexOf(Environment.NewLine); - - if (idx < 0) - { - yield return input; - break; - } - - yield return input.Substring(0, idx); - input = input.Substring(idx + Environment.NewLine.Length); - } - } - - /// - /// Unwraps exceptions and their inner exceptions. - /// - /// The exception to be converted. - /// The failure information. - public static IFailureInformation ConvertExceptionToFailureInformation(Exception ex) - { - var exceptionTypes = new List(); - var messages = new List(); - var stackTraces = new List(); - var indices = new List(); - - ConvertExceptionToFailureInformation(ex, -1, exceptionTypes, messages, stackTraces, indices); - - return new FailureInformation - { - ExceptionParentIndices = indices.ToArray(), - ExceptionTypes = exceptionTypes.ToArray(), - Messages = messages.ToArray(), - StackTraces = stackTraces.ToArray(), - }; - } - - static void ConvertExceptionToFailureInformation(Exception ex, int parentIndex, List exceptionTypes, List messages, List stackTraces, List indices) - { - var myIndex = exceptionTypes.Count; - - exceptionTypes.Add(ex.GetType().FullName); - messages.Add(ex.Message); - stackTraces.Add(ex.StackTrace); - indices.Add(parentIndex); - -#if XUNIT_CORE_DLL - var aggEx = ex as AggregateException; - if (aggEx != null) - foreach (var innerException in aggEx.InnerExceptions) - ConvertExceptionToFailureInformation(innerException, myIndex, exceptionTypes, messages, stackTraces, indices); - else -#endif - if (ex.InnerException != null) - ConvertExceptionToFailureInformation(ex.InnerException, myIndex, exceptionTypes, messages, stackTraces, indices); - } - - class FailureInformation : IFailureInformation - { - public string[] ExceptionTypes { get; set; } - public string[] Messages { get; set; } - public string[] StackTraces { get; set; } - public int[] ExceptionParentIndices { get; set; } - } - - } -} diff --git a/src/common/FailSkipVisitor.cs b/src/common/FailSkipVisitor.cs deleted file mode 100644 index 9051cd1f6f..0000000000 --- a/src/common/FailSkipVisitor.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit -{ - public class FailSkipVisitor : TestMessageVisitor, IExecutionVisitor - { - readonly IExecutionVisitor Visitor; - int SkipCount; - - public FailSkipVisitor(IExecutionVisitor visitor) - { - Visitor = visitor; - } - - public ExecutionSummary ExecutionSummary => Visitor.ExecutionSummary; - - public override bool OnMessage(IMessageSinkMessage message) - { - var testSkipped = message as ITestSkipped; - if (testSkipped != null) - { - SkipCount++; - var testFailed = new TestFailed(testSkipped.Test, 0M, "", - new[] { "FAIL_SKIP" }, - new[] { testSkipped.Reason }, - new[] { "" }, - new[] { -1 }); - return Visitor.OnMessage(testFailed); - } - - var testCollectionFinished = message as ITestCollectionFinished; - if (testCollectionFinished != null) - { - testCollectionFinished = new TestCollectionFinished(testCollectionFinished.TestCases, - testCollectionFinished.TestCollection, - testCollectionFinished.ExecutionTime, - testCollectionFinished.TestsRun, - testCollectionFinished.TestsFailed + testCollectionFinished.TestsSkipped, - 0); - return Visitor.OnMessage(testCollectionFinished); - } - - var assemblyFinished = message as ITestAssemblyFinished; - if (assemblyFinished != null) - { - assemblyFinished = new TestAssemblyFinished(assemblyFinished.TestCases, - assemblyFinished.TestAssembly, - assemblyFinished.ExecutionTime, - assemblyFinished.TestsRun, - assemblyFinished.TestsFailed + assemblyFinished.TestsSkipped, - 0); - var result = Visitor.OnMessage(assemblyFinished); - base.OnMessage(assemblyFinished); - return result; - } - - return Visitor.OnMessage(message); - } - } -} diff --git a/src/common/Guard.cs b/src/common/Guard.cs deleted file mode 100644 index 5e9e5c040f..0000000000 --- a/src/common/Guard.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections; -using System.Diagnostics.CodeAnalysis; -using System.IO; - -/// -/// Guard class, used for guard clauses and argument validation -/// -internal static class Guard -{ - /// - public static void ArgumentNotNull(string argName, object argValue) - { - if (argValue == null) - throw new ArgumentNullException(argName); - } - - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method may not be called by all users of Guard.")] - public static void ArgumentNotNullOrEmpty(string argName, IEnumerable argValue) - { - ArgumentNotNull(argName, argValue); - - if (!argValue.GetEnumerator().MoveNext()) - throw new ArgumentException("Argument was empty", argName); - } - - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method may not be called by all users of Guard.")] - public static void ArgumentValid(string argName, string message, bool test) - { - if (!test) - throw new ArgumentException(message, argName); - } - -#if !XUNIT_CORE_DLL - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method may not be called by all users of Guard.")] - public static void FileExists(string argName, string fileName) - { -#if !ANDROID && !ASPNET50 && !ASPNETCORE50 - Guard.ArgumentNotNullOrEmpty(argName, fileName); - Guard.ArgumentValid("assemblyFileName", - String.Format("File not found: {0}", fileName), - File.Exists(fileName)); -#endif - } -#endif -} \ No newline at end of file diff --git a/src/common/LongLivedMarshalByRefObject_Runner_NoAppDomain.cs b/src/common/LongLivedMarshalByRefObject_Runner_NoAppDomain.cs deleted file mode 100644 index d4cc5c758e..0000000000 --- a/src/common/LongLivedMarshalByRefObject_Runner_NoAppDomain.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Xunit -{ - /// - /// Base class for all long-lived objects that may cross over an AppDomain. - /// - public abstract class LongLivedMarshalByRefObject -#if !WINDOWS_PHONE_APP && !WINDOWS_PHONE && !ASPNETCORE50 - : MarshalByRefObject -#endif - { } -} diff --git a/src/common/ParallelismOption.cs b/src/common/ParallelismOption.cs deleted file mode 100644 index 9d4147ef05..0000000000 --- a/src/common/ParallelismOption.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Xunit.ConsoleClient -{ - public enum ParallelismOption - { - none, - collections, - assemblies, - all - } -} diff --git a/src/common/RemoteAppDomainManager_WPA81.cs b/src/common/RemoteAppDomainManager_WPA81.cs deleted file mode 100644 index 022c2eb6c7..0000000000 --- a/src/common/RemoteAppDomainManager_WPA81.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Reflection; - -namespace Xunit -{ - internal class RemoteAppDomainManager : IDisposable - { - public RemoteAppDomainManager(string assemblyFileName, string configFileName, bool shadowCopy, string shadowCopyFolder) - { - Guard.ArgumentNotNullOrEmpty("assemblyFileName", assemblyFileName); - Guard.FileExists("assemblyFileName", assemblyFileName); - - AssemblyFileName = assemblyFileName; - ConfigFileName = configFileName; - } - - public string AssemblyFileName { get; private set; } - - public string ConfigFileName { get; private set; } - - public TObject CreateObject(string assemblyName, string typeName, params object[] args) - { - try - { - var type = Type.GetType(typeName + ", " + assemblyName, true); - return (TObject)Activator.CreateInstance(type, args); - } - catch (TargetInvocationException ex) - { - ex.InnerException.RethrowWithNoStackTraceLoss(); - return default(TObject); - } - } - - public virtual void Dispose() { } - } -} \ No newline at end of file diff --git a/src/common/SerializationInfoExtensions.cs b/src/common/SerializationInfoExtensions.cs deleted file mode 100644 index 845140a93d..0000000000 --- a/src/common/SerializationInfoExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -#if XUNIT_CORE_DLL || WINDOWS_PHONE_APP || WINDOWS_PHONE -using Xunit.Serialization; -#endif - -#if WINDOWS_PHONE_APP || WINDOWS_PHONE || ASPNETCORE50 -using Xunit; -#else -using System.Runtime.Serialization; -#endif - -internal static class SerializationInfoExtensions -{ - public static T GetValue(this SerializationInfo info, string name) - { - return (T)info.GetValue(name, typeof(T)); - } - -#if XUNIT_CORE_DLL || WINDOWS_PHONE_APP || WINDOWS_PHONE - public static T GetValue(this XunitSerializationInfo info, string name) - { - return (T)info.GetValue(name, typeof(T)); - } -#endif -} diff --git a/src/common/SourceInformation.cs b/src/common/SourceInformation.cs deleted file mode 100644 index 16f1bba3db..0000000000 --- a/src/common/SourceInformation.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using Xunit.Abstractions; -#if !ASPNETCORE50 -using System.Runtime.Serialization; -#endif - -#if XUNIT_CORE_DLL -using Xunit.Serialization; - -namespace Xunit.Sdk -#else -namespace Xunit -#endif -{ - /// - /// Default implementation of . - /// - [Serializable] - public class SourceInformation : LongLivedMarshalByRefObject, ISourceInformation, ISerializable -#if XUNIT_CORE_DLL - , IGetTypeData -#endif - { - /// - /// Initializes a new instance of the class. - /// - public SourceInformation() { } - - /// - public string FileName { get; set; } - - /// - public int? LineNumber { get; set; } - - // -------------------- Serialization -------------------- - - /// - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("FileName", FileName); - info.AddValue("LineNumber", LineNumber, typeof(int?)); - } - - /// - protected SourceInformation(SerializationInfo info, StreamingContext context) - { - FileName = info.GetString("FileName"); - LineNumber = (int?)info.GetValue("LineNumber", typeof(int?)); - } - -#if XUNIT_CORE_DLL - /// - public void GetData(XunitSerializationInfo info) - { - info.AddValue("FileName", FileName); - info.AddValue("LineNumber", LineNumber, typeof(int?)); - } - - /// - public void SetData(XunitSerializationInfo info) - { - FileName = info.GetString("FileName"); - LineNumber = (int?)info.GetValue("LineNumber", typeof(int?)); - } -#endif - } -} \ No newline at end of file diff --git a/src/common/TestDiscoveryVisitor.cs b/src/common/TestDiscoveryVisitor.cs deleted file mode 100644 index 51408e8887..0000000000 --- a/src/common/TestDiscoveryVisitor.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; -using Xunit.Abstractions; - -#if XUNIT_CORE_DLL -namespace Xunit.Sdk -#else -namespace Xunit -#endif -{ - internal class TestDiscoveryVisitor : TestMessageVisitor - { - public TestDiscoveryVisitor() - { - TestCases = new List(); - } - - public List TestCases { get; private set; } - - protected override bool Visit(ITestCaseDiscoveryMessage discovery) - { - TestCases.Add(discovery.TestCase); - - return true; - } - } -} \ No newline at end of file diff --git a/src/common/TestMessageVisitor.cs b/src/common/TestMessageVisitor.cs deleted file mode 100644 index 1aa8c07243..0000000000 --- a/src/common/TestMessageVisitor.cs +++ /dev/null @@ -1,454 +0,0 @@ -using System; -using System.Threading; -using Xunit.Abstractions; - -#if XUNIT_CORE_DLL -namespace Xunit.Sdk -#else -namespace Xunit -#endif -{ - /// - /// An implementation of that provides several Visit methods that - /// can provide access to specific message types without the burden of casting. - /// - public class TestMessageVisitor : LongLivedMarshalByRefObject, IMessageSink - { - /// - /// Dispatches the message to the given callback, if it's of the correct type. - /// - /// The message type - /// The message - /// The callback - /// The result of the callback, if called; true, otherwise - protected static bool DoVisit(IMessageSinkMessage message, Func callback) - where TMessage : class, IMessageSinkMessage - { - var castMessage = message as TMessage; - if (castMessage != null) - return callback(castMessage); - - return true; - } - - /// - public virtual bool OnMessage(IMessageSinkMessage message) - { - return - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit) && - DoVisit(message, Visit); - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(IAfterTestFinished afterTestFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(IAfterTestStarting afterTestStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(IBeforeTestFinished beforeTestFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(IBeforeTestStarting beforeTestStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue discovering/executing tests; false otherwise. - protected virtual bool Visit(IDiagnosticMessage diagnosticMessage) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue discovering tests; false otherwise. - protected virtual bool Visit(IDiscoveryCompleteMessage discoveryComplete) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(IErrorMessage error) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestAssemblyCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestAssemblyFinished assemblyFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestAssemblyStarting assemblyStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCaseCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue discovering tests; false otherwise. - protected virtual bool Visit(ITestCaseDiscoveryMessage testCaseDiscovered) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCaseFinished testCaseFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestOutput testCaseOutput) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCaseStarting testCaseStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassConstructionFinished testClassConstructionFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassConstructionStarting testClassConstructionStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassDisposeFinished testClassDisposedFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassDisposeStarting testClassDisposeStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassFinished testClassFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestClassStarting testClassStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCollectionCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCollectionFinished testCollectionFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestCollectionStarting testCollectionStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestFailed testFailed) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestFinished testFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestMethodCleanupFailure cleanupFailure) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestMethodFinished testMethodFinished) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestMethodStarting testMethodStarting) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestPassed testPassed) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestSkipped testSkipped) - { - return true; - } - - /// - /// Called when an instance of is sent to the message sink. - /// - /// The message. - /// Return true to continue executing tests; false otherwise. - protected virtual bool Visit(ITestStarting testStarting) - { - return true; - } - } - - /// - /// An implementation of that provides several Visit methods that - /// can provide access to specific message types without the burden of casting. It also records - /// when it sees a completion message, and sets the event appropriately. - /// - /// The type of the completion message. - public class TestMessageVisitor : TestMessageVisitor, IDisposable - where TCompleteMessage : IMessageSinkMessage - { - /// - /// Initializes a new instance of the class. - /// - public TestMessageVisitor() - { - Finished = new ManualResetEvent(initialState: false); - } - - /// - /// This event is triggered when the completion message has been seen. - /// - public ManualResetEvent Finished { get; private set; } - - /// - public void Dispose() - { - ((IDisposable)Finished).Dispose(); - } - - /// - public override bool OnMessage(IMessageSinkMessage message) - { - var result = base.OnMessage(message); - - if (message is TCompleteMessage) - Finished.Set(); - - return result; - } - } -} \ No newline at end of file diff --git a/src/common/TestMethodDisplay.cs b/src/common/TestMethodDisplay.cs deleted file mode 100644 index 117070384e..0000000000 --- a/src/common/TestMethodDisplay.cs +++ /dev/null @@ -1,22 +0,0 @@ -#if XUNIT_CORE_DLL -namespace Xunit.Sdk -#else -namespace Xunit -#endif -{ - /// - /// Indicates the default display name format for test methods. - /// - public enum TestMethodDisplay - { - /// - /// Use a fully qualified name (namespace + class + method) - /// - ClassAndMethod = 1, - - /// - /// Use just the method name (without class) - /// - Method = 2 - } -} diff --git a/src/common/TestOptionsNames.cs b/src/common/TestOptionsNames.cs deleted file mode 100644 index f4c8343e43..0000000000 --- a/src/common/TestOptionsNames.cs +++ /dev/null @@ -1,27 +0,0 @@ -internal static class TestOptionsNames -{ - internal static class Configuration - { - public const string DiagnosticMessages = "xunit.diagnosticMessages"; - public const string MaxParallelThreads = "xunit.maxParallelThreads"; - public const string MethodDisplay = "xunit.methodDisplay"; - public const string ParallelizeAssembly = "xunit.parallelizeAssembly"; - public const string ParallelizeTestCollections = "xunit.parallelizeTestCollections"; - public const string PreEnumerateTheories = "xunit.preEnumerateTheories"; - } - - internal static class Discovery - { - public static readonly string DiagnosticMessages = "xunit.discovery.DiagnosticMessages"; - public static readonly string MethodDisplay = "xunit.discovery.MethodDisplay"; - public static readonly string PreEnumerateTheories = "xunit.discovery.PreEnumerateTheories"; - } - - internal static class Execution - { - public static readonly string DiagnosticMessages = "xunit.execution.DiagnosticMessages"; - public static readonly string DisableParallelization = "xunit.execution.DisableParallelization"; - public static readonly string MaxParallelThreads = "xunit.execution.MaxParallelThreads"; - public static readonly string SynchronousMessageReporting = "xunit.execution.SynchronousMessageReporting"; - } -} \ No newline at end of file diff --git a/src/common/WinRTDirectory.cs b/src/common/WinRTDirectory.cs deleted file mode 100644 index f837d888f3..0000000000 --- a/src/common/WinRTDirectory.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using Windows.ApplicationModel; - -namespace System.IO -{ - internal static class Directory - { - public static bool Exists(string path) - { - if (Package.Current.InstalledLocation.Path.Contains(path)) - return true; - - return false; - } - - public static string[] GetFiles(string path, string searchOption) - { - var list = new List(); - var extension = Path.GetExtension(searchOption); - var filesAsync = Package.Current.InstalledLocation.GetFilesAsync(); - filesAsync.AsTask().Wait(); - - foreach (var file in filesAsync.GetResults()) - if (string.Equals(Path.GetExtension(file.Path), extension, StringComparison.OrdinalIgnoreCase)) - list.Add(file.Path); - - return list.ToArray(); - } - } -} \ No newline at end of file diff --git a/src/common/WinRTFile.cs b/src/common/WinRTFile.cs deleted file mode 100644 index 7bf4b4860f..0000000000 --- a/src/common/WinRTFile.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Windows.ApplicationModel; -using Windows.Storage; - -namespace System.IO -{ - internal static class File - { - public static bool Exists(string path) - { - return GetStorageFile(path) != null; - } - - public static Stream OpenRead(string path) - { - var storageFile = GetStorageFile(path); - if (storageFile == null) - throw new FileNotFoundException("Could not open file for read", path); - - return storageFile.OpenStreamForReadAsync().GetAwaiter().GetResult(); - } - - // Helpers - - static StorageFile GetStorageFile(string path) - { - if (String.IsNullOrWhiteSpace(path)) - return null; - - var folder = Package.Current.InstalledLocation; - - if (!path.Contains(folder.Path)) - return null; - - var fileName = Path.GetFileName(path); - var fileAsync = folder.GetFileAsync(fileName); - - try - { - fileAsync.AsTask().Wait(); - return fileAsync.GetResults(); - } - catch - { - return null; - } - } - } -} diff --git a/src/nuget/Microsoft.xunit.extensibility.execution.netcore.nuspec b/src/nuget/Microsoft.xunit.extensibility.execution.netcore.nuspec deleted file mode 100644 index f2bb751f34..0000000000 --- a/src/nuget/Microsoft.xunit.extensibility.execution.netcore.nuspec +++ /dev/null @@ -1,26 +0,0 @@ - - - - Microsoft.xunit.extensibility.execution.netcore - $PackageVersion$ - Redist of xunit.execution.execution to target netstandard1.0 - Microsoft - Microsoft - - This is a redisted package of xunit.extensibility.execution and it's dependencies for use - in the xunit-perfomance library (github.com/Microsoft/xunit-performance) - - en-US - http://go.microsoft.com/fwlink/?LinkId=518631 - http://go.microsoft.com/fwlink/?LinkId=329770 - http://go.microsoft.com/fwlink/?LinkID=288859 - false - - - - - - - - - \ No newline at end of file diff --git a/src/nuget/Microsoft.xunit.netcore.extensions.nuspec b/src/nuget/Microsoft.xunit.netcore.extensions.nuspec deleted file mode 100644 index badcb36eef..0000000000 --- a/src/nuget/Microsoft.xunit.netcore.extensions.nuspec +++ /dev/null @@ -1,45 +0,0 @@ - - - - Microsoft.xunit.netcore.extensions - $PackageVersion$ - xUnit extensions of .NET Core test projects - Microsoft - Microsoft - true - http://go.microsoft.com/fwlink/?LinkId=329770 - http://go.microsoft.com/fwlink/?LinkId=518631 - http://go.microsoft.com/fwlink/?LinkID=288859 - xUnit extensions of .NET Core test projects - This package provides things like various traits and discovers like OuterLoop/ActiveIssue that are used by .NET Core framework test projects. - Copyright © Microsoft Corporation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/nuget/xunit.console.netcore.nuspec b/src/nuget/xunit.console.netcore.nuspec deleted file mode 100644 index 6bddd2b5a0..0000000000 --- a/src/nuget/xunit.console.netcore.nuspec +++ /dev/null @@ -1,56 +0,0 @@ - - - - xunit.console.netcore - $PackageVersion$ - xUnit.net [Runners - .NET Core] - James Newkirk, Brad Wilson (.NET Core package by Matt Cohn) - Microsoft - true - http://go.microsoft.com/fwlink/?LinkId=329770 - http://go.microsoft.com/fwlink/?LinkId=518631 - http://go.microsoft.com/fwlink/?LinkID=288859 - .NET Core Framework Test Host - - Console runner for the xUnit.net framework. - Supported platforms: .NET Core. - Based on xunit.runners - https://github.com/xunit/xunit - - Copyright © Microsoft Corporation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/xunit.console.netcore/App.config b/src/xunit.console.netcore/App.config deleted file mode 100644 index 734e179bc2..0000000000 --- a/src/xunit.console.netcore/App.config +++ /dev/null @@ -1,17 +0,0 @@ - - - -
- - - - - - - - - - - - - diff --git a/src/xunit.console.netcore/CommandLine.cs b/src/xunit.console.netcore/CommandLine.cs deleted file mode 100644 index 4b9b5a641a..0000000000 --- a/src/xunit.console.netcore/CommandLine.cs +++ /dev/null @@ -1,307 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Xunit.ConsoleClient.Project; - -namespace Xunit.ConsoleClient -{ - public class CommandLine - { - readonly Stack arguments = new Stack(); - - protected CommandLine(string[] args, Predicate fileExists = null) - { - if (fileExists == null) - fileExists = fileName => File.Exists(fileName); - - for (var i = args.Length - 1; i >= 0; i--) - { - if (args[i][0] == '@') - { - // Parse response file - IList rspArguments = ParseResponseFile(args[i].Substring(1)); - for (int j = rspArguments.Count - 1; j >= 0; j--) - arguments.Push(rspArguments[j]); - continue; - } - arguments.Push(args[i]); - } - - TeamCity = Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null; - AppVeyor = Environment.GetEnvironmentVariable("APPVEYOR_API_URL") != null; - Project = Parse(fileExists); - } - - /// - /// Parse a response file passed as a command-line arguments. - /// No verification here to make this completely opaque - /// - /// Path to the response file - /// The data structure in - private IList ParseResponseFile(string responseFile) - { - - var argumentsList = new List(); - - if (!File.Exists(responseFile)) - throw new ArgumentException(String.Format("Response file {0} not found", responseFile)); - - // Add contents from the text file to the command line - foreach (string line in File.ReadAllLines(responseFile)) - { - string cleanLine = line.Trim(); - if (string.IsNullOrEmpty(cleanLine)) - continue; - var rspArguments = cleanLine.Split(); - foreach(string arg in rspArguments) - argumentsList.Add(arg); - } - - return argumentsList; - } - - public bool AppVeyor { get; protected set; } - - public int? MaxParallelThreads { get; set; } - - public ExtendedXunitProject Project { get; protected set; } - - public bool? ParallelizeAssemblies { get; protected set; } - - public bool? ParallelizeTestCollections { get; set; } - - public bool RedirectOutput { get; protected set; } - - public bool ShowProgress { get; protected set; } - - public bool TeamCity { get; protected set; } - - public bool Wait { get; protected set; } - - - static ExtendedXunitProject GetProjectFile(List> assemblies) - { - var result = new ExtendedXunitProject(); - - foreach (var assembly in assemblies) - result.Add(new XunitProjectAssembly - { - AssemblyFilename = Path.GetFullPath(assembly.Item1), - ConfigFilename = assembly.Item2 != null ? Path.GetFullPath(assembly.Item2) : null, - }); - - return result; - } - - static void GuardNoOptionValue(KeyValuePair option) - { - if (option.Value != null) - throw new ArgumentException(String.Format("error: unknown command line option: {0}", option.Value)); - } - - public static CommandLine Parse(params string[] args) - { - return new CommandLine(args); - } - - protected ExtendedXunitProject Parse(Predicate fileExists) - { - var assemblies = new List>(); - - while (arguments.Count > 0) - { - if (arguments.Peek().StartsWith("-")) - break; - - var assemblyFile = arguments.Pop(); - if (assemblyFile.EndsWith(".config", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(String.Format("expecting assembly, got config file: {0}", assemblyFile)); - if (!fileExists(assemblyFile)) - throw new ArgumentException(String.Format("file not found: {0}", assemblyFile)); - - string configFile = null; - if (arguments.Count > 0) - { - var value = arguments.Peek(); - if (!value.StartsWith("-") && value.EndsWith(".config", StringComparison.OrdinalIgnoreCase)) - { - configFile = arguments.Pop(); - if (!fileExists(configFile)) - throw new ArgumentException(String.Format("config file not found: {0}", configFile)); - } - } - - assemblies.Add(Tuple.Create(assemblyFile, configFile)); - } - - if (assemblies.Count == 0) - throw new ArgumentException("must specify at least one assembly"); - - var project = GetProjectFile(assemblies); - - while (arguments.Count > 0) - { - var option = PopOption(arguments); - var optionName = option.Key.ToLowerInvariant(); - - if (!optionName.StartsWith("-")) - throw new ArgumentException(String.Format("unknown command line option: {0}", option.Key)); - - if (optionName == "-wait") - { - GuardNoOptionValue(option); - Wait = true; - } - else if (optionName == "-maxthreads") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -maxthreads"); - - int threadValue; - if (!Int32.TryParse(option.Value, out threadValue) || threadValue < 0) - throw new ArgumentException("incorrect argument value for -maxthreads"); - - MaxParallelThreads = threadValue; - } - else if (optionName == "-parallel") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -parallel"); - - ParallelismOption parallelismOption; - if (!Enum.TryParse(option.Value, out parallelismOption)) - throw new ArgumentException("incorrect argument value for -parallel"); - - switch (parallelismOption) - { - case ParallelismOption.all: - ParallelizeAssemblies = true; - ParallelizeTestCollections = true; - break; - - case ParallelismOption.assemblies: - ParallelizeAssemblies = true; - ParallelizeTestCollections = false; - break; - - case ParallelismOption.collections: - ParallelizeAssemblies = false; - ParallelizeTestCollections = true; - break; - - case ParallelismOption.none: - default: - ParallelizeAssemblies = false; - ParallelizeTestCollections = false; - break; - } - } - else if (optionName == "-teamcity") - { - GuardNoOptionValue(option); - TeamCity = true; - } - else if (optionName == "-appveyor") - { - GuardNoOptionValue(option); - AppVeyor = true; - } - else if (optionName == "-redirectoutput") - { - GuardNoOptionValue(option); - RedirectOutput = true; - } - else if (optionName == "-showprogress") - { - GuardNoOptionValue(option); - ShowProgress = true; - } - else if (optionName == "-noshadow") - { - GuardNoOptionValue(option); - foreach (var assembly in project.Assemblies) - assembly.Configuration.ShadowCopy = false; - } - else if (optionName == "-trait") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -trait"); - - var pieces = option.Value.Split('='); - if (pieces.Length != 2 || String.IsNullOrEmpty(pieces[0]) || String.IsNullOrEmpty(pieces[1])) - throw new ArgumentException("incorrect argument format for -trait (should be \"name=value\")"); - - var name = pieces[0]; - var value = pieces[1]; - project.Filters.IncludedTraits.Add(name, value); - } - else if (optionName == "-notrait") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -notrait"); - - var pieces = option.Value.Split('='); - if (pieces.Length != 2 || String.IsNullOrEmpty(pieces[0]) || String.IsNullOrEmpty(pieces[1])) - throw new ArgumentException("incorrect argument format for -notrait (should be \"name=value\")"); - - var name = pieces[0]; - var value = pieces[1]; - project.Filters.ExcludedTraits.Add(name, value); - } - else if (optionName == "-class") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -class"); - - project.Filters.IncludedClasses.Add(option.Value); - } - else if (optionName == "-method") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -method"); - - project.Filters.IncludedMethods.Add(option.Value); - } - else if (optionName == "-skipmethod") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -skipmethod"); - project.Filters.ExcludedMethods.Add(option.Value); - - } - else if (optionName == "-skipclass") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -skipclass"); - project.Filters.ExcludedClasses.Add(option.Value); - } - else if (optionName == "-skipnamespace") - { - if (option.Value == null) - throw new ArgumentException("missing argument for -skipnamespace"); - project.Filters.ExcludedNamespaces.Add(option.Value); - } - else - { - if (option.Value == null) - throw new ArgumentException(String.Format("missing filename for {0}", option.Key)); - - project.Output.Add(optionName.Substring(1), option.Value); - } - } - - return project; - } - - static KeyValuePair PopOption(Stack arguments) - { - var option = arguments.Pop(); - string value = null; - - if (arguments.Count > 0 && !arguments.Peek().StartsWith("-")) - value = arguments.Pop(); - - return new KeyValuePair(option, value); - } - } -} diff --git a/src/xunit.console.netcore/Config/TransformConfigurationElement.cs b/src/xunit.console.netcore/Config/TransformConfigurationElement.cs deleted file mode 100644 index f6736c9904..0000000000 --- a/src/xunit.console.netcore/Config/TransformConfigurationElement.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Configuration; - -namespace Xunit.ConsoleClient -{ - public class TransformConfigurationElement : ConfigurationElement - { - [ConfigurationProperty("commandline", IsRequired = true, IsKey = true)] - public string CommandLine - { - get { return (string)this["commandline"]; } - set { this["commandline"] = value; } - } - - [ConfigurationProperty("description", IsRequired = true)] - public string Description - { - get { return (string)this["description"]; } - set { this["description"] = value; } - } - - [ConfigurationProperty("xslfile", IsRequired = true)] - public string XslFile - { - get { return (string)this["xslfile"]; } - set { this["xslfile"] = value; } - } - } -} \ No newline at end of file diff --git a/src/xunit.console.netcore/Config/TransformConfigurationElementCollection.cs b/src/xunit.console.netcore/Config/TransformConfigurationElementCollection.cs deleted file mode 100644 index 6275dcda17..0000000000 --- a/src/xunit.console.netcore/Config/TransformConfigurationElementCollection.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Configuration; - -namespace Xunit.ConsoleClient -{ - public class TransformConfigurationElementCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new TransformConfigurationElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((TransformConfigurationElement)element).CommandLine; - } - } -} \ No newline at end of file diff --git a/src/xunit.console.netcore/Config/XunitConsoleConfigurationSection.cs b/src/xunit.console.netcore/Config/XunitConsoleConfigurationSection.cs deleted file mode 100644 index d58e023074..0000000000 --- a/src/xunit.console.netcore/Config/XunitConsoleConfigurationSection.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Configuration; - -namespace Xunit.ConsoleClient -{ - public class XunitConsoleConfigurationSection : ConfigurationSection - { - [ConfigurationProperty("transforms", IsDefaultCollection = false)] - public TransformConfigurationElementCollection Transforms - { - get { return (TransformConfigurationElementCollection)this["transforms"]; } - set { this["transforms"] = value; } - } - } -} \ No newline at end of file diff --git a/src/xunit.console.netcore/Filters/ExtendedXunitFilters.cs b/src/xunit.console.netcore/Filters/ExtendedXunitFilters.cs deleted file mode 100644 index b51b5fe741..0000000000 --- a/src/xunit.console.netcore/Filters/ExtendedXunitFilters.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Xunit.Abstractions; - -namespace Xunit.ConsoleClient.Filters -{ - /// - /// Wrapper class, which hides XunitFilters' Filter method and adds logic to exclude methods or namespaces - /// - public class ExtendedXunitFilters : XunitFilters - { - public HashSet ExcludedMethods { get; private set; } - public HashSet ExcludedClasses { get; private set; } - public HashSet ExcludedNamespaces { get; private set; } - - public ExtendedXunitFilters() : base() - { - ExcludedMethods = new HashSet(); - ExcludedClasses = new HashSet(); - ExcludedNamespaces = new HashSet(); - } - - /// - /// Determine whether a passed test case should run - /// - /// Test case to filter - /// Boolean - True runs the test case, False skips - public new bool Filter(ITestCase testCase) - { - // Exclusions supersede inclusions - i.e. if a method/class/namespace is both included and excluded it won't run - return FilterExcludedMethodsAndClasses(testCase) && base.Filter(testCase); - } - - bool FilterExcludedMethodsAndClasses(ITestCase testCase) - { - // If no explicit exclusions have been defined, return true - if (ExcludedMethods.Count == 0 && ExcludedClasses.Count == 0 && ExcludedNamespaces.Count == 0) - return true; - - if (ExcludedClasses.Count != 0 && ExcludedClasses.Contains(testCase.TestMethod.TestClass.Class.Name)) - return false; - - var methodName = $"{testCase.TestMethod.TestClass.Class.Name}.{testCase.TestMethod.Method.Name}"; - - if (ExcludedMethods.Count != 0 && ExcludedMethods.Contains(methodName)) - return false; - - if (ExcludedNamespaces.Count != 0 && ExcludedNamespaces.Any(a => testCase.TestMethod.TestClass.Class.Name.StartsWith($"{a}.", StringComparison.Ordinal))) - return false; - - return true; - } - - } -} diff --git a/src/xunit.console.netcore/HTML.xslt b/src/xunit.console.netcore/HTML.xslt deleted file mode 100644 index cf055bf170..0000000000 --- a/src/xunit.console.netcore/HTML.xslt +++ /dev/null @@ -1,239 +0,0 @@ - - - - - - ]]> - - - xUnit.net Test Results - - - - -

- Assemblies Run -

- -

- Summary -

-
- Tests run:   - - Errors: , - - - Failures: , - - - Skipped: , - - Run time: s -
- -
-

- Errors -

- -
- -
-

- Failed tests -

- - - -
- -
-

- Collection failures -

- - - -
- -
-

- Skipped tests -

- - - -
-
-

- All tests -

-
Click test class name to expand/collapse test details
- - - -

- - s - - - ToggleClass('class') - ToggleClass('class') - - - - - - -   -   - ( tests) - - -
-

-
- - display: none; - - class - - - -
-
- - -
- - -
- -
-
- - -
- altrow - - - s - - - - Skipped - - - - - - - - -   -
- -
-
- -
-
- -
Output:
-
-
- -
Traits:
- - -
-
-
-
- - - - - - - - - -

- -
- altrow -
- -
-
- -
-
-
-
-
- - - -
- - altrow - - - Test Assembly Cleanup - Test Collection Cleanup - Test Class Cleanup - Test Method Cleanup - Test Case Cleanup - Test Cleanup - Fatal Error - - () - -
- -
-
- -
-
-
-
-
- -
\ No newline at end of file diff --git a/src/xunit.console.netcore/Program.cs b/src/xunit.console.netcore/Program.cs deleted file mode 100644 index fd6969ae75..0000000000 --- a/src/xunit.console.netcore/Program.cs +++ /dev/null @@ -1,372 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using System.Xml.Linq; -using Xunit.ConsoleClient.Filters; -using Xunit.ConsoleClient.Project; - -namespace Xunit.ConsoleClient -{ - public class Program - { - volatile static bool cancel; - static bool failed; - static readonly ConcurrentDictionary completionMessages = new ConcurrentDictionary(); - - [STAThread] - public static int Main(string[] args) - { - try - { - Console.ForegroundColor = ConsoleColor.White; -#if !NETCORE - var netVersion = Environment.Version; -#else - var netVersion = "Core"; -#endif - Console.WriteLine("xUnit.net console test runner ({0}-bit .NET {1})", IntPtr.Size * 8, netVersion); - Console.WriteLine("Copyright (C) 2014 Outercurve Foundation."); - Console.WriteLine(); - Console.ForegroundColor = ConsoleColor.Gray; - - if (args.Length == 0 || args[0] == "-?") - { - PrintUsage(); - return 2; - } - -#if !NETCORE - AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; -#endif - try - { - Console.CancelKeyPress += (sender, e) => - { - if (!cancel) - { - Console.WriteLine("Canceling... (Press Ctrl+C again to terminate)"); - cancel = true; - e.Cancel = true; - } - }; - } - catch (PlatformNotSupportedException) - { - Debug.WriteLine("Ignoring PlatformNotSupportedException from Console PAL"); - } - - var defaultDirectory = Directory.GetCurrentDirectory(); - if (!defaultDirectory.EndsWith(new String(new[] { Path.DirectorySeparatorChar }))) - { - defaultDirectory += Path.DirectorySeparatorChar; - } - - var commandLine = CommandLine.Parse(args); - - if (commandLine.RedirectOutput) - { - // Workaround for NetCore50 (UWP) implementations: - // When running against a version that will be no-op'ing the - // standard output stream, we will just redirect console output to a well known file name. - // - // This allows the most recent run's output to be logged. Could allow customization if it's interesting later. - StreamWriter textFileOutput = new StreamWriter(new FileStream("Xunit.Console.Output.txt", FileMode.Create)) - { - AutoFlush = true - }; - Console.SetOut(textFileOutput); - // Repeat output for consistency. - Console.WriteLine("xUnit.net console test runner ({0}-bit .NET {1})", IntPtr.Size * 8, netVersion); - Console.WriteLine("Copyright (C) 2014 Outercurve Foundation."); - Console.WriteLine(); - } - - var failCount = RunProject(defaultDirectory, commandLine.Project, commandLine.TeamCity, commandLine.AppVeyor, commandLine.ShowProgress, - commandLine.ParallelizeAssemblies, commandLine.ParallelizeTestCollections, - commandLine.MaxParallelThreads); - - if (commandLine.Wait) - { - Console.WriteLine(); - Console.Write("Press enter key to continue..."); - Console.ReadLine(); - Console.WriteLine(); - } - - return failCount > 0 ? 1 : 0; - } - catch (ArgumentException ex) - { - Console.WriteLine("error: {0}", ex.Message); - return 3; - } - catch (BadImageFormatException ex) - { - Console.WriteLine("{0}", ex.Message); - return 4; - } - finally - { - Console.ResetColor(); - } - } - -#if !NETCORE - static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) - { - var ex = e.ExceptionObject as Exception; - - if (ex != null) - Console.WriteLine(ex.ToString()); - else - Console.WriteLine("Error of unknown type thrown in application domain"); - - Environment.Exit(1); - } -#endif - - static void PrintUsage() - { -#if !NETCORE - var executableName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetLocalCodeBase()); -#else - var executableName = "xunit.console.netcore"; -#endif - - Console.WriteLine("usage: {0} [configFile] [assemblyFile [configFile]...] [options]", executableName); - Console.WriteLine(); - Console.WriteLine("Note: Configuration files must end in .config"); - Console.WriteLine(); - Console.WriteLine("Valid options:"); - Console.WriteLine(" -parallel option : set parallelization based on option"); - Console.WriteLine(" : none - turn off all parallelization"); - Console.WriteLine(" : collections - only parallelize collections"); - Console.WriteLine(" : assemblies - only parallelize assemblies"); - Console.WriteLine(" : all - parallelize assemblies & collections"); - Console.WriteLine(" -maxthreads count : maximum thread count for collection parallelization"); - Console.WriteLine(" : 0 - run with unbounded thread count"); - Console.WriteLine(" : >0 - limit task thread pool size to 'count'"); - Console.WriteLine(" -noshadow : do not shadow copy assemblies"); -#if !NETCORE - Console.WriteLine(" -teamcity : forces TeamCity mode (normally auto-detected)"); - Console.WriteLine(" -appveyor : forces AppVeyor CI mode (normally auto-detected)"); -#endif - Console.WriteLine(" -showprogress : display the names of tests as they start and finish"); - Console.WriteLine(" -wait : wait for input after completion"); - Console.WriteLine(" -trait \"name=value\" : only run tests with matching name/value traits"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -notrait \"name=value\" : do not run tests with matching name/value traits"); - Console.WriteLine(" : if specified more than once, acts as an AND operation"); - Console.WriteLine(" -method \"name\" : run a given test method (should be fully specified;"); - Console.WriteLine(" : i.e., 'MyNamespace.MyClass.MyTestMethod')"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -class \"name\" : run all methods in a given test class (should be fully"); - Console.WriteLine(" : specified; i.e., 'MyNamespace.MyClass')"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -redirectoutput : Redirect calls to Console APIs to file output,"); - Console.WriteLine(" : for platforms where console output is a noop."); - - TransformFactory.AvailableTransforms.ForEach( - transform => Console.WriteLine(" {0} : {1}", - String.Format("-{0} ", transform.CommandLine).PadRight(22).Substring(0, 22), - transform.Description) - ); - } - - static int RunProject(string defaultDirectory, ExtendedXunitProject project, bool teamcity, bool appVeyor, bool showProgress, bool? parallelizeAssemblies, bool? parallelizeTestCollections, int? maxThreadCount) - { - XElement assembliesElement = null; - var xmlTransformers = TransformFactory.GetXmlTransformers(project); - var needsXml = xmlTransformers.Count > 0; - var consoleLock = new object(); - - if (!parallelizeAssemblies.HasValue) - parallelizeAssemblies = project.All(assembly => assembly.Configuration.ParallelizeAssembly ?? false); - - if (needsXml) - assembliesElement = new XElement("assemblies"); - - var originalWorkingFolder = Directory.GetCurrentDirectory(); - - using (AssemblyHelper.SubscribeResolve()) - { - var clockTime = Stopwatch.StartNew(); - - if (parallelizeAssemblies.GetValueOrDefault()) - { - var tasks = project.Assemblies.Select(assembly => Task.Run(() => ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, showProgress, parallelizeTestCollections, maxThreadCount, project.Filters))); - var results = Task.WhenAll(tasks).GetAwaiter().GetResult(); - foreach (var assemblyElement in results.Where(result => result != null)) - assembliesElement.Add(assemblyElement); - } - else - { - foreach (var assembly in project.Assemblies) - { - var assemblyElement = ExecuteAssembly(consoleLock, defaultDirectory, assembly, needsXml, teamcity, appVeyor, showProgress, parallelizeTestCollections, maxThreadCount, project.Filters); - if (assemblyElement != null) - assembliesElement.Add(assemblyElement); - } - } - - clockTime.Stop(); - - if (completionMessages.Count > 0) - { - Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine(); - Console.WriteLine("=== TEST EXECUTION SUMMARY ==="); - Console.ForegroundColor = ConsoleColor.Gray; - - var totalTestsRun = completionMessages.Values.Sum(summary => summary.Total); - var totalTestsFailed = completionMessages.Values.Sum(summary => summary.Failed); - var totalTestsSkipped = completionMessages.Values.Sum(summary => summary.Skipped); - var totalTime = completionMessages.Values.Sum(summary => summary.Time).ToString("0.000s"); - var totalErrors = completionMessages.Values.Sum(summary => summary.Errors); - var longestAssemblyName = completionMessages.Keys.Max(key => key.Length); - var longestTotal = totalTestsRun.ToString().Length; - var longestFailed = totalTestsFailed.ToString().Length; - var longestSkipped = totalTestsSkipped.ToString().Length; - var longestTime = totalTime.Length; - var longestErrors = totalErrors.ToString().Length; - - foreach (var message in completionMessages.OrderBy(m => m.Key)) - Console.WriteLine(" {0} Total: {1}, Errors: {2}, Failed: {3}, Skipped: {4}, Time: {5}", - message.Key.PadRight(longestAssemblyName), - message.Value.Total.ToString().PadLeft(longestTotal), - message.Value.Errors.ToString().PadLeft(longestErrors), - message.Value.Failed.ToString().PadLeft(longestFailed), - message.Value.Skipped.ToString().PadLeft(longestSkipped), - message.Value.Time.ToString("0.000s").PadLeft(longestTime)); - - if (completionMessages.Count > 1) - Console.WriteLine(" {0} {1} {2} {3} {4} {5}" + Environment.NewLine + - " {6} {7} {8} {9} {10} {11} ({12})", - " ".PadRight(longestAssemblyName), - "-".PadRight(longestTotal, '-'), - "-".PadRight(longestErrors, '-'), - "-".PadRight(longestFailed, '-'), - "-".PadRight(longestSkipped, '-'), - "-".PadRight(longestTime, '-'), - "GRAND TOTAL:".PadLeft(longestAssemblyName), - totalTestsRun, - totalErrors, - totalTestsFailed, - totalTestsSkipped, - totalTime, - clockTime.Elapsed.TotalSeconds.ToString("0.000s")); - - } - } - - Directory.SetCurrentDirectory(originalWorkingFolder); - - xmlTransformers.ForEach(transformer => transformer(assembliesElement)); - - return failed ? 1 : completionMessages.Values.Sum(summary => summary.Failed); - } - - static XmlTestExecutionVisitor CreateVisitor(object consoleLock, string defaultDirectory, XElement assemblyElement, bool teamCity, bool appVeyor, bool showProgress) - { -#if !NETCORE - if (teamCity) - return new TeamCityVisitor(assemblyElement, () => cancel); - else if (appVeyor) - return new AppVeyorVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages); -#endif - - return new StandardOutputVisitor(consoleLock, defaultDirectory, assemblyElement, () => cancel, completionMessages, showProgress); - } - - static XElement ExecuteAssembly(object consoleLock, string defaultDirectory, XunitProjectAssembly assembly, bool needsXml, bool teamCity, bool appVeyor, bool showProgress, bool? parallelizeTestCollections, int? maxThreadCount, ExtendedXunitFilters filters) - { - if (cancel) - return null; - - var assemblyElement = needsXml ? new XElement("assembly") : null; - - try - { - if (!ValidateFileExists(consoleLock, assembly.AssemblyFilename) || !ValidateFileExists(consoleLock, assembly.ConfigFilename)) - return null; - - // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner - assembly.Configuration.PreEnumerateTheories = false; - - var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration); - var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration); - if (maxThreadCount.HasValue) - executionOptions.SetMaxParallelThreads(maxThreadCount.GetValueOrDefault()); - if (parallelizeTestCollections.HasValue) - executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault()); - - lock (consoleLock) - { - if (assembly.Configuration.DiagnosticMessages ?? false) - Console.WriteLine("Discovering: {0} (method display = {1}, parallel test collections = {2}, max threads = {3})", - Path.GetFileNameWithoutExtension(assembly.AssemblyFilename), - discoveryOptions.GetMethodDisplay(), - !executionOptions.GetDisableParallelization(), - executionOptions.GetMaxParallelThreads()); - else - Console.WriteLine("Discovering: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); - } - - using (var controller = new XunitFrontController(AppDomainSupport.Denied, assembly.AssemblyFilename, assembly.ConfigFilename, assembly.Configuration.ShadowCopyOrDefault)) - using (var discoveryVisitor = new TestDiscoveryVisitor()) - { - controller.Find(includeSourceInformation: false, messageSink: discoveryVisitor, discoveryOptions: discoveryOptions); - discoveryVisitor.Finished.WaitOne(); - - lock (consoleLock) - { - Console.WriteLine("Discovered: {0}", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); - } - - var resultsVisitor = CreateVisitor(consoleLock, defaultDirectory, assemblyElement, teamCity, appVeyor, showProgress); - var filteredTestCases = discoveryVisitor.TestCases.Where(filters.Filter).ToList(); - if (filteredTestCases.Count == 0) - { - lock (consoleLock) - { - Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine("Info: {0} has no tests to run", Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)); - Console.ForegroundColor = ConsoleColor.Gray; - } - } - else - { - controller.RunTests(filteredTestCases, resultsVisitor, executionOptions); - resultsVisitor.Finished.WaitOne(); - } - } - } - catch (Exception ex) - { - Console.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message); - failed = true; - } - - return assemblyElement; - } - - static bool ValidateFileExists(object consoleLock, string fileName) - { - if (String.IsNullOrWhiteSpace(fileName) || File.Exists(fileName)) - return true; - - lock (consoleLock) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("File not found: {0}", fileName); - Console.ForegroundColor = ConsoleColor.Gray; - } - - return false; - } - } -} diff --git a/src/xunit.console.netcore/Project/ExtendedXunitProject.cs b/src/xunit.console.netcore/Project/ExtendedXunitProject.cs deleted file mode 100644 index 5da9319c85..0000000000 --- a/src/xunit.console.netcore/Project/ExtendedXunitProject.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit.ConsoleClient.Filters; - -namespace Xunit.ConsoleClient.Project -{ - public class ExtendedXunitProject : XunitProject - { - public new ExtendedXunitFilters Filters { get; private set; } - public ExtendedXunitProject() : base() - { - Filters = new ExtendedXunitFilters(); - } - } -} diff --git a/src/xunit.console.netcore/Properties/AssemblyInfo.cs b/src/xunit.console.netcore/Properties/AssemblyInfo.cs deleted file mode 100644 index 0afdef48eb..0000000000 --- a/src/xunit.console.netcore/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Reflection; - -[assembly : AssemblyTitle("xUnit.net Console Test Runner")] \ No newline at end of file diff --git a/src/xunit.console.netcore/RunnerCallbacks/RunnerCallback.cs b/src/xunit.console.netcore/RunnerCallbacks/RunnerCallback.cs deleted file mode 100644 index 65328da703..0000000000 --- a/src/xunit.console.netcore/RunnerCallbacks/RunnerCallback.cs +++ /dev/null @@ -1,84 +0,0 @@ -//using System; - -//namespace Xunit.ConsoleClient -//{ -// public class RunnerCallback : ITestMethodRunnerCallback -// { -// public int TotalTests { get; set; } -// public int TotalFailures { get; set; } -// public int TotalSkips { get; set; } -// public double TotalTime { get; set; } - -// public virtual void AssemblyFinished(TestAssembly testAssembly, int total, int failed, int skipped, double time) -// { -// TotalTests = total; -// TotalFailures = failed; -// TotalSkips = skipped; -// TotalTime = time; -// } - -// public virtual void AssemblyStart(TestAssembly testAssembly) -// { -// } - -// public virtual bool ClassFailed(TestClass testClass, string exceptionType, string message, string stackTrace) -// { -// return true; -// } - -// public virtual void ExceptionThrown(TestAssembly testAssembly, Exception exception) -// { -// Console.WriteLine(); -// Console.WriteLine("CATASTROPHIC ERROR OCCURRED:"); -// Console.WriteLine(exception.ToString()); -// Console.WriteLine("WHILE RUNNING:"); -// Console.WriteLine(testAssembly.AssemblyFilename); -// Console.WriteLine(); -// } - -// protected virtual void TestFailed(TestMethod method, TestFailedResult result) -// { -// } - -// public bool TestFinished(TestMethod method) -// { -// TestResult result = method.RunResults[method.RunResults.Count - 1]; - -// TestPassedResult passedResult = result as TestPassedResult; -// if (passedResult != null) -// TestPassed(method, passedResult); -// else -// { -// TestFailedResult failedResult = result as TestFailedResult; -// if (failedResult != null) -// TestFailed(method, failedResult); -// else -// { -// TestSkippedResult skippedResult = result as TestSkippedResult; -// if (skippedResult != null) -// TestSkipped(method, skippedResult); -// } -// } - -// return TestFinished(method, result); -// } - -// protected virtual bool TestFinished(TestMethod method, TestResult result) -// { -// return true; -// } - -// protected virtual void TestPassed(TestMethod method, TestPassedResult result) -// { -// } - -// protected virtual void TestSkipped(TestMethod method, TestSkippedResult result) -// { -// } - -// public virtual bool TestStart(TestMethod method) -// { -// return true; -// } -// } -//} \ No newline at end of file diff --git a/src/xunit.console.netcore/RunnerCallbacks/StandardRunnerCallback.cs b/src/xunit.console.netcore/RunnerCallbacks/StandardRunnerCallback.cs deleted file mode 100644 index 6b9c2d83f0..0000000000 --- a/src/xunit.console.netcore/RunnerCallbacks/StandardRunnerCallback.cs +++ /dev/null @@ -1,115 +0,0 @@ -//using System; -//using System.Globalization; - -//namespace Xunit.ConsoleClient -//{ -// public class StandardRunnerCallback : RunnerCallback -// { -// readonly bool silent; -// int testCount = 0; -// readonly int totalCount; - -// public StandardRunnerCallback(bool silent, int totalCount) -// { -// this.silent = silent; -// this.totalCount = totalCount; -// } - -// public override void AssemblyFinished(TestAssembly testAssembly, int total, int failed, int skipped, double time) -// { -// base.AssemblyFinished(testAssembly, total, failed, skipped, time); - -// if (!silent) -// Console.Write("\r"); - -// Console.WriteLine("{0} total, {1} failed, {2} skipped, took {3} seconds", total, failed, skipped, time.ToString("0.000", CultureInfo.CurrentCulture)); -// } - -// public override bool ClassFailed(TestClass testClass, string exceptionType, string message, string stackTrace) -// { -// if (!silent) -// Console.Write("\r"); - -// Console.ForegroundColor = ConsoleColor.Red; -// Console.WriteLine("{0} [FIXTURE FAIL]", testClass.TypeName); -// Console.ResetColor(); - -// Console.WriteLine(Indent(message)); - -// if (stackTrace != null) -// { -// Console.WriteLine(Indent("Stack Trace:")); -// Console.WriteLine(Indent(StackFrameTransformer.TransformStack(stackTrace))); -// } - -// Console.WriteLine(); -// return true; -// } - -// protected override void TestFailed(TestMethod testMethod, TestFailedResult result) -// { -// if (!silent) -// Console.Write("\r"); - -// Console.ForegroundColor = ConsoleColor.Red; -// Console.WriteLine("{0} [FAIL]", result.DisplayName); -// Console.ResetColor(); - -// Console.WriteLine(Indent(result.ExceptionMessage)); - -// if (result.ExceptionStackTrace != null) -// { -// Console.ForegroundColor = ConsoleColor.DarkGray; -// Console.WriteLine(Indent("Stack Trace:")); -// Console.ResetColor(); - -// Console.WriteLine(Indent(StackFrameTransformer.TransformStack(result.ExceptionStackTrace))); -// } - -// Console.WriteLine(); -// } - -// protected override bool TestFinished(TestMethod testMethod, TestResult testResult) -// { -// if (!silent) -// { -// Console.ForegroundColor = ConsoleColor.DarkGray; -// Console.Write("\rTests complete: {0} of {1}", ++testCount, totalCount); -// Console.ResetColor(); -// } - -// return true; -// } - -// protected override void TestSkipped(TestMethod testMethod, TestSkippedResult result) -// { -// if (!silent) -// Console.Write("\r"); - -// Console.ForegroundColor = ConsoleColor.Yellow; -// Console.WriteLine("{0} [SKIP]", result.DisplayName); -// Console.ResetColor(); - -// Console.WriteLine(Indent(result.Reason)); -// Console.WriteLine(); -// } - -// // Helpers - -// string Indent(string message) -// { -// return Indent(message, 0); -// } - -// string Indent(string message, int additionalSpaces) -// { -// string result = ""; -// string indent = "".PadRight(additionalSpaces + 3); - -// foreach (string line in message.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) -// result += indent + line + Environment.NewLine; - -// return result.TrimEnd(); -// } -// } -//} \ No newline at end of file diff --git a/src/xunit.console.netcore/RunnerCallbacks/TeamCityRunnerCallback.cs b/src/xunit.console.netcore/RunnerCallbacks/TeamCityRunnerCallback.cs deleted file mode 100644 index ff4300143f..0000000000 --- a/src/xunit.console.netcore/RunnerCallbacks/TeamCityRunnerCallback.cs +++ /dev/null @@ -1,106 +0,0 @@ -//using System; -//using System.IO; - -//namespace Xunit.ConsoleClient -//{ -// public class TeamCityRunnerCallback : RunnerCallback -// { -// public override void AssemblyFinished(TestAssembly testAssembly, int total, int failed, int skipped, double time) -// { -// base.AssemblyFinished(testAssembly, total, failed, skipped, time); - -// Console.WriteLine( -// "##teamcity[testSuiteFinished name='{0}']", -// Escape(Path.GetFileName(testAssembly.AssemblyFilename)) -// ); -// } - -// public override void AssemblyStart(TestAssembly testAssembly) -// { -// Console.WriteLine( -// "##teamcity[testSuiteStarted name='{0}']", -// Escape(Path.GetFileName(testAssembly.AssemblyFilename)) -// ); -// } - -// public override bool ClassFailed(TestClass testClass, string exceptionType, string message, string stackTrace) -// { -// Console.WriteLine( -// "##teamcity[buildStatus status='FAILURE' text='Class failed: {0}: {1}|r|n{2}']", -// Escape(testClass.TypeName), -// Escape(message), -// Escape(stackTrace) -// ); - -// return true; -// } - -// protected override void TestFailed(TestMethod method, TestFailedResult result) -// { -// Console.WriteLine( -// "##teamcity[testFailed name='{0}' details='{1}|r|n{2}']", -// Escape(method.DisplayName), -// Escape(result.ExceptionMessage), -// Escape(result.ExceptionStackTrace) -// ); - -// WriteOutput(result.DisplayName, result.Output); -// } - -// protected override bool TestFinished(TestMethod method, TestResult result) -// { -// WriteFinished(method.DisplayName, result.Duration); -// return true; -// } - -// protected override void TestPassed(TestMethod method, TestPassedResult result) -// { -// WriteOutput(method.DisplayName, result.Output); -// } - -// protected override void TestSkipped(TestMethod method, TestSkippedResult result) -// { -// Console.WriteLine( -// "##teamcity[testIgnored name='{0}' message='{1}']", -// Escape(method.DisplayName), -// Escape(result.Reason) -// ); -// } - -// public override bool TestStart(TestMethod method) -// { -// Console.WriteLine( -// "##teamcity[testStarted name='{0}']", -// Escape(method.DisplayName) -// ); - -// return true; -// } - -// // Helpers - -// static string Escape(string value) -// { -// if (value == null) -// return String.Empty; - -// return value.Replace("|", "||") -// .Replace("'", "|'") -// .Replace("\r", "|r") -// .Replace("\n", "|n") -// .Replace("]", "|]"); -// } - -// static void WriteFinished(string name, double duration) -// { -// Console.WriteLine("##teamcity[testFinished name='{0}' duration='{1}']", -// Escape(name), (int)(duration * 1000D)); -// } - -// static void WriteOutput(string name, string output) -// { -// if (output != null) -// Console.WriteLine("##teamcity[testStdOut name='{0}' out='{1}']", Escape(name), Escape(output)); -// } -// } -//} \ No newline at end of file diff --git a/src/xunit.console.netcore/Utility/StackFrameTransformer.cs b/src/xunit.console.netcore/Utility/StackFrameTransformer.cs deleted file mode 100644 index ff907e891e..0000000000 --- a/src/xunit.console.netcore/Utility/StackFrameTransformer.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace Xunit.ConsoleClient -{ - /// - /// Transforms stack frames and stack traces into compiler-like output - /// so they can be double-clicked in Visual Studio. - /// - public static class StackFrameTransformer - { - static Regex regex; - - static StackFrameTransformer() - { - regex = new Regex(@"^\s*at (?.*) in (?.*):(line )?(?\d+)$"); - } - - /// - public static string TransformFrame(string stackFrame, string defaultDirectory) - { - if (stackFrame == null) - return null; - - var match = regex.Match(stackFrame); - if (match == Match.Empty) - return stackFrame; - - var file = match.Groups["file"].Value; - if (file.StartsWith(defaultDirectory, StringComparison.OrdinalIgnoreCase)) - file = file.Substring(defaultDirectory.Length); - - return String.Format("{0}({1},0): at {2}", - file, - match.Groups["line"].Value, - match.Groups["method"].Value); - } - - /// - public static string TransformStack(string stack, string defaultDirectory) - { - if (stack == null) - return null; - - List results = new List(); - - foreach (string frame in stack.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) - results.Add(TransformFrame(frame, defaultDirectory)); - - return String.Join(Environment.NewLine, results.ToArray()); - } - } -} diff --git a/src/xunit.console.netcore/Utility/Transform.cs b/src/xunit.console.netcore/Utility/Transform.cs deleted file mode 100644 index 5b4541a0f8..0000000000 --- a/src/xunit.console.netcore/Utility/Transform.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Xml.Linq; - -namespace Xunit.ConsoleClient -{ - public class Transform - { - public string CommandLine; - public string Description; - public Action OutputHandler; - } -} diff --git a/src/xunit.console.netcore/Utility/TransformFactory.cs b/src/xunit.console.netcore/Utility/TransformFactory.cs deleted file mode 100644 index f21b8e7639..0000000000 --- a/src/xunit.console.netcore/Utility/TransformFactory.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Xml; -using System.Xml.Linq; -using Xunit.ConsoleClient.Project; - -#if !NETCORE -using System.Configuration; -using System.Xml.Xsl; -#endif - -namespace Xunit.ConsoleClient -{ - public class TransformFactory - { - static readonly TransformFactory instance = new TransformFactory(); - - readonly Dictionary availableTransforms = new Dictionary(StringComparer.OrdinalIgnoreCase); - - protected TransformFactory() - { - availableTransforms.Add("xml", new Transform { CommandLine = "xml", Description = "output results to xUnit.net v2 style XML file", OutputHandler = Handler_DirectWrite }); -#if !NETCORE - var executablePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetLocalCodeBase()); - var exeConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); - var configSection = (XunitConsoleConfigurationSection)exeConfiguration.GetSection("xunit") ?? new XunitConsoleConfigurationSection(); - - - configSection.Transforms.Cast().ToList().ForEach(configElement => - { - string xslFileName = Path.Combine(executablePath, configElement.XslFile); - if (!File.Exists(xslFileName)) - throw new ArgumentException(String.Format("cannot find transform XSL file '{0}' for transform '{1}'", xslFileName, configElement.CommandLine)); - - availableTransforms.Add(configElement.CommandLine, - new Transform - { - CommandLine = configElement.CommandLine, - Description = configElement.Description, - OutputHandler = (xml, outputFileName) => Handler_XslTransform(xslFileName, xml, outputFileName) - }); - }); -#endif - } - - public static List AvailableTransforms - { - get { return instance.availableTransforms.Values.ToList(); } - } - - public static List> GetXmlTransformers(ExtendedXunitProject project) - { - return project.Output.Select(output => new Action(xml => instance.availableTransforms[output.Key].OutputHandler(xml, output.Value))).ToList(); - } - - static void Handler_DirectWrite(XElement xml, string outputFileName) - { - using (var fileStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, false)) - { - xml.Save(fileStream); - } - } - -#if !NETCORE - static void Handler_XslTransform(string xslPath, XElement xml, string outputFileName) - { - var xmlTransform = new XslCompiledTransform(); - - using (var writer = XmlWriter.Create(outputFileName, new XmlWriterSettings { Indent = true })) - using (var xsltStream = File.Open(xslPath, FileMode.Open)) - using (var xsltReader = XmlReader.Create(xsltStream)) - using (var xmlReader = xml.CreateReader()) - { - xmlTransform.Load(xsltReader); - xmlTransform.Transform(xmlReader, writer); - } - } -#endif - } -} diff --git a/src/xunit.console.netcore/Visitors/AppVeyorLogger.cs b/src/xunit.console.netcore/Visitors/AppVeyorLogger.cs deleted file mode 100644 index 2df5bf290f..0000000000 --- a/src/xunit.console.netcore/Visitors/AppVeyorLogger.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Net; -using System.Text; -using System.Web.Script.Serialization; - -namespace Xunit.ConsoleClient -{ - public class AppVeyorLogger - { - const int MaxLength = 4096; - - static string apiUrl; - - public static void AddTest(string testName, string testFramework, string fileName, string outcome, long? durationMilliseconds, - string errorMessage, string errorStackTrace, string stdOut, string stdErr) - { - if (GetApiUrl() == null) - return; - - var body = new AddUpdateTestRequest - { - TestName = testName, - TestFramework = testFramework, - FileName = fileName, - Outcome = outcome, - DurationMilliseconds = durationMilliseconds, - ErrorMessage = errorMessage, - ErrorStackTrace = errorStackTrace, - StdOut = TrimStdOut(stdOut), - StdErr = TrimStdOut(stdErr) - }; - - try - { - using (var wc = GetClient()) - wc.UploadData("api/tests", "POST", Json(body)); - } - catch (Exception ex) - { - Console.Error.WriteLine("Error communicating AppVeyor Build Worker API: " + ex.Message); - } - } - - public static void UpdateTest(string testName, string testFramework, string fileName, string outcome, long? durationMilliseconds, - string errorMessage, string errorStackTrace, string stdOut, string stdErr) - { - if (GetApiUrl() == null) - return; - - var body = new AddUpdateTestRequest - { - TestName = testName, - TestFramework = testFramework, - FileName = fileName, - Outcome = outcome, - DurationMilliseconds = durationMilliseconds, - ErrorMessage = errorMessage, - ErrorStackTrace = errorStackTrace, - StdOut = TrimStdOut(stdOut), - StdErr = TrimStdOut(stdErr) - }; - - try - { - using (var wc = GetClient()) - wc.UploadData("api/tests", "PUT", Json(body)); - } - catch (Exception ex) - { - Console.Error.WriteLine("Error communicating AppVeyor Build Worker API: " + ex.Message); - } - } - - static string TrimStdOut(string str) - { - return str != null && str.Length > MaxLength ? str.Substring(0, MaxLength) : str; - } - - static byte[] Json(object data) - { - var serializer = new JavaScriptSerializer(); - var json = serializer.Serialize(data); - return Encoding.UTF8.GetBytes(json); - } - - static WebClient GetClient() - { - var wc = new WebClient() { BaseAddress = GetApiUrl() }; - wc.Headers["Accept"] = "application/json"; - wc.Headers["Content-type"] = "application/json"; - return wc; - } - - static string GetApiUrl() - { - if (apiUrl == null) - { - apiUrl = Environment.GetEnvironmentVariable("APPVEYOR_API_URL"); - - if (apiUrl != null) - apiUrl = apiUrl.TrimEnd('/') + "/"; - } - - return apiUrl; - } - - public class AddUpdateTestRequest - { - public string TestName { get; set; } - public string FileName { get; set; } - public string TestFramework { get; set; } - public string Outcome { get; set; } - public long? DurationMilliseconds { get; set; } - public string ErrorMessage { get; set; } - public string ErrorStackTrace { get; set; } - public string StdOut { get; set; } - public string StdErr { get; set; } - } - } -} diff --git a/src/xunit.console.netcore/Visitors/AppVeyorVisitor.cs b/src/xunit.console.netcore/Visitors/AppVeyorVisitor.cs deleted file mode 100644 index e04808bb95..0000000000 --- a/src/xunit.console.netcore/Visitors/AppVeyorVisitor.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.IO; -using System.Net; -using System.Text; -using System.Web.Script.Serialization; -using System.Xml.Linq; -using Xunit.Abstractions; - -namespace Xunit.ConsoleClient -{ - public class AppVeyorVisitor : XmlTestExecutionVisitor - { - const string FrameworkName = "xUnit"; - - string assemblyFileName; - readonly object consoleLock; - readonly ConcurrentDictionary completionMessages; - readonly string defaultDirectory; - readonly ConcurrentDictionary testMethods = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - public AppVeyorVisitor(object consoleLock, - string defaultDirectory, - XElement assemblyElement, - Func cancelThunk, - ConcurrentDictionary completionMessages = null) - : base(assemblyElement, cancelThunk) - { - this.consoleLock = consoleLock; - this.defaultDirectory = defaultDirectory; - this.completionMessages = completionMessages; - } - - protected override bool Visit(ITestAssemblyStarting assemblyStarting) - { - assemblyFileName = Path.GetFileName(assemblyStarting.TestAssembly.Assembly.AssemblyPath); - - lock (consoleLock) - Console.WriteLine("Starting: {0}", assemblyFileName); - - return base.Visit(assemblyStarting); - } - - protected override bool Visit(ITestAssemblyFinished assemblyFinished) - { - // Base class does computation of results, so call it first. - var result = base.Visit(assemblyFinished); - - lock (consoleLock) - Console.WriteLine("Finished: {0}", assemblyFileName); - - if (completionMessages != null) - completionMessages.TryAdd(assemblyFileName, new ExecutionSummary - { - Total = assemblyFinished.TestsRun, - Failed = assemblyFinished.TestsFailed, - Skipped = assemblyFinished.TestsSkipped, - Time = assemblyFinished.ExecutionTime, - Errors = Errors - }); - - return result; - } - - protected override bool Visit(IErrorMessage error) - { - lock (consoleLock) - { - Console.Error.WriteLine(" {0} [FATAL]", Escape(error.ExceptionTypes[0])); - Console.Error.WriteLine(" {0}", Escape(ExceptionUtility.CombineMessages(error))); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(error)); - } - - return base.Visit(error); - } - - protected override bool Visit(ITestStarting testStarting) - { - var testName = testStarting.Test.DisplayName; - if (testMethods.ContainsKey(testName)) - testName = String.Format("{0} {1}", testName, testMethods[testName]); - - AppVeyorLogger.AddTest(testName, FrameworkName, assemblyFileName, "Running", null, null, null, null, null); - - return base.Visit(testStarting); - } - - protected override bool Visit(ITestPassed testPassed) - { - AppVeyorLogger.UpdateTest(GetFinishedTestName(testPassed.Test.DisplayName), FrameworkName, assemblyFileName, "Passed", - Convert.ToInt64(testPassed.ExecutionTime * 1000), null, null, testPassed.Output, null); - - return base.Visit(testPassed); - } - - protected override bool Visit(ITestSkipped testSkipped) - { - AppVeyorLogger.UpdateTest(GetFinishedTestName(testSkipped.Test.DisplayName), FrameworkName, assemblyFileName, "Skipped", - Convert.ToInt64(testSkipped.ExecutionTime * 1000), null, null, null, null); - - lock (consoleLock) - { - Console.Error.WriteLine(" {0} [SKIP]", Escape(testSkipped.Test.DisplayName)); - Console.Error.WriteLine(" {0}", Escape(testSkipped.Reason)); - } - - return base.Visit(testSkipped); - } - - protected override bool Visit(ITestFailed testFailed) - { - AppVeyorLogger.UpdateTest(GetFinishedTestName(testFailed.Test.DisplayName), FrameworkName, assemblyFileName, "Failed", - Convert.ToInt64(testFailed.ExecutionTime * 1000), ExceptionUtility.CombineMessages(testFailed), - ExceptionUtility.CombineStackTraces(testFailed), testFailed.Output, null); - - lock (consoleLock) - { - Console.Error.WriteLine(" {0} [FAIL]", Escape(testFailed.Test.DisplayName)); - Console.Error.WriteLine(" {0}", Escape(ExceptionUtility.CombineMessages(testFailed))); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(testFailed)); - } - - return base.Visit(testFailed); - } - - protected override bool Visit(IAfterTestFinished afterTestFinished) - { - Console.Write("."); - - return base.Visit(afterTestFinished); - } - - private string GetFinishedTestName(string methodName) - { - var testName = methodName; - var number = 0; - - if (testMethods.ContainsKey(methodName)) - { - number = testMethods[methodName]; - testName = String.Format("{0} {1}", methodName, number); - } - - testMethods[methodName] = number + 1; - - return testName; - } - - void WriteStackTrace(string stackTrace) - { - if (String.IsNullOrWhiteSpace(stackTrace)) - return; - - Console.Error.WriteLine(" Stack Trace:"); - Array.ForEach(stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None), - stackFrame => Console.Error.WriteLine(" {0}", StackFrameTransformer.TransformFrame(stackFrame, defaultDirectory))); - } - } -} \ No newline at end of file diff --git a/src/xunit.console.netcore/Visitors/StandardOutputVisitor.cs b/src/xunit.console.netcore/Visitors/StandardOutputVisitor.cs deleted file mode 100644 index e02a38855d..0000000000 --- a/src/xunit.console.netcore/Visitors/StandardOutputVisitor.cs +++ /dev/null @@ -1,273 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Xml.Linq; -using Xunit.Abstractions; - -namespace Xunit.ConsoleClient -{ - public class StandardOutputVisitor : XmlTestExecutionVisitor - { - string assemblyFileName; - readonly object consoleLock; - readonly ConcurrentDictionary completionMessages; - readonly string defaultDirectory; - readonly bool showProgress; - readonly Stopwatch clock; - private ConcurrentDictionary runningTests; - private Thread watcher; - readonly int longTestMaxMilliseconds = 1000 * 60 * 5; - readonly int longTestCheckMilliseconds = 1000 * 60; - - - public StandardOutputVisitor(object consoleLock, - string defaultDirectory, - XElement assemblyElement, - Func cancelThunk, - ConcurrentDictionary completionMessages = null, - bool showProgress = false) - : base(assemblyElement, cancelThunk) - { - this.consoleLock = consoleLock; - this.defaultDirectory = defaultDirectory; - this.completionMessages = completionMessages; - this.showProgress = showProgress; - - this.clock = new Stopwatch(); - this.runningTests = new ConcurrentDictionary(); - } - - protected override bool Visit(ITestAssemblyStarting assemblyStarting) - { - assemblyFileName = Path.GetFileName(assemblyStarting.TestAssembly.Assembly.AssemblyPath); - - lock (consoleLock) - Console.WriteLine("Starting: {0}", Path.GetFileNameWithoutExtension(assemblyFileName)); - - clock.Start(); - watcher = new Thread(new ThreadStart(TestWatcher)); - watcher.IsBackground = true; - watcher.Start(); - - return base.Visit(assemblyStarting); - } - - protected override bool Visit(ITestAssemblyFinished assemblyFinished) - { - // Base class does computation of results, so call it first. - var result = base.Visit(assemblyFinished); - - lock (consoleLock) - Console.WriteLine("Finished: {0}", Path.GetFileNameWithoutExtension(assemblyFileName)); - - if (completionMessages != null) - completionMessages.TryAdd(Path.GetFileNameWithoutExtension(assemblyFileName), new ExecutionSummary - { - Total = assemblyFinished.TestsRun, - Failed = assemblyFinished.TestsFailed, - Skipped = assemblyFinished.TestsSkipped, - Time = assemblyFinished.ExecutionTime, - Errors = Errors - }); - - runningTests = null; - clock.Stop(); - return result; - } - - protected override bool Visit(ITestFailed testFailed) - { - lock (consoleLock) - { - // TODO: Thread-safe way to figure out the default foreground color - - Console.ForegroundColor = ConsoleColor.Red; - Console.Error.WriteLine(" {0} [FAIL]", XmlEscape(testFailed.Test.DisplayName)); - Console.ForegroundColor = ConsoleColor.Gray; - Console.Error.WriteLine(" {0}", ExceptionUtility.CombineMessages(testFailed).Replace(Environment.NewLine, Environment.NewLine + " ")); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(testFailed)); - } - - return base.Visit(testFailed); - } - - protected override bool Visit(ITestPassed testPassed) - { - return base.Visit(testPassed); - } - - protected override bool Visit(ITestSkipped testSkipped) - { - lock (consoleLock) - { - // TODO: Thread-safe way to figure out the default foreground color - Console.ForegroundColor = ConsoleColor.Yellow; - Console.Error.WriteLine(" {0} [SKIP]", XmlEscape(testSkipped.Test.DisplayName)); - Console.ForegroundColor = ConsoleColor.Gray; - Console.Error.WriteLine(" {0}", XmlEscape(testSkipped.Reason)); - } - - return base.Visit(testSkipped); - } - - protected override bool Visit(ITestStarting testStarting) - { - if (showProgress) - { - lock (consoleLock) - { - Console.WriteLine(" {0} [STARTING]", XmlEscape(testStarting.Test.DisplayName)); - } - } - - if (!runningTests.TryAdd(testStarting.Test.DisplayName, clock.ElapsedMilliseconds)) - { - lock (consoleLock) - { - Console.WriteLine("ERROR: Failed to add {0} to running tests set.", testStarting.Test.DisplayName); - } - } - - return base.Visit(testStarting); - } - - protected override bool Visit(ITestFinished testFinished) - { - if (showProgress) - { - lock (consoleLock) - { - Console.WriteLine(" {0} [FINISHED] Time: {1}s", XmlEscape(testFinished.Test.DisplayName), testFinished.ExecutionTime); - } - } - long elapsed; - if (!runningTests.TryRemove(testFinished.Test.DisplayName, out elapsed)) - { - lock (consoleLock) - { - Console.WriteLine("ERROR: Failed to find {0} in running test set.", testFinished.Test.DisplayName); - } - } - if (elapsed > longTestMaxMilliseconds) - { - lock (consoleLock) - { - Console.WriteLine("WARNING: Long running test {0} finished in {1}ms.", testFinished.Test.DisplayName, elapsed); - } - - } - - return base.Visit(testFinished); - } - - protected override bool Visit(IErrorMessage error) - { - WriteError("FATAL", error); - - return base.Visit(error); - } - - protected override bool Visit(ITestAssemblyCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Assembly Cleanup Failure ({0})", cleanupFailure.TestAssembly.Assembly.AssemblyPath), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCaseCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Case Cleanup Failure ({0})", cleanupFailure.TestCase.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestClassCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Class Cleanup Failure ({0})", cleanupFailure.TestClass.Class.Name), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCollectionCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Collection Cleanup Failure ({0})", cleanupFailure.TestCollection.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Cleanup Failure ({0})", cleanupFailure.Test.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestMethodCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Method Cleanup Failure ({0})", cleanupFailure.TestMethod.Method.Name), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected void WriteError(string failureName, IFailureInformation failureInfo) - { - lock (consoleLock) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.Error.WriteLine(" [{0}] {1}", failureName, XmlEscape(failureInfo.ExceptionTypes[0])); - Console.ForegroundColor = ConsoleColor.Gray; - Console.Error.WriteLine(" {0}", XmlEscape(ExceptionUtility.CombineMessages(failureInfo))); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(failureInfo)); - } - } - - void WriteStackTrace(string stackTrace) - { - if (String.IsNullOrWhiteSpace(stackTrace)) - return; - - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.Error.WriteLine(" Stack Trace:"); - - Console.ForegroundColor = ConsoleColor.Gray; - foreach (var stackFrame in stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) - { - Console.Error.WriteLine(" {0}", StackFrameTransformer.TransformFrame(stackFrame, defaultDirectory)); - } - } - - private void TestWatcher() - { - try - { - while (runningTests != null) - { - Thread.Sleep(longTestCheckMilliseconds); - - if (runningTests == null) - { - break; - } - - long now = clock.ElapsedMilliseconds; - foreach (KeyValuePair pair in runningTests) - { - if (( now - pair.Value) > longTestMaxMilliseconds) - { - lock (consoleLock) - { - Console.WriteLine("WARNING: {0} is running for {1}s.", pair.Key, (now - pair.Value) / 1000); - } - } - } - } - } - catch { }; - } - } -} diff --git a/src/xunit.console.netcore/Visitors/TeamCityVisitor.cs b/src/xunit.console.netcore/Visitors/TeamCityVisitor.cs deleted file mode 100644 index 01a3ac294c..0000000000 --- a/src/xunit.console.netcore/Visitors/TeamCityVisitor.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Xml.Linq; -using Xunit.Abstractions; - -namespace Xunit.ConsoleClient -{ - public class TeamCityVisitor : XmlTestExecutionVisitor - { - readonly ConcurrentDictionary flowMappings = new ConcurrentDictionary(); - readonly Func flowIdMapper; - - public TeamCityVisitor(XElement assembliesElement, Func cancelThunk) - : this(assembliesElement, cancelThunk, _ => Guid.NewGuid().ToString("N")) { } - - public TeamCityVisitor(XElement assembliesElement, Func cancelThunk, Func flowIdMapper) - : base(assembliesElement, cancelThunk) - { - this.flowIdMapper = flowIdMapper; - } - - void LogFinish(ITestResultMessage testResult) - { - Console.WriteLine("##teamcity[testFinished name='{0}' duration='{1}' flowId='{2}']", - TeamCityEscape(testResult.Test.DisplayName), - (int)(testResult.ExecutionTime * 1000M), - ToFlowId(testResult.TestCollection.DisplayName)); - } - - protected override bool Visit(ITestCollectionFinished testCollectionFinished) - { - // Base class does computation of results, so call it first. - var result = base.Visit(testCollectionFinished); - - Console.WriteLine("##teamcity[testSuiteFinished name='{0}' flowId='{1}']", - TeamCityEscape(testCollectionFinished.TestCollection.DisplayName), - ToFlowId(testCollectionFinished.TestCollection.DisplayName)); - - return result; - } - - protected override bool Visit(ITestCollectionStarting testCollectionStarting) - { - Console.WriteLine("##teamcity[testSuiteStarted name='{0}' flowId='{1}']", - TeamCityEscape(testCollectionStarting.TestCollection.DisplayName), - ToFlowId(testCollectionStarting.TestCollection.DisplayName)); - - return base.Visit(testCollectionStarting); - } - - protected override bool Visit(ITestFailed testFailed) - { - Console.WriteLine("##teamcity[testFailed name='{0}' details='{1}|r|n{2}' flowId='{3}']", - TeamCityEscape(testFailed.Test.DisplayName), - TeamCityEscape(ExceptionUtility.CombineMessages(testFailed)), - TeamCityEscape(ExceptionUtility.CombineStackTraces(testFailed)), - ToFlowId(testFailed.TestCollection.DisplayName)); - LogFinish(testFailed); - - return base.Visit(testFailed); - } - - protected override bool Visit(ITestPassed testPassed) - { - LogFinish(testPassed); - - return base.Visit(testPassed); - } - - protected override bool Visit(ITestSkipped testSkipped) - { - Console.WriteLine("##teamcity[testIgnored name='{0}' message='{1}' flowId='{2}']", - TeamCityEscape(testSkipped.Test.DisplayName), - TeamCityEscape(testSkipped.Reason), - ToFlowId(testSkipped.TestCollection.DisplayName)); - LogFinish(testSkipped); - - return base.Visit(testSkipped); - } - - protected override bool Visit(ITestStarting testStarting) - { - Console.WriteLine("##teamcity[testStarted name='{0}' flowId='{1}']", - TeamCityEscape(testStarting.Test.DisplayName), - ToFlowId(testStarting.TestCollection.DisplayName)); - - return base.Visit(testStarting); - } - - protected override bool Visit(IErrorMessage error) - { - WriteError("FATAL", error); - - return base.Visit(error); - } - - protected override bool Visit(ITestAssemblyCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Assembly Cleanup Failure ({0})", cleanupFailure.TestAssembly.Assembly.AssemblyPath), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCaseCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Case Cleanup Failure ({0})", cleanupFailure.TestCase.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestClassCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Class Cleanup Failure ({0})", cleanupFailure.TestClass.Class.Name), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCollectionCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Collection Cleanup Failure ({0})", cleanupFailure.TestCollection.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Cleanup Failure ({0})", cleanupFailure.Test.DisplayName), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestMethodCleanupFailure cleanupFailure) - { - WriteError(String.Format("Test Method Cleanup Failure ({0})", cleanupFailure.TestMethod.Method.Name), cleanupFailure); - - return base.Visit(cleanupFailure); - } - - static string TeamCityEscape(string value) - { - if (value == null) - return String.Empty; - - return value.Replace("|", "||") - .Replace("'", "|'") - .Replace("\r", "|r") - .Replace("\n", "|n") - .Replace("]", "|]") - .Replace("[", "|[") - .Replace("\u0085", "|x") - .Replace("\u2028", "|l") - .Replace("\u2029", "|p"); - } - - string ToFlowId(string testCollectionName) - { - return flowMappings.GetOrAdd(testCollectionName, flowIdMapper); - } - - static void WriteError(string messageType, IFailureInformation failureInfo) - { - var message = String.Format("[{0}] {1}: {2}", messageType, failureInfo.ExceptionTypes[0], ExceptionUtility.CombineMessages(failureInfo)); - var stack = ExceptionUtility.CombineStackTraces(failureInfo); - - Console.WriteLine("##teamcity[message text='{0}' errorDetails='{1}' status='ERROR']", TeamCityEscape(message), TeamCityEscape(stack)); - } - } -} \ No newline at end of file diff --git a/src/xunit.console.netcore/_._ b/src/xunit.console.netcore/_._ deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/xunit.console.netcore/project.json b/src/xunit.console.netcore/project.json deleted file mode 100644 index aadf674546..0000000000 --- a/src/xunit.console.netcore/project.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "dependencies": { - "xunit": "2.2.0-beta2-build3300", - "xunit.runner.utility": "2.2.0-beta2-build3300", - "Microsoft.NETCore.App": { - "type": "platform", - "version": "1.0.0" - } - }, - "frameworks": { - "netcoreapp1.1": {} - }, - "runtimes": { - "win7-x64": {} - } -} diff --git a/src/xunit.console.netcore/xUnit1.xslt b/src/xunit.console.netcore/xUnit1.xslt deleted file mode 100644 index a8425d36ef..0000000000 --- a/src/xunit.console.netcore/xUnit1.xslt +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/xunit.console.netcore/xunit.console.netcore.csproj b/src/xunit.console.netcore/xunit.console.netcore.csproj deleted file mode 100644 index f375f3a389..0000000000 --- a/src/xunit.console.netcore/xunit.console.netcore.csproj +++ /dev/null @@ -1,75 +0,0 @@ - - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {83FC1994-BCE0-427A-803B-02F20233A2D1} - Exe - Properties - Xunit.ConsoleClient - xunit.console.netcore - $(DefineConstants);NETCORE - true - false - win7-x64 - .NETCoreApp,Version=v1.0 - - - - - - - - Common\AssemblyExtensions.cs - - - Common\DictionaryExtensions.cs - - - Properties\GlobalAssemblyInfo.cs - - - Common\Guard.cs - - - Common\ParallelismOption.cs - - - Common\TestDiscoveryVisitor.cs - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - - - - - PreserveNewest - - - - diff --git a/src/xunit.console.uwp/App.config b/src/xunit.console.uwp/App.config deleted file mode 100644 index 860833c88c..0000000000 --- a/src/xunit.console.uwp/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/xunit.console.uwp/HostedAppxTest.cs b/src/xunit.console.uwp/HostedAppxTest.cs deleted file mode 100644 index ac57785227..0000000000 --- a/src/xunit.console.uwp/HostedAppxTest.cs +++ /dev/null @@ -1,394 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; -using System.Security.AccessControl; -using System.Threading; -using System.Xml; -using System.Xml.Linq; -using Windows.Management.Deployment; - -namespace Xunit.UwpClient -{ - internal class HostedAppxTest - { - private string[] originalArgs; - private string argsToPass; - private XunitProject project; - private string tempDir; - private string runnerAppxPath; - private string packageFullName = null; - private string manifestPath = null; - private string appUserModelId = null; - - private string InstallLocation = null; - - private int ReturnCode = 0; - - public HostedAppxTest(string[] args, XunitProject project, string runnerAppxPath, string installPath) - { - this.originalArgs = args; - this.project = project; - this.runnerAppxPath = runnerAppxPath; - this.InstallLocation = installPath; - NativeMethods.CoInitializeEx(IntPtr.Zero, 2); - } - - public void Setup() - { - tempDir = InstallLocation; - if (!Directory.Exists(tempDir)) - { - DirectorySecurity securityRules = new DirectorySecurity(); - securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow)); - - DirectoryInfo di = Directory.CreateDirectory(tempDir, securityRules); - Console.WriteLine("Creating directory:" + tempDir); - } - object appxFactoryRet; - NativeMethods.CoCreateInstance(Guids.AppxFactory, null, NativeMethods.CLSCTX_INPROC_SERVER, Guids.IAppxFactory, out appxFactoryRet); - var appxFactory = (IAppxFactory)appxFactoryRet; - uint hr; - var appx = project.Assemblies.SingleOrDefault(a => a.AssemblyFilename.ToLowerInvariant().EndsWith("appx")); - if (appx != null) - { - Console.WriteLine("AppX mode"); - IStream inputStream = null; - NativeMethods.SHCreateStreamOnFileEx(appx.AssemblyFilename, STGM_CONSTANTS.STGM_READ | STGM_CONSTANTS.STGM_SHARE_EXCLUSIVE, 0, false, null, ref inputStream); - IAppxPackageReader packageReader; - appxFactory.CreatePackageReader(inputStream, out packageReader); - var appxFile = GetManifestInfoFromPackage(appxFactory, packageReader); - ExtractFile(tempDir, appxFile); - manifestPath = Path.Combine(tempDir, appxFile.GetName()); - var appxFilesEnumerator = packageReader.GetPayloadFiles(); - var payloadFiles = new List(); - while (appxFilesEnumerator.GetHasCurrent()) - { - IAppxFile payloadFile; - hr = appxFilesEnumerator.GetCurrent(out payloadFile); - ThrowIfFailed(hr); - ExtractFile(tempDir, payloadFile); - appxFilesEnumerator.MoveNext(); - var name = payloadFile.GetName(); - if (name.ToLowerInvariant().EndsWith(".dll") || name.ToLowerInvariant().EndsWith(".exe") && name == Path.GetFileName(name)) - { - payloadFiles.Add(name); - } - } - argsToPass = string.Join("\x1F", originalArgs.Where(s => !s.ToLowerInvariant().EndsWith(".appx")).Concat(payloadFiles).ToArray()); - CopyXunitDlls(this.runnerAppxPath, this.tempDir); - } - else - { - Console.WriteLine("DLL mode"); - - Console.WriteLine("Using temp dir: " + tempDir); - RecurseCopy(Path.Combine(Directory.GetCurrentDirectory()), Path.GetFullPath(tempDir)); - - Console.WriteLine("Install Location: " + tempDir); - foreach (var a in project.Assemblies) - { - Console.WriteLine("Assembly to be tested: " + a.AssemblyFilename); - File.Copy(a.AssemblyFilename, Path.Combine(tempDir, Path.GetFileName(a.AssemblyFilename)), true); - } - - argsToPass = string.Join("\x1F", originalArgs); - Console.WriteLine("Arguments passed: " + argsToPass); - } - manifestPath = Path.Combine(tempDir, "AppxManifest.xml"); - Console.WriteLine("Using manifest path: " + manifestPath); - SetupManifestForXunit(manifestPath); - GetManifestInfoFromFile(appxFactory, manifestPath); - Console.WriteLine("Registering: " + manifestPath); - RegisterAppx(new Uri(Path.GetFullPath(manifestPath))); - } - - private static void RegisterAppx(Uri manifestUri) - { - var packageManager = new PackageManager(); - var result = packageManager.RegisterPackageAsync(manifestUri, null, DeploymentOptions.DevelopmentMode); - var completed = new AutoResetEvent(false); - result.Completed = (waitResult, status) => completed.Set(); - completed.WaitOne(); - } - - public int Run(bool debug) - { - return this.Run(debug, TimeSpan.FromMinutes(10)); - } - - public int Run(bool debug, TimeSpan timeout) - { - object returnedComObj = null; - NativeMethods.CoCreateInstance(Guids.ApplicationActivationManager, null, NativeMethods.CLSCTX_LOCAL_SERVER, Guids.IApplicationActivationManager, out returnedComObj); - var activationManager = (IApplicationActivationManager)returnedComObj; - if (debug) - { - var packageDebugSettings = new PackageDebugSettings() as IPackageDebugSettings; - packageDebugSettings.EnableDebugging(packageFullName, null, null); - } - IntPtr pid; - Console.WriteLine("Activating: " + appUserModelId); - var hr = activationManager.ActivateApplication(appUserModelId, this.argsToPass, ACTIVATEOPTIONS.AO_NOERRORUI | ACTIVATEOPTIONS.AO_NOSPLASHSCREEN, out pid); - var timer = Stopwatch.StartNew(); - Console.WriteLine("UWP Activation HRESULT: " + hr); - if (hr == 0) - { - var p = Process.GetProcessById(pid.ToInt32()); - Console.WriteLine($"Running {p.ProcessName} in process {pid} at {DateTimeOffset.Now}"); - while (timer.ElapsedMilliseconds < timeout.TotalMilliseconds && !p.HasExited) - { - Thread.Sleep(1000); - } - var cleanExit = p.HasExited; - if (!cleanExit) - { - Console.WriteLine($"Killing {pid}"); - p.Kill(); - ReturnCode = -1; - } - Console.WriteLine($"Finished waiting for {pid} at {DateTimeOffset.Now}, clean exit: {cleanExit}"); - } - else - { - ReturnCode = -1; - } - - var resultPath = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "Packages", appUserModelId.Substring(0, appUserModelId.IndexOf('!')), "LocalState", "testResults.xml"); - var logsPath = Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "Packages", appUserModelId.Substring(0, appUserModelId.IndexOf('!')), "LocalState", "logs.txt"); - - var destinationResultPath = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(resultPath)); - var destinationLogsPath = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(logsPath)); - if (File.Exists(resultPath)) - { - Console.WriteLine($"Copying {resultPath} to test directory"); - File.Copy(resultPath, destinationResultPath, true); - PrintTestResults(destinationResultPath); - } - else - { - Console.WriteLine($"No results found at {resultPath}"); - } - if (File.Exists(logsPath)) - { - File.Copy(logsPath, destinationLogsPath, true); - PrintLogResults(destinationLogsPath); - } - else - { - Console.WriteLine($"No logs found at {logsPath}"); - } - - Console.WriteLine("Cleaning up..."); - if (File.Exists(resultPath)) - { - File.Delete(resultPath); - } - if (File.Exists(logsPath)) - { - File.Delete(logsPath); - } - return ReturnCode; - } - - private void PrintLogResults(string destinationPath) - { - using (StreamReader reader = new StreamReader(destinationPath)) - { - Console.WriteLine("UWP App Log:"); - Console.WriteLine(reader.ReadToEnd()); - } - } - - private void PrintTestResults(string destinationPath) - { - XElement root = XElement.Load(destinationPath); - IEnumerable address = - from el in root.Descendants("assembly") - select el; - if (address != null && address.Any()) - { - foreach (XElement el in address) - { - List xmlResults = el.Attributes().ToList(); - Console.WriteLine("=== TEST EXECUTION SUMMARY ==="); - Console.WriteLine($"{xmlResults[0]} {xmlResults[5]} {xmlResults[10]} {xmlResults[7]} {xmlResults[8]} {xmlResults[9]}"); - Console.WriteLine($"Finished running tests. {xmlResults[6]}"); - if (!xmlResults[7].ToString().Contains("failed=\"0\"")) - { - ReturnCode = -1; - } - if (!xmlResults[10].ToString().Contains("errors=\"0\"")) - { - ReturnCode = -1; - } - } - } - else - { - Console.WriteLine($"{destinationPath} - xml is malformed/missing data."); - ReturnCode = -1; - } - } - - public void Cleanup() - { - var packageManager = new PackageManager(); - var result = packageManager.RemovePackageAsync(packageFullName, RemovalOptions.PreserveApplicationData); - var completed = new AutoResetEvent(false); - result.Completed = (waitResult, status) => completed.Set(); - completed.WaitOne(); - } - - private void SetupManifestForXunit(string manifestPath) - { - Console.WriteLine("Updating manifest for testing: " + manifestPath); - var manifest = new XmlDocument(); - manifest.Load(manifestPath); - manifest["Package"]["Applications"]["Application"].Attributes["Executable"].Value = "XunitUwpRunner.exe"; - manifest["Package"]["Applications"]["Application"].Attributes["EntryPoint"].Value = "XunitUwpRunner.App"; - var depToRemove = manifest["Package"]["Dependencies"].SelectSingleNode("PackageDependency[@Name='Microsoft.NET.CoreRuntime.1.0']"); - foreach (XmlNode x in manifest["Package"]["Dependencies"]) - { - Console.WriteLine("Dependency found: {0} -- {1}", x.Attributes["Name"].Value, x.OuterXml); - if (depToRemove == null && x.Attributes["Name"].Value == "Microsoft.NET.CoreRuntime.1.0") - { - depToRemove = x; - } - } - if (depToRemove != null) - { - Console.WriteLine("Removing: " + depToRemove.OuterXml); - manifest["Package"]["Dependencies"].RemoveChild(depToRemove); - } - else - { - Console.WriteLine("No CoreRuntime dependency to remove."); - } - Console.WriteLine("Saving manifest: " + manifestPath); - manifest.Save(manifestPath); - } - - private static void CopyXunitDlls(string runnerAppxPath, string destination) - { - File.Copy(runnerAppxPath, Path.Combine(destination, Path.GetFileName(runnerAppxPath))); - foreach (var f in Directory.GetFiles(Path.GetDirectoryName(runnerAppxPath), "xunit*")) - { - if (!File.Exists(Path.Combine(destination, Path.GetFileName(f)))) - { - File.Copy(f, Path.Combine(destination, Path.GetFileName(f))); - } - } - } - - private void GetManifestInfo(IAppxManifestReader manifestReader) - { - uint hr; - IAppxManifestPackageId packageId; - hr = manifestReader.GetPackageId(out packageId); - ThrowIfFailed(hr); - hr = packageId.GetPackageFullName(out packageFullName); - ThrowIfFailed(hr); - Console.WriteLine("Read package full name: " + packageFullName); - IAppxManifestApplicationsEnumerator appEnumerator; - hr = manifestReader.GetApplications(out appEnumerator); - ThrowIfFailed(hr); - bool hasCurrent; - hr = appEnumerator.GetHasCurrent(out hasCurrent); - ThrowIfFailed(hr); - if (hasCurrent) - { - IAppxManifestApplication app; - hr = appEnumerator.GetCurrent(out app); - ThrowIfFailed(hr); - app.GetAppUserModelId(out appUserModelId); - Console.WriteLine("Read app user model ID: " + appUserModelId); - } - } - - private IAppxFile GetManifestInfoFromPackage(IAppxFactory appxFactory, IAppxPackageReader packageReader) - { - var appxFile = packageReader.GetFootprintFile(APPX_FOOTPRINT_FILE_TYPE.MANIFEST); - IAppxManifestReader manifestReader; - appxFactory.CreateManifestReader(appxFile.GetStream(), out manifestReader); - GetManifestInfo(manifestReader); - return appxFile; - } - - private void GetManifestInfoFromFile(IAppxFactory appxFactory, string manifestPath) - { - Console.WriteLine("Reading manifest info from: " + manifestPath); - using (var stream = new StreamWrapper(File.OpenRead(manifestPath))) - { - IAppxManifestReader manifestReader; - appxFactory.CreateManifestReader(stream, out manifestReader); - GetManifestInfo(manifestReader); - } - } - - private void ThrowIfFailed(uint hr) - { - if (hr != 0) - { - throw new COMException("GetManifestInfo error", (int)hr); - } - } - - private static void RecurseCopy(string sourceDirName, string destDirName) - { - // Get the subdirectories for the specified directory. - DirectoryInfo dir = new DirectoryInfo(sourceDirName); - - if (!dir.Exists) - { - throw new DirectoryNotFoundException( - "Source directory does not exist or could not be found: " - + sourceDirName); - } - - DirectoryInfo[] dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!Directory.Exists(destDirName)) - { - Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - FileInfo[] files = dir.GetFiles(); - foreach (FileInfo file in files) - { - string temppath = Path.Combine(destDirName, file.Name); - file.CopyTo(temppath, false); - } - - // Copy subdirectories and their contents to new location. - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - RecurseCopy(subdir.FullName, temppath); - } - } - - private static void ExtractFile(string tempDir, IAppxFile appxFile) - { - var fileName = appxFile.GetName(); - var dest = Path.Combine(tempDir, fileName); - Directory.CreateDirectory(Path.GetDirectoryName(dest)); - var fileStream = appxFile.GetStream(); - System.Runtime.InteropServices.ComTypes.STATSTG stats; - fileStream.Stat(out stats, 0); - using (var wrappedStream = new StreamWrapper(File.OpenWrite(dest))) - { - var read = Marshal.AllocHGlobal(sizeof(long)); - var written = Marshal.AllocHGlobal(sizeof(long)); - fileStream.CopyTo(wrappedStream, stats.cbSize, read, written); - Debug.Assert(Marshal.ReadInt64(read) == Marshal.ReadInt64(written)); - Marshal.FreeHGlobal(read); - Marshal.FreeHGlobal(written); - } - } - } -} diff --git a/src/xunit.console.uwp/NativeMethods.cs b/src/xunit.console.uwp/NativeMethods.cs deleted file mode 100644 index 86bfcf3ee0..0000000000 --- a/src/xunit.console.uwp/NativeMethods.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; - -namespace Xunit.UwpClient -{ - internal static class NativeMethods - { - public const int CLSCTX_LOCAL_SERVER = 0x4; - public const int CLSCTX_INPROC_SERVER = 0x1; - - [DllImport(@"ole32.dll")] - public static extern int CoInitializeEx(IntPtr reserved, int coInit); - - [DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)] - [return: MarshalAs(UnmanagedType.Interface)] - public static extern void CoCreateInstance( - [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, - [MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, - int dwClsContext, - [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, - [MarshalAs(UnmanagedType.IUnknown)] out object rReturnedComObject); - - [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, EntryPoint = "SHCreateStreamOnFileEx", SetLastError = true)] - public static extern void SHCreateStreamOnFileEx(string fileName, - STGM_CONSTANTS mode, - uint attributes, - [MarshalAs(UnmanagedType.Bool)]bool fCreate, - IStream stream, - ref IStream outStream); - } - - [Flags] - public enum STGM_CONSTANTS - { - STGM_READ = 0x0, - STGM_WRITE = 0x1, - STGM_READWRITE = 0x2, - STGM_SHARE_DENY_NONE = 0x40, - STGM_SHARE_DENY_READ = 0x30, - STGM_SHARE_DENY_WRITE = 0x20, - STGM_SHARE_EXCLUSIVE = 0x10, - STGM_PRIORITY = 0x40000, - STGM_CREATE = 0x1000, - STGM_CONVERT = 0x20000, - STGM_FAILIFTHERE = 0x0, - STGM_DIRECT = 0x0, - STGM_TRANSACTED = 0x10000, - STGM_NOSCRATCH = 0x100000, - STGM_NOSNAPSHOT = 0x200000, - STGM_SIMPLE = 0x8000000, - STGM_DIRECT_SWMR = 0x400000, - STGM_DELETEONRELEASE = 0x4000000 - } -} diff --git a/src/xunit.console.uwp/Program.cs b/src/xunit.console.uwp/Program.cs deleted file mode 100644 index c058317c4b..0000000000 --- a/src/xunit.console.uwp/Program.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.IO; -using Xunit.Shared; - -namespace Xunit.UwpClient -{ - public class Program - { - private const string runnerPath = @"XunitUwpRunner.exe"; - - [STAThread] - public static int Main(string[] args) - { - try - { - if (args.Length == 0 || args[0] == "-?") - { - PrintHeader(); - PrintUsage(); - return 2; - } - - var commandLine = CommandLine.Parse(args); - - if (!commandLine.NoLogo) - { - PrintHeader(); - } - - string installLocation = commandLine.InstallLocation == null ? Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()) : commandLine.InstallLocation; - - var test = new HostedAppxTest(args, commandLine.Project, runnerPath, installLocation); - - int returnCode = 0; - try - { - test.Setup(); - returnCode = test.Run(commandLine.Debug); - } - finally - { - test.Cleanup(); - } - - if (commandLine.Wait) - { - Console.WriteLine(); - Console.Write("Press any key to continue..."); - Console.ReadKey(); - Console.WriteLine(); - } - - return returnCode; - } - catch (ArgumentException ex) - { - Console.WriteLine($"error: {ex.Message}"); - return 3; - } - catch (BadImageFormatException ex) - { - Console.WriteLine(ex.Message); - return 4; - } - finally - { - Console.ResetColor(); - } - } - - static void PrintHeader() - { - Console.WriteLine($"xUnit.net UWP Runner ({IntPtr.Size * 8}-bit .NET {Environment.Version})"); - } - - static void PrintUsage() - { - var executableName = "xunit.console.uwp.exe"; - - Console.WriteLine("Copyright (C) 2015 Outercurve Foundation."); - Console.WriteLine(); - Console.WriteLine($"usage: {executableName} [configFile] [assemblyFile [configFile]...] [options] [reporter] [resultFormat filename [...]]"); - Console.WriteLine(); - Console.WriteLine("Note: Configuration files must end in .json (for JSON) or .config (for XML)"); - Console.WriteLine(); - Console.WriteLine("Console Runner options:"); - Console.WriteLine(" -installlocation : path to install application"); - Console.WriteLine(); - Console.WriteLine("Valid options:"); - Console.WriteLine(" -nologo : do not show the copyright message"); - Console.WriteLine(" -nocolor : do not output results with colors"); - Console.WriteLine(" -noappdomain : do not use app domains to run test code"); - Console.WriteLine(" -failskips : convert skipped tests into failures"); - Console.WriteLine(" -parallel option : set parallelization based on option"); - Console.WriteLine(" : none - turn off all parallelization"); - Console.WriteLine(" : collections - only parallelize collections"); - Console.WriteLine(" : assemblies - only parallelize assemblies"); - Console.WriteLine(" : all - parallelize assemblies & collections"); - Console.WriteLine(" -maxthreads count : maximum thread count for collection parallelization"); - Console.WriteLine(" : default - run with default (1 thread per CPU thread)"); - Console.WriteLine(" : unlimited - run with unbounded thread count"); - Console.WriteLine(" : (number) - limit task thread pool size to 'count'"); - Console.WriteLine(" -noshadow : do not shadow copy assemblies"); - Console.WriteLine(" -wait : wait for input after completion"); - Console.WriteLine(" -diagnostics : enable diagnostics messages for all test assemblies"); - Console.WriteLine(" -debug : launch the debugger to debug the tests"); - Console.WriteLine(" -serialize : serialize all test cases (for diagnostic purposes only)"); - Console.WriteLine(" -trait \"name=value\" : only run tests with matching name/value traits"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -notrait \"name=value\" : do not run tests with matching name/value traits"); - Console.WriteLine(" : if specified more than once, acts as an AND operation"); - Console.WriteLine(" -method \"name\" : run a given test method (should be fully specified;"); - Console.WriteLine(" : i.e., 'MyNamespace.MyClass.MyTestMethod')"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -class \"name\" : run all methods in a given test class (should be fully"); - Console.WriteLine(" : specified; i.e., 'MyNamespace.MyClass')"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(" -namespace \"name\" : run all methods in a given namespace (i.e.,"); - Console.WriteLine(" : 'MyNamespace.MySubNamespace')"); - Console.WriteLine(" : if specified more than once, acts as an OR operation"); - Console.WriteLine(); - } - - static bool ValidateFileExists(object consoleLock, string fileName) - { - if (string.IsNullOrWhiteSpace(fileName) || File.Exists(fileName)) - return true; - - lock (consoleLock) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"File not found: {fileName}"); - Console.ForegroundColor = ConsoleColor.Gray; - } - - return false; - } - } -} diff --git a/src/xunit.console.uwp/StreamWrapper.cs b/src/xunit.console.uwp/StreamWrapper.cs deleted file mode 100644 index f28ccf7e16..0000000000 --- a/src/xunit.console.uwp/StreamWrapper.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; - -namespace Xunit.UwpClient -{ - internal class StreamWrapper : Stream, IStream - { - private Stream stream; - - public StreamWrapper(Stream stream) - { - this.stream = stream; - } - - public override bool CanRead - { - get - { - return this.stream.CanRead; - } - } - - public override bool CanSeek - { - get - { - return this.stream.CanSeek; - } - } - - public override bool CanWrite - { - get - { - return this.stream.CanWrite; - } - } - - public override long Length - { - get - { - return this.stream.Length; - } - } - - public override long Position - { - get - { - return this.stream.Position; - } - - set - { - this.stream.Position = value; - } - } - - public void Clone(out IStream ppstm) - { - var clone = new StreamWrapper(this.stream); - ppstm = clone; - } - - public void Commit(int grfCommitFlags) - { - this.stream.Flush(); - } - - public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) - { - var bytes = new byte[cb]; - int read = this.stream.Read(bytes, 0, (int)cb); - if (pcbRead != IntPtr.Zero) - { - Marshal.WriteInt64(pcbRead, read); - } - pstm.Write(bytes, (int)cb, pcbWritten); - } - - public override void Flush() - { - this.stream.Flush(); - } - - public void LockRegion(long libOffset, long cb, int dwLockType) - { - throw new NotSupportedException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - return this.stream.Read(buffer, offset, count); - } - - public void Read(byte[] pv, int cb, IntPtr pcbRead) - { - var read = this.Read(pv, 0, cb); - if (pcbRead != IntPtr.Zero) - { - Marshal.WriteInt64(pcbRead, read); - } - } - - public void Revert() - { - - } - - public override long Seek(long offset, SeekOrigin origin) - { - return this.stream.Seek(offset, origin); - } - - public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition) - { - var pos = this.Seek(dlibMove, (SeekOrigin)dwOrigin); - if (plibNewPosition != IntPtr.Zero) - { - Marshal.WriteInt64(plibNewPosition, pos); - } - } - - public override void SetLength(long value) - { - this.stream.SetLength(value); - } - - public void SetSize(long libNewSize) - { - this.SetLength(libNewSize); - } - - public void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, int grfStatFlag) - { - pstatstg = new System.Runtime.InteropServices.ComTypes.STATSTG(); - pstatstg.cbSize = this.stream.Length; - } - - public void UnlockRegion(long libOffset, long cb, int dwLockType) - { - throw new NotSupportedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - this.stream.Write(buffer, offset, count); - } - - public void Write(byte[] pv, int cb, IntPtr pcbWritten) - { - this.Write(pv, 0, cb); - if (pcbWritten != IntPtr.Zero) - { - Marshal.WriteInt64(pcbWritten, cb); - } - } - - protected override void Dispose(bool disposing) - { - if (this.stream != null) - { - this.stream.Dispose(); - this.stream = null; - } - base.Dispose(disposing); - } - } -} diff --git a/src/xunit.console.uwp/UwpInterop.cs b/src/xunit.console.uwp/UwpInterop.cs deleted file mode 100644 index e23db88aee..0000000000 --- a/src/xunit.console.uwp/UwpInterop.cs +++ /dev/null @@ -1,406 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; -using System.Runtime.CompilerServices; - -namespace Xunit.UwpClient -{ - internal enum ACTIVATEOPTIONS - { - AO_NONE = 0x00000000, - AO_DESIGNMODE = 0x00000001, - AO_NOERRORUI = 0x00000002, - AO_NOSPLASHSCREEN = 0x00000004, - } - - internal enum PACKAGE_EXECUTION_STATE - { - PES_UNKNOWN = 0, - PES_RUNNING = 1, - PES_SUSPENDING = 2, - PES_SUSPENDED = 3, - PES_TERMINATED = 4 - } - - [ComImport] - [Guid("2e941141-7f97-4756-ba1d-9decde894a3d")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IApplicationActivationManager - { - [PreserveSig] - int ActivateApplication( - [In, MarshalAs(UnmanagedType.LPWStr)] string appUserModelId, - [In, MarshalAs(UnmanagedType.LPWStr)] string arguments, - [In] ACTIVATEOPTIONS options, - [Out] out IntPtr processId); - - [PreserveSig] - int ActivateForFile( - [In, MarshalAs(UnmanagedType.LPWStr)] string appUserModelId, - [In] object itemArray, //IShellItemArray - [In, MarshalAs(UnmanagedType.LPWStr)] string verb, - [Out] out IntPtr processId); - - [PreserveSig] - int ActivateForProtocol( - [In, MarshalAs(UnmanagedType.LPWStr)] string appUserModelId, - [In] object itemArray, //IShellItemArray - [Out] out IntPtr processId); - } - - [ComImport] - [Guid("1BB12A62-2AD8-432B-8CCF-0C2C52AFCD5B")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IPackageExecutionStateChangeNotification - { - [PreserveSig] - int OnStateChanged([In, MarshalAs(UnmanagedType.LPWStr)] string pszPackageFullName, [In] PACKAGE_EXECUTION_STATE pesNewState); - } - - [ComImport, - Guid("B1AEC16F-2383-4852-B0E9-8F0B1DC66B4D")] - public class PackageDebugSettings - { - } - - [ComImport] - [Guid("F27C3930-8029-4AD1-94E3-3DBA417810C1")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IPackageDebugSettings - { - [PreserveSig] - int EnableDebugging( - [In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, - [In, MarshalAs(UnmanagedType.LPWStr)] string debuggerCommandLine, - [In, MarshalAs(UnmanagedType.LPWStr)] string environment); - [PreserveSig] - int DisableDebugging([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int Suspend([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int Resume([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int TerminateAllProcesses([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int SetTargetSessionId([In] UIntPtr sessionId); - [PreserveSig] - int EnumerateBackgroundTasks( - [In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, - [Out] UIntPtr taskCount, - [Out, MarshalAs(UnmanagedType.LPStruct)] Guid taskIds, - [Out, MarshalAs(UnmanagedType.LPWStr)] string taskNames); - [PreserveSig] - int ActivateBackgroundTask([In, MarshalAs(UnmanagedType.LPStruct)] Guid taskId); - [PreserveSig] - int StartServicing([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int StopServicing([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int StartSessionRedirection([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, [In] uint sessionId); - [PreserveSig] - int StopSessionRedirection([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName); - [PreserveSig] - int GetPackageExecutionState([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, [Out] out PACKAGE_EXECUTION_STATE packageExecutionState); - [PreserveSig] - int RegisterForPackageStateChanges([In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, [In] IPackageExecutionStateChangeNotification pPackageExecutionStateChangeNotification, [Out] UIntPtr pdwCookie); - [PreserveSig] - int UnregisterForPackageStateChanges([In] uint dwCookie); - } - - internal enum Uri_PROPERTY - { - Uri_PROPERTY_ABSOLUTE_URI = 0, - Uri_PROPERTY_AUTHORITY = 1, - Uri_PROPERTY_DISPLAY_URI = 2, - Uri_PROPERTY_DOMAIN = 3, - Uri_PROPERTY_DWORD_LAST = 0x12, - Uri_PROPERTY_DWORD_START = 15, - Uri_PROPERTY_EXTENSION = 4, - Uri_PROPERTY_FRAGMENT = 5, - Uri_PROPERTY_HOST = 6, - Uri_PROPERTY_HOST_TYPE = 15, - Uri_PROPERTY_PASSWORD = 7, - Uri_PROPERTY_PATH = 8, - Uri_PROPERTY_PATH_AND_QUERY = 9, - Uri_PROPERTY_PORT = 0x10, - Uri_PROPERTY_QUERY = 10, - Uri_PROPERTY_RAW_URI = 11, - Uri_PROPERTY_SCHEME = 0x11, - Uri_PROPERTY_SCHEME_NAME = 12, - Uri_PROPERTY_STRING_LAST = 14, - Uri_PROPERTY_STRING_START = 0, - Uri_PROPERTY_USER_INFO = 13, - Uri_PROPERTY_USER_NAME = 14, - Uri_PROPERTY_ZONE = 0x12 - } - - [ComImport, Guid("A39EE748-6A27-4817-A6F2-13914BEF5890"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IUri - { - void GetPropertyBSTR([In] Uri_PROPERTY uriProp, [MarshalAs(UnmanagedType.BStr)] out string pbstrProperty, [In] uint dwFlags); - void GetPropertyLength([In] Uri_PROPERTY uriProp, out uint pcchProperty, [In] uint dwFlags); - void GetPropertyDWORD([In] Uri_PROPERTY uriProp, out uint pdwProperty, [In] uint dwFlags); - void HasProperty([In] Uri_PROPERTY uriProp, out int pfHasProperty); - void GetAbsoluteUri([MarshalAs(UnmanagedType.BStr)] out string pbstrAbsoluteUri); - void GetAuthority([MarshalAs(UnmanagedType.BStr)] out string pbstrAuthority); - void GetDisplayUri([MarshalAs(UnmanagedType.BStr)] out string pbstrDisplayString); - void GetDomain([MarshalAs(UnmanagedType.BStr)] out string pbstrDomain); - void GetExtension([MarshalAs(UnmanagedType.BStr)] out string pbstrExtension); - void GetFragment([MarshalAs(UnmanagedType.BStr)] out string pbstrFragment); - void GetHost([MarshalAs(UnmanagedType.BStr)] out string pbstrHost); - void GetPassword([MarshalAs(UnmanagedType.BStr)] out string pbstrPassword); - void GetPath([MarshalAs(UnmanagedType.BStr)] out string pbstrPath); - void GetPathAndQuery([MarshalAs(UnmanagedType.BStr)] out string pbstrPathAndQuery); - void GetQuery([MarshalAs(UnmanagedType.BStr)] out string pbstrQuery); - void GetRawUri([MarshalAs(UnmanagedType.BStr)] out string pbstrRawUri); - void GetSchemeName([MarshalAs(UnmanagedType.BStr)] out string pbstrSchemeName); - void GetUserInfo([MarshalAs(UnmanagedType.BStr)] out string pbstrUserInfo); - void GetUserName([MarshalAs(UnmanagedType.BStr)] out string pbstrUserName); - void GetHostType(out uint pdwHostType); - void GetPort(out uint pdwPort); - void GetScheme(out uint pdwScheme); - void GetZone(out uint pdwZone); - void GetProperties(out uint pdwFlags); - void IsEqual([In, MarshalAs(UnmanagedType.Interface)] IUri pUri, out int pfEqual); - } - - [StructLayout(LayoutKind.Sequential)] - internal struct APPX_PACKAGE_SETTINGS - { - public bool forceZip32; - [MarshalAs(UnmanagedType.Interface)] - public IUri hashMethod; - } - - internal enum APPX_COMPRESSION_OPTION - { - APPX_COMPRESSION_OPTION_NONE, - APPX_COMPRESSION_OPTION_NORMAL, - APPX_COMPRESSION_OPTION_MAXIMUM, - APPX_COMPRESSION_OPTION_FAST, - APPX_COMPRESSION_OPTION_SUPERFAST - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9099e33b-246f-41e4-881a-008eb613f858")] - internal interface IAppxPackageWriter - { - void AddPayloadFile([In, MarshalAs(UnmanagedType.LPWStr)] string fileName, [In, MarshalAs(UnmanagedType.LPWStr)] string contentType, - [In] APPX_COMPRESSION_OPTION compressionOption, [In, MarshalAs(UnmanagedType.Interface)] IStream inputStream); - void Close([In, MarshalAs(UnmanagedType.Interface)] IStream manifest); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("beb94909-e451-438b-b5a7-d79e767b75d8")] - internal interface IAppxFactory - { - uint CreatePackageWriter([In] IStream outputStream, [In] ref APPX_PACKAGE_SETTINGS settings, [Out] out IAppxPackageWriter packageWriter); - uint CreatePackageReader([In] IStream inputStream, [Out] out IAppxPackageReader packageReader); - uint CreateManifestReader([In] IStream inputStream, [Out] out IAppxManifestReader manifestReader); - uint CreateBlockMapReader(); - uint CreateValidatedBlockMapReader(); - } - - [ComImport, Guid("5842a140-ff9f-4166-8f5c-62f5b7b0c781")] - internal class AppxFactory - { - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("91df827b-94fd-468f-827b-57f41b2f6f2e")] - internal interface IAppxFile - { - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - APPX_COMPRESSION_OPTION GetCompressionOption(); - - [return: MarshalAs(UnmanagedType.LPWStr)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - string GetContentType(); - - [return: MarshalAs(UnmanagedType.LPWStr)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - string GetName(); - - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - ulong GetSize(); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IStream GetStream(); - } - - internal enum APPX_FOOTPRINT_FILE_TYPE - { - MANIFEST = 0, - BLOCKMAP = 1, - SIGNATURE = 2 - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("283ce2d7-7153-4a91-9649-7a0f7240945f")] - internal interface IAppxManifestPackageId - { - uint GetName([Out, MarshalAs(UnmanagedType.LPWStr)] out string name); - uint GetArchitecture(); - uint GetPublisher([Out, MarshalAs(UnmanagedType.LPWStr)] out string publisher); - uint GetVersion([Out, MarshalAs(UnmanagedType.U8)] out ulong packageVersion); - uint GetResourceId([Out, MarshalAs(UnmanagedType.LPWStr)] out string resourceId); - uint ComparePublisher([In, MarshalAs(UnmanagedType.LPWStr)] string other, [Out, MarshalAs(UnmanagedType.Bool)] out bool isSame); - uint GetPackageFullName([Out, MarshalAs(UnmanagedType.LPWStr)] out string packageFullName); - uint GetPackageFamilyName([Out, MarshalAs(UnmanagedType.LPWStr)] out string packageFamilyName); - }; - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5da89bf4-3773-46be-b650-7e744863b7e8")] - internal interface IAppxManifestApplication - { - void GetStringValue([In, MarshalAs(UnmanagedType.LPWStr)] string name, [Out, MarshalAs(UnmanagedType.LPWStr)] out string value); - void GetAppUserModelId([Out, MarshalAs(UnmanagedType.LPWStr)] out string appUserModelId); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9eb8a55a-f04b-4d0d-808d-686185d4847a")] - internal interface IAppxManifestApplicationsEnumerator - { - uint GetCurrent([Out] out IAppxManifestApplication application); - uint GetHasCurrent([Out] out bool hasCurrent); - uint MoveNext([Out] bool hasNext); - }; - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("4e1bd148-55a0-4480-a3d1-15544710637c")] - internal interface IAppxManifestReader - { - uint GetPackageId([Out] out IAppxManifestPackageId packageId); - uint GetProperties(); - uint GetPackageDependencies(); - uint GetCapabilities(); - uint GetResources(); - uint GetDeviceCapabilities(); - uint GetPrerequisite(); - uint GetApplications([Out] out IAppxManifestApplicationsEnumerator applications); - uint GetStream([Out] out IStream manifestStream); - }; - - [ComImport, - InterfaceType(ComInterfaceType.InterfaceIsIUnknown), - Guid("F007EEAF-9831-411C-9847-917CDC62D1FE")] - internal interface IAppxFilesEnumerator - { - uint GetCurrent([Out] out IAppxFile appxFile); - - [return: MarshalAs(UnmanagedType.Bool)] - bool GetHasCurrent(); - - [return: MarshalAs(UnmanagedType.Bool)] - bool MoveNext(); - } - - [ComImport, ComConversionLoss, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("75CF3930-3244-4FE0-A8C8-E0BCB270B889")] - internal interface IAppxBlockMapBlock - { - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IntPtr GetHash(out uint bufferSize); - - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - uint GetCompressedSize(); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("6B429B5B-36EF-479E-B9EB-0C1482B49E16")] - internal interface IAppxBlockMapBlocksEnumerator - { - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapBlock GetCurrent(); - - [return: MarshalAs(UnmanagedType.Bool)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - bool GetHasCurrent(); - - [return: MarshalAs(UnmanagedType.Bool)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - bool MoveNext(); - } - - [ComImport, Guid("277672AC-4F63-42C1-8ABC-BEAE3600EB59"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IAppxBlockMapFile - { - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapBlocksEnumerator GetBlocks(); - - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - uint GetLocalFileHeaderSize(); - - [return: MarshalAs(UnmanagedType.LPWStr)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - string GetName(); - - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - ulong GetUncompressedSize(); - - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - int ValidateFileHash([In, MarshalAs(UnmanagedType.Interface)] IStream fileStream); - } - - [ComImport, Guid("02B856A2-4262-4070-BACB-1A8CBBC42305"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IAppxBlockMapFilesEnumerator - { - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapFile GetCurrent(); - - [return: MarshalAs(UnmanagedType.Bool)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - bool GetHasCurrent(); - - [return: MarshalAs(UnmanagedType.Bool)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - bool MoveNext(); - } - - [ComImport, Guid("5EFEC991-BCA3-42D1-9EC2-E92D609EC22A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IAppxBlockMapReader - { - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapFile GetFile([In, MarshalAs(UnmanagedType.LPWStr)] string fileName); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapFilesEnumerator GetFiles(); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IUri GetHashMethod(); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IStream GetStream(); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("b5c49650-99bc-481c-9a34-3d53a4106708")] - internal interface IAppxPackageReader - { - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxBlockMapReader GetBlockMap(); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxFile GetFootprintFile([In] APPX_FOOTPRINT_FILE_TYPE type); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxFile GetPayloadFile([In, MarshalAs(UnmanagedType.LPWStr)] string fileName); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxFilesEnumerator GetPayloadFiles(); - - [return: MarshalAs(UnmanagedType.Interface)] - [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] - IAppxManifestReader GetManifest(); - } - - internal class Guids - { - internal static readonly Guid ApplicationActivationManager = new Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C"); - internal static readonly Guid AppxFactory = new Guid("5842a140-ff9f-4166-8f5c-62f5b7b0c781"); - internal static readonly Guid IApplicationActivationManager = new Guid("2e941141-7f97-4756-ba1d-9decde894a3d"); - internal static readonly Guid IAppxFactory = new Guid("beb94909-e451-438b-b5a7-d79e767b75d8"); - } -} diff --git a/src/xunit.console.uwp/packages.config b/src/xunit.console.uwp/packages.config deleted file mode 100644 index 6052af228c..0000000000 --- a/src/xunit.console.uwp/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/xunit.console.uwp/xunit.console.uwp.csproj b/src/xunit.console.uwp/xunit.console.uwp.csproj deleted file mode 100644 index 27920da46c..0000000000 --- a/src/xunit.console.uwp/xunit.console.uwp.csproj +++ /dev/null @@ -1,83 +0,0 @@ - - - - - Debug - AnyCPU - {36219AA4-D36A-4CB4-9C7B-FB48641D411A} - Exe - Properties - Xunit.UwpClient - xunit.console.uwp - true - .NETFramework - v4.6 - False - - - true - full - DEBUG;TRACE - prompt - 4 - false - false - - - pdbonly - true - TRACE - prompt - 4 - false - false - - - - - - - - - - C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd - - - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.runner.utility.2.2.0-beta2-build3300\lib\net45\xunit.runner.utility.desktop.dll - True - - - - - Common\AppxCommandLine.cs - - - Common\DictionaryExtensions.cs - - - Common\Guard.cs - - - Common\ParallelismOption.cs - - - - - - - - - - - Designer - - - - - - - \ No newline at end of file diff --git a/src/xunit.netcore.extensions.46/DesktopTestTraceListener.cs b/src/xunit.netcore.extensions.46/DesktopTestTraceListener.cs deleted file mode 100644 index 060b8ad0c8..0000000000 --- a/src/xunit.netcore.extensions.46/DesktopTestTraceListener.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. - // The .NET Foundation licenses this file to you under the MIT license. - // See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; - -namespace Xunit.NetCore.Extensions -{ - /// - /// Trace Listener for corefx Desktop test execution to avoid showing assert pop-ups and making the test fail when an Assert fails. - /// - public class DesktopTestTraceListener : DefaultTraceListener - { - /// - /// Override of to handle Assert failures with custom behavior. - /// When an Assert failure happens during test execution we will rather throw a DebugAssertException so that the test fails and we have a full StackTrace. - /// - public override void Fail(string message, string detailMessage) - { - throw new DebugAssertException(message, detailMessage); - } - - private sealed class DebugAssertException : Exception - { - internal DebugAssertException(string message, string detailMessage) : - base(message + Environment.NewLine + detailMessage) - { - } - } - } -} diff --git a/src/xunit.netcore.extensions.46/project.json b/src/xunit.netcore.extensions.46/project.json deleted file mode 100644 index 962969618d..0000000000 --- a/src/xunit.netcore.extensions.46/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "NETStandard.Library": "1.6.0", - "xunit": "2.2.0-beta2-build3300", - "xunit.extensibility.execution": "2.2.0-beta2-build3300", - "xunit.abstractions": "2.0.0" - }, - "frameworks": { - "net46": { - "dependencies": { - "Microsoft.TargetingPack.NETFramework.v4.6": "1.0.1" - } - } - }, - "runtimes": { - "win7-x64": {} - } -} diff --git a/src/xunit.netcore.extensions.46/xunit.netcore.extensions.net46.csproj b/src/xunit.netcore.extensions.46/xunit.netcore.extensions.net46.csproj deleted file mode 100644 index 1401857ebe..0000000000 --- a/src/xunit.netcore.extensions.46/xunit.netcore.extensions.net46.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - .NETFramework - v4.6 - win7-x64 - true - ..\xunit.netcore.extensions\ - - - - .NETFramework,Version=v4.6 - - - - - - - - - - - \ No newline at end of file diff --git a/src/xunit.netcore.extensions/Attributes/ActiveIssueAttribute.cs b/src/xunit.netcore.extensions/Attributes/ActiveIssueAttribute.cs deleted file mode 100644 index d4060615d8..0000000000 --- a/src/xunit.netcore.extensions/Attributes/ActiveIssueAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - /// - /// Apply this attribute to your test method to specify an active issue. - /// - [TraitDiscoverer("Xunit.NetCore.Extensions.ActiveIssueDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] - public class ActiveIssueAttribute : Attribute, ITraitAttribute - { - public ActiveIssueAttribute(int issueNumber, TestPlatforms platforms) { } - public ActiveIssueAttribute(string issue, TestPlatforms platforms) { } - public ActiveIssueAttribute(int issueNumber, TargetFrameworkMonikers framework) { } - public ActiveIssueAttribute(string issue, TargetFrameworkMonikers framework) { } - public ActiveIssueAttribute(int issueNumber, TestPlatforms platforms = TestPlatforms.Any, TargetFrameworkMonikers framework = (TargetFrameworkMonikers)0) { } - public ActiveIssueAttribute(string issue, TestPlatforms platforms = TestPlatforms.Any, TargetFrameworkMonikers framework = (TargetFrameworkMonikers)0) { } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/ConditionalClassAttribute.cs b/src/xunit.netcore.extensions/Attributes/ConditionalClassAttribute.cs deleted file mode 100644 index 7940a1acf7..0000000000 --- a/src/xunit.netcore.extensions/Attributes/ConditionalClassAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - [TraitDiscoverer("Xunit.NetCore.Extensions.ConditionalClassDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public sealed class ConditionalClassAttribute : Attribute, ITraitAttribute - { - public Type CalleeType { get; private set; } - public string[] ConditionMemberNames { get; private set; } - - public ConditionalClassAttribute(Type calleeType, params string[] conditionMemberNames) - { - CalleeType = calleeType; - ConditionMemberNames = conditionMemberNames; - } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/ConditionalFactAttribute.cs b/src/xunit.netcore.extensions/Attributes/ConditionalFactAttribute.cs deleted file mode 100644 index f0951064b1..0000000000 --- a/src/xunit.netcore.extensions/Attributes/ConditionalFactAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - [XunitTestCaseDiscoverer("Xunit.NetCore.Extensions.ConditionalFactDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public sealed class ConditionalFactAttribute : FactAttribute - { - public Type CalleeType { get; private set; } - public string[] ConditionMemberNames { get; private set; } - - public ConditionalFactAttribute(Type calleeType, params string[] conditionMemberNames) - { - CalleeType = calleeType; - ConditionMemberNames = conditionMemberNames; - } - - public ConditionalFactAttribute(params string[] conditionMemberNames) - { - ConditionMemberNames = conditionMemberNames; - } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/ConditionalTheoryAttribute.cs b/src/xunit.netcore.extensions/Attributes/ConditionalTheoryAttribute.cs deleted file mode 100644 index 761f1ff4f1..0000000000 --- a/src/xunit.netcore.extensions/Attributes/ConditionalTheoryAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - [XunitTestCaseDiscoverer("Xunit.NetCore.Extensions.ConditionalTheoryDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public sealed class ConditionalTheoryAttribute : TheoryAttribute - { - public Type CalleeType { get; private set; } - public string[] ConditionMemberNames { get; private set; } - - public ConditionalTheoryAttribute(Type calleeType, params string[] conditionMemberNames) - { - CalleeType = calleeType; - ConditionMemberNames = conditionMemberNames; - } - - public ConditionalTheoryAttribute(params string[] conditionMemberNames) - { - ConditionMemberNames = conditionMemberNames; - } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/OuterLoopAttribute.cs b/src/xunit.netcore.extensions/Attributes/OuterLoopAttribute.cs deleted file mode 100644 index d09a52f478..0000000000 --- a/src/xunit.netcore.extensions/Attributes/OuterLoopAttribute.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - /// - /// Apply this attribute to your test method to specify a outer-loop category. - /// - [TraitDiscoverer("Xunit.NetCore.Extensions.OuterLoopTestsDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] - public class OuterLoopAttribute : Attribute, ITraitAttribute - { - public OuterLoopAttribute() { } - public OuterLoopAttribute(string reason) { } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/PlatformSpecificAttribute.cs b/src/xunit.netcore.extensions/Attributes/PlatformSpecificAttribute.cs deleted file mode 100644 index 5053288481..0000000000 --- a/src/xunit.netcore.extensions/Attributes/PlatformSpecificAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - /// - /// Apply this attribute to your test method to specify this is a platform specific test. - /// - [TraitDiscoverer("Xunit.NetCore.Extensions.PlatformSpecificDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] - public class PlatformSpecificAttribute : Attribute, ITraitAttribute - { - public PlatformSpecificAttribute(TestPlatforms platforms) { } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/SkipOnTargetFrameworkAttribute.cs b/src/xunit.netcore.extensions/Attributes/SkipOnTargetFrameworkAttribute.cs deleted file mode 100644 index c44881202a..0000000000 --- a/src/xunit.netcore.extensions/Attributes/SkipOnTargetFrameworkAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - /// - /// Apply this attribute to your test method to specify this is a platform specific test. - /// - [TraitDiscoverer("Xunit.NetCore.Extensions.SkipOnTargetFrameworkDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] - public class SkipOnTargetFrameworkAttribute : Attribute, ITraitAttribute - { - public SkipOnTargetFrameworkAttribute(TargetFrameworkMonikers platform, string reason = null) { } - } -} diff --git a/src/xunit.netcore.extensions/Attributes/TestCategoryAttribute.cs b/src/xunit.netcore.extensions/Attributes/TestCategoryAttribute.cs deleted file mode 100644 index 14eb96ab3b..0000000000 --- a/src/xunit.netcore.extensions/Attributes/TestCategoryAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit -{ - /// - /// Apply this attribute to your test method to specify the test category. - /// - [TraitDiscoverer("Xunit.NetCore.Extensions.TestCategoryDiscoverer", "Xunit.NetCore.Extensions")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] - public class TestCategoryAttribute : Attribute, ITraitAttribute - { - public TestCategoryAttribute(string category) { } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/ActiveIssueDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/ActiveIssueDiscoverer.cs deleted file mode 100644 index 0839e333bf..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/ActiveIssueDiscoverer.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation 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.Diagnostics; -using System.Linq; -using System.Runtime.InteropServices; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// - /// This class discovers all of the tests and test classes that have - /// applied the ActiveIssue attribute - /// - public class ActiveIssueDiscoverer : ITraitDiscoverer - { - /// - /// Gets the trait values from the Category attribute. - /// - /// The trait attribute containing the trait values. - /// The trait values. - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - IEnumerable ctorArgs = traitAttribute.GetConstructorArguments(); - Debug.Assert(ctorArgs.Count() >= 2); - - string issue = ctorArgs.First().ToString(); - TestPlatforms platforms = TestPlatforms.Any; - TargetFrameworkMonikers frameworks = (TargetFrameworkMonikers)0; - - foreach (object arg in ctorArgs.Skip(1)) // First argument is the issue number. - { - if (arg is TestPlatforms) - { - platforms = (TestPlatforms)arg; - } - else if (arg is TargetFrameworkMonikers) - { - frameworks = (TargetFrameworkMonikers)arg; - } - } - - if ((platforms.HasFlag(TestPlatforms.FreeBSD) && RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD"))) || - (platforms.HasFlag(TestPlatforms.Linux) && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) || - (platforms.HasFlag(TestPlatforms.NetBSD) && RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD"))) || - (platforms.HasFlag(TestPlatforms.OSX) && RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) || - (platforms.HasFlag(TestPlatforms.Windows) && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))) - { - if (frameworks.HasFlag(TargetFrameworkMonikers.NetFramework)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetfxTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.Mono)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonMonoTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcoreapp)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreappTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.UapNotUapAot)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonUapTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.UapAot)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonUapAotTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.NetcoreCoreRT)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreCoreRTTest); - if (frameworks == (TargetFrameworkMonikers)0) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.Failing); - - yield return new KeyValuePair(XunitConstants.ActiveIssue, issue); - } - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/ConditionalClassDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/ConditionalClassDiscoverer.cs deleted file mode 100644 index 5d861d2e27..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/ConditionalClassDiscoverer.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// - /// This class discovers all of the tests and test classes that have - /// applied the ConditionalClass attribute - /// - public class ConditionalClassDiscoverer : ITraitDiscoverer - { - /// - /// Gets the trait values from the Category attribute. - /// - /// The trait attribute containing the trait values. - /// The trait values. - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - // If evaluated to false, skip the test class entirely. - if (!EvaluateParameterHelper(traitAttribute)) - { - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.Failing); - } - } - - internal static bool EvaluateParameterHelper(IAttributeInfo traitAttribute) - { - // Parse the traitAttribute. We make sure it contains two parts: - // 1. Type 2. nameof(conditionMemberName) - object[] conditionArguments = traitAttribute.GetConstructorArguments().ToArray(); - Debug.Assert(conditionArguments.Count() == 2); - - Type calleeType = null; - string[] conditionMemberNames = null; - - if (ConditionalTestDiscoverer.CheckInputToSkipExecution(conditionArguments, ref calleeType, ref conditionMemberNames)) - { - return true; - } - - foreach (string entry in conditionMemberNames) - { - // Null condition member names are silently tolerated. - if (string.IsNullOrWhiteSpace(entry)) continue; - - MethodInfo conditionMethodInfo = ConditionalTestDiscoverer.LookupConditionalMethod(calleeType, entry); - if (conditionMethodInfo == null) - { - throw new InvalidOperationException($"Unable to get MethodInfo, please check input for {entry}."); - } - - // If one of the conditions is false, then return the category failing trait. - if (!(bool)conditionMethodInfo.Invoke(null, null)) return false; - } - - return true; - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/ConditionalFactDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/ConditionalFactDiscoverer.cs deleted file mode 100644 index 07b8a9c7d6..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/ConditionalFactDiscoverer.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - public class ConditionalFactDiscoverer : FactDiscoverer - { - private readonly IMessageSink _diagnosticMessageSink; - - public ConditionalFactDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) - { - _diagnosticMessageSink = diagnosticMessageSink; - } - - public override IEnumerable Discover( - ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute) - { - IEnumerable testCases = base.Discover(discoveryOptions, testMethod, factAttribute); - return ConditionalTestDiscoverer.Discover(discoveryOptions, _diagnosticMessageSink, testMethod, testCases, factAttribute.GetConstructorArguments().ToArray()); - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/ConditionalTestDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/ConditionalTestDiscoverer.cs deleted file mode 100644 index ba5a3837a2..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/ConditionalTestDiscoverer.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - // Internal helper class for code common to conditional test discovery through - // [ConditionalFact] and [ConditionalTheory] - internal class ConditionalTestDiscoverer - { - // This helper method evaluates the given condition member names for a given set of test cases. - // If any condition member evaluates to 'false', the test cases are marked to be skipped. - // The skip reason is the collection of all the condition members that evalated to 'false'. - internal static IEnumerable Discover( - ITestFrameworkDiscoveryOptions discoveryOptions, - IMessageSink diagnosticMessageSink, - ITestMethod testMethod, - IEnumerable testCases, - object[] conditionArguments) - { - Type calleeType = null; - string[] conditionMemberNames = null; - - if (CheckInputToSkipExecution(conditionArguments, ref calleeType, ref conditionMemberNames, testMethod)) return testCases; - - MethodInfo testMethodInfo = testMethod.Method.ToRuntimeMethod(); - Type testMethodDeclaringType = testMethodInfo.DeclaringType; - List falseConditions = new List(conditionMemberNames.Count()); - - foreach (string entry in conditionMemberNames) - { - string conditionMemberName = entry; - - // Null condition member names are silently tolerated - if (string.IsNullOrWhiteSpace(conditionMemberName)) - { - continue; - } - - Type declaringType; - - if (calleeType != null) - { - declaringType = calleeType; - } - else - { - declaringType = testMethodDeclaringType; - - string[] symbols = conditionMemberName.Split('.'); - if (symbols.Length == 2) - { - conditionMemberName = symbols[1]; - ITypeInfo type = testMethod.TestClass.Class.Assembly.GetTypes(false).Where(t => t.Name.Contains(symbols[0])).FirstOrDefault(); - if (type != null) - { - declaringType = type.ToRuntimeType(); - } - } - } - - MethodInfo conditionMethodInfo; - if ((conditionMethodInfo = LookupConditionalMethod(declaringType, conditionMemberName)) == null) - { - return new[] - { - new ExecutionErrorTestCase( - diagnosticMessageSink, - discoveryOptions.MethodDisplayOrDefault(), - testMethod, - GetFailedLookupString(conditionMemberName, declaringType)) - }; - } - - // In the case of multiple conditions, collect the results of all - // of them to produce a summary skip reason. - try - { - if (!(bool)conditionMethodInfo.Invoke(null, null)) - { - falseConditions.Add(conditionMemberName); - } - } - catch (Exception exc) - { - falseConditions.Add($"{conditionMemberName} ({exc.GetType().Name})"); - } - } - - // Compose a summary of all conditions that returned false. - if (falseConditions.Count > 0) - { - string skippedReason = string.Format("Condition(s) not met: \"{0}\"", string.Join("\", \"", falseConditions)); - return testCases.Select(tc => new SkippedTestCase(tc, skippedReason)); - } - - // No conditions returned false (including the absence of any conditions). - return testCases; - } - - internal static string GetFailedLookupString(string name, Type type) - { - return - $"An appropriate member '{name}' could not be found. " + - $"The conditional method needs to be a static method or property on the type {type} or any ancestor, " + - "of any visibility, accepting zero arguments, and having a return type of Boolean."; - } - - internal static MethodInfo LookupConditionalMethod(Type t, string name) - { - if (t == null || name == null) - return null; - - TypeInfo ti = t.GetTypeInfo(); - - MethodInfo mi = ti.GetDeclaredMethod(name); - if (mi != null && mi.IsStatic && mi.GetParameters().Length == 0 && mi.ReturnType == typeof(bool)) - return mi; - - PropertyInfo pi = ti.GetDeclaredProperty(name); - if (pi != null && pi.PropertyType == typeof(bool) && pi.GetMethod != null && pi.GetMethod.IsStatic && pi.GetMethod.GetParameters().Length == 0) - return pi.GetMethod; - - return LookupConditionalMethod(ti.BaseType, name); - } - - internal static bool CheckInputToSkipExecution(object[] conditionArguments, ref Type calleeType, ref string[] conditionMemberNames, ITestMethod testMethod = null) - { - // A null or empty list of conditionArguments is treated as "no conditions". - // and the test cases will be executed. - // Example: [ConditionalClass()] - if (conditionArguments == null || conditionArguments.Length == 0) return true; - - calleeType = conditionArguments[0] as Type; - if (calleeType != null) - { - if (conditionArguments.Length < 2) - { - // [ConditionalFact(typeof(x))] no provided methods. - return true; - } - - // [ConditionalFact(typeof(x), "MethodName")] - conditionMemberNames = conditionArguments[1] as string[]; - } - else - { - // For [ConditionalClass], unable to get the Type info. All test cases will be executed. - if (testMethod == null) return true; - - // [ConditionalFact("MethodName")] - conditionMemberNames = conditionArguments[0] as string[]; - } - - // [ConditionalFact((string[]) null)] - if (conditionMemberNames == null || conditionMemberNames.Count() == 0) return true; - - return false; - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/ConditionalTheoryDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/ConditionalTheoryDiscoverer.cs deleted file mode 100644 index 7a1919e5db..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/ConditionalTheoryDiscoverer.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - public class ConditionalTheoryDiscoverer : TheoryDiscoverer - { - private readonly IMessageSink _diagnosticMessageSink; - - public ConditionalTheoryDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) - { - _diagnosticMessageSink = diagnosticMessageSink; - } - - public override IEnumerable Discover( - ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo theoryAttribute) - { - IEnumerable testCases = base.Discover(discoveryOptions, testMethod, theoryAttribute); - return ConditionalTestDiscoverer.Discover(discoveryOptions, _diagnosticMessageSink, testMethod, testCases, theoryAttribute.GetConstructorArguments().ToArray()); - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/OuterLoopTestsDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/OuterLoopTestsDiscoverer.cs deleted file mode 100644 index db67037d84..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/OuterLoopTestsDiscoverer.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation 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 Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// - /// This class discovers all of the tests and test classes that have - /// applied the OuterLoop attribute - /// - public class OuterLoopTestsDiscoverer : ITraitDiscoverer - { - /// - /// Gets the trait values from the Category attribute. - /// - /// The trait attribute containing the trait values. - /// The trait values. - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.OuterLoop); - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/PlatformSpecificDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/PlatformSpecificDiscoverer.cs deleted file mode 100644 index ce3b9e4b99..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/PlatformSpecificDiscoverer.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Linq; -using System.Collections.Generic; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// - /// This class discovers all of the tests and test classes that have - /// applied the PlatformSpecific attribute - /// - public class PlatformSpecificDiscoverer : ITraitDiscoverer - { - /// - /// Gets the trait values from the Category attribute. - /// - /// The trait attribute containing the trait values. - /// The trait values. - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - TestPlatforms platforms = (TestPlatforms)traitAttribute.GetConstructorArguments().First(); - if (!platforms.HasFlag(TestPlatforms.Windows)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonWindowsTest); - if (!platforms.HasFlag(TestPlatforms.Linux)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonLinuxTest); - if (!platforms.HasFlag(TestPlatforms.OSX)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonOSXTest); - if (!platforms.HasFlag(TestPlatforms.FreeBSD)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonFreeBSDTest); - if (!platforms.HasFlag(TestPlatforms.NetBSD)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetBSDTest); - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/SkipOnTargetFrameworkDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/SkipOnTargetFrameworkDiscoverer.cs deleted file mode 100644 index d698923b4a..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/SkipOnTargetFrameworkDiscoverer.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Linq; -using System.Collections.Generic; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// - /// This class discovers all of the tests and test classes that have - /// applied the TestOnTargetFrameworkDiscoverer attribute - /// - public class SkipOnTargetFrameworkDiscoverer : ITraitDiscoverer - { - /// - /// Gets the trait values from the Category attribute. - /// - /// The trait attribute containing the trait values. - /// The trait values. - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - TargetFrameworkMonikers frameworks = (TargetFrameworkMonikers)traitAttribute.GetConstructorArguments().First(); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net45)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet45Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net451)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet451Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net452)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet452Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net46)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet46Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net461)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet461Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net462)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet462Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Net463)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNet463Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcore50)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcore50Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcore50aot)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcore50aotTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcoreapp1_0)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreapp1_0Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcoreapp1_1)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreapp1_1Test); - if (frameworks.HasFlag(TargetFrameworkMonikers.NetFramework)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetfxTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.Mono)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonMonoTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.Netcoreapp)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreappTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.UapNotUapAot)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonUapTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.UapAot)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonUapAotTest); - if (frameworks.HasFlag(TargetFrameworkMonikers.NetcoreCoreRT)) - yield return new KeyValuePair(XunitConstants.Category, XunitConstants.NonNetcoreCoreRTTest); - } - } -} diff --git a/src/xunit.netcore.extensions/Discoverers/TestCategoryDiscoverer.cs b/src/xunit.netcore.extensions/Discoverers/TestCategoryDiscoverer.cs deleted file mode 100644 index e04e0d827f..0000000000 --- a/src/xunit.netcore.extensions/Discoverers/TestCategoryDiscoverer.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Xunit.Abstractions; -using Xunit.Sdk; - -/// -/// This is a replacement for the MSTest [TestCategoryAttribute] on xunit -/// xunit does not have the concept of Category for tests and instead, the have [TraitAttribute(string key, string value)] -/// If we replace the MSTest [TestCategoryAttribute] for the [TestCategory("BVT")], we will surely fall at some time in cases -/// where people will typo on the "Category" key part of the Trait. -/// On order to achieve the same behaviour as on MSTest, a custom [TestCategory] was created -/// to mimic the MSTest one and avoid replace it on every existent test. -/// The tests can be filtered by xunit runners by usage of "-trait" on the command line with the expresion like -/// -trait "Category=BVT" for example that will only run the tests with [TestCategory("BVT")] on it. -/// - -namespace Xunit.NetCore.Extensions -{ - public class TestCategoryDiscoverer : ITraitDiscoverer - { - public IEnumerable> GetTraits(IAttributeInfo traitAttribute) - { - var ctorArgs = traitAttribute.GetConstructorArguments().ToList(); - yield return new KeyValuePair("Category", ctorArgs[0].ToString()); - } - } -} diff --git a/src/xunit.netcore.extensions/SkippedTestCase.cs b/src/xunit.netcore.extensions/SkippedTestCase.cs deleted file mode 100644 index 6caae9065a..0000000000 --- a/src/xunit.netcore.extensions/SkippedTestCase.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Xunit; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - /// Wraps another test case that should be skipped. - internal sealed class SkippedTestCase : LongLivedMarshalByRefObject, IXunitTestCase - { - private readonly IXunitTestCase _testCase; - private readonly string _skippedReason; - - internal SkippedTestCase(IXunitTestCase testCase, string skippedReason) - { - _testCase = testCase; - _skippedReason = skippedReason; - } - - public string DisplayName { get { return _testCase.DisplayName; } } - - public IMethodInfo Method { get { return _testCase.Method; } } - - public string SkipReason { get { return _skippedReason; } } - - public ISourceInformation SourceInformation { get { return _testCase.SourceInformation; } set { _testCase.SourceInformation = value; } } - - public ITestMethod TestMethod { get { return _testCase.TestMethod; } } - - public object[] TestMethodArguments { get { return _testCase.TestMethodArguments; } } - - public Dictionary> Traits { get { return _testCase.Traits; } } - - public string UniqueID { get { return _testCase.UniqueID; } } - - public void Deserialize(IXunitSerializationInfo info) { _testCase.Deserialize(info); } - - public Task RunAsync( - IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, - ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) - { - return new XunitTestCaseRunner(this, DisplayName, _skippedReason, constructorArguments, TestMethodArguments, messageBus, aggregator, cancellationTokenSource).RunAsync(); - } - - public void Serialize(IXunitSerializationInfo info) { _testCase.Serialize(info); } - } -} diff --git a/src/xunit.netcore.extensions/TargetFrameworkMonikers.cs b/src/xunit.netcore.extensions/TargetFrameworkMonikers.cs deleted file mode 100644 index 3091730edc..0000000000 --- a/src/xunit.netcore.extensions/TargetFrameworkMonikers.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace Xunit -{ - [Flags] - public enum TargetFrameworkMonikers - { - Net45 = 0x1, - Net451 = 0x2, - Net452 = 0x4, - Net46 = 0x8, - Net461 = 0x10, - Net462 = 0x20, - Net463 = 0x40, - Netcore50 = 0x80, - Netcore50aot = 0x100, - Netcoreapp1_0 = 0x200, - Netcoreapp1_1 = 0x400, - NetFramework = 0x800, - Netcoreapp = 0x1000, - UapNotUapAot = 0x2000, - UapAot = 0x4000, - Uap = UapAot | UapNotUapAot, - NetcoreCoreRT = 0x8000, - Mono = 0x10000 - } -} diff --git a/src/xunit.netcore.extensions/TestPlatforms.cs b/src/xunit.netcore.extensions/TestPlatforms.cs deleted file mode 100644 index fe905803be..0000000000 --- a/src/xunit.netcore.extensions/TestPlatforms.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -namespace Xunit -{ - [Flags] - public enum TestPlatforms - { - Windows = 1, - Linux = 2, - OSX = 4, - FreeBSD = 8, - NetBSD = 16, - AnyUnix = FreeBSD | Linux | NetBSD | OSX, - Any = ~0 - } -} diff --git a/src/xunit.netcore.extensions/XunitConstants.cs b/src/xunit.netcore.extensions/XunitConstants.cs deleted file mode 100644 index 99b4d53eb4..0000000000 --- a/src/xunit.netcore.extensions/XunitConstants.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Xunit.Sdk; - -namespace Xunit.NetCore.Extensions -{ - public struct XunitConstants - { - internal const string NonFreeBSDTest = "nonfreebsdtests"; - internal const string NonLinuxTest = "nonlinuxtests"; - internal const string NonNetBSDTest = "nonnetbsdtests"; - internal const string NonOSXTest = "nonosxtests"; - internal const string NonWindowsTest = "nonwindowstests"; - - internal const string NonNet45Test = "nonnet45tests"; - internal const string NonNet451Test = "nonnet451tests"; - internal static string NonNet452Test = "nonnet452tests"; - internal static string NonNet46Test = "nonnet46tests"; - internal static string NonNet461Test = "nonnet461tests"; - internal static string NonNet462Test = "nonnet462tests"; - internal static string NonNet463Test = "nonnet463tests"; - internal static string NonNetcore50Test = "nonnetcore50tests"; - internal static string NonNetcore50aotTest = "nonnetcore50aottests"; - internal static string NonNetcoreapp1_0Test = "nonnetcoreapp1.0tests"; - internal static string NonNetcoreapp1_1Test = "nonnetcoreapp1.1tests"; - - //Non version framework constants - internal static string NonNetfxTest = "nonnetfxtests"; - internal static string NonMonoTest = "nonmonotests"; - internal static string NonUapTest = "nonuaptests"; - internal static string NonUapAotTest = "nonuapaottests"; - internal static string NonNetcoreappTest = "nonnetcoreapptests"; - internal static string NonNetcoreCoreRTTest = "nonnetcorecorerttests"; - - internal const string Failing = "failing"; - internal const string ActiveIssue = "activeissue"; - internal const string OuterLoop = "outerloop"; - - public const string Category = "category"; - public const string IgnoreForCI = "ignoreforci"; - public const string RequiresElevation = "requireselevation"; - } -} diff --git a/src/xunit.netcore.extensions/project.json b/src/xunit.netcore.extensions/project.json deleted file mode 100644 index c3b3fb5b92..0000000000 --- a/src/xunit.netcore.extensions/project.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "dependencies": { - "NETStandard.Library": "1.6.0", - "xunit": "2.2.0-beta2-build3300" - }, - "__comment": "RuntimeInformation and OSPlatform are not on netstandard1.0 hence 1.1 was selected", - "frameworks": { - "netstandard1.1": {} - } -} diff --git a/src/xunit.netcore.extensions/xunit.netcore.extensions.csproj b/src/xunit.netcore.extensions/xunit.netcore.extensions.csproj deleted file mode 100644 index 5774c2656b..0000000000 --- a/src/xunit.netcore.extensions/xunit.netcore.extensions.csproj +++ /dev/null @@ -1,44 +0,0 @@ - - - - - Debug - AnyCPU - {BE8ED8C1-C314-4C4E-A929-64C9C8B3552A} - Library - Xunit.NetCore.Extensions - Xunit.NetCore.Extensions - false - true - .NETStandard,Version=v1.1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/xunit.runner.uap/App.xaml b/src/xunit.runner.uap/App.xaml deleted file mode 100644 index ae8f1a0e22..0000000000 --- a/src/xunit.runner.uap/App.xaml +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/xunit.runner.uap/App.xaml.cs b/src/xunit.runner.uap/App.xaml.cs deleted file mode 100644 index ed5003cbfa..0000000000 --- a/src/xunit.runner.uap/App.xaml.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; - -namespace XUnit.Runner.Uap -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - private static LaunchActivatedEventArgs launchArgs; - - public static LaunchActivatedEventArgs LaunchArgs - { - get - { - return launchArgs; - } - } - - - /// - /// 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. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - launchArgs = e; - 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; - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (e.PrelaunchActivated == false) - { - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// 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. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/src/xunit.runner.uap/Assets/LockScreenLogo.scale-200.png b/src/xunit.runner.uap/Assets/LockScreenLogo.scale-200.png deleted file mode 100644 index 735f57adb5..0000000000 Binary files a/src/xunit.runner.uap/Assets/LockScreenLogo.scale-200.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/SplashScreen.scale-200.png b/src/xunit.runner.uap/Assets/SplashScreen.scale-200.png deleted file mode 100644 index 023e7f1fed..0000000000 Binary files a/src/xunit.runner.uap/Assets/SplashScreen.scale-200.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/Square150x150Logo.scale-200.png b/src/xunit.runner.uap/Assets/Square150x150Logo.scale-200.png deleted file mode 100644 index af49fec1a5..0000000000 Binary files a/src/xunit.runner.uap/Assets/Square150x150Logo.scale-200.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/Square44x44Logo.scale-200.png b/src/xunit.runner.uap/Assets/Square44x44Logo.scale-200.png deleted file mode 100644 index ce342a2ec8..0000000000 Binary files a/src/xunit.runner.uap/Assets/Square44x44Logo.scale-200.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/src/xunit.runner.uap/Assets/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index f6c02ce97e..0000000000 Binary files a/src/xunit.runner.uap/Assets/Square44x44Logo.targetsize-24_altform-unplated.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/StoreLogo.png b/src/xunit.runner.uap/Assets/StoreLogo.png deleted file mode 100644 index 7385b56c0e..0000000000 Binary files a/src/xunit.runner.uap/Assets/StoreLogo.png and /dev/null differ diff --git a/src/xunit.runner.uap/Assets/Wide310x150Logo.scale-200.png b/src/xunit.runner.uap/Assets/Wide310x150Logo.scale-200.png deleted file mode 100644 index 288995b397..0000000000 Binary files a/src/xunit.runner.uap/Assets/Wide310x150Logo.scale-200.png and /dev/null differ diff --git a/src/xunit.runner.uap/Helpers.cs b/src/xunit.runner.uap/Helpers.cs deleted file mode 100644 index 558347c7aa..0000000000 --- a/src/xunit.runner.uap/Helpers.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Storage; - -namespace XUnit.Runner.Uap -{ - internal static class Helpers - { - public static async Task GetStorageFileAsync(string test) - { - var folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("TestResults", CreationCollisionOption.OpenIfExists); - return await folder.CreateFileAsync(test, CreationCollisionOption.ReplaceExisting); - } - - public static async Task GetFileStreamWriterInLocalStorageAsync(string fileName) - { - var localFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("AC", CreationCollisionOption.OpenIfExists); - var file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); - return new StreamWriter(await file.OpenStreamForWriteAsync()) - { - AutoFlush = true - }; - } - - } -} diff --git a/src/xunit.runner.uap/MainPage.xaml b/src/xunit.runner.uap/MainPage.xaml deleted file mode 100644 index 2c947f5ae0..0000000000 --- a/src/xunit.runner.uap/MainPage.xaml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Xunit UAP Runner - - - - - - - diff --git a/src/xunit.runner.uap/MainPage.xaml.cs b/src/xunit.runner.uap/MainPage.xaml.cs deleted file mode 100644 index 2afe08affc..0000000000 --- a/src/xunit.runner.uap/MainPage.xaml.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; - -// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 - -namespace XUnit.Runner.Uap -{ - public sealed partial class MainPage : Page - { - - public MainPage() - { - this.InitializeComponent(); - Application.Current.UnhandledException += OnUnhandledException; - } - - private void RunXunitTestsInDirectory(object sender, RoutedEventArgs e) - { - // Run tests for assemblies in current directory - XunitTestRunner runner = new XunitTestRunner(); - Task.Run(() => runner.RunTests(App.LaunchArgs.Arguments)); - } - - static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) - { - var ex = e.Exception as Exception; - StreamWriter log = Helpers.GetFileStreamWriterInLocalStorageAsync("stdout.txt").GetAwaiter().GetResult(); - - if (ex != null) - { - log.WriteLine(ex.ToString()); - } - else - { - log.WriteLine("Error of unknown type thrown in application domain"); - } - - log.Dispose(); - Application.Current.Exit(); - } - } -} diff --git a/src/xunit.runner.uap/Package.appxmanifest b/src/xunit.runner.uap/Package.appxmanifest deleted file mode 100644 index 382b90a7c3..0000000000 --- a/src/xunit.runner.uap/Package.appxmanifest +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - XUnit.Runner.Uap - dotnet - Assets\StoreLogo.png - - - - - - - - - - - - - - - - - - xml - - .xml - - - - - - Log file - - .txt - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.cs b/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.cs deleted file mode 100644 index 6c0c7370e8..0000000000 --- a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System; -using System.Text; -using System.Reflection; -using System.Threading.Tasks; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -using Windows.ApplicationModel.AppService; -using Windows.ApplicationModel.Background; -using Windows.Foundation.Collections; -using Windows.Foundation; - -namespace RunnerRemoteExecutionService -{ - public sealed class RemoteExecutor : IBackgroundTask - { - private BackgroundTaskDeferral backgroundTaskDeferral; - private AppServiceConnection appServiceconnection; - internal const int SuccessExitCode = 42; - - public void Run(IBackgroundTaskInstance taskInstance) - { - this.backgroundTaskDeferral = taskInstance.GetDeferral(); // Get a deferral so that the service isn't terminated. - taskInstance.Canceled += OnTaskCanceled; // Associate a cancellation handler with the background task. - - // Retrieve the app service connection and set up a listener for incoming app service requests. - var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; - appServiceconnection = details.AppServiceConnection; - appServiceconnection.RequestReceived += OnRequestReceived; - } - - private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) - { - // Get a deferral because we use an awaitable API below to respond to the message - // and we don't want this call to get cancelled while we are waiting. - var messageDeferral = args.GetDeferral(); - - ValueSet returnData = new ValueSet(); - HandleTheRequest(args.Request.Message, returnData); - - // Return the data to the caller. - // Complete the deferral so that the platform knows that we're done responding to the app service call. - // Note for error handling: this must be called even if SendResponseAsync() throws an exception. - await args.Request.SendResponseAsync(returnData); - - messageDeferral.Complete(); - } - - private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) - { - if (this.backgroundTaskDeferral != null) - { - // Complete the service deferral. - this.backgroundTaskDeferral.Complete(); - } - } - - private void HandleTheRequest(ValueSet message, ValueSet returnData) - { - string assemblyName; - string typeName; - string methodName; - string[] additionalArgs; - - // default the results to SuccessExitCode as success. We override it at failures. - returnData["Results"] = SuccessExitCode; - - // The message expects to be passed the target assembly name to load, the type - // from that assembly to find, and the method from that assembly to invoke. - // Any additional arguments are passed as strings to the method. - - if (!GetStringValueFromValueSet(message, "AssemblyName", out assemblyName) || String.IsNullOrEmpty(assemblyName)) - { - returnData["Results"] = -1; - returnData["Log"] = $"RemoteExecuter Error: Missing assembly name"; - return; - } - - if (!GetStringValueFromValueSet(message, "TypeName", out typeName) || String.IsNullOrEmpty(typeName)) - { - returnData["Results"] = -2; - returnData["Log"] = $"RemoteExecuter Error: Missing type name"; - return; - } - - if (!GetStringValueFromValueSet(message, "MethodName", out methodName) || String.IsNullOrEmpty(methodName)) - { - returnData["Results"] = -3; - returnData["Log"] = $"RemoteExecuter Error: Missing method name"; - return; - } - - List argList = new List(); - int i = 0; - string arg; - while (GetStringValueFromValueSet(message, "Arg"+i, out arg)) - { - argList.Add(arg); - i++; - } - additionalArgs = argList.ToArray(); - - StringBuilder log = new StringBuilder(); - - // Load the specified assembly, type, and method, then invoke the method. - // The program's exit code is the return value of the invoked method. - object instance = null; - log.Append($"RemoteExecuter: {assemblyName} {methodName} {string.Join(", ", additionalArgs)}{Environment.NewLine}"); - - try - { - // Create the test class if necessary - Assembly a = Assembly.Load(new AssemblyName(assemblyName)); - Type t = a.GetType(typeName); - MethodInfo mi = t.GetTypeInfo().GetDeclaredMethod(methodName); - if (!mi.IsStatic) - { - instance = Activator.CreateInstance(t); - } - - // Invoke the test - object result = mi.Invoke(instance, additionalArgs); - - int exitCode = 0; - if (result is Task task) - { - exitCode = task.GetAwaiter().GetResult(); - } - else if (result is int exit) - { - exitCode = exit; - } - - returnData["Results"] = exitCode; - } - catch (Exception exc) - { - returnData["Results"] = -4; - log.Append(exc); - } - finally - { - (instance as IDisposable)?.Dispose(); - } - returnData["Log"] = log.ToString(); - } - - private bool GetStringValueFromValueSet(ValueSet message, string key, out string val) - { - val = null; - - object valObject; - if (!message.TryGetValue(key, out valObject)) - return false; - - val = (string)valObject; - - return true; - } - } -} diff --git a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.csproj b/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.csproj deleted file mode 100644 index b985ea34fa..0000000000 --- a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/RunnerRemoteExecutionServiceUAP.csproj +++ /dev/null @@ -1,122 +0,0 @@ - - - - - Debug - x64 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B} - winmdobj - Properties - RunnerRemoteExecutionService - RunnerRemoteExecutionService - en-US - UAP - 10.0.15063.0 - 10.0.10586.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - false - False - - - x86 - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x86 - false - prompt - - - x86 - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x86 - false - prompt - - - ARM - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - - - ARM - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - - - x64 - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - - - x64 - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - - - PackageReference - - - - - - - - - - - - - - - 14.0 - - - - - - \ No newline at end of file diff --git a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/project.json b/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/project.json deleted file mode 100644 index fa8894d70e..0000000000 --- a/src/xunit.runner.uap/RunnerRemoteExecutionServiceUAP/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2", - "xunit": "2.2.0-beta2-build3300", - "xunit.runner.utility": "2.2.0-beta2-build3300" - }, - "frameworks": { - "uap10.0": {} - }, - "runtimes": { - "win10-arm": {}, - "win10-arm-aot": {}, - "win10-x86": {}, - "win10-x86-aot": {}, - "win10-x64": {}, - "win10-x64-aot": {} - } -} \ No newline at end of file diff --git a/src/xunit.runner.uap/StandardUapVisitor.cs b/src/xunit.runner.uap/StandardUapVisitor.cs deleted file mode 100644 index 7e7d06ed93..0000000000 --- a/src/xunit.runner.uap/StandardUapVisitor.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.IO; -using System.Text; -using System.Xml.Linq; -using Xunit.Abstractions; - -namespace Xunit.ConsoleClient -{ - public class StandardUapVisitor : XmlTestExecutionVisitor - { - private string _assemblyName; - private readonly ConcurrentDictionary _completionMessages; - private readonly StreamWriter _log; - private readonly bool _showProgress; - private readonly bool _failSkips; - - public StandardUapVisitor(XElement assemblyElement, - Func cancelThunk, - StreamWriter log, - ConcurrentDictionary completionMessages, - bool showProgress, - bool failSkips) - : base(assemblyElement, cancelThunk) - { - _completionMessages = completionMessages; - _log = log; - _showProgress = showProgress; - _failSkips = failSkips; - } - - public ExecutionSummary ExecutionSummary - { - get - { - ExecutionSummary summary; - if (_completionMessages.TryGetValue(_assemblyName, out summary)) - { - return summary; - } - - return new ExecutionSummary(); - } - } - - protected override bool Visit(ITestAssemblyStarting assemblyStarting) - { - _assemblyName = Path.GetFileNameWithoutExtension(assemblyStarting.TestAssembly.Assembly.AssemblyPath); - - _log.WriteLine($"Starting: {_assemblyName}"); - - return base.Visit(assemblyStarting); - } - - protected override bool Visit(ITestAssemblyFinished assemblyFinished) - { - // Base class does computation of results, so call it first. - var result = base.Visit(assemblyFinished); - - _log.WriteLine($"Finished: {_assemblyName}"); - - _completionMessages.TryAdd(_assemblyName, new ExecutionSummary - { - Total = assemblyFinished.TestsRun, - Failed = !_failSkips ? assemblyFinished.TestsFailed : assemblyFinished.TestsFailed + assemblyFinished.TestsSkipped, - Skipped = !_failSkips ? assemblyFinished.TestsSkipped : 0, - Time = assemblyFinished.ExecutionTime, - Errors = Errors - }); - - return result; - } - - protected override bool Visit(ITestFailed testFailed) - { - _log.WriteLine($" {XmlEscape(testFailed.Test.DisplayName)} [FAIL]"); - _log.WriteLine($" {ExceptionUtility.CombineMessages(testFailed).Replace(Environment.NewLine, Environment.NewLine + " ")}"); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(testFailed)); - - return base.Visit(testFailed); - } - - protected override bool Visit(ITestPassed testPassed) - { - return base.Visit(testPassed); - } - - protected override bool Visit(ITestSkipped testSkipped) - { - if (_failSkips) - { - return Visit(new TestFailed(testSkipped.Test, 0M, "", new[] { "FAIL_SKIP" }, new[] { testSkipped.Reason }, new[] { "" }, new[] { -1 })); - } - - _log.WriteLine($" {XmlEscape(testSkipped.Test.DisplayName)} [SKIP]"); - _log.WriteLine($" {XmlEscape(testSkipped.Reason)}"); - - return base.Visit(testSkipped); - } - - protected override bool Visit(ITestStarting testStarting) - { - if (_showProgress) - { - _log.WriteLine($" {XmlEscape(testStarting.Test.DisplayName)} [STARTING]"); - } - return base.Visit(testStarting); - } - - protected override bool Visit(ITestFinished testFinished) - { - if (_showProgress) - { - _log.WriteLine($" {XmlEscape(testFinished.Test.DisplayName)} [FINISHED] Time: {testFinished.ExecutionTime}s"); - } - return base.Visit(testFinished); - } - - protected override bool Visit(IErrorMessage error) - { - WriteError("FATAL", error); - - return base.Visit(error); - } - - protected override bool Visit(ITestAssemblyCleanupFailure cleanupFailure) - { - WriteError($"Test Assembly Cleanup Failure ({cleanupFailure.TestAssembly.Assembly.AssemblyPath})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCaseCleanupFailure cleanupFailure) - { - WriteError($"Test Case Cleanup Failure ({cleanupFailure.TestCase.DisplayName})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestClassCleanupFailure cleanupFailure) - { - WriteError($"Test Class Cleanup Failure ({cleanupFailure.TestClass.Class.Name})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCollectionCleanupFailure cleanupFailure) - { - WriteError($"Test Collection Cleanup Failure ({cleanupFailure.TestCollection.DisplayName})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestCleanupFailure cleanupFailure) - { - WriteError($"Test Cleanup Failure ({cleanupFailure.Test.DisplayName})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected override bool Visit(ITestMethodCleanupFailure cleanupFailure) - { - WriteError($"Test Method Cleanup Failure ({cleanupFailure.TestMethod.Method.Name})", cleanupFailure); - - return base.Visit(cleanupFailure); - } - - protected void WriteError(string failureName, IFailureInformation failureInfo) - { - _log.WriteLine($" [{failureName}] {XmlEscape(failureInfo.ExceptionTypes[0])}"); - _log.WriteLine($" {XmlEscape(ExceptionUtility.CombineMessages(failureInfo))}"); - - WriteStackTrace(ExceptionUtility.CombineStackTraces(failureInfo)); - } - - void WriteStackTrace(string stackTrace) - { - if (String.IsNullOrWhiteSpace(stackTrace)) - return; - - _log.WriteLine(" Stack Trace:"); - - foreach (var stackFrame in stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) - { - _log.WriteLine($" {StackFrameTransformer.TransformFrame(stackFrame, Directory.GetCurrentDirectory())}"); - } - } - } -} \ No newline at end of file diff --git a/src/xunit.runner.uap/UpdateScript/AppxManifest_master.xml b/src/xunit.runner.uap/UpdateScript/AppxManifest_master.xml deleted file mode 100644 index 986b6f3edb..0000000000 --- a/src/xunit.runner.uap/UpdateScript/AppxManifest_master.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - XUnit.Runner.Uap - dotnet - Assets\StoreLogo.png - - - - - - - - - - - - - - - - - xml - - .xml - - - - - - Log file - - .txt - - - - - - - - - - - - - XUnit.Runner.Uap.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/xunit.runner.uap/UpdateScript/buildAndUpdateRunner.bat b/src/xunit.runner.uap/UpdateScript/buildAndUpdateRunner.bat deleted file mode 100644 index c21f0dea03..0000000000 --- a/src/xunit.runner.uap/UpdateScript/buildAndUpdateRunner.bat +++ /dev/null @@ -1,60 +0,0 @@ -setlocal - echo off - set RunnerSourceCodeFolder=%1 - set DestinationFolder=%2 - - REM Rebuild the runner project - msbuild /t:rebuild "%RunnerSourceCodeFolder%\XUnit.Runner.Uap.csproj" /p:AppxPackageDir=%RunnerSourceCodeFolder%\AppPackages - - REM Unpack the appx file to a folder - makeappx unpack /l /o /p "%RunnerSourceCodeFolder%\AppPackages\XUnit.Runner.Uap_1.0.0.0_x64_Debug_Test\XUnit.Runner.Uap_1.0.0.0_x64_Debug.appx" /d "%RunnerSourceCodeFolder%\UnpackedAppx" - - REM Copy the files we care about from the unpacked folder - call :CopyRunnerFilesFromAppx "%RunnerSourceCodeFolder%\UnpackedAppx" %DestinationFolder% - - REM Copy the master Appxmanifest file to the clean runner since that can change - REM The assumption is that the Appxmanifest file is next to this script - copy /y %~dp0Appxmanifest_master.xml %DestinationFolder%\AppxManifest.xml - - echo on - goto :EOF - -:CopyRunnerFilesFromAppx - set _source=%~1 - set _dest=%~2 - - xcopy /y %_source%\Assets\LockScreenLogo.scale-200.png %_dest%\Assets\ - xcopy /y %_source%\Assets\SplashScreen.scale-200.png %_dest%\Assets\ - xcopy /y %_source%\Assets\Square150x150Logo.scale-200.png %_dest%\Assets\ - xcopy /y %_source%\Assets\Square44x44Logo.scale-200.png %_dest%\Assets\ - xcopy /y %_source%\Assets\Square44x44Logo.targetsize-24_altform-unplated.png %_dest%\Assets\ - xcopy /y %_source%\Assets\StoreLogo.png %_dest%\Assets\ - xcopy /y %_source%\Assets\Wide310x150Logo.scale-200.png %_dest%\Assets\ - xcopy /y %_source%\clrcompression.dll %_dest%\ - xcopy /y %_source%\entrypoint\XUnit.Runner.Uap.exe %_dest%\entrypoint\ - xcopy /y %_source%\Properties\Default.rd.xml %_dest%\Properties\ - xcopy /y %_source%\resources.pri %_dest%\ - xcopy /y %_source%\System.ComponentModel.DataAnnotations.dll %_dest%\ - xcopy /y %_source%\System.Net.dll %_dest%\ - xcopy /y %_source%\System.Private.ServiceModel.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.Duplex.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.Http.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.NetTcp.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.Primitives.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.Security.dll %_dest%\ - xcopy /y %_source%\System.ServiceModel.Web.dll %_dest%\ - xcopy /y %_source%\System.Windows.dll %_dest%\ - xcopy /y %_source%\System.Xml.Serialization.dll %_dest%\ - xcopy /y %_source%\vs.appxrecipe %_dest%\ - xcopy /y %_source%\WinMetadata\Windows.winmd %_dest%\WinMetadata\ - xcopy /y %_source%\XUnit.Runner.Uap.exe %_dest%\ - xcopy /y %_source%\XUnit.Runner.Uap.xr.xml %_dest%\ - xcopy /y %_source%\xunit.runner.utility.dotnet.dll %_dest%\ - xcopy /y %_source%\RunnerRemoteExecutionService.winmd %_dest%\ - - xcopy /y "C:\Program Files\WindowsApps\Microsoft.VCLibs.140.00_14.0.24123.0_x64__8wekyb3d8bbwe\*.dll" %_dest%\ - xcopy /y "C:\Program Files\WindowsApps\Microsoft.NET.CoreRuntime.1.1_1.1.24920.0_x64__8wekyb3d8bbwe\uaphost.dll" %_dest%\ - xcopy /y "C:\Program Files\WindowsApps\Microsoft.NET.CoreRuntime.1.1_1.1.24920.0_x64__8wekyb3d8bbwe\uwphost.dll" %_dest%\ -GOTO:EOF -endlocal \ No newline at end of file diff --git a/src/xunit.runner.uap/XUnit.Runner.Uap.csproj b/src/xunit.runner.uap/XUnit.Runner.Uap.csproj deleted file mode 100644 index af89aa9991..0000000000 --- a/src/xunit.runner.uap/XUnit.Runner.Uap.csproj +++ /dev/null @@ -1,157 +0,0 @@ - - - - - Debug - x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14} - AppContainerExe - Properties - XUnit.Runner.Uap - XUnit.Runner.Uap - en-US - UAP - 10.0.15063.0 - 10.0.10586.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - true - False - $(BinDir)\AppPackages - XUnit.Runner.Uap_TemporaryKey.pfx - true - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x86 - false - prompt - true - true - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - true - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - - - - - - - - Common\AppxCommandLine.cs - - - Common\DictionaryExtensions.cs - - - Common\ParallelismOption.cs - - - Common\TestDiscoveryVisitor.cs - - - App.xaml - - - - MainPage.xaml - - - - - - - Designer - - - - - - - - - - - - - - - {a5a5bb82-734b-443a-99ae-aac7d7caa03b} - RunnerRemoteExecutionServiceUAP - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - 14.0 - - - - \ No newline at end of file diff --git a/src/xunit.runner.uap/XUnit.Runner.Uap.sln b/src/xunit.runner.uap/XUnit.Runner.Uap.sln deleted file mode 100644 index 2c0faec379..0000000000 --- a/src/xunit.runner.uap/XUnit.Runner.Uap.sln +++ /dev/null @@ -1,54 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26430.6 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XUnit.Runner.Uap", "XUnit.Runner.Uap.csproj", "{8C6C0E38-4E67-4E89-973F-6AB7786B8A14}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RunnerRemoteExecutionServiceUAP", "RunnerRemoteExecutionServiceUAP\RunnerRemoteExecutionServiceUAP.csproj", "{A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|ARM.ActiveCfg = Debug|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|ARM.Build.0 = Debug|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|ARM.Deploy.0 = Debug|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x64.ActiveCfg = Debug|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x64.Build.0 = Debug|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x64.Deploy.0 = Debug|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x86.ActiveCfg = Debug|x86 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x86.Build.0 = Debug|x86 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Debug|x86.Deploy.0 = Debug|x86 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|ARM.ActiveCfg = Release|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|ARM.Build.0 = Release|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|ARM.Deploy.0 = Release|ARM - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x64.ActiveCfg = Release|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x64.Build.0 = Release|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x64.Deploy.0 = Release|x64 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x86.ActiveCfg = Release|x86 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x86.Build.0 = Release|x86 - {8C6C0E38-4E67-4E89-973F-6AB7786B8A14}.Release|x86.Deploy.0 = Release|x86 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|ARM.ActiveCfg = Debug|ARM - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|ARM.Build.0 = Debug|ARM - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|x64.ActiveCfg = Debug|x64 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|x64.Build.0 = Debug|x64 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|x86.ActiveCfg = Debug|x86 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Debug|x86.Build.0 = Debug|x86 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|ARM.ActiveCfg = Release|ARM - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|ARM.Build.0 = Release|ARM - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|x64.ActiveCfg = Release|x64 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|x64.Build.0 = Release|x64 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|x86.ActiveCfg = Release|x86 - {A5A5BB82-734B-443A-99AE-AAC7D7CAA03B}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/xunit.runner.uap/XUnit.Runner.Uap_TemporaryKey.pfx b/src/xunit.runner.uap/XUnit.Runner.Uap_TemporaryKey.pfx deleted file mode 100644 index e52e736a5b..0000000000 Binary files a/src/xunit.runner.uap/XUnit.Runner.Uap_TemporaryKey.pfx and /dev/null differ diff --git a/src/xunit.runner.uap/XunitTestRunner.cs b/src/xunit.runner.uap/XunitTestRunner.cs deleted file mode 100644 index 6bb7759b68..0000000000 --- a/src/xunit.runner.uap/XunitTestRunner.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using System.Xml.Linq; -using Windows.UI.Xaml; -using Xunit; -using Xunit.ConsoleClient; -using Xunit.Shared; - -namespace XUnit.Runner.Uap -{ - class XunitTestRunner - { - volatile static bool cancel = false; - - private static StreamWriter log; - - public async void RunTests(string arguments) - { - log = await Helpers.GetFileStreamWriterInLocalStorageAsync("stdout.txt"); - - string[] args = arguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - - log.WriteLine(arguments); - - var commandLine = CommandLine.Parse(args); - if (commandLine.Debug) - { - Debugger.Launch(); - } - var completionMessages = new ConcurrentDictionary(); - var assembliesElement = new XElement("assemblies"); - - foreach (var assembly in commandLine.Project.Assemblies) - { - if (cancel) - { - return; - } - assembly.Configuration.PreEnumerateTheories = false; - assembly.Configuration.DiagnosticMessages |= commandLine.DiagnosticMessages; - assembly.Configuration.AppDomain = AppDomainSupport.Denied; - var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration); - var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration); - executionOptions.SetDisableParallelization(true); - - try - { - using (var xunit = new XunitFrontController(AppDomainSupport.Denied, assembly.AssemblyFilename, assembly.ConfigFilename, assembly.Configuration.ShadowCopyOrDefault)) - using (var discoveryVisitor = new TestDiscoveryVisitor()) - { - string assemblyName = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename); - // Discover & filter the tests - log.WriteLine($"Discovering: {assemblyName}"); - xunit.Find(false, discoveryVisitor, discoveryOptions); - discoveryVisitor.Finished.WaitOne(); - - var testCasesDiscovered = discoveryVisitor.TestCases.Count; - var filteredTestCases = discoveryVisitor.TestCases.Where(commandLine.Project.Filters.Filter).ToList(); - var testCasesToRun = filteredTestCases.Count; - - log.WriteLine($"Discovered: {assemblyName}"); - - // Run the filtered tests - if (testCasesToRun == 0) - { - log.WriteLine($"Info: {assemblyName} has no tests to run"); - } - else - { - if (commandLine.Serialize) - { - filteredTestCases = filteredTestCases.Select(xunit.Serialize).Select(xunit.Deserialize).ToList(); - } - - var assemblyElement = new XElement("assembly"); - - StandardUapVisitor resultsVisitor = new StandardUapVisitor(assemblyElement, () => cancel, log, completionMessages, commandLine.ShowProgress, commandLine.FailSkips); - - xunit.RunTests(filteredTestCases, resultsVisitor, executionOptions); - - resultsVisitor.Finished.WaitOne(); - - assembliesElement.Add(assemblyElement); - - log.WriteLine($"{Path.GetFileNameWithoutExtension(assembly.AssemblyFilename)} Total: {resultsVisitor.ExecutionSummary.Total}, Errors: {resultsVisitor.ExecutionSummary.Errors}, Failed: {resultsVisitor.ExecutionSummary.Failed}, Skipped: {resultsVisitor.ExecutionSummary.Skipped}, Time: {resultsVisitor.ExecutionSummary.Time}"); - } - } - } - catch (Exception e) - { - assembliesElement = new XElement("error"); - assembliesElement.Add(e); - log.WriteLine(e); - } - finally - { - await WriteResults(Path.GetFileName(assembly.AssemblyFilename), assembliesElement); - log.Dispose(); - } - } - - Application.Current.Exit(); - } - - - static async Task WriteResults(string test, XElement data) - { - var file = await Helpers.GetStorageFileAsync($"{test}.xml"); - using (var stream = await file.OpenStreamForWriteAsync()) - { - data.Save(stream); - stream.Flush(); - } - } - } -} diff --git a/src/xunit.runner.uap/project.json b/src/xunit.runner.uap/project.json deleted file mode 100644 index fa8894d70e..0000000000 --- a/src/xunit.runner.uap/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2", - "xunit": "2.2.0-beta2-build3300", - "xunit.runner.utility": "2.2.0-beta2-build3300" - }, - "frameworks": { - "uap10.0": {} - }, - "runtimes": { - "win10-arm": {}, - "win10-arm-aot": {}, - "win10-x86": {}, - "win10-x86-aot": {}, - "win10-x64": {}, - "win10-x64-aot": {} - } -} \ No newline at end of file