diff --git a/Documentation/issue-filing-guide.md b/Documentation/issue-filing-guide.md new file mode 100644 index 000000000..dff05d5af --- /dev/null +++ b/Documentation/issue-filing-guide.md @@ -0,0 +1,39 @@ +Filing issues for .NET Core CLI +=============================== + +As you may notice based on our issues page, the CLI repo is what is known as a +"high-profile" and "high-volume" repo; we +get a lot of issues. This, in turn, may mean that some issues get +lost in the noise and/or are not reacted on with the needed speed. + +In order to help with the above situation, we need to have a certain way to file +issues so that the core team of maintainers can react as fast as +possible and can triage effectively. + +The below steps are something that we believe is not a huge increase in process, +but would help us react much faster to any issues that are filed. + +1. Check if the [known issues](known-issues.md) cover the issue you are running +into. We are collecting issues that are known and that have workarounds, so it +could be that you can get unblocked pretty easily. + +2. Add a label to determine which type of issue it is. If it is a defect, use +the "bug" label, if it is a suggestion for a feature, use the "enhancement" +label. This helps the team get to defects more effectively. + +3. Unless you are sure in which milestone the issue falls into, leave it blank. + +4. /cc the person that the issue should be assigned to (or @blackdwarf) so that person +would get notified. In this way the correct person can immediately jump on the +issue and triage it. + +5. For bugs, please be as concrete as possible on what is working, what +is not working. Things like operating system, the version of the tools, the +version of the installer and when you installed all help us determine the +potential problem and allows us to easily reproduce the problem at hand. + +6. For enhancements please be as concrete as possible on what is the addition +you would like to see, what scenario it covers and especially why the current +tools cannot satisfy that scenario. + +Thanks and happy filing! :) diff --git a/Documentation/specs/runtime-configuration-file.md b/Documentation/specs/runtime-configuration-file.md index 5587e95b9..7dc3c21ca 100644 --- a/Documentation/specs/runtime-configuration-file.md +++ b/Documentation/specs/runtime-configuration-file.md @@ -13,6 +13,8 @@ There are two runtime configuration files for a particular application. Given a * `MyApp.config.json` - An **optional** configuration file containing runtime configuration settings. * `MyApp.deps.json` - A list of dependencies, as well as compilation context data and compilation dependencies. Not technically required, but required to use the servicing or package cache/shared package install features. +**IMPORTANT**: Portable Applications, i.e. those published without a specific RID, have some adjustments to this spec which is covered at the end. + ## File format The files are both JSON files stored in UTF-8 encoding. Below are sample files. Note that not all sections are required and some will be opt-in only (see below for more details). The `.config.json` file is completely optional, and in the `.deps.json` file, only the `runtimeTarget`, `targets` and `libraries` sections are required (and within the `targets` section, only the runtime-specific target is required). @@ -30,12 +32,15 @@ The files are both JSON files stored in UTF-8 encoding. Below are sample files. ### [appname].deps.json ```json { - "runtimeTarget": "DNXCore,Version=v5.0/osx.10.10-x64", + "runtimeTarget": { + "name": ".NETStandardApp,Version=v1.5/osx.10.10-x64", + "portable": false + }, "compilationOptions": { "defines": [ "DEBUG" ] }, "targets": { - "DNXCore,Version=v5.0": { + ".NETStandardApp,Version=v1.5": { "MyApp/1.0": { "type": "project", "dependencies": { @@ -55,7 +60,7 @@ The files are both JSON files stored in UTF-8 encoding. Below are sample files. } } }, - "DNXCore,Version=v5.0/osx.10.10-x64": { + ".NETStandardApp,Version=v1.5/osx.10.10-x64": { "MyApp/1.0": { "type": "project", "dependencies": { @@ -97,7 +102,16 @@ The files are both JSON files stored in UTF-8 encoding. Below are sample files. "System.Banana/1.0": { "type": "package", "sha512": "[base64 string]" - } + } + }, + "runtimes": { + ".NETStandardApp,Version=v1.5": { + "win7-x64": [ ], + "win7-x86": [ ], + "win8-x64": [ "win7-x64" ], + "win8-x86": [ "win7-x64" ], + "etc...": [ "etc..." ] + } } } ``` @@ -127,7 +141,6 @@ As an example, here is a possible `project.json` file: "compilationOptions": { "allowUnsafe": true }, - "frameworks": { "net451": { "compilationOptions": { @@ -140,7 +153,6 @@ As an example, here is a possible `project.json` file: } } }, - "configurations": { "Debug": { "compilationOptions": { @@ -162,17 +174,17 @@ When this project is built for `dnxcore50` in the `Debug` configuration, the out } ``` -### `runtimeTarget` property (`.deps.json`) +### `runtimeTarget` Section (`.deps.json`) -This property contains the name of the target from `targets` that should be used by the runtime. This is present to simplify `corehost` so that it does not have to parse or understand target names. +This property contains the name of the target from `targets` that should be used by the runtime as well as a boolean indicating if this is a "portable" deployment, meaning there are runtime-specific assets within "subtargets" (see description of portable apps below) or if it is a "standalone" deployment meaning that all the assets are in a single target and published for a single RID. This is present to simplify `corehost` so that it does not have to parse or understand target names and the meaning thereof. ### `targets` Section (`.deps.json`) This section contains subsetted data from the input `project.lock.json`. -Each property under `targets` describes a "target", which is a collection of libraries required by the application when run or compiled in a certain framework and platform context. A target **must** specify a Framework name, and **may** specify a Runtime Identifier. Targets without Runtime Identifiers represent the dependencies and assets used for compiling the application for a particular framework. Targets with Runtime Identifiers represent the dependencies and assets used for running the application under a particular framework and on the platform defined by the Runtime Identifier. In the example above, the `DNXCore,Version=v5.0` target lists the dependencies and assets used to compile the application for `dnxcore50`, and the `DNXCore,Version=v5.0/osx.10.10-x64` target lists the dependencies and assets used to run the application on `dnxcore50` on a 64-bit Mac OS X 10.10 machine. +Each property under `targets` describes a "target", which is a collection of libraries required by the application when run or compiled in a certain framework and platform context. A target **must** specify a Framework name, and **may** specify a Runtime Identifier. Targets without Runtime Identifiers represent the dependencies and assets used for compiling the application for a particular framework. Targets with Runtime Identifiers represent the dependencies and assets used for running the application under a particular framework and on the platform defined by the Runtime Identifier. In the example above, the `.NETStandardApp,Version=v1.5` target lists the dependencies and assets used to compile the application for `dnxcore50`, and the `.NETStandardApp,Version=v1.5/osx.10.10-x64` target lists the dependencies and assets used to run the application on `dnxcore50` on a 64-bit Mac OS X 10.10 machine. -There will always be two targets in the `runtime.config.json` file: A compilation target, and a runtime target. The compilation target will be named with the framework name used for the compilation (`DNXCore,Version=v5.0` in the example above). The runtime target will be named with the framework name and runtime identifier used to execute the application (`DNXCore,Version=v5.0/osx.10.10-x64` in the example above). However, the runtime target will also be identified by name in the `runtimeOptions` section, so that `corehost` need not parse and understand target names. +There will always be two targets in the `runtime.config.json` file: A compilation target, and a runtime target. The compilation target will be named with the framework name used for the compilation (`.NETStandardApp,Version=v1.5` in the example above). The runtime target will be named with the framework name and runtime identifier used to execute the application (`.NETStandardApp,Version=v1.5/osx.10.10-x64` in the example above). However, the runtime target will also be identified by name in the `runtimeOptions` section, so that `corehost` need not parse and understand target names. The content of each target property in the JSON is a JSON object. Each property of that JSON object represents a single dependency required by the application when compiled for/run on that target. The name of the property contains the ID and Version of the dependency in the form `[Id]/[Version]`. The content of the property is another JSON object containing metadata about the dependency. @@ -198,6 +210,10 @@ This section contains a union of all the dependencies found in the various targe **Open Question**: We could probably exclude projects from this set in order to reduce duplication. The main reason this is a separate section is because that's how the lock file is formatted and we want to try an keep this format the same if possible. +## `runtimes` Section + +This section contains data gathered from the `runtime.json` files in packages during the restore process. It is used by the "portable" deployment model to encode the fallbacks through various RIDs. For example, `corehost` may detect that the current RID is `win8-x64`, due to running on Windows 8 in a 64-bit process. However, packages in the portable deployment model may provide assets for the `win7-x64` RID. In this case, `corehost` needs to know that `win8-x64` can load `win7-x64` assets. This data is encoded in the `runtimes` section of the deps file. The data is stored separately per Target Framework Moniker (though in practice, a `.deps.json` file will only ever have one entry; this is done simply to mirror the `project.lock.json` format). When running a particular target (as defined by `runtimeTarget`), where `portable` is set to `true`, only the `runtimes` entry matching that target name should be used. + ## How the file is used The file is read by two different components: @@ -215,7 +231,7 @@ Some of the sections in the `.deps.json` file contain data used for runtime comp ```json { "targets": { - "DNXCore,Version=v5.0/osx.10.10-x64": { + ".NETStandardApp,Version=v1.5/osx.10.10-x64": { "MyApp/1.0": { "type": "project", "dependencies": { @@ -261,3 +277,76 @@ Some of the sections in the `.deps.json` file contain data used for runtime comp } } ``` + +## Portable Deployment Model + +An application can be deployed in a "portable" deployment model. In this case, the RID-specific assets of packages are published within a folder structure that preserves the RID metadata. However, `corehost` does not use this folder structure, rather it reads data from the `.deps.json` file. Also, during deployment, the `.exe` file (`corehost` renamed) is not deployed. + +In a `portable` target, the package entries may have an additional `subtargets` section detailing RID-specific assets. The `corehost` application should use this data, along with the current RID and the fallback data defined in the `runtimes` section to select one **and only one** "subtarget" out of each package individually. The most specific subtarget should always be selected. In practice, this means selecting the first RID shown on the appropriate line in `runtimes`. For example, given a package containing the following subtargets: + +```json +{ + "targets": { + ".NETStandardApp,Version=v1.5": { + "System.Data.SqlClient/4.0.0": { + "compile": { + "ref/netstandard1.5/System.Data.SqlClient.dll": {} + }, + "subtargets": { + "runtime": { + "runtimes/unix/lib/netstandard1.5/System.Data.SqlClient.dll": { "rid": "unix" }, + "runtimes/win7-x64/lib/netstandard1.5/System.Data.SqlClient.dll": { "rid": "win7-x64" }, + "runtimes/win7-x86/lib/netstandard1.5/System.Data.SqlClient.dll": { "rid": "win7-x86" } + }, + "native": { + "runtimes/win7-x64/native/sni.dll": { "rid": "win7-x64" }, + "runtimes/win7-x86/native/sni.dll": { "rid": "win7-x86" } + } + } + } + } + }, + "runtimes": { + ".NETStandardApp,Version=v1.5": { + "win7-x64": [ ], + "win7-x86": [ ], + "win8-x64": [ "win7-x64" ], + "win8-x86": [ "win7-x86" ], + "win81-x64": [ "win7-x64" ], + "win81-x86": [ "win7-x86" ], + "win10-x64": [ "win7-x64" ], + "win10-x86": [ "win7-x86" ], + "osx.10.10-x64": [ "osx", "unix" ], + "osx.10.11-x64": [ "osx", "unix" ], + "rhel.7-x64": [ "linux-x64", "unix" ], + "rhel.7.1-x64": [ "linux-x64", "unix" ], + "rhel.7.2-x64": [ "linux-x64", "unix" ], + "rhel.7.3-x64": [ "linux-x64", "unix" ], + "centos.7-x64": [ "linux-x64", "unix" ], + "centos.7.1-x64": [ "linux-x64", "unix" ], + "debian.8-x64": [ "linux-x64", "unix" ], + "ubuntu.14.04-x64": [ "linux-x64", "unix" ], + "ubuntu.14.10-x64": [ "linux-x64", "unix" ], + "ubuntu.15.04-x64": [ "linux-x64", "unix" ], + "linuxmint.17-x64": [ "linux-x64", "unix" ], + "linuxmint.17.1-x64": [ "linux-x64", "unix" ], + "linuxmint.17.2-x64": [ "linux-x64", "unix" ], + "linuxmint.17.3-x64": [ "linux-x64", "unix" ] + } + } +} +``` + +(How the data in `runtimes` was generated is beyond the scope of this document, `dotnet-publish` and NuGet will work together to ensure the appropriate data is present). + +Consider `corehost` running on `debian.8-x64`. When setting up the TPA and native library lists, it will do the following for `System.Data.SqlClient`: + +1. Add all entries from the root `runtime` and `native` sections (not present in the example). This is the current behavior +2. Add all appropriate entries from the `subtargets.runtime` and `subtargets.native` sections, based on the `rid` property of each item: + 1. Attempt to locate any item (in both lists) for `debian.8-x64`. If any asset is matched, take **only** the items matching that RID exactly and add them to the appropriate lists + 2. Reattempt the previous step using the first RID in the list provided by `runtimes.".NETStandardApp,Version=v1.5"."debian.8-x64"` (in this case `linux-x64`). If any asset is matched, take **only** the items matching that RID exactly and add them to the appropriate lists + 3. Continue to reattempt the previous search for each RID in the list, from left to right until a match is found or the list is exhausted. Exhausting the list without finding an asset, when a `subtargets` section is present is **not** an error. + +Note one important aspect about asset resolution: The resolution scope is **per-package**, **not per-application**, **nor per-asset**. For each individual package, the most appropriate RID is selected, and **all** assets taken from that package must match the selected RID exactly. For example, if a package provides both a `linux-x64` and a `unix` RID (in the `debian.8-x64` example above), **only** the `linux-x64` asset would be selected for that package. However, if a different package provides only a `unix` RID, then the asset from the `unix` RID would be selected. + +The path to subtarget assets is resolved in the same way as normal assets with **one exception**. When searching app-local, rather than just looking for the simple file name in the app-local directory, subtarget assets are expected to be located in subdirectories matching their relative path information in the lock file. So the `native` `sni.dll` asset for `win7-x64` in the above example would be located at `APPROOT/runtimes/win7-x64/native/sni.dll`, rather than the normal app-local path of `APPROOT/sni.dll` diff --git a/Microsoft.DotNet.Cli.sln b/Microsoft.DotNet.Cli.sln index 203948f0c..faa3eb2c8 100644 --- a/Microsoft.DotNet.Cli.sln +++ b/Microsoft.DotNet.Cli.sln @@ -1,12 +1,8 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 +VisualStudioVersion = 14.0.25020.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{ED2FE3E2-F7E7-4389-8231-B65123F2076F}" - ProjectSection(SolutionItems) = preProject - src\Microsoft.Extensions.EnvironmentAbstractions\project.json = src\Microsoft.Extensions.EnvironmentAbstractions\project.json - EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5A29E8E3-A0FC-4C57-81DD-297B56D1A119}" ProjectSection(SolutionItems) = preProject @@ -22,8 +18,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.Compiler.C EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.ProjectModel.Workspaces", "src\Microsoft.DotNet.ProjectModel.Workspaces\Microsoft.DotNet.ProjectModel.Workspaces.xproj", "{BD7833F8-3209-4682-BF75-B4BCA883E279}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.Runtime", "src\Microsoft.DotNet.Runtime\Microsoft.DotNet.Runtime.xproj", "{DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}" -EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.Extensions.Testing.Abstractions", "src\Microsoft.Extensions.Testing.Abstractions\Microsoft.Extensions.Testing.Abstractions.xproj", "{DCDFE282-03DE-4DBC-B90C-CC3CE3EC8162}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.ProjectModel.Loader", "src\Microsoft.DotNet.ProjectModel.Loader\Microsoft.DotNet.ProjectModel.Loader.xproj", "{C7AF0290-EF0D-44DC-9EDC-600803B664F8}" @@ -64,16 +58,10 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.Cli.Build. EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "dotnet-compile.UnitTests", "test\dotnet-compile.UnitTests\dotnet-compile.UnitTests.xproj", "{920B71D8-62DA-4F5E-8A26-926C113F1D97}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestApp", "TestAssets\TestProjects\TestApp\TestApp.xproj", "{58808BBC-371E-47D6-A3D0-4902145EDA4E}" -EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestAppWithArgs", "TestAssets\TestProjects\TestAppWithArgs\TestAppWithArgs.xproj", "{DA8E0E9E-A6D6-4583-864C-8F40465E3A48}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestAppWithContents", "TestAssets\TestProjects\TestAppWithContents\TestAppWithContents.xproj", "{0138CB8F-4AA9-4029-A21E-C07C30F425BA}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestLibrary", "TestAssets\TestProjects\TestLibrary\TestLibrary.xproj", "{947DD232-8D9B-4B78-9C6A-94F807D2DD58}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestProjectToProjectDependencies", "TestAssets\TestProjects\TestProjectToProjectDependencies\TestProjectToProjectDependencies.xproj", "{947DD232-8D9B-4B78-9C6A-94F807D22222}" -EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.InternalAbstractions", "src\Microsoft.DotNet.InternalAbstractions\Microsoft.DotNet.InternalAbstractions.xproj", "{BD4F0750-4E81-4AD2-90B5-E470881792C3}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.ProjectModel.Tests", "test\Microsoft.DotNet.ProjectModel.Tests\Microsoft.DotNet.ProjectModel.Tests.xproj", "{0745410A-6629-47EB-AAB5-08D6288CAD72}" @@ -82,7 +70,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Installer", "Installer", "{ EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.Cli.Msi.Tests", "test\Installer\Microsoft.DotNet.Cli.Msi.Tests\Microsoft.DotNet.Cli.Msi.Tests.xproj", "{0B31C336-149D-471A-B7B1-27B0F1E80F83}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.Extensions.DependencyModel.Tests", "..\cli1\test\Microsoft.Extensions.DependencyModel.Tests\Microsoft.Extensions.DependencyModel.Tests.xproj", "{4A4711D8-4312-49FC-87B5-4F183F4C6A51}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.Extensions.DependencyModel.Tests", "test\Microsoft.Extensions.DependencyModel.Tests\Microsoft.Extensions.DependencyModel.Tests.xproj", "{4A4711D8-4312-49FC-87B5-4F183F4C6A51}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.DotNet.TestFramework", "src\Microsoft.DotNet.TestFramework\Microsoft.DotNet.TestFramework.xproj", "{0724ED7C-56E3-4604-9970-25E600611383}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "dotnet-test.UnitTests", "test\dotnet-test.UnitTests\dotnet-test.UnitTests.xproj", "{857274AC-E741-4266-A7FD-14DEE0C1CC96}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -160,22 +152,6 @@ Global {BD7833F8-3209-4682-BF75-B4BCA883E279}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU {BD7833F8-3209-4682-BF75-B4BCA883E279}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {BD7833F8-3209-4682-BF75-B4BCA883E279}.RelWithDebInfo|x64.Build.0 = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Debug|x64.ActiveCfg = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Debug|x64.Build.0 = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.MinSizeRel|x64.Build.0 = Debug|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Release|Any CPU.Build.0 = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Release|x64.ActiveCfg = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.Release|x64.Build.0 = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0}.RelWithDebInfo|x64.Build.0 = Release|Any CPU {DCDFE282-03DE-4DBC-B90C-CC3CE3EC8162}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DCDFE282-03DE-4DBC-B90C-CC3CE3EC8162}.Debug|Any CPU.Build.0 = Debug|Any CPU {DCDFE282-03DE-4DBC-B90C-CC3CE3EC8162}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -432,22 +408,6 @@ Global {920B71D8-62DA-4F5E-8A26-926C113F1D97}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU {920B71D8-62DA-4F5E-8A26-926C113F1D97}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {920B71D8-62DA-4F5E-8A26-926C113F1D97}.RelWithDebInfo|x64.Build.0 = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Debug|x64.ActiveCfg = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Debug|x64.Build.0 = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.MinSizeRel|x64.Build.0 = Debug|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Release|Any CPU.Build.0 = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Release|x64.ActiveCfg = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.Release|x64.Build.0 = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU - {58808BBC-371E-47D6-A3D0-4902145EDA4E}.RelWithDebInfo|x64.Build.0 = Release|Any CPU {DA8E0E9E-A6D6-4583-864C-8F40465E3A48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DA8E0E9E-A6D6-4583-864C-8F40465E3A48}.Debug|Any CPU.Build.0 = Debug|Any CPU {DA8E0E9E-A6D6-4583-864C-8F40465E3A48}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -480,38 +440,6 @@ Global {0138CB8F-4AA9-4029-A21E-C07C30F425BA}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU {0138CB8F-4AA9-4029-A21E-C07C30F425BA}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {0138CB8F-4AA9-4029-A21E-C07C30F425BA}.RelWithDebInfo|x64.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Debug|Any CPU.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Debug|x64.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Debug|x64.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.MinSizeRel|x64.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Release|Any CPU.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Release|Any CPU.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Release|x64.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.Release|x64.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D2DD58}.RelWithDebInfo|x64.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Debug|Any CPU.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Debug|x64.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Debug|x64.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.MinSizeRel|x64.Build.0 = Debug|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Release|Any CPU.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Release|Any CPU.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Release|x64.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.Release|x64.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU - {947DD232-8D9B-4B78-9C6A-94F807D22222}.RelWithDebInfo|x64.Build.0 = Release|Any CPU {BD4F0750-4E81-4AD2-90B5-E470881792C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BD4F0750-4E81-4AD2-90B5-E470881792C3}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD4F0750-4E81-4AD2-90B5-E470881792C3}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -528,6 +456,22 @@ Global {BD4F0750-4E81-4AD2-90B5-E470881792C3}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU {BD4F0750-4E81-4AD2-90B5-E470881792C3}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {BD4F0750-4E81-4AD2-90B5-E470881792C3}.RelWithDebInfo|x64.Build.0 = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Debug|x64.ActiveCfg = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Debug|x64.Build.0 = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.MinSizeRel|x64.Build.0 = Debug|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Release|Any CPU.Build.0 = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Release|x64.ActiveCfg = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.Release|x64.Build.0 = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU + {0745410A-6629-47EB-AAB5-08D6288CAD72}.RelWithDebInfo|x64.Build.0 = Release|Any CPU {4A4711D8-4312-49FC-87B5-4F183F4C6A51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4A4711D8-4312-49FC-87B5-4F183F4C6A51}.Debug|Any CPU.Build.0 = Debug|Any CPU {4A4711D8-4312-49FC-87B5-4F183F4C6A51}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -560,6 +504,38 @@ Global {0B31C336-149D-471A-B7B1-27B0F1E80F83}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU {0B31C336-149D-471A-B7B1-27B0F1E80F83}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {0B31C336-149D-471A-B7B1-27B0F1E80F83}.RelWithDebInfo|x64.Build.0 = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Debug|Any CPU.Build.0 = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Debug|x64.ActiveCfg = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Debug|x64.Build.0 = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.MinSizeRel|x64.Build.0 = Debug|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Release|Any CPU.ActiveCfg = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Release|Any CPU.Build.0 = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Release|x64.ActiveCfg = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.Release|x64.Build.0 = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU + {857274AC-E741-4266-A7FD-14DEE0C1CC96}.RelWithDebInfo|x64.Build.0 = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Debug|x64.ActiveCfg = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Debug|x64.Build.0 = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.MinSizeRel|x64.Build.0 = Debug|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Release|Any CPU.Build.0 = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Release|x64.ActiveCfg = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.Release|x64.Build.0 = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU + {0724ED7C-56E3-4604-9970-25E600611383}.RelWithDebInfo|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -569,7 +545,6 @@ Global {303677D5-7312-4C3F-BAEE-BEB1A9BD9FE6} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {A16958E1-24C7-4F1E-B317-204AD91625DD} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {BD7833F8-3209-4682-BF75-B4BCA883E279} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} - {DB29F219-DC92-4AF7-A2EE-E89FFBB3F5F0} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {DCDFE282-03DE-4DBC-B90C-CC3CE3EC8162} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {C7AF0290-EF0D-44DC-9EDC-600803B664F8} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {08A68C6A-86F6-4ED2-89A7-B166D33E9F85} = {0722D325-24C8-4E83-B5AF-0A083E7F0749} @@ -587,14 +562,14 @@ Global {D7B9695D-23EB-4EA8-B8AB-707A0092E1D5} = {88278B81-7649-45DC-8A6A-D3A645C5AFC3} {49BEB486-AB5A-4416-91EA-8CD34ABB0C9D} = {88278B81-7649-45DC-8A6A-D3A645C5AFC3} {920B71D8-62DA-4F5E-8A26-926C113F1D97} = {17735A9D-BFD9-4585-A7CB-3208CA6EA8A7} - {58808BBC-371E-47D6-A3D0-4902145EDA4E} = {713CBFBB-5392-438D-B766-A9A585EF1BB8} {DA8E0E9E-A6D6-4583-864C-8F40465E3A48} = {713CBFBB-5392-438D-B766-A9A585EF1BB8} {0138CB8F-4AA9-4029-A21E-C07C30F425BA} = {713CBFBB-5392-438D-B766-A9A585EF1BB8} - {947DD232-8D9B-4B78-9C6A-94F807D2DD58} = {713CBFBB-5392-438D-B766-A9A585EF1BB8} - {947DD232-8D9B-4B78-9C6A-94F807D22222} = {713CBFBB-5392-438D-B766-A9A585EF1BB8} {BD4F0750-4E81-4AD2-90B5-E470881792C3} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} {4A4711D8-4312-49FC-87B5-4F183F4C6A51} = {17735A9D-BFD9-4585-A7CB-3208CA6EA8A7} + {0745410A-6629-47EB-AAB5-08D6288CAD72} = {17735A9D-BFD9-4585-A7CB-3208CA6EA8A7} {0E3300A4-DF54-40BF-87D8-E7658330C288} = {17735A9D-BFD9-4585-A7CB-3208CA6EA8A7} {0B31C336-149D-471A-B7B1-27B0F1E80F83} = {0E3300A4-DF54-40BF-87D8-E7658330C288} + {857274AC-E741-4266-A7FD-14DEE0C1CC96} = {17735A9D-BFD9-4585-A7CB-3208CA6EA8A7} + {0724ED7C-56E3-4604-9970-25E600611383} = {ED2FE3E2-F7E7-4389-8231-B65123F2076F} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index a53baac6c..790d84169 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,14 @@ This repo contains the source code for cross-platform [.NET Core](http://github. New to .NET CLI? ------------ -Check out our http://dotnet.github.io/getting-started/ +Check out our http://dotnet.github.io/getting-started/ page. + +Found an issue? +--------------- +You can consult the [known issues page](Documentation/known-issues.md) to find out the current issues and +to see the workarounds. + +If you don't find your issue, please file one! However, given that this is a very high-frequency repo, we've setup some [basic guidelines](Documentation/issue-filing-guide.md) to help you. Please consult those first. Build Status ------------ @@ -24,10 +31,10 @@ Installers |**Installers**|[Download Debian Package](https://dotnetcli.blob.core.windows.net/dotnet/beta/Installers/Latest/dotnet-ubuntu-x64.latest.deb)|[Download Msi](https://dotnetcli.blob.core.windows.net/dotnet/beta/Installers/Latest/dotnet-win-x64.latest.exe)|[Download Pkg](https://dotnetcli.blob.core.windows.net/dotnet/beta/Installers/Latest/dotnet-osx-x64.latest.pkg) |N/A | |**Binaries**|[Download tar file](https://dotnetcli.blob.core.windows.net/dotnet/beta/Binaries/Latest/dotnet-ubuntu-x64.latest.tar.gz)|[Download zip file](https://dotnetcli.blob.core.windows.net/dotnet/beta/Binaries/Latest/dotnet-win-x64.latest.zip)|[Download tar file](https://dotnetcli.blob.core.windows.net/dotnet/beta/Binaries/Latest/dotnet-osx-x64.latest.tar.gz) |[Download tar file](https://dotnetcli.blob.core.windows.net/dotnet/beta/Binaries/Latest/dotnet-centos-x64.latest.tar.gz) | -Interested in .NET Core + ASP.NET 5 RC bits? ----------------------------------------- +Interested in .NET Core + ASP.NET Core 1.0 RC1 bits? +---------------------------------------------------- -This toolchain is independent from the DNX-based .NET Core + ASP.NET 5 RC bits. If you are looking for .NET Core + ASP.NET 5 RC bits, you can find instructions on the http://get.asp.net/. +This toolchain is independent from the DNX-based .NET Core + ASP.NET Core 1.0 RC1 bits. If you are looking for .NET Core + ASP.NET Core 1.0 RC1 bits, you can find instructions on the http://get.asp.net/. Docker ------ @@ -53,19 +60,8 @@ Then you can either run from source or compile the sample. Running from source i Compiling to IL is done using: dotnet build -This will drop a binary in `./bin/[configuration]/[framework]/[binary name]` that you can just run. -Finally, you can also try out native compilation using RyuJIT as shown below: - - dotnet build --native - -The following command will perform native compilation using the C++ Codegenerator: - - dotnet build --native --cpp - -If you are in Windows, make sure that you run the above command inside the *VS 2015 x64 Native Tools* prompt, otherwise you will get errors. This command will drop a native single binary in `./bin/[configuration]/[framework]/native/[binary name]` that you can run. - -**Note:** At this point, only the `helloworld` and `dotnetbot` samples will work with native compilation. +This will drop a binary in `./bin/[configuration]/[framework]/[rid]/[binary name]` that you can just run. For more details, please refer to the [documentation](https://github.com/dotnet/corert/tree/master/Documentation). @@ -74,11 +70,7 @@ Building from source If you are building from source, take note that the build depends on NuGet packages hosted on Myget, so if it is down, the build may fail. If that happens, you can always see the [Myget status page](http://status.myget.org/) for more info. -Known issues ------------- - -You can also consult the [known issues page](Documentation/known-issues.md) to find out the current issues and -to see the workarounds. +Read over the [contributing guidelines](https://github.com/dotnet/cli/tree/master/CONTRIBUTING.md) and [developer documentation](https://github.com/dotnet/cli/tree/master/Documentation) for prerequisites for building from source. Questions & Comments -------------------- diff --git a/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/DependencyContextValidator.xproj b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/DependencyContextValidator.xproj new file mode 100644 index 000000000..c827617ac --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/DependencyContextValidator.xproj @@ -0,0 +1,19 @@ + + + + 14.0.24720 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + 6d84ef36-a5d5-4eaf-b38b-ced635473785 + DependencyContextValidator + ..\..\..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\..\..\artifacts\bin\$(MSBuildProjectName)\ + + + + 2.0 + + + \ No newline at end of file diff --git a/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/Validator.cs b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/Validator.cs new file mode 100644 index 000000000..81d057a29 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/Validator.cs @@ -0,0 +1,65 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace Microsoft.Extensions.DependencyModel +{ + public static class DependencyContextValidator + { + private static void Error(string message) + { + throw new InvalidOperationException(message); + } + + private static void CheckMetadata(Library library) + { + if (string.Equals(library.LibraryType, "package", StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(library.PackageName) || + string.IsNullOrWhiteSpace(library.Hash) || + string.IsNullOrWhiteSpace(library.Version)) + { + Error($"Empty metadata for {library.GetType().ToString()} {library.PackageName}"); + } + } + } + + public static void Validate(bool full) + { + var context = DependencyContext.Default; + if (full) + { + if (!context.CompileLibraries.Any()) + { + Error("Compilation libraries empty"); + } + foreach (var compilationLibrary in context.CompileLibraries) + { + CheckMetadata(compilationLibrary); + var resolvedPaths = compilationLibrary.ResolveReferencePaths(); + foreach (var resolvedPath in resolvedPaths) + { + if (!File.Exists(resolvedPath)) + { + Error($"Compilataion library resolved to non existent path {resolvedPath}"); + } + } + } + } + + foreach (var runtimeLibrary in context.RuntimeLibraries) + { + CheckMetadata(runtimeLibrary); + foreach (var runtimeAssembly in runtimeLibrary.Assemblies) + { + var assembly = Assembly.Load(runtimeAssembly.Name); + } + } + + } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/project.json b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/project.json new file mode 100644 index 000000000..a8b1c8d28 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/project.json @@ -0,0 +1,14 @@ +{ + "version": "1.0.0-*", + "dependencies": { + "NETStandard.Library": "1.0.0-rc2-23811", + "Microsoft.Extensions.DependencyModel": { + "target": "project", + "version": "1.0.0-*" + } + }, + + "frameworks": { + "dnxcore50": { } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/TestApp/Program.cs b/TestAssets/TestProjects/DependencyContextValidator/TestApp/Program.cs new file mode 100644 index 000000000..28b8f8435 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/TestApp/Program.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace TestApp +{ + public class Program + { + public static void Main(string[] args) + { + Microsoft.Extensions.DependencyModel.DependencyContextValidator.Validate(true); + } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/TestApp/project.json b/TestAssets/TestProjects/DependencyContextValidator/TestApp/project.json new file mode 100644 index 000000000..688252bf4 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/TestApp/project.json @@ -0,0 +1,16 @@ +{ + "version": "1.0.0-*", + "compilationOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true + }, + + "dependencies": { + "NETStandard.Library": "1.0.0-rc2-23811", + "DependencyContextValidator": "1.0.0-*" + }, + + "frameworks": { + "dnxcore50": { } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/Program.cs b/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/Program.cs new file mode 100644 index 000000000..504c9a5bd --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/Program.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace TestApp +{ + public class Program + { + public static void Main(string[] args) + { + Microsoft.Extensions.DependencyModel.DependencyContextValidator.Validate(false); + } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/project.json b/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/project.json new file mode 100644 index 000000000..f36764265 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/TestAppDeps/project.json @@ -0,0 +1,15 @@ +{ + "version": "1.0.0-*", + "compilationOptions": { + "emitEntryPoint": true, + }, + + "dependencies": { + "NETStandard.Library": "1.0.0-rc2-23811", + "DependencyContextValidator": "1.0.0-*" + }, + + "frameworks": { + "dnxcore50": { } + } +} diff --git a/TestAssets/TestProjects/DependencyContextValidator/global.json b/TestAssets/TestProjects/DependencyContextValidator/global.json new file mode 100644 index 000000000..0c1944453 --- /dev/null +++ b/TestAssets/TestProjects/DependencyContextValidator/global.json @@ -0,0 +1,3 @@ +{ + "projects": [ ".", "../../../src" ] +} \ No newline at end of file diff --git a/TestAssets/TestProjects/RunTestsApps/TestAppFullClr/Program.cs b/TestAssets/TestProjects/RunTestsApps/TestAppFullClr/Program.cs index 6c7b146ea..1d00917a4 100644 --- a/TestAssets/TestProjects/RunTestsApps/TestAppFullClr/Program.cs +++ b/TestAssets/TestProjects/RunTestsApps/TestAppFullClr/Program.cs @@ -6,7 +6,7 @@ namespace ConsoleApplication { public static void Main(string[] args) { - .WriteLine("NET451"); + Console.WriteLine("NET451"); } } } diff --git a/TestAssets/TestProjects/RunTestsApps/TestAppMultiTargetNoCoreClr/project.json b/TestAssets/TestProjects/RunTestsApps/TestAppMultiTargetNoCoreClr/project.json index 470e49702..2e7a025eb 100644 --- a/TestAssets/TestProjects/RunTestsApps/TestAppMultiTargetNoCoreClr/project.json +++ b/TestAssets/TestProjects/RunTestsApps/TestAppMultiTargetNoCoreClr/project.json @@ -5,7 +5,7 @@ }, "frameworks": { - "dummy1": { }, - "net451": { } + "net451": { }, + "net45": { } } } diff --git a/TestAssets/TestProjects/TestAppCompilationContext/TestApp/Program.cs b/TestAssets/TestProjects/TestAppCompilationContext/TestApp/Program.cs index ac3163a58..fee6a5079 100644 --- a/TestAssets/TestProjects/TestAppCompilationContext/TestApp/Program.cs +++ b/TestAssets/TestProjects/TestAppCompilationContext/TestApp/Program.cs @@ -8,10 +8,8 @@ namespace TestApp { public class Program { - public static int Main(string[] args) + public static void Main(string[] args) { - Console.WriteLine(TestLibrary.Helper.GetMessage()); - return 100; } } } diff --git a/TestAssets/TestProjects/TestAppCompilationContext/global.json b/TestAssets/TestProjects/TestAppCompilationContext/global.json index 3a4684c26..c92e10596 100644 --- a/TestAssets/TestProjects/TestAppCompilationContext/global.json +++ b/TestAssets/TestProjects/TestAppCompilationContext/global.json @@ -1,3 +1,3 @@ { - "projects": [ "."] + "projects": [ "." ] } \ No newline at end of file diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/Program.cs b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/Program.cs new file mode 100644 index 000000000..ac3163a58 --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/Program.cs @@ -0,0 +1,17 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace TestApp +{ + public class Program + { + public static int Main(string[] args) + { + Console.WriteLine(TestLibrary.Helper.GetMessage()); + return 100; + } + } +} diff --git a/TestAssets/TestProjects/TestProjectToProjectDependencies/TestProjectToProjectDependencies.xproj b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/TestApp.xproj similarity index 87% rename from TestAssets/TestProjects/TestProjectToProjectDependencies/TestProjectToProjectDependencies.xproj rename to TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/TestApp.xproj index 92027115c..4cef17daa 100644 --- a/TestAssets/TestProjects/TestProjectToProjectDependencies/TestProjectToProjectDependencies.xproj +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/TestApp.xproj @@ -4,10 +4,11 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + - 947dd232-8d9b-4b78-9c6a-94f807d22222 - TestProjectToProjectDependencies + 58808bbc-371e-47d6-a3d0-4902145eda4e + TestApp ..\..\artifacts\obj\$(MSBuildProjectName) ..\..\artifacts\bin\$(MSBuildProjectName)\ @@ -16,4 +17,4 @@ 2.0 - \ No newline at end of file + diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/project.json b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/project.json new file mode 100644 index 000000000..64ba761af --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestApp/project.json @@ -0,0 +1,17 @@ +{ + "version": "1.0.0-*", + "compilationOptions": { + "emitEntryPoint": true, + "preserveCompilationContext": true + }, + + "dependencies": { + "TestLibrary": { "target":"project", "version":"1.0.0-*" }, + + "NETStandard.Library": "1.0.0-rc2-23811" + }, + + "frameworks": { + "dnxcore50": { } + } +} diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/.noautobuild b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/.noautobuild new file mode 100644 index 000000000..8f7edc4ac --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/.noautobuild @@ -0,0 +1 @@ +noautobuild \ No newline at end of file diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.dll b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.dll new file mode 100644 index 000000000..bfd7fd465 Binary files /dev/null and b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.dll differ diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.pdb b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.pdb new file mode 100644 index 000000000..36cc512f7 Binary files /dev/null and b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.pdb differ diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.xml b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.xml new file mode 100644 index 000000000..92371c77c --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/bin/Debug/dnxcore50/TestLibrary.xml @@ -0,0 +1,14 @@ + + + + TestLibraryWithConfiguration + + + + + Gets the message from the helper. This comment is here to help test XML documentation file generation, please do not remove it. + + A message + + + diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/project.json b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/project.json new file mode 100644 index 000000000..10bf5d798 --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/TestLibrary/project.json @@ -0,0 +1,10 @@ +{ + "frameworks": { + "dnxcore50": { + "bin": { + "assembly": "bin\\{configuration}\\dnxcore50\\TestLibrary.dll", + "pdb": "bin\\{configuration}\\dnxcore50\\TestLibrary.pdb" + } + } + } +} \ No newline at end of file diff --git a/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/global.json b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/global.json new file mode 100644 index 000000000..3a4684c26 --- /dev/null +++ b/TestAssets/TestProjects/TestAppWithWrapperProjectDependency/global.json @@ -0,0 +1,3 @@ +{ + "projects": [ "."] +} \ No newline at end of file diff --git a/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/Program.cs b/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/Program.cs new file mode 100644 index 000000000..f5f4b6d13 --- /dev/null +++ b/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/Program.cs @@ -0,0 +1,12 @@ +using System; + +namespace ConsoleApplication +{ + public class Program + { + public static void Main() + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/project.json b/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/project.json new file mode 100644 index 000000000..4d87acf96 --- /dev/null +++ b/TestAssets/TestProjects/TestLibraryWithMultipleFrameworks/project.json @@ -0,0 +1,20 @@ +{ + "version": "1.0.0-*", + "compilationOptions": { + "emitEntryPoint": false + }, + + "dependencies": { }, + + "frameworks": { + "net20": { }, + "net35": { }, + "net40": { }, + "net461": { }, + "dnxcore50": { + "dependencies": { + "NETStandard.Library": "1.0.0-rc2-23811" + } + } + } +} diff --git a/global.json b/global.json index 6ea600c29..9a66d5edc 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,3 @@ { - "projects": [ "src", "test" ] + "projects": [ "src", "test" ] } diff --git a/netci.groovy b/netci.groovy index 852a9c456..31f2b29eb 100644 --- a/netci.groovy +++ b/netci.groovy @@ -8,7 +8,7 @@ import jobs.generation.Utilities; def project = GithubProject def branch = GithubBranchName -def osList = ['Ubuntu', 'OSX', 'Windows_NT', 'CentOS7.1'] +def osList = ['Ubuntu', 'OSX', 'Windows_NT', 'Windows_2016', 'CentOS7.1'] def static getBuildJobName(def configuration, def os) { return configuration.toLowerCase() + '_' + os.toLowerCase() @@ -28,6 +28,9 @@ def static getBuildJobName(def configuration, def os) { if (os == 'Windows_NT') { buildCommand = ".\\build.cmd -Configuration ${lowerConfiguration} Default" } + else if (os == 'Windows_2016') { + buildCommand = ".\\build.cmd -Configuration ${lowerConfiguration} -RunInstallerTestsInDocker Default" + } else if (os == 'Ubuntu') { buildCommand = "./build.sh --skip-prereqs --configuration ${lowerConfiguration} --docker ubuntu Default" } @@ -39,7 +42,7 @@ def static getBuildJobName(def configuration, def os) { def newJob = job(Utilities.getFullJobName(project, jobName, isPR)) { // Set the label. steps { - if (os == 'Windows_NT') { + if (os == 'Windows_NT' || os == 'Windows_2016') { // Batch batchFile(buildCommand) } diff --git a/packaging/release_debian_config.json b/packaging/release_debian_config.json deleted file mode 100644 index e69de29bb..000000000 diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/AnsiConsole.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/AnsiConsole.cs index 8458eb629..7f3e26852 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/AnsiConsole.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/AnsiConsole.cs @@ -8,39 +8,40 @@ namespace Microsoft.DotNet.Cli.Build.Framework { public class AnsiConsole { - private AnsiConsole(TextWriter writer, bool useConsoleColor) + private AnsiConsole(TextWriter writer) { Writer = writer; - - _useConsoleColor = useConsoleColor; - if (_useConsoleColor) - { - OriginalForegroundColor = Console.ForegroundColor; - } + + OriginalForegroundColor = Console.ForegroundColor; } - + private int _boldRecursion; - private bool _useConsoleColor; - - public static AnsiConsole GetOutput(bool useConsoleColor) + + public static AnsiConsole GetOutput() { - return new AnsiConsole(Console.Out, useConsoleColor); + return new AnsiConsole(Console.Out); } - - public static AnsiConsole GetError(bool useConsoleColor) + + public static AnsiConsole GetError() { - return new AnsiConsole(Console.Error, useConsoleColor); + return new AnsiConsole(Console.Error); } - + public TextWriter Writer { get; } - + public ConsoleColor OriginalForegroundColor { get; } - + private void SetColor(ConsoleColor color) { - Console.ForegroundColor = (ConsoleColor)(((int)Console.ForegroundColor & 0x08) | ((int)color & 0x07)); - } + const int Light = 0x08; + int c = (int)color; + Console.ForegroundColor = + c < 0 ? color : // unknown, just use it + _boldRecursion > 0 ? (ConsoleColor)(c & ~Light) : // ensure color is dark + (ConsoleColor)(c | Light); // ensure color is light + } + private void SetBold(bool bold) { _boldRecursion += bold ? 1 : -1; @@ -48,18 +49,20 @@ namespace Microsoft.DotNet.Cli.Build.Framework { return; } - - Console.ForegroundColor = (ConsoleColor)((int)Console.ForegroundColor ^ 0x08); + + // switches on _boldRecursion to handle boldness + SetColor(Console.ForegroundColor); } public void WriteLine(string message) { - if (!_useConsoleColor) - { - Writer.WriteLine(message); - return; - } + Write(message); + Writer.WriteLine(); + } + + public void Write(string message) + { var escapeScan = 0; for (;;) { @@ -80,14 +83,14 @@ namespace Microsoft.DotNet.Cli.Build.Framework { endIndex += 1; } - + var text = message.Substring(escapeScan, escapeIndex - escapeScan); Writer.Write(text); if (endIndex == message.Length) { break; } - + switch (message[endIndex]) { case 'm': @@ -133,11 +136,10 @@ namespace Microsoft.DotNet.Cli.Build.Framework } break; } - + escapeScan = endIndex + 1; } } - Writer.WriteLine(); } } } diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildContext.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildContext.cs index a7b059ce0..e4d8846f4 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildContext.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildContext.cs @@ -42,7 +42,13 @@ namespace Microsoft.DotNet.Cli.Build.Framework BuildTarget target; if (!Targets.TryGetValue(name, out target)) { - Reporter.Verbose.WriteLine($"Skipping undefined target: {name}"); + throw new UndefinedTargetException($"Undefined target: {name}"); + } + + if (!EvaluateTargetConditions(target)) + { + Reporter.Verbose.WriteLine($"Skipping, Target Conditions not met: {target.Name}"); + return new BuildTargetResult(target, success: true); } // Check if it's been completed @@ -53,7 +59,6 @@ namespace Microsoft.DotNet.Cli.Build.Framework return result; } - // It hasn't, or we're forcing, so run it result = ExecTarget(target); _completedTargets[target.Name] = result; @@ -80,8 +85,36 @@ namespace Microsoft.DotNet.Cli.Build.Framework Reporter.Error.WriteLine("error".Red().Bold() + $": {message}"); } + private bool EvaluateTargetConditions(BuildTarget target) + { + if (target == null) + { + throw new ArgumentNullException("target"); + } + + if (target.Conditions == null) + { + return true; + } + + foreach (var condition in target.Conditions) + { + if (!condition()) + { + return false; + } + } + + return true; + } + private BuildTargetResult ExecTarget(BuildTarget target) { + if (target == null) + { + throw new ArgumentNullException("target"); + } + var sectionName = $"{target.Name.PadRight(_maxTargetLen + 2).Yellow()} ({target.Source.White()})"; BuildReporter.BeginSection("TARGET", sectionName); diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildSetup.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildSetup.cs index 34eb86afa..17847ccaa 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildSetup.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildSetup.cs @@ -52,8 +52,6 @@ namespace Microsoft.DotNet.Cli.Build.Framework public int Run(string[] args) { - DebugHelper.HandleDebugSwitch(ref args); - var targets = new[] { BuildContext.DefaultTarget }; if(args.Length > 0) { @@ -104,18 +102,40 @@ namespace Microsoft.DotNet.Cli.Build.Framework private static IEnumerable CollectTargets(Type typ) { return from m in typ.GetMethods() - let attr = m.GetCustomAttribute() - where attr != null - select CreateTarget(m, attr); + let targetAttribute = m.GetCustomAttribute() + let conditionalAttributes = m.GetCustomAttributes(false) + where targetAttribute != null + select CreateTarget(m, targetAttribute, conditionalAttributes); } - private static BuildTarget CreateTarget(MethodInfo m, TargetAttribute attr) + private static BuildTarget CreateTarget( + MethodInfo methodInfo, + TargetAttribute targetAttribute, + IEnumerable targetConditionAttributes) { + var name = targetAttribute.Name ?? methodInfo.Name; + + var conditions = ExtractTargetConditionsFromAttributes(targetConditionAttributes); + return new BuildTarget( - attr.Name ?? m.Name, - $"{m.DeclaringType.FullName}.{m.Name}", - attr.Dependencies, - (Func)m.CreateDelegate(typeof(Func))); + name, + $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}", + targetAttribute.Dependencies, + conditions, + (Func)methodInfo.CreateDelegate(typeof(Func))); + } + + private static IEnumerable> ExtractTargetConditionsFromAttributes( + IEnumerable targetConditionAttributes) + { + if (targetConditionAttributes == null || targetConditionAttributes.Count() == 0) + { + return Enumerable.Empty>(); + } + + return targetConditionAttributes + .Select>(c => c.EvaluateCondition) + .ToArray(); } private string GenerateSourceString(string file, int? line, string member) diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildTarget.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildTarget.cs index 303e0ae66..d3b161885 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildTarget.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/BuildTarget.cs @@ -4,21 +4,28 @@ using System.Linq; namespace Microsoft.DotNet.Cli.Build.Framework { - public class BuildTarget - { - public string Name { get; } + public class BuildTarget + { + public string Name { get; } public string Source { get; } - public IEnumerable Dependencies { get; } - public Func Body { get; } + public IEnumerable Dependencies { get; } + public IEnumerable> Conditions { get; } + public Func Body { get; } - public BuildTarget(string name, string source) : this(name, source, Enumerable.Empty(), null) { } - public BuildTarget(string name, string source, IEnumerable dependencies) : this(name, source, dependencies, null) { } - public BuildTarget(string name, string source, IEnumerable dependencies, Func body) - { - Name = name; + public BuildTarget(string name, string source) : this(name, source, Enumerable.Empty(), Enumerable.Empty>(), null) { } + public BuildTarget(string name, string source, IEnumerable dependencies) : this(name, source, dependencies, Enumerable.Empty>(), null) { } + public BuildTarget( + string name, + string source, + IEnumerable dependencies, + IEnumerable> conditions, + Func body) + { + Name = name; Source = source; - Dependencies = dependencies; - Body = body; - } - } + Dependencies = dependencies; + Conditions = conditions; + Body = body; + } + } } \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/Command.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/Command.cs index 70faf13c2..89c0e9f16 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/Command.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/Command.cs @@ -25,6 +25,7 @@ namespace Microsoft.DotNet.Cli.Build.Framework private Action _stdErrHandler; private bool _running = false; + private bool _quietBuildReporter = false; private Command(string executable, string args) { @@ -148,6 +149,12 @@ namespace Microsoft.DotNet.Cli.Build.Framework return this; } + public Command QuietBuildReporter() + { + _quietBuildReporter = true; + return this; + } + public CommandResult Execute() { ThrowIfRunning(); @@ -172,7 +179,7 @@ namespace Microsoft.DotNet.Cli.Build.Framework _process.EnableRaisingEvents = true; var sw = Stopwatch.StartNew(); - BuildReporter.BeginSection("EXEC", FormatProcessInfo(_process.StartInfo)); + ReportExecBegin(); _process.Start(); @@ -190,15 +197,7 @@ namespace Microsoft.DotNet.Cli.Build.Framework var exitCode = _process.ExitCode; - var message = $"{FormatProcessInfo(_process.StartInfo)} exited with {exitCode}"; - if (exitCode == 0) - { - BuildReporter.EndSection("EXEC", message.Green(), success: true); - } - else - { - BuildReporter.EndSection("EXEC", message.Red().Bold(), success: false); - } + ReportExecEnd(exitCode); return new CommandResult( _process.StartInfo, @@ -299,6 +298,30 @@ namespace Microsoft.DotNet.Cli.Build.Framework return info.FileName + " " + info.Arguments; } + private void ReportExecBegin() + { + if (!_quietBuildReporter) + { + BuildReporter.BeginSection("EXEC", FormatProcessInfo(_process.StartInfo)); + } + } + + private void ReportExecEnd(int exitCode) + { + if (!_quietBuildReporter) + { + var message = $"{FormatProcessInfo(_process.StartInfo)} exited with {exitCode}"; + if (exitCode == 0) + { + BuildReporter.EndSection("EXEC", message.Green(), success: true); + } + else + { + BuildReporter.EndSection("EXEC", message.Red().Bold(), success: false); + } + } + } + private void ThrowIfRunning([CallerMemberName] string memberName = null) { if (_running) diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentArchitecture.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentArchitecture.cs new file mode 100644 index 000000000..71aedf03c --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentArchitecture.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.Extensions.PlatformAbstractions; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public static class CurrentArchitecture + { + public static BuildArchitecture Current + { + get + { + return DetermineCurrentArchitecture(); + } + } + + public static bool Isx86 + { + get + { + var archName = PlatformServices.Default.Runtime.RuntimeArchitecture; + return string.Equals(archName, "x86", StringComparison.OrdinalIgnoreCase); + } + } + + public static bool Isx64 + { + get + { + var archName = PlatformServices.Default.Runtime.RuntimeArchitecture; + return string.Equals(archName, "x64", StringComparison.OrdinalIgnoreCase); + } + } + + private static BuildArchitecture DetermineCurrentArchitecture() + { + if (Isx86) + { + return BuildArchitecture.x86; + } + else if (Isx64) + { + return BuildArchitecture.x64; + } + else + { + return default(BuildArchitecture); + } + } + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentPlatform.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentPlatform.cs new file mode 100644 index 000000000..fb70d37c1 --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/CurrentPlatform.cs @@ -0,0 +1,75 @@ +using System; +using System.Runtime.InteropServices; +using Microsoft.Extensions.PlatformAbstractions; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public static class CurrentPlatform + { + public static BuildPlatform Current + { + get + { + return DetermineCurrentPlatform(); + } + } + + public static bool IsWindows + { + get + { + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + } + } + + public static bool IsOSX + { + get + { + return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + } + } + + public static bool IsUbuntu + { + get + { + var osname = PlatformServices.Default.Runtime.OperatingSystem; + return string.Equals(osname, "ubuntu", StringComparison.OrdinalIgnoreCase); + } + } + + public static bool IsCentOS + { + get + { + var osname = PlatformServices.Default.Runtime.OperatingSystem; + return string.Equals(osname, "centos", StringComparison.OrdinalIgnoreCase); + } + } + + private static BuildPlatform DetermineCurrentPlatform() + { + if (IsWindows) + { + return BuildPlatform.Windows; + } + else if (IsOSX) + { + return BuildPlatform.OSX; + } + else if (IsUbuntu) + { + return BuildPlatform.Ubuntu; + } + else if (IsCentOS) + { + return BuildPlatform.CentOS; + } + else + { + return default(BuildPlatform); + } + } + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildArchitecture.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildArchitecture.cs new file mode 100644 index 000000000..b2137ea07 --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildArchitecture.cs @@ -0,0 +1,8 @@ +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public enum BuildArchitecture + { + x86 = 1, + x64 = 2 + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildPlatform.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildPlatform.cs new file mode 100644 index 000000000..d594ca604 --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/Enumerations/BuildPlatform.cs @@ -0,0 +1,10 @@ +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public enum BuildPlatform + { + Windows = 1, + OSX = 2, + Ubuntu = 3, + CentOS = 4 + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/Reporter.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/Reporter.cs index 766ddf764..664d8fc53 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/Reporter.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/Reporter.cs @@ -19,16 +19,9 @@ namespace Microsoft.DotNet.Cli.Build.Framework _console = console; } - public static Reporter Output { get; } = Create(AnsiConsole.GetOutput); - public static Reporter Error { get; } = Create(AnsiConsole.GetOutput); - public static Reporter Verbose { get; } = Create(AnsiConsole.GetOutput); - - public static Reporter Create(Func getter) - { - var stripColors = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || - string.Equals(Environment.GetEnvironmentVariable("NO_COLOR"), "1"); - return new Reporter(getter(stripColors)); - } + public static Reporter Output { get; } = new Reporter(AnsiConsole.GetOutput()); + public static Reporter Error { get; } = new Reporter(AnsiConsole.GetOutput()); + public static Reporter Verbose { get; } = new Reporter(AnsiConsole.GetOutput()); public void WriteLine(string message) { diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetAttribute.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetAttribute.cs index 6cc6771fc..c7b851808 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetAttribute.cs +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetAttribute.cs @@ -5,8 +5,8 @@ using System.Linq; namespace Microsoft.DotNet.Cli.Build.Framework { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] - public class TargetAttribute : Attribute - { + public class TargetAttribute : Attribute + { public string Name { get; set; } public IEnumerable Dependencies { get; } @@ -20,5 +20,5 @@ namespace Microsoft.DotNet.Cli.Build.Framework { Dependencies = dependencies; } - } + } } \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildArchitecturesAttribute.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildArchitecturesAttribute.cs new file mode 100644 index 000000000..b166dd36f --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildArchitecturesAttribute.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class BuildArchitecturesAttribute : TargetConditionAttribute + { + private IEnumerable _buildArchitectures; + + public BuildArchitecturesAttribute(params BuildArchitecture[] architectures) + { + if (architectures == null) + { + throw new ArgumentNullException("architectures"); + } + + _buildArchitectures = architectures; + } + + public override bool EvaluateCondition() + { + var currentArchitecture = CurrentArchitecture.Current; + + if (currentArchitecture == default(BuildArchitecture)) + { + throw new Exception("Unrecognized Architecture"); + } + + foreach (var architecture in _buildArchitectures) + { + if (architecture == currentArchitecture) + { + return true; + } + } + + return false; + } + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildPlatformsAttribute.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildPlatformsAttribute.cs new file mode 100644 index 000000000..d05655a67 --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/BuildPlatformsAttribute.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class BuildPlatformsAttribute : TargetConditionAttribute + { + private IEnumerable _buildPlatforms; + + public BuildPlatformsAttribute(params BuildPlatform[] platforms) + { + if (platforms == null) + { + throw new ArgumentNullException("platforms"); + } + + _buildPlatforms = platforms; + } + + public override bool EvaluateCondition() + { + var currentPlatform = CurrentPlatform.Current; + + if (currentPlatform == default(BuildPlatform)) + { + throw new Exception("Unrecognized Platform."); + } + + foreach (var platform in _buildPlatforms) + { + if (platform == currentPlatform) + { + return true; + } + } + + return false; + } + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/TargetConditionAttribute.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/TargetConditionAttribute.cs new file mode 100644 index 000000000..74243f06a --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/TargetConditions/TargetConditionAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public abstract class TargetConditionAttribute : Attribute + { + public abstract bool EvaluateCondition(); + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/UndefinedTargetException.cs b/scripts/Microsoft.DotNet.Cli.Build.Framework/UndefinedTargetException.cs new file mode 100644 index 000000000..69243ced9 --- /dev/null +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/UndefinedTargetException.cs @@ -0,0 +1,9 @@ +using System; + +namespace Microsoft.DotNet.Cli.Build.Framework +{ + public class UndefinedTargetException : Exception + { + public UndefinedTargetException(string message) : base(message) { } + } +} \ No newline at end of file diff --git a/scripts/Microsoft.DotNet.Cli.Build.Framework/project.json b/scripts/Microsoft.DotNet.Cli.Build.Framework/project.json index dd887545d..ff3a3dbc6 100644 --- a/scripts/Microsoft.DotNet.Cli.Build.Framework/project.json +++ b/scripts/Microsoft.DotNet.Cli.Build.Framework/project.json @@ -3,7 +3,8 @@ "dependencies": { "NETStandard.Library": "1.0.0-rc2-23811", - "System.Diagnostics.Process": "4.1.0-rc2-23811" + "System.Diagnostics.Process": "4.1.0-rc2-23811", + "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc2-16537" }, "frameworks": { diff --git a/scripts/docker/ubuntu/Dockerfile b/scripts/docker/ubuntu/Dockerfile index b5511b589..852a81720 100644 --- a/scripts/docker/ubuntu/Dockerfile +++ b/scripts/docker/ubuntu/Dockerfile @@ -6,39 +6,80 @@ # Dockerfile that creates a container suitable to build dotnet-cli FROM ubuntu:14.04 +# Misc Dependencies for build +RUN apt-get update && apt-get -qqy install curl unzip gettext sudo + # This could become a "microsoft/coreclr" image, since it just installs the dependencies for CoreCLR (and stdlib) -# Install CoreCLR and CoreFx dependencies -RUN apt-get update && \ - apt-get -qqy install unzip curl libicu-dev libunwind8 gettext libssl-dev libcurl3-gnutls zlib1g liblttng-ust-dev lldb-3.6-dev lldb-3.6 +RUN echo "deb http://llvm.org/apt/trusty/ llvm-toolchain-trusty-3.6 main" | tee /etc/apt/sources.list.d/llvm.list && \ + curl http://llvm.org/apt/llvm-snapshot.gpg.key | apt-key add - && \ + apt-get update && apt-get -qqy install\ + libc6 \ + libedit2 \ + libffi6 \ + libgcc1 \ + libicu52 \ + liblldb-3.6 \ + libllvm3.6 \ + liblttng-ust0 \ + liblzma5 \ + libncurses5 \ + libpython2.7 \ + libstdc++6 \ + libtinfo5 \ + libunwind8 \ + liburcu1 \ + libuuid1 \ + zlib1g \ + libasn1-8-heimdal \ + libcomerr2 \ + libcurl3 \ + libgcrypt11 \ + libgnutls26 \ + libgpg-error0 \ + libgssapi3-heimdal \ + libgssapi-krb5-2 \ + libhcrypto4-heimdal \ + libheimbase1-heimdal \ + libheimntlm0-heimdal \ + libhx509-5-heimdal \ + libidn11 \ + libk5crypto3 \ + libkeyutils1 \ + libkrb5-26-heimdal \ + libkrb5-3 \ + libkrb5support0 \ + libldap-2.4-2 \ + libp11-kit0 \ + libroken18-heimdal \ + librtmp0 \ + libsasl2-2 \ + libsqlite3-0 \ + libssl1.0.0 \ + libtasn1-6 \ + libwind0-heimdal # Install Dotnet CLI dependencies. # clang is required for dotnet-compile-native RUN apt-get -qqy install clang-3.5 # Install Build Prereqs -RUN echo "deb http://llvm.org/apt/trusty/ llvm-toolchain-trusty-3.6 main" | tee /etc/apt/sources.list.d/llvm.list && \ - curl http://llvm.org/apt/llvm-snapshot.gpg.key | apt-key add - && \ - apt-get update && \ - apt-get install -y debhelper build-essential devscripts git cmake +RUN apt-get -qq install -y debhelper build-essential devscripts git cmake # Use clang as c++ compiler RUN update-alternatives --install /usr/bin/c++ c++ /usr/bin/clang++-3.5 100 RUN update-alternatives --set c++ /usr/bin/clang++-3.5 # Install azure cli. We need this to publish artifacts. -RUN apt-get -y install nodejs-legacy && \ - apt-get -y install npm && \ +RUN apt-get -qqy install nodejs-legacy && \ + apt-get -qqy install npm && \ npm install -g azure-cli - -RUN apt-get install -qqy sudo - # Setup User to match Host User, and give superuser permissions ARG USER_ID=0 RUN useradd -m code_executor -u ${USER_ID} -g sudo RUN echo 'code_executor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers -# With the User Change, we need to change permssions on these directories +# With the User Change, we need to change permissions on these directories RUN chmod -R a+rwx /usr/local RUN chmod -R a+rwx /home RUN chmod -R 755 /usr/lib/sudo diff --git a/scripts/dotnet-cli-build/PackageDependencies.cs b/scripts/dotnet-cli-build/PackageDependencies.cs new file mode 100644 index 000000000..9b51237b8 --- /dev/null +++ b/scripts/dotnet-cli-build/PackageDependencies.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Microsoft.DotNet.Cli.Build +{ + public class PackageDependencies + { + internal static string[] DebianPackageBuildDependencies + { + get + { + return new string[] + { + "devscripts", + "debhelper", + "build-essential" + }; + + } + } + + internal static string[] UbuntuCoreclrAndCoreFxDependencies + { + get + { + return new string[] + { + "libc6", + "libedit2", + "libffi6", + "libgcc1", + "libicu52", + "liblldb-3.6", + "libllvm3.6", + "liblttng-ust0", + "liblzma5", + "libncurses5", + "libpython2.7", + "libstdc++6", + "libtinfo5", + "libunwind8", + "liburcu1", + "libuuid1", + "zlib1g", + "libasn1-8-heimdal", + "libcomerr2", + "libcurl3", + "libgcrypt11", + "libgnutls26", + "libgpg-error0", + "libgssapi3-heimdal", + "libgssapi-krb5-2", + "libhcrypto4-heimdal", + "libheimbase1-heimdal", + "libheimntlm0-heimdal", + "libhx509-5-heimdal", + "libidn11", + "libk5crypto3", + "libkeyutils1", + "libkrb5-26-heimdal", + "libkrb5-3", + "libkrb5support0", + "libldap-2.4-2", + "libp11-kit0", + "libroken18-heimdal", + "librtmp0", + "libsasl2-2", + "libsqlite3-0", + "libssl1.0.0", + "libtasn1-6", + "libwind0-heimdal" + }; + } + } + + internal static string[] CentosCoreclrAndCoreFxDependencies + { + get + { + return new string[] + { + "unzip", + "libunwind", + "gettext", + "libcurl-devel", + "openssl-devel", + "zlib", + "libicu-devel" + }; + } + } + + } +} diff --git a/scripts/dotnet-cli-build/PrepareTargets.cs b/scripts/dotnet-cli-build/PrepareTargets.cs index dc4905c9d..bc10066e9 100644 --- a/scripts/dotnet-cli-build/PrepareTargets.cs +++ b/scripts/dotnet-cli-build/PrepareTargets.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; +using System.Text; using static Microsoft.DotNet.Cli.Build.FS; using static Microsoft.DotNet.Cli.Build.Utils; @@ -17,6 +18,18 @@ namespace Microsoft.DotNet.Cli.Build [Target(nameof(Init), nameof(RestorePackages))] public static BuildTargetResult Prepare(BuildTargetContext c) => c.Success(); + [Target(nameof(CheckPrereqCmakePresent), nameof(CheckPlatformDependencies))] + public static BuildTargetResult CheckPrereqs(BuildTargetContext c) => c.Success(); + + [Target(nameof(CheckCoreclrPlatformDependencies), nameof(CheckInstallerBuildPlatformDependencies))] + public static BuildTargetResult CheckPlatformDependencies(BuildTargetContext c) => c.Success(); + + [Target(nameof(CheckUbuntuCoreclrAndCoreFxDependencies), nameof(CheckCentOSCoreclrAndCoreFxDependencies))] + public static BuildTargetResult CheckCoreclrPlatformDependencies(BuildTargetContext c) => c.Success(); + + [Target(nameof(CheckUbuntuDebianPackageBuildDependencies))] + public static BuildTargetResult CheckInstallerBuildPlatformDependencies(BuildTargetContext c) => c.Success(); + // All major targets will depend on this in order to ensure variables are set up right if they are run independently [Target(nameof(GenerateVersions), nameof(CheckPrereqs), nameof(LocateStage0))] public static BuildTargetResult Init(BuildTargetContext c) @@ -91,38 +104,6 @@ namespace Microsoft.DotNet.Cli.Build return c.Success(); } - [Target] - public static BuildTargetResult CheckPrereqs(BuildTargetContext c) - { - try - { - Command.Create("cmake", "--version") - .CaptureStdOut() - .CaptureStdErr() - .Execute(); - } - catch (Exception ex) - { - string message = $@"Error running cmake: {ex.Message} -cmake is required to build the native host 'corehost'"; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - message += Environment.NewLine + "Download it from https://www.cmake.org"; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - message += Environment.NewLine + "Ubuntu: 'sudo apt-get install cmake'"; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - message += Environment.NewLine + "OS X w/Homebrew: 'brew install cmake'"; - } - return c.Failed(message); - } - - return c.Success(); - } - [Target] public static BuildTargetResult CheckPackageCache(BuildTargetContext c) { @@ -200,6 +181,134 @@ cmake is required to build the native host 'corehost'"; return c.Success(); } + [Target] + [BuildPlatforms(BuildPlatform.Ubuntu)] + public static BuildTargetResult CheckUbuntuDebianPackageBuildDependencies(BuildTargetContext c) + { + + var messageBuilder = new StringBuilder(); + var aptDependencyUtility = new AptDependencyUtility(); + + + foreach (var package in PackageDependencies.DebianPackageBuildDependencies) + { + if (!AptDependencyUtility.PackageIsInstalled(package)) + { + messageBuilder.Append($"Error: Debian package build dependency {package} missing."); + messageBuilder.Append(Environment.NewLine); + messageBuilder.Append($"-> install with apt-get install {package}"); + messageBuilder.Append(Environment.NewLine); + } + } + + if (messageBuilder.Length == 0) + { + return c.Success(); + } + else + { + return c.Failed(messageBuilder.ToString()); + } + } + + [Target] + [BuildPlatforms(BuildPlatform.Ubuntu)] + public static BuildTargetResult CheckUbuntuCoreclrAndCoreFxDependencies(BuildTargetContext c) + { + var errorMessageBuilder = new StringBuilder(); + var stage0 = DotNetCli.Stage0.BinPath; + + foreach (var package in PackageDependencies.UbuntuCoreclrAndCoreFxDependencies) + { + if (!AptDependencyUtility.PackageIsInstalled(package)) + { + errorMessageBuilder.Append($"Error: Coreclr package dependency {package} missing."); + errorMessageBuilder.Append(Environment.NewLine); + errorMessageBuilder.Append($"-> install with apt-get install {package}"); + errorMessageBuilder.Append(Environment.NewLine); + } + } + + if (errorMessageBuilder.Length == 0) + { + return c.Success(); + } + else + { + return c.Failed(errorMessageBuilder.ToString()); + } + } + + [Target] + [BuildPlatforms(BuildPlatform.CentOS)] + public static BuildTargetResult CheckCentOSCoreclrAndCoreFxDependencies(BuildTargetContext c) + { + var errorMessageBuilder = new StringBuilder(); + + foreach (var package in PackageDependencies.CentosCoreclrAndCoreFxDependencies) + { + if (!YumDependencyUtility.PackageIsInstalled(package)) + { + errorMessageBuilder.Append($"Error: Coreclr package dependency {package} missing."); + errorMessageBuilder.Append(Environment.NewLine); + errorMessageBuilder.Append($"-> install with yum install {package}"); + errorMessageBuilder.Append(Environment.NewLine); + } + } + + if (errorMessageBuilder.Length == 0) + { + return c.Success(); + } + else + { + return c.Failed(errorMessageBuilder.ToString()); + } + } + + [Target] + public static BuildTargetResult CheckPrereqCmakePresent(BuildTargetContext c) + { + try + { + Command.Create("cmake", "--version") + .CaptureStdOut() + .CaptureStdErr() + .Execute(); + } + catch (Exception ex) + { + string message = $@"Error running cmake: {ex.Message} +cmake is required to build the native host 'corehost'"; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + message += Environment.NewLine + "Download it from https://www.cmake.org"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + message += Environment.NewLine + "Ubuntu: 'sudo apt-get install cmake'"; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + message += Environment.NewLine + "OS X w/Homebrew: 'brew install cmake'"; + } + return c.Failed(message); + } + + return c.Success(); + } + + private static bool AptPackageIsInstalled(string packageName) + { + var result = Command.Create("dpkg", "-s", packageName) + .CaptureStdOut() + .CaptureStdErr() + .QuietBuildReporter() + .Execute(); + + return result.ExitCode == 0; + } + private static IDictionary ReadBranchInfo(BuildTargetContext c, string path) { var lines = File.ReadAllLines(path); diff --git a/scripts/dotnet-cli-build/Program.cs b/scripts/dotnet-cli-build/Program.cs index bc2661b2c..fe76c3af0 100755 --- a/scripts/dotnet-cli-build/Program.cs +++ b/scripts/dotnet-cli-build/Program.cs @@ -4,9 +4,14 @@ namespace Microsoft.DotNet.Cli.Build { public class Program { - public static int Main(string[] args) => BuildSetup.Create(".NET Core CLI") - .UseStandardGoals() - .UseAllTargetsFromAssembly() - .Run(args); + public static int Main(string[] args) + { + DebugHelper.HandleDebugSwitch(ref args); + + return BuildSetup.Create(".NET Core CLI") + .UseStandardGoals() + .UseAllTargetsFromAssembly() + .Run(args); + } } } diff --git a/scripts/dotnet-cli-build/TestTargets.cs b/scripts/dotnet-cli-build/TestTargets.cs index 9329b2cae..3ceea87e6 100644 --- a/scripts/dotnet-cli-build/TestTargets.cs +++ b/scripts/dotnet-cli-build/TestTargets.cs @@ -29,6 +29,7 @@ namespace Microsoft.DotNet.Cli.Build "dotnet-build.Tests", "dotnet-pack.Tests", "dotnet-resgen.Tests", + "dotnet-run.Tests", "Microsoft.DotNet.Cli.Utils.Tests", "Microsoft.DotNet.Compiler.Common.Tests", "Microsoft.DotNet.ProjectModel.Tests", diff --git a/scripts/dotnet-cli-build/Utils/AptDependencyUtility.cs b/scripts/dotnet-cli-build/Utils/AptDependencyUtility.cs new file mode 100644 index 000000000..031aa6981 --- /dev/null +++ b/scripts/dotnet-cli-build/Utils/AptDependencyUtility.cs @@ -0,0 +1,24 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.DotNet.Cli.Build.Framework; + +namespace Microsoft.DotNet.Cli.Build +{ + public class AptDependencyUtility + { + internal static bool PackageIsInstalled(string packageName) + { + var result = Command.Create("dpkg", "-s", packageName) + .CaptureStdOut() + .CaptureStdErr() + .QuietBuildReporter() + .Execute(); + + return result.ExitCode == 0; + } + } +} diff --git a/scripts/dotnet-cli-build/Utils/YumDependencyUtility.cs b/scripts/dotnet-cli-build/Utils/YumDependencyUtility.cs new file mode 100644 index 000000000..09e2f04ef --- /dev/null +++ b/scripts/dotnet-cli-build/Utils/YumDependencyUtility.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.DotNet.Cli.Build.Framework; + +namespace Microsoft.DotNet.Cli.Build +{ + public class YumDependencyUtility + { + internal static bool PackageIsInstalled(string packageName) + { + var result = Command.Create("yum", "list", "installed", packageName) + .CaptureStdOut() + .CaptureStdErr() + .QuietBuildReporter() + .Execute(); + + return result.ExitCode == 0; + } + } +} diff --git a/scripts/run-build.ps1 b/scripts/run-build.ps1 index 7206b3b0a..4e84a7af0 100644 --- a/scripts/run-build.ps1 +++ b/scripts/run-build.ps1 @@ -7,6 +7,7 @@ param( [string]$Configuration="Debug", [string]$Architecture="x64", [switch]$NoPackage, + [switch]$RunInstallerTestsInDocker, [switch]$Help) if($Help) @@ -17,6 +18,7 @@ if($Help) Write-Host " -Configuration Build the specified Configuration (Debug or Release, default: Debug)" Write-Host " -Architecture Build the specified architecture (x64 or x86 (supported only on Windows), default: x64)" Write-Host " -NoPackage Skip packaging targets" + Write-Host " -RunInstallerTestsInDocker Runs the .msi installer tests in a Docker container. Requires Windows 2016 TP4 or higher" Write-Host " -Help Display this help message" Write-Host " The build targets to run (Init, Compile, Publish, etc.; Default is a full build and publish)" exit 0 @@ -33,6 +35,11 @@ else $env:DOTNET_BUILD_SKIP_PACKAGING=0 } +if ($RunInstallerTestsInDocker) +{ + $env:RunInstallerTestsInDocker=1 +} + # Load Branch Info cat "$PSScriptRoot\..\branchinfo.txt" | ForEach-Object { if(!$_.StartsWith("#") -and ![String]::IsNullOrWhiteSpace($_)) { diff --git a/src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs b/src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs index 7401af673..f9fc34f14 100644 --- a/src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs +++ b/src/Microsoft.DotNet.Cli.Utils/AnsiConsole.cs @@ -8,28 +8,23 @@ namespace Microsoft.DotNet.Cli.Utils { public class AnsiConsole { - private AnsiConsole(TextWriter writer, bool useConsoleColor) + private AnsiConsole(TextWriter writer) { Writer = writer; - _useConsoleColor = useConsoleColor; - if (_useConsoleColor) - { - OriginalForegroundColor = Console.ForegroundColor; - } + OriginalForegroundColor = Console.ForegroundColor; } private int _boldRecursion; - private bool _useConsoleColor; - public static AnsiConsole GetOutput(bool useConsoleColor) + public static AnsiConsole GetOutput() { - return new AnsiConsole(Console.Out, useConsoleColor); + return new AnsiConsole(Console.Out); } - public static AnsiConsole GetError(bool useConsoleColor) + public static AnsiConsole GetError() { - return new AnsiConsole(Console.Error, useConsoleColor); + return new AnsiConsole(Console.Error); } public TextWriter Writer { get; } @@ -38,7 +33,13 @@ namespace Microsoft.DotNet.Cli.Utils private void SetColor(ConsoleColor color) { - Console.ForegroundColor = (ConsoleColor)(((int)Console.ForegroundColor & 0x08) | ((int)color & 0x07)); + const int Light = 0x08; + int c = (int)color; + + Console.ForegroundColor = + c < 0 ? color : // unknown, just use it + _boldRecursion > 0 ? (ConsoleColor)(c & ~Light) : // ensure color is dark + (ConsoleColor)(c | Light); // ensure color is light } private void SetBold(bool bold) @@ -48,8 +49,9 @@ namespace Microsoft.DotNet.Cli.Utils { return; } - - Console.ForegroundColor = (ConsoleColor)((int)Console.ForegroundColor ^ 0x08); + + // switches on _boldRecursion to handle boldness + SetColor(Console.ForegroundColor); } public void WriteLine(string message) @@ -61,12 +63,6 @@ namespace Microsoft.DotNet.Cli.Utils public void Write(string message) { - if (!_useConsoleColor) - { - Writer.Write(message); - return; - } - var escapeScan = 0; for (;;) { diff --git a/src/Microsoft.DotNet.Cli.Utils/Reporter.cs b/src/Microsoft.DotNet.Cli.Utils/Reporter.cs index 67d6220a3..8dcbd55fa 100644 --- a/src/Microsoft.DotNet.Cli.Utils/Reporter.cs +++ b/src/Microsoft.DotNet.Cli.Utils/Reporter.cs @@ -19,14 +19,11 @@ namespace Microsoft.DotNet.Cli.Utils _console = console; } - public static Reporter Output { get; } = Create(AnsiConsole.GetOutput); - public static Reporter Error { get; } = Create(AnsiConsole.GetError); - public static Reporter Verbose { get; } = CommandContext.IsVerbose() ? Create(AnsiConsole.GetOutput) : NullReporter; - - public static Reporter Create(Func getter) - { - return new Reporter(getter(PlatformServices.Default.Runtime.OperatingSystemPlatform == Platform.Windows)); - } + public static Reporter Output { get; } = new Reporter(AnsiConsole.GetOutput()); + public static Reporter Error { get; } = new Reporter(AnsiConsole.GetError()); + public static Reporter Verbose { get; } = CommandContext.IsVerbose() ? + new Reporter(AnsiConsole.GetOutput()) : + NullReporter; public void WriteLine(string message) { diff --git a/src/Microsoft.DotNet.Compiler.Common/AssemblyInfoFileGenerator.cs b/src/Microsoft.DotNet.Compiler.Common/AssemblyInfoFileGenerator.cs index ab24413fb..3e4408bc8 100644 --- a/src/Microsoft.DotNet.Compiler.Common/AssemblyInfoFileGenerator.cs +++ b/src/Microsoft.DotNet.Compiler.Common/AssemblyInfoFileGenerator.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CSharp; using System.IO; using System.Runtime.Versioning; using Microsoft.CodeAnalysis.CSharp.Syntax; +using NuGet.Frameworks; namespace Microsoft.DotNet.Cli.Compiler.Common { @@ -59,7 +60,7 @@ namespace Microsoft.DotNet.Cli.Compiler.Common private static Dictionary GetProjectAttributes(AssemblyInfoOptions metadata) { - return new Dictionary() + var attributes = new Dictionary() { [typeof(AssemblyTitleAttribute)] = EscapeCharacters(metadata.Title), [typeof(AssemblyDescriptionAttribute)] = EscapeCharacters(metadata.Description), @@ -68,9 +69,34 @@ namespace Microsoft.DotNet.Cli.Compiler.Common [typeof(AssemblyVersionAttribute)] = EscapeCharacters(metadata.AssemblyVersion?.ToString()), [typeof(AssemblyInformationalVersionAttribute)] = EscapeCharacters(metadata.InformationalVersion), [typeof(AssemblyCultureAttribute)] = EscapeCharacters(metadata.Culture), - [typeof(NeutralResourcesLanguageAttribute)] = EscapeCharacters(metadata.NeutralLanguage), - [typeof(TargetFrameworkAttribute)] = EscapeCharacters(metadata.TargetFramework) + [typeof(NeutralResourcesLanguageAttribute)] = EscapeCharacters(metadata.NeutralLanguage) }; + + if (SupportsTargetFrameworkAttribute(metadata)) + { + // TargetFrameworkAttribute only exists since .NET 4.0 + attributes[typeof(TargetFrameworkAttribute)] = EscapeCharacters(metadata.TargetFramework); + }; + + return attributes; + } + + private static bool SupportsTargetFrameworkAttribute(AssemblyInfoOptions metadata) + { + if (string.IsNullOrEmpty(metadata.TargetFramework)) + { + // target framework is unknown. to be on the safe side, return false. + return false; + } + + var targetFramework = NuGetFramework.Parse(metadata.TargetFramework); + if (!targetFramework.IsDesktop()) + { + // assuming .NET Core, which should support .NET 4.0 attributes + return true; + } + + return targetFramework.Version >= new Version(4, 0); } private static bool IsSameAttribute(Type attributeType, AttributeSyntax attributeSyntax) diff --git a/src/Microsoft.DotNet.ProjectModel/Compilation/LibraryExporter.cs b/src/Microsoft.DotNet.ProjectModel/Compilation/LibraryExporter.cs index ea5989e83..2ab423241 100644 --- a/src/Microsoft.DotNet.ProjectModel/Compilation/LibraryExporter.cs +++ b/src/Microsoft.DotNet.ProjectModel/Compilation/LibraryExporter.cs @@ -216,10 +216,14 @@ namespace Microsoft.DotNet.ProjectModel.Compilation var compileAsset = new LibraryAsset( project.Project.Name, null, - Path.GetFullPath(Path.Combine(project.Project.ProjectDirectory, assemblyPath))); + assemblyPath); builder.AddCompilationAssembly(compileAsset); - builder.AddRuntimeAsset(new LibraryAsset(Path.GetFileName(pdbPath), Path.GetFileName(pdbPath), pdbPath)); + builder.AddRuntimeAssembly(compileAsset); + if (File.Exists(pdbPath)) + { + builder.AddRuntimeAsset(new LibraryAsset(Path.GetFileName(pdbPath), Path.GetFileName(pdbPath), pdbPath)); + } } else if (project.Project.Files.SourceFiles.Any()) { @@ -286,7 +290,7 @@ namespace Microsoft.DotNet.ProjectModel.Compilation path = path.Replace("{configuration}", configuration); - return path; + return Path.Combine(project.ProjectDirectory, path); } private LibraryExport ExportFrameworkLibrary(LibraryDescription library) diff --git a/src/Microsoft.DotNet.ProjectModel/ProjectContext.cs b/src/Microsoft.DotNet.ProjectModel/ProjectContext.cs index 0a70f373c..9e237ff11 100644 --- a/src/Microsoft.DotNet.ProjectModel/ProjectContext.cs +++ b/src/Microsoft.DotNet.ProjectModel/ProjectContext.cs @@ -146,8 +146,12 @@ namespace Microsoft.DotNet.ProjectModel var context = Create(ProjectFile.ProjectFilePath, TargetFramework, runtimeIdentifiers); if (context.RuntimeIdentifier == null) { - var rids = string.Join(",", runtimeIdentifiers); - throw new InvalidOperationException($"Can not find runtime target for framework '{TargetFramework}' and RID's {rids}."); + var rids = string.Join(", ", runtimeIdentifiers); + throw new InvalidOperationException($"Can not find runtime target for framework '{TargetFramework}' and RID's '{rids}'. " + + "Possible causes:" + Environment.NewLine + + "1. Project is not restored or restore failed - run `dotnet restore`" + Environment.NewLine + + "2. Project is not targeting `runable` framework (`netstandardapp*` or `net*`)" + ); } return context; } diff --git a/src/Microsoft.DotNet.ProjectModel/project.json b/src/Microsoft.DotNet.ProjectModel/project.json index 3046ccab7..b0973d277 100644 --- a/src/Microsoft.DotNet.ProjectModel/project.json +++ b/src/Microsoft.DotNet.ProjectModel/project.json @@ -6,7 +6,7 @@ "description": "Types to model a .NET Project", "dependencies": { "System.Reflection.Metadata": "1.2.0-rc2-23811", - "NuGet.Packaging": "3.4.0-beta-625", + "NuGet.Packaging": "3.4.0-beta-632", "Microsoft.Extensions.FileSystemGlobbing": "1.0.0-rc2-15996", "Microsoft.Extensions.JsonParser.Sources": { "type": "build", diff --git a/src/Microsoft.Extensions.DependencyModel/DependencyContext.cs b/src/Microsoft.Extensions.DependencyModel/DependencyContext.cs index d1f06201c..b1cb8ccf7 100644 --- a/src/Microsoft.Extensions.DependencyModel/DependencyContext.cs +++ b/src/Microsoft.Extensions.DependencyModel/DependencyContext.cs @@ -11,6 +11,7 @@ namespace Microsoft.Extensions.DependencyModel public class DependencyContext { private const string DepsResourceSufix = ".deps.json"; + private const string DepsFileExtension = ".deps"; private static readonly Lazy _defaultContext = new Lazy(LoadDefault); @@ -43,22 +44,29 @@ namespace Microsoft.Extensions.DependencyModel public static DependencyContext Load(Assembly assembly) { - var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + DepsResourceSufix); - - if (stream == null) + if (assembly == null) { - return null; + throw new ArgumentNullException(nameof(assembly)); } - using (stream) + using (var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + DepsResourceSufix)) { - return Load(stream); + if (stream != null) + { + return new DependencyContextJsonReader().Read(stream); + } } - } - public static DependencyContext Load(Stream stream) - { - return new DependencyContextReader().Read(stream); + var depsFile = Path.ChangeExtension(assembly.Location, DepsFileExtension); + if (File.Exists(depsFile)) + { + using (var stream = File.OpenRead(depsFile)) + { + return new DependencyContextCsvReader().Read(stream); + } + } + + return null; } } } diff --git a/src/Microsoft.Extensions.DependencyModel/DependencyContextCsvReader.cs b/src/Microsoft.Extensions.DependencyModel/DependencyContextCsvReader.cs new file mode 100644 index 000000000..d466bd15c --- /dev/null +++ b/src/Microsoft.Extensions.DependencyModel/DependencyContextCsvReader.cs @@ -0,0 +1,130 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace Microsoft.Extensions.DependencyModel +{ + public class DependencyContextCsvReader + { + public DependencyContext Read(Stream stream) + { + var lines = new List(); + using (var reader = new StreamReader(stream)) + { + while (!reader.EndOfStream) + { + var line = new DepsFileLine(); + line.LibraryType = ReadValue(reader); + line.PackageName = ReadValue(reader); + line.PackageVersion = ReadValue(reader); + line.PackageHash = ReadValue(reader); + line.AssetType = ReadValue(reader); + line.AssetName = ReadValue(reader); + line.AssetPath = ReadValue(reader); + + if (line.AssetType == "runtime" && + !line.AssetPath.EndsWith(".ni.dll")) + { + lines.Add(line); + } + SkipWhitespace(reader); + } + } + + var runtimeLibraries = new List(); + var packageGroups = lines.GroupBy(PackageIdentity); + foreach (var packageGroup in packageGroups) + { + var identity = packageGroup.Key; + runtimeLibraries.Add(new RuntimeLibrary( + libraryType: identity.Item1, + packageName: identity.Item2, + version: identity.Item3, + hash: identity.Item4, + assemblies: packageGroup.Select(l => l.AssetPath).ToArray(), + dependencies: new Dependency[] { }, + serviceable: false + )); + } + + return new DependencyContext( + target: string.Empty, + runtime: string.Empty, + compilationOptions: CompilationOptions.Default, + compileLibraries: new CompilationLibrary[] {}, + runtimeLibraries: runtimeLibraries.ToArray()); + } + + private Tuple PackageIdentity(DepsFileLine line) + { + return Tuple.Create(line.LibraryType, line.PackageName, line.PackageVersion, line.PackageHash); + } + + private void SkipWhitespace(StreamReader reader) + { + // skip all whitespace + while (!reader.EndOfStream && char.IsWhiteSpace((char)reader.Peek())) + { + reader.Read(); + } + } + + private string ReadValue(StreamReader reader) + { + SkipWhitespace(reader); + + var c = ReadSucceed(reader.Read()); + if (c != '"') + { + throw new FormatException("Deps file value should start with '\"'"); + } + + var value = new StringBuilder(); + while (ReadSucceed(reader.Peek()) != '"') + { + c = ReadSucceed(reader.Read()); + if (c == '\\') + { + value.Append(ReadSucceed(reader.Read())); + } + else + { + value.Append(c); + } + } + // Read last " + ReadSucceed(reader.Read()); + // Read comment + if (reader.Peek() == ',') + { + reader.Read(); + } + return value.ToString(); + } + + private char ReadSucceed(int c) + { + if (c == -1) + { + throw new FormatException("Unexpected end of file"); + } + return (char) c; + } + + private struct DepsFileLine + { + public string LibraryType; + public string PackageName; + public string PackageVersion; + public string PackageHash; + public string AssetType; + public string AssetName; + public string AssetPath; + } + } +} \ No newline at end of file diff --git a/src/Microsoft.Extensions.DependencyModel/DependencyContextReader.cs b/src/Microsoft.Extensions.DependencyModel/DependencyContextJsonReader.cs similarity index 99% rename from src/Microsoft.Extensions.DependencyModel/DependencyContextReader.cs rename to src/Microsoft.Extensions.DependencyModel/DependencyContextJsonReader.cs index a02e99f40..881ae3441 100644 --- a/src/Microsoft.Extensions.DependencyModel/DependencyContextReader.cs +++ b/src/Microsoft.Extensions.DependencyModel/DependencyContextJsonReader.cs @@ -10,7 +10,7 @@ using Newtonsoft.Json.Linq; namespace Microsoft.Extensions.DependencyModel { - public class DependencyContextReader + public class DependencyContextJsonReader { public DependencyContext Read(Stream stream) { diff --git a/src/Microsoft.Extensions.DependencyModel/RuntimeAssembly.cs b/src/Microsoft.Extensions.DependencyModel/RuntimeAssembly.cs index 19c5499c9..fa1bc066d 100644 --- a/src/Microsoft.Extensions.DependencyModel/RuntimeAssembly.cs +++ b/src/Microsoft.Extensions.DependencyModel/RuntimeAssembly.cs @@ -8,18 +8,20 @@ namespace Microsoft.Extensions.DependencyModel { public class RuntimeAssembly { + private readonly string _assemblyName; + public RuntimeAssembly(string path) - : this(new AssemblyName(System.IO.Path.GetFileNameWithoutExtension(path)), path) + : this(System.IO.Path.GetFileNameWithoutExtension(path), path) { } - public RuntimeAssembly(AssemblyName name, string path) + public RuntimeAssembly(string assemblyName, string path) { - Name = name; + _assemblyName = assemblyName; Path = path; } - public AssemblyName Name { get; } + public AssemblyName Name => new AssemblyName(_assemblyName); public string Path { get; } } diff --git a/src/dotnet/Program.cs b/src/dotnet/Program.cs index f70bc48d6..be4048f7a 100644 --- a/src/dotnet/Program.cs +++ b/src/dotnet/Program.cs @@ -102,7 +102,6 @@ namespace Microsoft.DotNet.Cli var builtIns = new Dictionary> { ["build"] = BuildCommand.Run, - ["compile"] = CommpileCommand.Run, ["compile-csc"] = CompileCscCommand.Run, ["compile-fsc"] = CompileFscCommand.Run, ["compile-native"] = CompileNativeCommand.Run, diff --git a/src/dotnet/commands/dotnet-build/CompileContext.cs b/src/dotnet/commands/dotnet-build/CompileContext.cs index e66a08fd6..7e0e43957 100644 --- a/src/dotnet/commands/dotnet-build/CompileContext.cs +++ b/src/dotnet/commands/dotnet-build/CompileContext.cs @@ -357,6 +357,12 @@ namespace Microsoft.DotNet.Tools.Build args.Add("--cpp"); } + if (!string.IsNullOrWhiteSpace(_args.CppCompilerFlagsValue)) + { + args.Add("--cppcompilerflags"); + args.Add(_args.CppCompilerFlagsValue); + } + if (!string.IsNullOrWhiteSpace(_args.ArchValue)) { args.Add("--arch"); diff --git a/src/dotnet/commands/dotnet-pack/BuildProjectCommand.cs b/src/dotnet/commands/dotnet-pack/BuildProjectCommand.cs index 3b4bec6ae..ccdfb54b2 100644 --- a/src/dotnet/commands/dotnet-pack/BuildProjectCommand.cs +++ b/src/dotnet/commands/dotnet-pack/BuildProjectCommand.cs @@ -12,24 +12,19 @@ namespace Microsoft.DotNet.Tools.Pack internal class BuildProjectCommand { private readonly Project _project; - private readonly ArtifactPathsCalculator _artifactPathsCalculator; private readonly string _buildBasePath; private readonly string _configuration; private readonly string _versionSuffix; - private bool SkipBuild => _artifactPathsCalculator.CompiledArtifactsPathSet; - public BuildProjectCommand( Project project, - ArtifactPathsCalculator artifactPathsCalculator, string buildBasePath, string configuration, string versionSuffix) { _project = project; - _artifactPathsCalculator = artifactPathsCalculator; _buildBasePath = buildBasePath; _configuration = configuration; _versionSuffix = versionSuffix; @@ -37,11 +32,6 @@ namespace Microsoft.DotNet.Tools.Pack public int Execute() { - if (SkipBuild) - { - return 0; - } - if (_project.Files.SourceFiles.Any()) { var argsBuilder = new List(); diff --git a/src/dotnet/commands/dotnet-pack/Program.cs b/src/dotnet/commands/dotnet-pack/Program.cs index e939d67f0..3bb40b9df 100644 --- a/src/dotnet/commands/dotnet-pack/Program.cs +++ b/src/dotnet/commands/dotnet-pack/Program.cs @@ -72,7 +72,7 @@ namespace Microsoft.DotNet.Tools.Compiler int buildResult = 0; if (!noBuild.HasValue()) { - var buildProjectCommand = new BuildProjectCommand(project, artifactPathsCalculator, buildBasePathValue, configValue, versionSuffixValue); + var buildProjectCommand = new BuildProjectCommand(project, buildBasePathValue, configValue, versionSuffixValue); buildResult = buildProjectCommand.Execute(); } diff --git a/src/dotnet/commands/dotnet-projectmodel-server/InternalModels/ProjectContextSnapshot.cs b/src/dotnet/commands/dotnet-projectmodel-server/InternalModels/ProjectContextSnapshot.cs index 195bf5ba1..684d2e403 100644 --- a/src/dotnet/commands/dotnet-projectmodel-server/InternalModels/ProjectContextSnapshot.cs +++ b/src/dotnet/commands/dotnet-projectmodel-server/InternalModels/ProjectContextSnapshot.cs @@ -47,16 +47,21 @@ namespace Microsoft.DotNet.ProjectModel.Server foreach (var export in allExports.Values) { allSourceFiles.AddRange(export.SourceReferences.Select(f => f.ResolvedPath)); - allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath)); - var diagnostics = diagnosticsLookup[export.Library].ToList(); var description = DependencyDescription.Create(export.Library, diagnostics, allExports); allDependencies[description.Name] = description; var projectDescription = export.Library as ProjectDescription; - if (projectDescription != null && projectDescription.Identity.Name != context.ProjectFile.Name) + if (projectDescription != null) { - allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription)); + if (projectDescription.Identity.Name != context.ProjectFile.Name) + { + allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription)); + } + } + else + { + allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath)); } } diff --git a/src/dotnet/commands/dotnet-run/RunCommand.cs b/src/dotnet/commands/dotnet-run/RunCommand.cs index dd8be71c2..cc8c65e32 100644 --- a/src/dotnet/commands/dotnet-run/RunCommand.cs +++ b/src/dotnet/commands/dotnet-run/RunCommand.cs @@ -82,7 +82,9 @@ namespace Microsoft.DotNet.Tools.Run context = contexts.FirstOrDefault(c => defaultFrameworks.Contains(c.TargetFramework.Framework)); if (context == null) { - throw new InvalidOperationException($"Couldn't find target to run. Defaults: {string.Join(", ", defaultFrameworks)}"); + throw new InvalidOperationException($"Couldn't find target to run. Possible causes:" + Environment.NewLine + + "1. No project.lock.json file or restore failed - run `dotnet restore`" + Environment.NewLine + + $"2. project.lock.json has multiple targets none of which is in default list ({string.Join(", " , defaultFrameworks)})"); } } diff --git a/src/dotnet/commands/dotnet-test/CommandTestRunnerExtensions.cs b/src/dotnet/commands/dotnet-test/CommandTestRunnerExtensions.cs new file mode 100644 index 000000000..3188c167f --- /dev/null +++ b/src/dotnet/commands/dotnet-test/CommandTestRunnerExtensions.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using Microsoft.DotNet.Cli.Utils; + +namespace Microsoft.DotNet.Tools.Test +{ + public static class CommandTestRunnerExtensions + { + public static ProcessStartInfo ToProcessStartInfo(this ICommand command) + { + return new ProcessStartInfo(command.CommandName, command.CommandArgs); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/DotnetTest.cs b/src/dotnet/commands/dotnet-test/DotnetTest.cs new file mode 100644 index 000000000..ab895d248 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/DotnetTest.cs @@ -0,0 +1,106 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class DotnetTest : IDotnetTest + { + private readonly IList _channels; + private readonly IList _messageHandlers; + private readonly ITestMessagesCollection _messages; + + public IDotnetTestMessageHandler TestSessionTerminateMessageHandler { private get; set; } + public IDotnetTestMessageHandler UnknownMessageHandler { private get; set; } + + public DotnetTestState State { get; private set; } + + public string PathToAssemblyUnderTest { get; } + + public DotnetTest(ITestMessagesCollection messages, string pathToAssemblyUnderTest) + { + PathToAssemblyUnderTest = pathToAssemblyUnderTest; + State = DotnetTestState.InitialState; + _channels = new List(); + _messageHandlers = new List(); + _messages = messages; + } + + public DotnetTest AddMessageHandler(IDotnetTestMessageHandler messageHandler) + { + _messageHandlers.Add(messageHandler); + + return this; + } + + public void StartHandlingMessages() + { + Message message; + while (_messages.TryTake(out message)) + { + HandleMessage(message); + } + } + + public void StartListeningTo(IReportingChannel reportingChannel) + { + ValidateSpecialMessageHandlersArePresent(); + + _channels.Add(reportingChannel); + reportingChannel.MessageReceived += OnMessageReceived; + } + + public void Dispose() + { + foreach (var reportingChannel in _channels) + { + reportingChannel.Dispose(); + } + } + + private void ValidateSpecialMessageHandlersArePresent() + { + if (TestSessionTerminateMessageHandler == null) + { + throw new InvalidOperationException("The TestSession.Terminate message handler needs to be set."); + } + + if (UnknownMessageHandler == null) + { + throw new InvalidOperationException("The unknown message handler needs to be set."); + } + } + + private void HandleMessage(Message message) + { + foreach (var messageHandler in _messageHandlers) + { + var nextState = messageHandler.HandleMessage(this, message); + + if (nextState != DotnetTestState.NoOp) + { + State = nextState; + return; + } + } + + UnknownMessageHandler.HandleMessage(this, message); + } + + private void OnMessageReceived(object sender, Message message) + { + if (!TerminateTestSession(message)) + { + _messages.Add(message); + } + } + + private bool TerminateTestSession(Message message) + { + return TestSessionTerminateMessageHandler.HandleMessage(this, message) == DotnetTestState.Terminated; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/DotnetTestExtensions.cs b/src/dotnet/commands/dotnet-test/DotnetTestExtensions.cs new file mode 100644 index 000000000..9a173cb0a --- /dev/null +++ b/src/dotnet/commands/dotnet-test/DotnetTestExtensions.cs @@ -0,0 +1,61 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.DotNet.Cli.Tools.Test; + +namespace Microsoft.DotNet.Tools.Test +{ + public static class DotnetTestExtensions + { + public static IDotnetTest AddNonSpecificMessageHandlers( + this IDotnetTest dotnetTest, + ITestMessagesCollection messages, + IReportingChannel adapterChannel) + { + dotnetTest.TestSessionTerminateMessageHandler = new TestSessionTerminateMessageHandler(messages); + dotnetTest.UnknownMessageHandler = new UnknownMessageHandler(adapterChannel); + + dotnetTest.AddMessageHandler(new VersionCheckMessageHandler(adapterChannel)); + + return dotnetTest; + } + + public static IDotnetTest AddTestDiscoveryMessageHandlers( + this IDotnetTest dotnetTest, + IReportingChannel adapterChannel, + IReportingChannelFactory reportingChannelFactory, + ITestRunnerFactory testRunnerFactory) + { + dotnetTest.AddMessageHandler( + new TestDiscoveryStartMessageHandler(testRunnerFactory, adapterChannel, reportingChannelFactory)); + + return dotnetTest; + } + + public static IDotnetTest AddTestRunMessageHandlers( + this IDotnetTest dotnetTest, + IReportingChannel adapterChannel, + IReportingChannelFactory reportingChannelFactory, + ITestRunnerFactory testRunnerFactory) + { + dotnetTest.AddMessageHandler(new GetTestRunnerProcessStartInfoMessageHandler( + testRunnerFactory, + adapterChannel, + reportingChannelFactory)); + + return dotnetTest; + } + + public static IDotnetTest AddTestRunnnersMessageHandlers( + this IDotnetTest dotnetTest, + IReportingChannel adapterChannel) + { + dotnetTest.AddMessageHandler(new TestRunnerTestStartedMessageHandler(adapterChannel)); + dotnetTest.AddMessageHandler(new TestRunnerTestResultMessageHandler(adapterChannel)); + dotnetTest.AddMessageHandler(new TestRunnerTestFoundMessageHandler(adapterChannel)); + dotnetTest.AddMessageHandler(new TestRunnerTestCompletedMessageHandler(adapterChannel)); + + return dotnetTest; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/DotnetTestState.cs b/src/dotnet/commands/dotnet-test/DotnetTestState.cs new file mode 100644 index 000000000..7520f5c75 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/DotnetTestState.cs @@ -0,0 +1,18 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.DotNet.Tools.Test +{ + public enum DotnetTestState + { + NoOp, + InitialState, + VersionCheckCompleted, + TestDiscoveryStarted, + TestDiscoveryCompleted, + TestExecutionSentTestRunnerProcessStartInfo, + TestExecutionStarted, + TestExecutionCompleted, + Terminated + } +} diff --git a/src/dotnet/commands/dotnet-test/IDotnetTest.cs b/src/dotnet/commands/dotnet-test/IDotnetTest.cs new file mode 100644 index 000000000..3d0386b8a --- /dev/null +++ b/src/dotnet/commands/dotnet-test/IDotnetTest.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface IDotnetTest : IDisposable + { + string PathToAssemblyUnderTest { get; } + + DotnetTestState State { get; } + + DotnetTest AddMessageHandler(IDotnetTestMessageHandler messageHandler); + + IDotnetTestMessageHandler TestSessionTerminateMessageHandler { set; } + + IDotnetTestMessageHandler UnknownMessageHandler { set; } + + void StartHandlingMessages(); + + void StartListeningTo(IReportingChannel reportingChannel); + } +} diff --git a/src/dotnet/commands/dotnet-test/IReportingChannel.cs b/src/dotnet/commands/dotnet-test/IReportingChannel.cs new file mode 100644 index 000000000..f103c61e2 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/IReportingChannel.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface IReportingChannel : IDisposable + { + event EventHandler MessageReceived; + + int Port { get; } + + void Accept(); + + void Send(Message message); + + void SendError(string error); + + void SendError(Exception ex); + } +} diff --git a/src/dotnet/commands/dotnet-test/IReportingChannelFactory.cs b/src/dotnet/commands/dotnet-test/IReportingChannelFactory.cs new file mode 100644 index 000000000..a1e7274e1 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/IReportingChannelFactory.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.DotNet.Tools.Test +{ + public interface IReportingChannelFactory + { + IReportingChannel CreateChannelWithAnyAvailablePort(); + + IReportingChannel CreateChannelWithPort(int port); + } +} diff --git a/src/dotnet/commands/dotnet-test/ITestMessagesCollection.cs b/src/dotnet/commands/dotnet-test/ITestMessagesCollection.cs new file mode 100644 index 000000000..ff462fb6a --- /dev/null +++ b/src/dotnet/commands/dotnet-test/ITestMessagesCollection.cs @@ -0,0 +1,17 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface ITestMessagesCollection : IDisposable + { + void Drain(); + + void Add(Message message); + + bool TryTake(out Message message); + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/GetTestRunnerProcessStartInfoMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/GetTestRunnerProcessStartInfoMessageHandler.cs new file mode 100644 index 000000000..17ed2092f --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/GetTestRunnerProcessStartInfoMessageHandler.cs @@ -0,0 +1,70 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; +using Newtonsoft.Json.Linq; + +namespace Microsoft.DotNet.Tools.Test +{ + public class GetTestRunnerProcessStartInfoMessageHandler : IDotnetTestMessageHandler + { + private readonly ITestRunnerFactory _testRunnerFactory; + private readonly IReportingChannel _adapterChannel; + private readonly IReportingChannelFactory _reportingChannelFactory; + + public GetTestRunnerProcessStartInfoMessageHandler( + ITestRunnerFactory testRunnerFactory, + IReportingChannel adapterChannel, + IReportingChannelFactory reportingChannelFactory) + { + _testRunnerFactory = testRunnerFactory; + _adapterChannel = adapterChannel; + _reportingChannelFactory = reportingChannelFactory; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + + if (CanHandleMessage(dotnetTest, message)) + { + DoHandleMessage(dotnetTest, message); + nextState = DotnetTestState.TestExecutionSentTestRunnerProcessStartInfo; + } + + return nextState; + } + + private void DoHandleMessage(IDotnetTest dotnetTest, Message message) + { + var testRunnerChannel = _reportingChannelFactory.CreateChannelWithAnyAvailablePort(); + + dotnetTest.StartListeningTo(testRunnerChannel); + + testRunnerChannel.Accept(); + + var testRunner = _testRunnerFactory.CreateTestRunner( + new RunTestsArgumentsBuilder(dotnetTest.PathToAssemblyUnderTest, testRunnerChannel.Port, message)); + + var processStartInfo = testRunner.GetProcessStartInfo(); + + _adapterChannel.Send(new Message + { + MessageType = TestMessageTypes.TestExecutionTestRunnerProcessStartInfo, + Payload = JToken.FromObject(processStartInfo) + }); + } + + private static bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return IsAtAnAcceptableState(dotnetTest) && + message.MessageType == TestMessageTypes.TestExecutionGetTestRunnerProcessStartInfo; + } + + private static bool IsAtAnAcceptableState(IDotnetTest dotnetTest) + { + return dotnetTest.State == DotnetTestState.VersionCheckCompleted || + dotnetTest.State == DotnetTestState.InitialState; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/IDotnetTestMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/IDotnetTestMessageHandler.cs new file mode 100644 index 000000000..b2c44c614 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/IDotnetTestMessageHandler.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface IDotnetTestMessageHandler + { + DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message); + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestDiscoveryStartMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestDiscoveryStartMessageHandler.cs new file mode 100644 index 000000000..c6dcef258 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestDiscoveryStartMessageHandler.cs @@ -0,0 +1,82 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using NuGet.Protocol.Core.v3; + +namespace Microsoft.DotNet.Cli.Tools.Test +{ + public class TestDiscoveryStartMessageHandler : IDotnetTestMessageHandler + { + private readonly ITestRunnerFactory _testRunnerFactory; + private readonly IReportingChannel _adapterChannel; + private readonly IReportingChannelFactory _reportingChannelFactory; + + public TestDiscoveryStartMessageHandler( + ITestRunnerFactory testRunnerFactory, + IReportingChannel adapterChannel, + IReportingChannelFactory reportingChannelFactory) + { + _testRunnerFactory = testRunnerFactory; + _adapterChannel = adapterChannel; + _reportingChannelFactory = reportingChannelFactory; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + if (CanHandleMessage(dotnetTest, message)) + { + HandleMessage(dotnetTest); + nextState = DotnetTestState.TestDiscoveryStarted; + } + + return nextState; + } + + private void HandleMessage(IDotnetTest dotnetTest) + { + TestHostTracing.Source.TraceInformation("Starting Discovery"); + + DiscoverTests(dotnetTest); + } + + private void DiscoverTests(IDotnetTest dotnetTest) + { + var testRunnerResults = Enumerable.Empty(); + + try + { + var testRunnerChannel = _reportingChannelFactory.CreateChannelWithAnyAvailablePort(); + + dotnetTest.StartListeningTo(testRunnerChannel); + + testRunnerChannel.Accept(); + + var testRunner = _testRunnerFactory.CreateTestRunner( + new DiscoverTestsArgumentsBuilder(dotnetTest.PathToAssemblyUnderTest, testRunnerChannel.Port)); + + testRunner.RunTestCommand(); + } + catch (TestRunnerOperationFailedException e) + { + _adapterChannel.SendError(e.Message); + } + } + + private static bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return IsAtAnAcceptableState(dotnetTest) && message.MessageType == TestMessageTypes.TestDiscoveryStart; + } + + private static bool IsAtAnAcceptableState(IDotnetTest dotnetTest) + { + return (dotnetTest.State == DotnetTestState.VersionCheckCompleted || + dotnetTest.State == DotnetTestState.InitialState); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestMessageTypes.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestMessageTypes.cs new file mode 100644 index 000000000..1cf24c941 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestMessageTypes.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.DotNet.Tools.Test +{ + public static class TestMessageTypes + { + public const string TestRunnerTestResult = "TestExecution.TestResult"; + public const string TestRunnerTestStarted = "TestExecution.TestStarted"; + public const string TestRunnerTestCompleted = "TestRunner.TestCompleted"; + public const string TestRunnerTestFound = "TestDiscovery.TestFound"; + public const string TestSessionTerminate = "TestSession.Terminate"; + public const string VersionCheck = "ProtocolVersion"; + public const string TestDiscoveryStart = "TestDiscovery.Start"; + public const string TestDiscoveryCompleted = "TestDiscovery.Completed"; + public const string TestDiscoveryTestFound = "TestDiscovery.TestFound"; + public const string TestExecutionGetTestRunnerProcessStartInfo = "TestExecution.GetTestRunnerProcessStartInfo"; + public const string TestExecutionTestRunnerProcessStartInfo = "TestExecution.TestRunnerProcessStartInfo"; + public const string TestExecutionStarted = "TestExecution.TestStarted"; + public const string TestExecutionTestResult = "TestExecution.TestResult"; + public const string TestExecutionCompleted = "TestExecution.Completed"; + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerResultMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerResultMessageHandler.cs new file mode 100644 index 000000000..e33a4bbfb --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerResultMessageHandler.cs @@ -0,0 +1,47 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public abstract class TestRunnerResultMessageHandler : IDotnetTestMessageHandler + { + private readonly IReportingChannel _adapterChannel; + private readonly DotnetTestState _nextStateIfHandled; + private readonly string _messageIfHandled; + + protected TestRunnerResultMessageHandler( + IReportingChannel adapterChannel, + DotnetTestState nextStateIfHandled, + string messageIfHandled) + { + _adapterChannel = adapterChannel; + _nextStateIfHandled = nextStateIfHandled; + _messageIfHandled = messageIfHandled; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + if (CanHandleMessage(dotnetTest, message)) + { + HandleMessage(message); + nextState = _nextStateIfHandled; + } + + return nextState; + } + + private void HandleMessage(Message message) + { + _adapterChannel.Send(new Message + { + MessageType = _messageIfHandled, + Payload = message.Payload + }); + } + + protected abstract bool CanHandleMessage(IDotnetTest dotnetTest, Message message); + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestCompletedMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestCompletedMessageHandler.cs new file mode 100644 index 000000000..8e60b2838 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestCompletedMessageHandler.cs @@ -0,0 +1,67 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerTestCompletedMessageHandler : IDotnetTestMessageHandler + { + private readonly IReportingChannel _adapterChannel; + + public TestRunnerTestCompletedMessageHandler(IReportingChannel adapterChannel) + { + _adapterChannel = adapterChannel; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + if (CanHandleMessage(dotnetTest, message)) + { + DoHandleMessage(dotnetTest, message); + nextState = NextState(dotnetTest); + } + + return nextState; + } + + private void DoHandleMessage(IDotnetTest dotnetTest, Message message) + { + _adapterChannel.Send(new Message + { + MessageType = MessageType(dotnetTest) + }); + } + + private string MessageType(IDotnetTest dotnetTest) + { + return dotnetTest.State == DotnetTestState.TestDiscoveryStarted + ? TestMessageTypes.TestDiscoveryCompleted + : TestMessageTypes.TestExecutionCompleted; + } + + private DotnetTestState NextState(IDotnetTest dotnetTest) + { + return dotnetTest.State == DotnetTestState.TestDiscoveryStarted + ? DotnetTestState.TestDiscoveryCompleted + : DotnetTestState.TestExecutionCompleted; + } + + private bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return IsAtAnAcceptableState(dotnetTest) && CanAcceptMessage(message); + } + + private static bool CanAcceptMessage(Message message) + { + return message.MessageType == TestMessageTypes.TestRunnerTestCompleted; + } + + private static bool IsAtAnAcceptableState(IDotnetTest dotnetTest) + { + return (dotnetTest.State == DotnetTestState.TestDiscoveryStarted || + dotnetTest.State == DotnetTestState.TestExecutionStarted); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestFoundMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestFoundMessageHandler.cs new file mode 100644 index 000000000..78bbbba6a --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestFoundMessageHandler.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerTestFoundMessageHandler : TestRunnerResultMessageHandler + { + public TestRunnerTestFoundMessageHandler(IReportingChannel adapterChannel) + : base(adapterChannel, DotnetTestState.TestDiscoveryStarted, TestMessageTypes.TestDiscoveryTestFound) + { + } + + protected override bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return dotnetTest.State == DotnetTestState.TestDiscoveryStarted && + message.MessageType == TestMessageTypes.TestRunnerTestFound; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestResultMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestResultMessageHandler.cs new file mode 100644 index 000000000..78bcb4a32 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestResultMessageHandler.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerTestResultMessageHandler : TestRunnerResultMessageHandler + { + public TestRunnerTestResultMessageHandler(IReportingChannel adapterChannel) + : base(adapterChannel, DotnetTestState.TestExecutionStarted, TestMessageTypes.TestExecutionTestResult) + { + } + + protected override bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return dotnetTest.State == DotnetTestState.TestExecutionStarted && + message.MessageType == TestMessageTypes.TestRunnerTestResult; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestStartedMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestStartedMessageHandler.cs new file mode 100644 index 000000000..ac08ebc6c --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestRunnerTestStartedMessageHandler.cs @@ -0,0 +1,27 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerTestStartedMessageHandler : TestRunnerResultMessageHandler + { + public TestRunnerTestStartedMessageHandler(IReportingChannel adapterChannel) + : base(adapterChannel, DotnetTestState.TestExecutionStarted, TestMessageTypes.TestExecutionStarted) + { + } + + protected override bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return IsAtAnAcceptableState(dotnetTest) && + message.MessageType == TestMessageTypes.TestRunnerTestStarted; + } + + private static bool IsAtAnAcceptableState(IDotnetTest dotnetTest) + { + return dotnetTest.State == DotnetTestState.TestExecutionSentTestRunnerProcessStartInfo || + dotnetTest.State == DotnetTestState.TestExecutionStarted; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/TestSessionTerminateMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/TestSessionTerminateMessageHandler.cs new file mode 100644 index 000000000..39d1dd381 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/TestSessionTerminateMessageHandler.cs @@ -0,0 +1,30 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestSessionTerminateMessageHandler : IDotnetTestMessageHandler + { + private readonly ITestMessagesCollection _messages; + + public TestSessionTerminateMessageHandler(ITestMessagesCollection messages) + { + _messages = messages; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + + if (TestMessageTypes.TestSessionTerminate.Equals(message.MessageType)) + { + nextState = DotnetTestState.Terminated; + _messages.Drain(); + } + + return nextState; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/UnknownMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/UnknownMessageHandler.cs new file mode 100644 index 000000000..d0ce66db1 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/UnknownMessageHandler.cs @@ -0,0 +1,30 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class UnknownMessageHandler : IDotnetTestMessageHandler + { + private readonly IReportingChannel _adapterChannel; + + public UnknownMessageHandler(IReportingChannel adapterChannel) + { + _adapterChannel = adapterChannel; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var error = $"No handler for message '{message.MessageType}' when at state '{dotnetTest.State}'"; + + TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, error); + + _adapterChannel.SendError(error); + + throw new InvalidOperationException(error); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/MessageHandlers/VersionCheckMessageHandler.cs b/src/dotnet/commands/dotnet-test/MessageHandlers/VersionCheckMessageHandler.cs new file mode 100644 index 000000000..e6d458337 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/MessageHandlers/VersionCheckMessageHandler.cs @@ -0,0 +1,56 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; +using Newtonsoft.Json.Linq; + +namespace Microsoft.DotNet.Tools.Test +{ + public class VersionCheckMessageHandler : IDotnetTestMessageHandler + { + private const int SupportedVersion = 1; + + private readonly IReportingChannel _adapterChannel; + + public VersionCheckMessageHandler(IReportingChannel adapterChannel) + { + _adapterChannel = adapterChannel; + } + + public DotnetTestState HandleMessage(IDotnetTest dotnetTest, Message message) + { + var nextState = DotnetTestState.NoOp; + if (CanHandleMessage(dotnetTest, message)) + { + HandleMessage(message); + nextState = DotnetTestState.VersionCheckCompleted; + } + + return nextState; + } + + private void HandleMessage(Message message) + { + var version = message.Payload?.ToObject().Version; + TestHostTracing.Source.TraceInformation( + "[ReportingChannel]: Requested Version: {0} - Using Version: {1}", + version, + SupportedVersion); + + _adapterChannel.Send(new Message + { + MessageType = TestMessageTypes.VersionCheck, + Payload = JToken.FromObject(new ProtocolVersionMessage + { + Version = SupportedVersion, + }), + }); + } + + private static bool CanHandleMessage(IDotnetTest dotnetTest, Message message) + { + return dotnetTest.State == DotnetTestState.InitialState && + TestMessageTypes.VersionCheck.Equals(message.MessageType); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/Program.cs b/src/dotnet/commands/dotnet-test/Program.cs index 421626988..6ac79ccb0 100644 --- a/src/dotnet/commands/dotnet-test/Program.cs +++ b/src/dotnet/commands/dotnet-test/Program.cs @@ -9,10 +9,6 @@ using System.Linq; using Microsoft.DotNet.Cli.Utils; using Microsoft.Dnx.Runtime.Common.CommandLine; using Microsoft.DotNet.ProjectModel; -using Microsoft.Extensions.Testing.Abstractions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NuGet.Frameworks; namespace Microsoft.DotNet.Tools.Test { @@ -58,7 +54,7 @@ namespace Microsoft.DotNet.Tools.Test var projectContext = projectContexts.First(); var testRunner = projectContext.ProjectFile.TestRunner; - + var configuration = configurationOption.Value() ?? Constants.DefaultConfiguration; if (portOption.HasValue()) @@ -105,154 +101,54 @@ namespace Microsoft.DotNet.Tools.Test .ExitCode; } - private static int RunDesignTime(int port, ProjectContext projectContext, string testRunner, string configuration) + private static int RunDesignTime( + int port, + ProjectContext + projectContext, + string testRunner, + string configuration) { Console.WriteLine("Listening on port {0}", port); - using (var channel = ReportingChannel.ListenOn(port)) - { - Console.WriteLine("Client accepted {0}", channel.Socket.LocalEndPoint); - HandleDesignTimeMessages(projectContext, testRunner, channel, configuration); + HandleDesignTimeMessages(projectContext, testRunner, port, configuration); - return 0; - } + return 0; } - private static void HandleDesignTimeMessages(ProjectContext projectContext, string testRunner, ReportingChannel channel, string configuration) + private static void HandleDesignTimeMessages( + ProjectContext projectContext, + string testRunner, + int port, + string configuration) { + var reportingChannelFactory = new ReportingChannelFactory(); + var adapterChannel = reportingChannelFactory.CreateChannelWithPort(port); + try { - var message = channel.ReadQueue.Take(); + var assemblyUnderTest = projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly; + var messages = new TestMessagesCollection(); + using (var dotnetTest = new DotnetTest(messages, assemblyUnderTest)) + { + var commandFactory = new DotNetCommandFactory(); + var testRunnerFactory = new TestRunnerFactory(GetCommandName(testRunner), commandFactory); - if (message.MessageType == "ProtocolVersion") - { - HandleProtocolVersionMessage(message, channel); + dotnetTest + .AddNonSpecificMessageHandlers(messages, adapterChannel) + .AddTestDiscoveryMessageHandlers(adapterChannel, reportingChannelFactory, testRunnerFactory) + .AddTestRunMessageHandlers(adapterChannel, reportingChannelFactory, testRunnerFactory) + .AddTestRunnnersMessageHandlers(adapterChannel); - // Take the next message, which should be the command to execute. - message = channel.ReadQueue.Take(); - } + dotnetTest.StartListeningTo(adapterChannel); - if (message.MessageType == "TestDiscovery.Start") - { - HandleTestDiscoveryStartMessage(testRunner, channel, projectContext, configuration); - } - else if (message.MessageType == "TestExecution.Start") - { - HandleTestExecutionStartMessage(testRunner, message, channel, projectContext, configuration); - } - else - { - HandleUnknownMessage(message, channel); + adapterChannel.Accept(); + + dotnetTest.StartHandlingMessages(); } } catch (Exception ex) { - channel.SendError(ex); - } - } - - private static void HandleProtocolVersionMessage(Message message, ReportingChannel channel) - { - var version = message.Payload?.ToObject().Version; - var supportedVersion = 1; - TestHostTracing.Source.TraceInformation( - "[ReportingChannel]: Requested Version: {0} - Using Version: {1}", - version, - supportedVersion); - - channel.Send(new Message() - { - MessageType = "ProtocolVersion", - Payload = JToken.FromObject(new ProtocolVersionMessage() - { - Version = supportedVersion, - }), - }); - } - - private static void HandleTestDiscoveryStartMessage(string testRunner, ReportingChannel channel, ProjectContext projectContext, string configuration) - { - TestHostTracing.Source.TraceInformation("Starting Discovery"); - - var commandArgs = new List { projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly }; - - commandArgs.AddRange(new[] - { - "--list", - "--designtime" - }); - - ExecuteRunnerCommand(testRunner, channel, commandArgs); - - channel.Send(new Message() - { - MessageType = "TestDiscovery.Response", - }); - - TestHostTracing.Source.TraceInformation("Completed Discovery"); - } - - private static void HandleTestExecutionStartMessage(string testRunner, Message message, ReportingChannel channel, ProjectContext projectContext, string configuration) - { - TestHostTracing.Source.TraceInformation("Starting Execution"); - - var commandArgs = new List { projectContext.GetOutputPaths(configuration).CompilationFiles.Assembly }; - - commandArgs.AddRange(new[] - { - "--designtime" - }); - - var tests = message.Payload?.ToObject().Tests; - if (tests != null) - { - foreach (var test in tests) - { - commandArgs.Add("--test"); - commandArgs.Add(test); - } - } - - ExecuteRunnerCommand(testRunner, channel, commandArgs); - - channel.Send(new Message() - { - MessageType = "TestExecution.Response", - }); - - TestHostTracing.Source.TraceInformation("Completed Execution"); - } - - private static void HandleUnknownMessage(Message message, ReportingChannel channel) - { - var error = string.Format("Unexpected message type: '{0}'.", message.MessageType); - - TestHostTracing.Source.TraceEvent(TraceEventType.Error, 0, error); - - channel.SendError(error); - - throw new InvalidOperationException(error); - } - - private static void ExecuteRunnerCommand(string testRunner, ReportingChannel channel, List commandArgs) - { - var result = Command.CreateDotNet(GetCommandName(testRunner), commandArgs, new NuGetFramework("DNXCore", Version.Parse("5.0"))) - .OnOutputLine(line => - { - try - { - channel.Send(JsonConvert.DeserializeObject(line)); - } - catch - { - TestHostTracing.Source.TraceInformation(line); - } - }) - .Execute(); - - if (result.ExitCode != 0) - { - channel.SendError($"{GetCommandName(testRunner)} returned '{result.ExitCode}'."); + adapterChannel.SendError(ex); } } diff --git a/src/dotnet/commands/dotnet-test/ReportingChannel.cs b/src/dotnet/commands/dotnet-test/ReportingChannel.cs index cf2f2d33c..1597e2c91 100644 --- a/src/dotnet/commands/dotnet-test/ReportingChannel.cs +++ b/src/dotnet/commands/dotnet-test/ReportingChannel.cs @@ -2,57 +2,65 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; +using System.Threading.Tasks; using Microsoft.Extensions.Testing.Abstractions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.DotNet.Tools.Test { - public class ReportingChannel : IDisposable + public class ReportingChannel : IReportingChannel { public static ReportingChannel ListenOn(int port) { // This fixes the mono incompatibility but ties it to ipv4 connections - using (var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - { - listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, port)); - listenSocket.Listen(10); + var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - var socket = listenSocket.Accept(); + listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, port)); + listenSocket.Listen(10); - return new ReportingChannel(socket); - } + return new ReportingChannel(listenSocket); } - private readonly BinaryWriter _writer; - private readonly BinaryReader _reader; - private readonly ManualResetEventSlim _ackWaitHandle; + private BinaryWriter _writer; + private BinaryReader _reader; + private Socket _listenSocket; - private ReportingChannel(Socket socket) + private ReportingChannel(Socket listenSocket) { - Socket = socket; - - var stream = new NetworkStream(Socket); - _writer = new BinaryWriter(stream); - _reader = new BinaryReader(stream); - _ackWaitHandle = new ManualResetEventSlim(); - - ReadQueue = new BlockingCollection(boundedCapacity: 1); - - // Read incoming messages on the background thread - new Thread(ReadMessages) { IsBackground = true }.Start(); + _listenSocket = listenSocket; + Port = ((IPEndPoint)listenSocket.LocalEndPoint).Port; } - public BlockingCollection ReadQueue { get; } + public event EventHandler MessageReceived; public Socket Socket { get; private set; } + public int Port { get; } + + public void Accept() + { + new Thread(() => + { + using (_listenSocket) + { + Socket = _listenSocket.Accept(); + + var stream = new NetworkStream(Socket); + _writer = new BinaryWriter(stream); + _reader = new BinaryReader(stream); + + // Read incoming messages on the background thread + new Thread(ReadMessages) { IsBackground = true }.Start(); + } + }) { IsBackground = true }.Start(); + } + public void Send(Message message) { lock (_writer) @@ -62,7 +70,7 @@ namespace Microsoft.DotNet.Tools.Test TestHostTracing.Source.TraceEvent( TraceEventType.Verbose, 0, - "[ReportingChannel]: Send({0})", + "[ReportingChannel]: Send({0})", message); _writer.Write(JsonConvert.SerializeObject(message)); @@ -102,13 +110,13 @@ namespace Microsoft.DotNet.Tools.Test { try { - var message = JsonConvert.DeserializeObject(_reader.ReadString()); - ReadQueue.Add(message); + var rawMessage = _reader.ReadString(); + var message = JsonConvert.DeserializeObject(rawMessage); - if (string.Equals(message.MessageType, "TestHost.Acknowledge")) + MessageReceived?.Invoke(this, message); + + if (ShouldStopListening(message)) { - _ackWaitHandle.Set(); - ReadQueue.CompleteAdding(); break; } } @@ -124,26 +132,14 @@ namespace Microsoft.DotNet.Tools.Test } } + private static bool ShouldStopListening(Message message) + { + return message.MessageType == TestMessageTypes.TestRunnerTestCompleted || + message.MessageType == TestMessageTypes.TestSessionTerminate; + } + public void Dispose() { - // Wait for a graceful disconnect - drain the queue until we get an 'ACK' - Message message; - while (ReadQueue.TryTake(out message, millisecondsTimeout: 1)) - { - } - - if (_ackWaitHandle.Wait(TimeSpan.FromSeconds(10))) - { - TestHostTracing.Source.TraceInformation("[ReportingChannel]: Received for ack from test host"); - } - else - { - TestHostTracing.Source.TraceEvent( - TraceEventType.Error, - 0, - "[ReportingChannel]: Timed out waiting for ack from test host"); - } - Socket.Dispose(); } } diff --git a/src/dotnet/commands/dotnet-test/ReportingChannelFactory.cs b/src/dotnet/commands/dotnet-test/ReportingChannelFactory.cs new file mode 100644 index 000000000..0dac24eba --- /dev/null +++ b/src/dotnet/commands/dotnet-test/ReportingChannelFactory.cs @@ -0,0 +1,18 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.DotNet.Tools.Test +{ + public class ReportingChannelFactory : IReportingChannelFactory + { + public IReportingChannel CreateChannelWithAnyAvailablePort() + { + return ReportingChannel.ListenOn(0); + } + + public IReportingChannel CreateChannelWithPort(int port) + { + return ReportingChannel.ListenOn(port); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestMessagesCollection.cs b/src/dotnet/commands/dotnet-test/TestMessagesCollection.cs new file mode 100644 index 000000000..a34815f99 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestMessagesCollection.cs @@ -0,0 +1,73 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Threading; +using Microsoft.Extensions.Testing.Abstractions; +using System; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestMessagesCollection : ITestMessagesCollection + { + private readonly ManualResetEventSlim _terminateWaitHandle; + private readonly BlockingCollection _readQueue; + + public TestMessagesCollection() + { + _readQueue = new BlockingCollection(boundedCapacity: 1); + _terminateWaitHandle = new ManualResetEventSlim(); + } + + public void Drain() + { + _terminateWaitHandle.Set(); + _readQueue.CompleteAdding(); + DrainQueue(); + } + + public void Add(Message message) + { + _readQueue.Add(message); + } + + public bool TryTake(out Message message) + { + message = null; + try + { + message = _readQueue.Take(); + } + catch (InvalidOperationException) + { + return false; + } + + return true; + } + + public void Dispose() + { + if (_terminateWaitHandle.Wait(TimeSpan.FromSeconds(10))) + { + TestHostTracing.Source.TraceInformation("[ReportingChannel]: Received TestSession:Terminate from test host"); + } + else + { + TestHostTracing.Source.TraceEvent( + TraceEventType.Error, + 0, + "[ReportingChannel]: Timed out waiting for aTestSession:Terminate from test host"); + } + } + + private void DrainQueue() + { + Message message; + while (_readQueue.TryTake(out message, millisecondsTimeout: 1)) + { + } + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/DiscoverTestsArgumentsBuilder.cs b/src/dotnet/commands/dotnet-test/TestRunners/DiscoverTestsArgumentsBuilder.cs new file mode 100644 index 000000000..7f1202d00 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/DiscoverTestsArgumentsBuilder.cs @@ -0,0 +1,34 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; +using System.Collections.Generic; + +namespace Microsoft.DotNet.Tools.Test +{ + public class DiscoverTestsArgumentsBuilder : ITestRunnerArgumentsBuilder + { + private readonly string _assemblyUnderTest; + private readonly int _port; + + public DiscoverTestsArgumentsBuilder(string assemblyUnderTest, int port) + { + _assemblyUnderTest = assemblyUnderTest; + _port = port; + } + + public IEnumerable BuildArguments() + { + var commandArgs = new List + { + _assemblyUnderTest, + "--list", + "--designtime", + "--port", + $"{_port}" + }; + + return commandArgs; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/ITestRunner.cs b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunner.cs new file mode 100644 index 000000000..bdac41583 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunner.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface ITestRunner + { + void RunTestCommand(); + + ProcessStartInfo GetProcessStartInfo(); + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerArgumentsBuilder.cs b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerArgumentsBuilder.cs new file mode 100644 index 000000000..55bbd3aa9 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerArgumentsBuilder.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface ITestRunnerArgumentsBuilder + { + IEnumerable BuildArguments(); + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerFactory.cs b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerFactory.cs new file mode 100644 index 000000000..d702eccb7 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/ITestRunnerFactory.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public interface ITestRunnerFactory + { + ITestRunner CreateTestRunner(ITestRunnerArgumentsBuilder argumentsBuilder); + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/RunTestsArgumentsBuilder.cs b/src/dotnet/commands/dotnet-test/TestRunners/RunTestsArgumentsBuilder.cs new file mode 100644 index 000000000..4397731f4 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/RunTestsArgumentsBuilder.cs @@ -0,0 +1,45 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using Microsoft.Extensions.Testing.Abstractions; + +namespace Microsoft.DotNet.Tools.Test +{ + public class RunTestsArgumentsBuilder : ITestRunnerArgumentsBuilder + { + private readonly string _assemblyUnderTest; + private readonly int _port; + private readonly Message _message; + + public RunTestsArgumentsBuilder(string assemblyUnderTest, int port, Message message) + { + _assemblyUnderTest = assemblyUnderTest; + _port = port; + _message = message; + } + + public IEnumerable BuildArguments() + { + var commandArgs = new List + { + _assemblyUnderTest, + "--designtime", + "--port", + $"{_port}" + }; + + var tests = _message.Payload?.ToObject().Tests; + if (tests != null) + { + foreach (var test in tests) + { + commandArgs.Add("--test"); + commandArgs.Add(test); + } + } + + return commandArgs; + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/TestRunner.cs b/src/dotnet/commands/dotnet-test/TestRunners/TestRunner.cs new file mode 100644 index 000000000..7a3a14aed --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/TestRunner.cs @@ -0,0 +1,59 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; +using Microsoft.DotNet.Cli.Utils; +using NuGet.Frameworks; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunner : ITestRunner + { + private readonly string _testRunner; + private readonly ICommandFactory _commandFactory; + private readonly ITestRunnerArgumentsBuilder _argumentsBuilder; + + public TestRunner( + string testRunner, + ICommandFactory commandFactory, + ITestRunnerArgumentsBuilder argumentsBuilder) + { + _testRunner = testRunner; + _commandFactory = commandFactory; + _argumentsBuilder = argumentsBuilder; + } + + public void RunTestCommand() + { + ExecuteRunnerCommand(); + } + + public ProcessStartInfo GetProcessStartInfo() + { + var command = CreateTestRunnerCommand(); + + return command.ToProcessStartInfo(); + } + + private void ExecuteRunnerCommand() + { + var result = CreateTestRunnerCommand().Execute(); + + if (result.ExitCode != 0) + { + throw new TestRunnerOperationFailedException(_testRunner, result.ExitCode); + } + } + + private ICommand CreateTestRunnerCommand() + { + var commandArgs = _argumentsBuilder.BuildArguments(); + + return _commandFactory.Create( + _testRunner, + commandArgs, + new NuGetFramework("DNXCore", Version.Parse("5.0"))); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerFactory.cs b/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerFactory.cs new file mode 100644 index 000000000..7c28b910d --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerFactory.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.DotNet.Cli.Utils; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerFactory : ITestRunnerFactory + { + private readonly string _testRunner; + private readonly ICommandFactory _commandFactory; + + public TestRunnerFactory(string testRunner, ICommandFactory commandFactory) + { + _testRunner = testRunner; + _commandFactory = commandFactory; + } + + public ITestRunner CreateTestRunner(ITestRunnerArgumentsBuilder argumentsBuilder) + { + return new TestRunner(_testRunner, _commandFactory, argumentsBuilder); + } + } +} diff --git a/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerOperationFailedException.cs b/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerOperationFailedException.cs new file mode 100644 index 000000000..4a718f328 --- /dev/null +++ b/src/dotnet/commands/dotnet-test/TestRunners/TestRunnerOperationFailedException.cs @@ -0,0 +1,20 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; + +namespace Microsoft.DotNet.Tools.Test +{ + public class TestRunnerOperationFailedException : Exception + { + public string TestRunner { get; set; } + public int ExitCode { get; set; } + public override string Message => $"'{TestRunner}' returned '{ExitCode}'."; + + public TestRunnerOperationFailedException(string testRunner, int exitCode) + { + TestRunner = testRunner; + ExitCode = exitCode; + } + } +} diff --git a/src/dotnet/project.json b/src/dotnet/project.json index 00879f0be..9d364d513 100644 --- a/src/dotnet/project.json +++ b/src/dotnet/project.json @@ -24,7 +24,7 @@ "Microsoft.CodeAnalysis.CSharp": "1.2.0-beta1-20160202-02", "Microsoft.DiaSymReader.Native": "1.3.3", - "NuGet.CommandLine.XPlat": "3.4.0-beta-625", + "NuGet.CommandLine.XPlat": "3.4.0-beta-632", "System.CommandLine": "0.1.0-e160119-1", "Microsoft.DotNet.ProjectModel": "1.0.0-*", diff --git a/test/Installer/testmsi.ps1 b/test/Installer/testmsi.ps1 index b25f66a48..2a11669be 100644 --- a/test/Installer/testmsi.ps1 +++ b/test/Installer/testmsi.ps1 @@ -69,10 +69,14 @@ try { Write-Host "Running installer tests in Windows Container" + # --net="none" works around a networking issue on the containers on the CI machines. + # Since our installer tests don't require the network, it is fine to shut it off. $MsiFileName = [System.IO.Path]::GetFileName($inputMsi) docker run ` + --rm ` -v "$testBin\:D:" ` -e "CLI_MSI=D:\$MsiFileName" ` + --net="none" ` windowsservercore ` D:\xunit.console.exe D:\$testName.dll | Out-Host diff --git a/test/Microsoft.DotNet.Tools.Tests.Utilities/Commands/PackCommand.cs b/test/Microsoft.DotNet.Tools.Tests.Utilities/Commands/PackCommand.cs index 99abacc46..ffedf3f0a 100644 --- a/test/Microsoft.DotNet.Tools.Tests.Utilities/Commands/PackCommand.cs +++ b/test/Microsoft.DotNet.Tools.Tests.Utilities/Commands/PackCommand.cs @@ -10,6 +10,7 @@ namespace Microsoft.DotNet.Tools.Test.Utilities { private string _projectPath; private string _outputDirectory; + private string _buildBasePath; private string _tempOutputDirectory; private string _configuration; private string _versionSuffix; @@ -23,6 +24,15 @@ namespace Microsoft.DotNet.Tools.Test.Utilities $"-o \"{_outputDirectory}\""; } } + private string BuildBasePathOption + { + get + { + return _buildBasePath == string.Empty ? + "" : + $"-b \"{_buildBasePath}\""; + } + } private string TempOutputOption { @@ -55,8 +65,9 @@ namespace Microsoft.DotNet.Tools.Test.Utilities } public PackCommand( - string projectPath, - string output="", + string projectPath, + string output = "", + string buildBasePath = "", string tempOutput="", string configuration="", string versionSuffix="") @@ -64,6 +75,7 @@ namespace Microsoft.DotNet.Tools.Test.Utilities { _projectPath = projectPath; _outputDirectory = output; + _buildBasePath = buildBasePath; _tempOutputDirectory = tempOutput; _configuration = configuration; _versionSuffix = versionSuffix; @@ -77,7 +89,7 @@ namespace Microsoft.DotNet.Tools.Test.Utilities private string BuildArgs() { - return $"{_projectPath} {OutputOption} {TempOutputOption} {ConfigurationOption} {VersionSuffixOption}"; + return $"{_projectPath} {OutputOption} {BuildBasePathOption} {TempOutputOption} {ConfigurationOption} {VersionSuffixOption}"; } } } diff --git a/test/Microsoft.Extensions.DependencyModel.Tests/DependencyContextCsvReaderTests.cs b/test/Microsoft.Extensions.DependencyModel.Tests/DependencyContextCsvReaderTests.cs new file mode 100644 index 000000000..e5ebe1a3c --- /dev/null +++ b/test/Microsoft.Extensions.DependencyModel.Tests/DependencyContextCsvReaderTests.cs @@ -0,0 +1,94 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Text; +using Microsoft.Extensions.DependencyModel; +using FluentAssertions; +using Xunit; + +namespace Microsoft.Extensions.DependencyModel.Tests +{ + public class DependencyContextCsvReaderTests + { + private DependencyContext Read(string text) + { + using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text))) + { + return new DependencyContextCsvReader().Read(stream); + } + } + + [Fact] + public void GroupsAssetsCorrectlyIntoLibraries() + { + var context = Read(@" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.Runtime.dll"" +"); + context.RuntimeLibraries.Should().HaveCount(1); + var library = context.RuntimeLibraries.Single(); + library.LibraryType.Should().Be("Package"); + library.PackageName.Should().Be("runtime.any.System.AppContext"); + library.Version.Should().Be("4.1.0-rc2-23811"); + library.Hash.Should().Be("sha512-1"); + library.Assemblies.Should().HaveCount(2).And + .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll").And + .Contain(a => a.Path == "lib\\dnxcore50\\System.Runtime.dll"); + } + + [Fact] + public void IgnoresAllButRuntimeAssets() + { + var context = Read(@" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""native"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext2.so"" +"); + context.RuntimeLibraries.Should().HaveCount(1); + var library = context.RuntimeLibraries.Single(); + library.Assemblies.Should().HaveCount(1).And + .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll"); + } + + [Fact] + public void IgnoresNiDllAssemblies() + { + var context = Read(@" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.ni.dll"" +"); + context.RuntimeLibraries.Should().HaveCount(1); + var library = context.RuntimeLibraries.Single(); + library.Assemblies.Should().HaveCount(1).And + .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll"); + } + + [Fact] + public void UsesTypeNameVersionAndHashToGroup() + { + var context = Read(@" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23812"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-2"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Package"",""runtime.any.System.AppContext2"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +""Project"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" +"); + context.RuntimeLibraries.Should().HaveCount(5); + } + + [Theory] + [InlineData("text")] + [InlineData(" ")] + [InlineData("\"")] + [InlineData(@""",""")] + [InlineData(@"\\")] + public void ThrowsFormatException(string intput) + { + Assert.Throws(() => Read(intput)); + } + } +} diff --git a/test/dotnet-build.Tests/BuildOutputTests.cs b/test/dotnet-build.Tests/BuildOutputTests.cs index 1f4a702a8..a2083c087 100644 --- a/test/dotnet-build.Tests/BuildOutputTests.cs +++ b/test/dotnet-build.Tests/BuildOutputTests.cs @@ -3,10 +3,12 @@ using System.IO; using System.Linq; +using System.Runtime.InteropServices; using FluentAssertions; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.PlatformAbstractions; +using NuGet.Frameworks; using Xunit; namespace Microsoft.DotNet.Tools.Builder.Tests @@ -128,6 +130,42 @@ namespace Microsoft.DotNet.Tools.Builder.Tests informationalVersion.Should().BeEquivalentTo("1.0.0-85"); } + [Theory] + [InlineData("net461", true, true)] + [InlineData("dnxcore50", true, false)] + public void MultipleFrameworks_ShouldHaveValidTargetFrameworkAttribute(string frameworkName, bool shouldHaveTargetFrameworkAttribute, bool windowsOnly) + { + var framework = NuGetFramework.Parse(frameworkName); + + var testInstance = TestAssetsManager.CreateTestInstance("TestLibraryWithMultipleFrameworks") + .WithLockFiles(); + + var cmd = new BuildCommand(Path.Combine(testInstance.TestRoot, Project.FileName), framework: framework.GetShortFolderName()); + + if (windowsOnly && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + // on non-windows platforms, desktop frameworks will not build + cmd.ExecuteWithCapturedOutput().Should().Fail(); + } + else + { + cmd.ExecuteWithCapturedOutput().Should().Pass(); + + var output = Path.Combine(testInstance.TestRoot, "bin", "Debug", framework.GetShortFolderName(), "TestLibraryWithMultipleFrameworks.dll"); + var targetFramework = PeReaderUtils.GetAssemblyAttributeValue(output, "TargetFrameworkAttribute"); + + if (shouldHaveTargetFrameworkAttribute) + { + targetFramework.Should().NotBeNull(); + targetFramework.Should().BeEquivalentTo(framework.DotNetFrameworkName); + } + else + { + targetFramework.Should().BeNull(); + } + } + } + [Fact] public void ResourceTest() { diff --git a/test/dotnet-build.Tests/WrappedProjectTests.cs b/test/dotnet-build.Tests/WrappedProjectTests.cs new file mode 100644 index 000000000..73f8ee102 --- /dev/null +++ b/test/dotnet-build.Tests/WrappedProjectTests.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.DotNet.Cli.Utils; +using Microsoft.DotNet.Tools.Test.Utilities; +using FluentAssertions; +using Xunit; + +namespace Microsoft.DotNet.Tools.Builder.Tests +{ + public class WrappedProjectTests: TestBase + { + [Fact] + public void WrappedProjectFilesResolvedCorrectly() + { + var testInstance = TestAssetsManager.CreateTestInstance("TestAppWithWrapperProjectDependency") + .WithBuildArtifacts() + .WithLockFiles(); + + var root = testInstance.TestRoot; + + // run compile + var outputDir = Path.Combine(root, "bin"); + var testProject = ProjectUtils.GetProjectJson(root, "TestApp"); + var buildCommand = new BuildCommand(testProject, output: outputDir, framework: DefaultFramework); + var result = buildCommand.ExecuteWithCapturedOutput(); + result.Should().Pass(); + + new DirectoryInfo(outputDir).Should() + .HaveFiles(new [] { "TestLibrary.dll", "TestLibrary.pdb" }); + } + + } +} diff --git a/test/dotnet-compile.Tests/CompilerTests.cs b/test/dotnet-compile.Tests/CompilerTests.cs index 4c4057e7e..132e1e0c6 100644 --- a/test/dotnet-compile.Tests/CompilerTests.cs +++ b/test/dotnet-compile.Tests/CompilerTests.cs @@ -4,6 +4,7 @@ using System; using System.IO; using Microsoft.DotNet.Cli.Utils; +using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using FluentAssertions; using Xunit; @@ -146,6 +147,26 @@ namespace Microsoft.DotNet.Tools.Compiler.Tests result.StdOut.Should().Contain("MyNamespace.Util"); } + [Fact] + public void EmbeddedDependencyContextIsValidOnBuild() + { + var testProjectPath = Path.Combine(RepoRoot, "TestAssets", "TestProjects", "DependencyContextValidator", "TestApp"); + var testProject = Path.Combine(testProjectPath, "project.json"); + + var runCommand = new RunCommand(testProject); + runCommand.Execute().Should().Pass(); + } + + [Fact] + public void DepsDependencyContextIsValidOnBuild() + { + var testProjectPath = Path.Combine(RepoRoot, "TestAssets", "TestProjects", "DependencyContextValidator", "TestAppDeps"); + var testProject = Path.Combine(testProjectPath, "project.json"); + + var runCommand = new RunCommand(testProject); + runCommand.Execute().Should().Pass(); + } + private void CopyProjectToTempDir(string projectDir, TempDirectory tempDir) { // copy all the files to temp dir diff --git a/test/dotnet-compile.Tests/project.json b/test/dotnet-compile.Tests/project.json index 6853f6a19..85fc82774 100644 --- a/test/dotnet-compile.Tests/project.json +++ b/test/dotnet-compile.Tests/project.json @@ -20,6 +20,7 @@ }, "content": [ + "../../TestAssets/TestProjects/DependencyContextValidator/**/*", "../../TestAssets/TestProjects/TestLibraryWithAnalyzer/*", "../../TestAssets/TestProjects/TestAppWithLibrary/TestLibrary/*", "../../TestAssets/TestProjects/TestProjectWithCultureSpecificResource/*", diff --git a/test/dotnet-pack.Tests/PackTests.cs b/test/dotnet-pack.Tests/PackTests.cs index 002e917e7..aaf66b551 100644 --- a/test/dotnet-pack.Tests/PackTests.cs +++ b/test/dotnet-pack.Tests/PackTests.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.IO.Compression; using FluentAssertions; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Test.Utilities; @@ -78,6 +79,22 @@ namespace Microsoft.DotNet.Tools.Compiler.Tests File.Exists(outputPackage).Should().BeTrue(outputPackage); } + [Fact] + public void HasBuildOutputWhenUsingBuildBasePath() + { + var testInstance = TestAssetsManager.CreateTestInstance("TestLibraryWithConfiguration") + .WithLockFiles(); + + var cmd = new PackCommand(Path.Combine(testInstance.TestRoot, Project.FileName), buildBasePath: "buildBase"); + cmd.Execute().Should().Pass(); + + var outputPackage = Path.Combine(testInstance.TestRoot, "bin", "Debug", "TestLibraryWithConfiguration.1.0.0.nupkg"); + File.Exists(outputPackage).Should().BeTrue(outputPackage); + + var zip = ZipFile.Open(outputPackage, ZipArchiveMode.Read); + zip.Entries.Should().Contain(e => e.FullName == "lib/dnxcore50/TestLibraryWithConfiguration.dll"); + } + private void CopyProjectToTempDir(string projectDir, TempDirectory tempDir) { // copy all the files to temp dir diff --git a/test/dotnet-pack.Tests/project.json b/test/dotnet-pack.Tests/project.json index 7ea509721..ef0d0b593 100644 --- a/test/dotnet-pack.Tests/project.json +++ b/test/dotnet-pack.Tests/project.json @@ -3,7 +3,8 @@ "dependencies": { "NETStandard.Library": "1.0.0-rc2-23811", - + "System.IO.Compression.ZipFile": "4.0.1-rc2-23811", + "Microsoft.DotNet.Tools.Tests.Utilities": { "target": "project" }, "Microsoft.DotNet.Cli.Utils": { "target": "project" diff --git a/test/dotnet-publish.Tests/Microsoft.DotNet.Tools.Publish.Tests.cs b/test/dotnet-publish.Tests/Microsoft.DotNet.Tools.Publish.Tests.cs index 9ab89cc6c..c19c7b10b 100644 --- a/test/dotnet-publish.Tests/Microsoft.DotNet.Tools.Publish.Tests.cs +++ b/test/dotnet-publish.Tests/Microsoft.DotNet.Tools.Publish.Tests.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; +using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.PlatformAbstractions; @@ -163,7 +164,6 @@ namespace Microsoft.DotNet.Tools.Publish.Tests refsDirectory.Should().NotHaveFile("TestLibrary.dll"); } - [Fact] public void CompilationFailedTest() { diff --git a/test/dotnet-run.Tests/RunTests.cs b/test/dotnet-run.Tests/RunTests.cs index 5b82db95c..eaadc4c09 100644 --- a/test/dotnet-run.Tests/RunTests.cs +++ b/test/dotnet-run.Tests/RunTests.cs @@ -3,38 +3,41 @@ using System; using System.IO; +using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using Xunit; -namespace Microsoft.DotNet.Tools.Compiler.Tests +namespace Microsoft.DotNet.Tools.Run.Tests { - public class CompilerTests : TestBase + public class RunTests : TestBase { - private static const string RunTestsBase = "RunTestsApps"; + private const string RunTestsBase = "RunTestsApps"; [WindowsOnlyFact] public void RunsSingleTarget() { - TestInstance instance = TestAssetsManager.CreateTestInstance(Path.Combine(RunTestsBase, "TestAppDesktopClr")) + TestInstance instance = TestAssetsManager.CreateTestInstance(Path.Combine(RunTestsBase, "TestAppFullClr")) .WithLockFiles() .WithBuildArtifacts(); - new RunCommand(testInstance.TestRoot).Execute().Should().Pass(); + new RunCommand(instance.TestRoot).Execute().Should().Pass(); } + [Fact] public void RunsDefaultWhenPresent() { TestInstance instance = TestAssetsManager.CreateTestInstance(Path.Combine(RunTestsBase, "TestAppMultiTarget")) .WithLockFiles() .WithBuildArtifacts(); - new RunCommand(testInstance.TestRoot).Execute().Should().Pass(); + new RunCommand(instance.TestRoot).Execute().Should().Pass(); } + [Fact] public void FailsWithMultipleTargetAndNoDefault() { - TestInstance instance = TestAssetsManager.CreateTestInstance(RunTestsBase, "TestAppMultiTargetNoCoreClr") + TestInstance instance = TestAssetsManager.CreateTestInstance(Path.Combine(RunTestsBase, "TestAppMultiTargetNoCoreClr")) .WithLockFiles() .WithBuildArtifacts(); - new RunCommand(testInstance.TestRoot).Execute().Should().Fail(); + new RunCommand(instance.TestRoot).Execute().Should().Fail(); } private void CopyProjectToTempDir(string projectDir, TempDirectory tempDir) diff --git a/test/dotnet-test.UnitTests/DotnetTestMessageScenario.cs b/test/dotnet-test.UnitTests/DotnetTestMessageScenario.cs new file mode 100644 index 000000000..975ccdf38 --- /dev/null +++ b/test/dotnet-test.UnitTests/DotnetTestMessageScenario.cs @@ -0,0 +1,76 @@ +using Microsoft.DotNet.Cli.Utils; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class DotnetTestMessageScenario + { + private TestMessagesCollection _messages; + private const string AssemblyUnderTest = "assembly.dll"; + private const string TestRunner = "testRunner"; + private const int Port = 1; + + public DotnetTest DotnetTestUnderTest { get; private set; } + public Mock TestRunnerMock { get; private set; } + public Mock AdapterChannelMock { get; private set; } + public Mock TestRunnerChannelMock { get; private set; } + + public DotnetTestMessageScenario() + { + _messages = new TestMessagesCollection(); + DotnetTestUnderTest = new DotnetTest(_messages, AssemblyUnderTest); + TestRunnerChannelMock = new Mock(); + TestRunnerMock = new Mock(); + AdapterChannelMock = new Mock(); + } + + public void Run() + { + var reportingChannelFactoryMock = new Mock(); + reportingChannelFactoryMock + .Setup(r => r.CreateChannelWithAnyAvailablePort()) + .Returns(TestRunnerChannelMock.Object); + + var commandFactoryMock = new Mock(); + + var testRunnerFactoryMock = new Mock(); + testRunnerFactoryMock + .Setup(t => t.CreateTestRunner(It.IsAny())) + .Returns(TestRunnerMock.Object); + + testRunnerFactoryMock + .Setup(t => t.CreateTestRunner(It.IsAny())) + .Returns(TestRunnerMock.Object); + + var reportingChannelFactory = reportingChannelFactoryMock.Object; + var adapterChannel = AdapterChannelMock.Object; + var commandFactory = commandFactoryMock.Object; + var testRunnerFactory = testRunnerFactoryMock.Object; + + using (DotnetTestUnderTest) + { + DotnetTestUnderTest + .AddNonSpecificMessageHandlers(_messages, adapterChannel) + .AddTestDiscoveryMessageHandlers(adapterChannel, reportingChannelFactory, testRunnerFactory) + .AddTestRunMessageHandlers(adapterChannel, reportingChannelFactory, testRunnerFactory) + .AddTestRunnnersMessageHandlers(adapterChannel); + + DotnetTestUnderTest.StartListeningTo(adapterChannel); + + AdapterChannelMock.Raise(r => r.MessageReceived += null, DotnetTestUnderTest, new Message + { + MessageType = TestMessageTypes.VersionCheck, + Payload = JToken.FromObject(new ProtocolVersionMessage { Version = 1 }) + }); + + DotnetTestUnderTest.StartHandlingMessages(); + } + + AdapterChannelMock.Verify(); + TestRunnerMock.Verify(); + } + } +} \ No newline at end of file diff --git a/test/dotnet-test.UnitTests/GivenADiscoverTestsArgumentsBuilder.cs b/test/dotnet-test.UnitTests/GivenADiscoverTestsArgumentsBuilder.cs new file mode 100644 index 000000000..7ba88c06e --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenADiscoverTestsArgumentsBuilder.cs @@ -0,0 +1,25 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenADiscoverTestsArgumentsBuilder + { + [Fact] + public void It_generates_the_right_arguments_for_DiscoverTests() + { + const int port = 1; + const string assembly = "assembly.dll"; + + var discoverTestsArgumentsBuilder = new DiscoverTestsArgumentsBuilder(assembly, port); + + var arguments = discoverTestsArgumentsBuilder.BuildArguments(); + + arguments.Should().BeEquivalentTo(assembly, "--list", "--designtime", "--port", $"{port}"); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenADotnetTestApp.cs b/test/dotnet-test.UnitTests/GivenADotnetTestApp.cs new file mode 100644 index 000000000..69c501715 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenADotnetTestApp.cs @@ -0,0 +1,157 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenADotnetTestApp + { + private const string AssemblyUnderTest = "assembly.dll"; + + private Mock _reportingChannelMock; + private Mock _noOpMessageHandlerMock; + private Mock _realMessageHandlerMock; + private Mock _unknownMessageHandlerMock; + private DotnetTest _dotnetTest; + + public GivenADotnetTestApp() + { + _noOpMessageHandlerMock = new Mock(); + _noOpMessageHandlerMock + .Setup(mh => mh.HandleMessage(It.IsAny(), It.IsAny())) + .Returns(DotnetTestState.NoOp) + .Verifiable(); + + _realMessageHandlerMock = new Mock(); + _realMessageHandlerMock + .Setup(mh => mh.HandleMessage(It.IsAny(), It.Is(m => m.MessageType == "Test message"))) + .Returns(DotnetTestState.VersionCheckCompleted).Callback(() => + _reportingChannelMock.Raise(r => r.MessageReceived += null, _dotnetTest, new Message + { + MessageType = TestMessageTypes.TestSessionTerminate + })); + + _reportingChannelMock = new Mock(); + _unknownMessageHandlerMock = new Mock(); + _unknownMessageHandlerMock + .Setup(mh => mh.HandleMessage(It.IsAny(), It.IsAny())) + .Throws(); + + var testMessagesCollection = new TestMessagesCollection(); + _dotnetTest = new DotnetTest(testMessagesCollection, AssemblyUnderTest) + { + TestSessionTerminateMessageHandler = new TestSessionTerminateMessageHandler(testMessagesCollection), + UnknownMessageHandler = _unknownMessageHandlerMock.Object + }; + + _dotnetTest.StartListeningTo(_reportingChannelMock.Object); + + _reportingChannelMock.Raise(r => r.MessageReceived += null, _dotnetTest, new Message + { + MessageType = "Test message" + }); + } + + [Fact] + public void DotnetTest_handles_TestSession_Terminate_messages_implicitly() + { + _reportingChannelMock.Raise(r => r.MessageReceived += null, _dotnetTest, new Message + { + MessageType = TestMessageTypes.TestSessionTerminate + }); + + _dotnetTest.StartHandlingMessages(); + + //just the fact that we are not hanging means we stopped waiting for messages + } + + [Fact] + public void DotnetTest_calls_each_MessageHandler_until_one_returns_a_state_different_from_NoOp() + { + var secondNoOpMessageHandler = new Mock(); + + _dotnetTest + .AddMessageHandler(_noOpMessageHandlerMock.Object) + .AddMessageHandler(_realMessageHandlerMock.Object) + .AddMessageHandler(secondNoOpMessageHandler.Object); + + _dotnetTest.StartHandlingMessages(); + + _noOpMessageHandlerMock.Verify(); + _realMessageHandlerMock.Verify(); + secondNoOpMessageHandler.Verify( + mh => mh.HandleMessage(It.IsAny(), It.IsAny()), + Times.Never); + } + + [Fact] + public void DotnetTest_does_not_send_an_error_when_the_message_gets_handled() + { + _dotnetTest.AddMessageHandler(_realMessageHandlerMock.Object); + + _dotnetTest.StartHandlingMessages(); + + _reportingChannelMock.Verify(r => r.SendError(It.IsAny()), Times.Never); + } + + [Fact] + public void DotnetTest_calls_the_unknown_message_handler_when_the_message_is_not_handled() + { + _dotnetTest.AddMessageHandler(_noOpMessageHandlerMock.Object); + + Action action = () => _dotnetTest.StartHandlingMessages(); + + action.ShouldThrow(); + } + + [Fact] + public void It_throws_an_InvalidOperationException_if_StartListening_is_called_without_setting_a_TestSessionTerminateMessageHandler() + { + var dotnetTest = new DotnetTest(new TestMessagesCollection(), AssemblyUnderTest) + { + UnknownMessageHandler = new Mock().Object + }; + + Action action = () => dotnetTest.StartListeningTo(new Mock().Object); + + action.ShouldThrow(); + } + + [Fact] + public void It_throws_an_InvalidOperationException_if_StartListeningTo_is_called_without_setting_a_UnknownMessageHandler() + { + var dotnetTest = new DotnetTest(new TestMessagesCollection(), AssemblyUnderTest) + { + TestSessionTerminateMessageHandler = new Mock().Object + }; + + Action action = () => dotnetTest.StartListeningTo(new Mock().Object); + + action.ShouldThrow(); + } + + [Fact] + public void It_disposes_all_reporting_channels_that_it_was_listening_to_when_it_gets_disposed() + { + var firstReportingChannelMock = new Mock(); + var secondReportingChannelMock = new Mock(); + using (var dotnetTest = new DotnetTest(new TestMessagesCollection(), AssemblyUnderTest)) + { + dotnetTest.TestSessionTerminateMessageHandler = new Mock().Object; + dotnetTest.UnknownMessageHandler = new Mock().Object; + + dotnetTest.StartListeningTo(firstReportingChannelMock.Object); + dotnetTest.StartListeningTo(secondReportingChannelMock.Object); + } + + firstReportingChannelMock.Verify(r => r.Dispose(), Times.Once); + secondReportingChannelMock.Verify(r => r.Dispose(), Times.Once); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenARunTestsArgumentsBuilder.cs b/test/dotnet-test.UnitTests/GivenARunTestsArgumentsBuilder.cs new file mode 100644 index 000000000..31d2f8de8 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenARunTestsArgumentsBuilder.cs @@ -0,0 +1,41 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenARunTestsArgumentsBuilder + { + [Fact] + public void It_generates_the_right_arguments_for_RunTests() + { + const int port = 1; + const string assembly = "assembly.dll"; + + var message = new Message + { + Payload = JToken.FromObject(new RunTestsMessage { Tests = new List { "test1", "test2" } }) + }; + + var runTestsArgumentsBuilder = new RunTestsArgumentsBuilder(assembly, port, message); + + var arguments = runTestsArgumentsBuilder.BuildArguments(); + + arguments.Should().BeEquivalentTo( + assembly, + "--designtime", + "--port", + $"{port}", + "--test", + "test1", + "--test", + "test2"); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestDiscoveryStartMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestDiscoveryStartMessageHandler.cs new file mode 100644 index 000000000..d70242130 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestDiscoveryStartMessageHandler.cs @@ -0,0 +1,174 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Cli.Tools.Test; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestDiscoveryStartMessageHandler + { + private const int TestRunnerPort = 1; + private const string AssemblyUnderTest = "assembly.dll"; + + private TestDiscoveryStartMessageHandler _testDiscoveryStartMessageHandler; + private IDotnetTest _dotnetTestAtVersionCheckCompletedState; + private Message _validMessage; + private Mock _testRunnerFactoryMock; + private Mock _testRunnerMock; + private Mock _adapterChannelMock; + private Mock _testRunnerChannelMock; + private Mock _reportingChannelFactoryMock; + private DiscoverTestsArgumentsBuilder _argumentsBuilder; + private Mock _dotnetTestMock; + + public GivenATestDiscoveryStartMessageHandler() + { + _dotnetTestMock = new Mock(); + _dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.VersionCheckCompleted); + _dotnetTestMock.Setup(d => d.PathToAssemblyUnderTest).Returns(AssemblyUnderTest); + _dotnetTestAtVersionCheckCompletedState = _dotnetTestMock.Object; + + _testRunnerMock = new Mock(); + _testRunnerFactoryMock = new Mock(); + _testRunnerFactoryMock + .Setup(c => c.CreateTestRunner(It.IsAny())) + .Callback(r => _argumentsBuilder = r as DiscoverTestsArgumentsBuilder) + .Returns(_testRunnerMock.Object); + + _adapterChannelMock = new Mock(); + + _testRunnerChannelMock = new Mock(); + _testRunnerChannelMock.Setup(t => t.Port).Returns(TestRunnerPort); + + _reportingChannelFactoryMock = new Mock(); + _reportingChannelFactoryMock.Setup(r => + r.CreateChannelWithAnyAvailablePort()).Returns(_testRunnerChannelMock.Object); + + _testDiscoveryStartMessageHandler = new TestDiscoveryStartMessageHandler( + _testRunnerFactoryMock.Object, + _adapterChannelMock.Object, + _reportingChannelFactoryMock.Object); + + _validMessage = new Message + { + MessageType = TestMessageTypes.TestDiscoveryStart + }; + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_VersionCheckCompleted_or_InitialState() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testDiscoveryStartMessageHandler.HandleMessage( + dotnetTestMock.Object, + new Message { MessageType = TestMessageTypes.TestDiscoveryStart }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestDiscoveryStart() + { + var nextState = _testDiscoveryStartMessageHandler.HandleMessage( + _dotnetTestAtVersionCheckCompletedState, + new Message { MessageType = "Something different from TestDiscovery.Start" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestDiscoveryCompleted_when_it_handles_the_message_and_current_state_is_InitialState() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.InitialState); + + var nextState = + _testDiscoveryStartMessageHandler.HandleMessage(dotnetTestMock.Object, _validMessage); + + nextState.Should().Be(DotnetTestState.TestDiscoveryStarted); + } + + [Fact] + public void It_returns_TestDiscoveryCompleted_when_it_handles_the_message_and_current_state_is_VersionCheckCompleted() + { + var nextState = + _testDiscoveryStartMessageHandler.HandleMessage(_dotnetTestAtVersionCheckCompletedState, _validMessage); + + nextState.Should().Be(DotnetTestState.TestDiscoveryStarted); + } + + [Fact] + public void It_uses_the_test_runner_to_discover_tests_when_it_handles_the_message() + { + _testDiscoveryStartMessageHandler.HandleMessage(_dotnetTestAtVersionCheckCompletedState, _validMessage); + + _testRunnerMock.Verify(t => t.RunTestCommand(), Times.Once); + } + + [Fact] + public void It_sends_an_error_when_the_test_runner_fails() + { + const string testRunner = "SomeTestRunner"; + + _testRunnerMock.Setup(t => t.RunTestCommand()).Throws(new TestRunnerOperationFailedException(testRunner, 1)); + + _testDiscoveryStartMessageHandler.HandleMessage(_dotnetTestAtVersionCheckCompletedState, _validMessage); + + _adapterChannelMock.Verify(r => r.SendError($"'{testRunner}' returned '1'."), Times.Once); + } + + [Fact] + public void It_creates_a_new_reporting_channel() + { + _testDiscoveryStartMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _reportingChannelFactoryMock.Verify(r => r.CreateChannelWithAnyAvailablePort(), Times.Once); + } + + [Fact] + public void It_calls_accept_on_the_test_runner_channel() + { + _testDiscoveryStartMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _testRunnerChannelMock.Verify(t => t.Accept(), Times.Once); + } + + [Fact] + public void It_makes_dotnet_test_listen_on_the_test_runner_port_for_messages_when_it_handles_the_message() + { + _testDiscoveryStartMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _dotnetTestMock.Verify(d => d.StartListeningTo(_testRunnerChannelMock.Object), Times.Once); + } + + [Fact] + public void It_passes_the_right_arguments_to_the_run_tests_arguments_builder() + { + _testDiscoveryStartMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _argumentsBuilder.Should().NotBeNull(); + + var arguments = _argumentsBuilder.BuildArguments(); + + arguments.Should().Contain("--port", $"{TestRunnerPort}"); + arguments.Should().Contain($"{AssemblyUnderTest}"); + arguments.Should().Contain("--list"); + arguments.Should().Contain("--designtime"); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestExecutionGetTestRunnerProcessStartInfoMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestExecutionGetTestRunnerProcessStartInfoMessageHandler.cs new file mode 100644 index 000000000..f1e4d1b61 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestExecutionGetTestRunnerProcessStartInfoMessageHandler.cs @@ -0,0 +1,188 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using System.Diagnostics; +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestExecutionGetTestRunnerProcessStartInfoMessageHandler + { + private const int TestRunnerPort = 1; + private const string AssemblyUnderTest = "assembly.dll"; + + private GetTestRunnerProcessStartInfoMessageHandler _testGetTestRunnerProcessStartInfoMessageHandler; + private Message _validMessage; + private ProcessStartInfo _processStartInfo; + + private Mock _testRunnerMock; + private Mock _testRunnerFactoryMock; + private Mock _adapterChannelMock; + private Mock _testRunnerChannelMock; + private Mock _reportingChannelFactoryMock; + private Mock _dotnetTestMock; + + private RunTestsArgumentsBuilder _argumentsBuilder; + + public GivenATestExecutionGetTestRunnerProcessStartInfoMessageHandler() + { + _validMessage = new Message + { + MessageType = TestMessageTypes.TestExecutionGetTestRunnerProcessStartInfo, + Payload = JToken.FromObject(new RunTestsMessage { Tests = new List { "test1", "test2" } }) + }; + + _dotnetTestMock = new Mock(); + _dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.VersionCheckCompleted); + _dotnetTestMock.Setup(d => d.PathToAssemblyUnderTest).Returns(AssemblyUnderTest); + + _processStartInfo = new ProcessStartInfo("runner", "arguments"); + + _testRunnerMock = new Mock(); + _testRunnerMock.Setup(t => t.GetProcessStartInfo()).Returns(_processStartInfo); + + _testRunnerFactoryMock = new Mock(); + _testRunnerFactoryMock + .Setup(c => c.CreateTestRunner(It.IsAny())) + .Callback(r => _argumentsBuilder = r as RunTestsArgumentsBuilder) + .Returns(_testRunnerMock.Object); + + _adapterChannelMock = new Mock(); + _testRunnerChannelMock = new Mock(); + _testRunnerChannelMock.Setup(t => t.Port).Returns(TestRunnerPort); + + _reportingChannelFactoryMock = new Mock(); + _reportingChannelFactoryMock.Setup(r => + r.CreateChannelWithAnyAvailablePort()).Returns(_testRunnerChannelMock.Object); + + _testGetTestRunnerProcessStartInfoMessageHandler = new GetTestRunnerProcessStartInfoMessageHandler( + _testRunnerFactoryMock.Object, + _adapterChannelMock.Object, + _reportingChannelFactoryMock.Object); + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_VersionCheckCompleted_or_InitialState() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestDiscoveryStart() + { + var nextState = _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + new Message { MessageType = "Something different from TestDiscovery.Start" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestExecutionSentTestRunnerProcessStartInfo_when_it_handles_the_message_and_current_state_is_InitialState() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.InitialState); + + var nextState = _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionSentTestRunnerProcessStartInfo); + } + + [Fact] + public void It_returns_TestExecutionSentTestRunnerProcessStartInfo_when_it_handles_the_message_and_current_state_is_VersionCheckCompleted() + { + var nextState = _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionSentTestRunnerProcessStartInfo); + } + + [Fact] + public void It_gets_the_process_start_info_from_the_test_runner_when_it_handles_the_message() + { + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _testRunnerMock.Verify(t => t.GetProcessStartInfo(), Times.Once); + } + + [Fact] + public void It_sends_the_process_start_info_when_it_handles_the_message() + { + _adapterChannelMock.Setup(r => r.Send(It.Is(m => + m.MessageType == TestMessageTypes.TestExecutionTestRunnerProcessStartInfo && + m.Payload.ToObject().FileName == _processStartInfo.FileName && + m.Payload.ToObject().Arguments == _processStartInfo.Arguments))).Verifiable(); + + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + + [Fact] + public void It_creates_a_new_reporting_channel() + { + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _reportingChannelFactoryMock.Verify(r => r.CreateChannelWithAnyAvailablePort(), Times.Once); + } + + [Fact] + public void It_calls_accept_on_the_test_runner_channel() + { + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _testRunnerChannelMock.Verify(t => t.Accept(), Times.Once); + } + + [Fact] + public void It_makes_dotnet_test_listen_on_the_test_runner_port_for_messages_when_it_handles_the_message() + { + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _dotnetTestMock.Verify(d => d.StartListeningTo(_testRunnerChannelMock.Object), Times.Once); + } + + [Fact] + public void It_passes_the_right_arguments_to_the_run_tests_arguments_builder() + { + _testGetTestRunnerProcessStartInfoMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _argumentsBuilder.Should().NotBeNull(); + + var arguments = _argumentsBuilder.BuildArguments(); + + arguments.Should().Contain("--port", $"{TestRunnerPort}"); + arguments.Should().Contain($"{AssemblyUnderTest}"); + arguments.Should().Contain("--test", "test1"); + arguments.Should().Contain("--test", "test2"); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestRunner.cs b/test/dotnet-test.UnitTests/GivenATestRunner.cs new file mode 100644 index 000000000..d7a095c8d --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestRunner.cs @@ -0,0 +1,106 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using FluentAssertions; +using Microsoft.DotNet.Cli.Utils; +using Microsoft.DotNet.Tools.Test; +using Moq; +using NuGet.Frameworks; +using Xunit; +using Newtonsoft.Json; +using Microsoft.Extensions.Testing.Abstractions; +using System.Linq; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestRunner + { + private Mock _commandMock; + private Mock _commandFactoryMock; + private Mock _argumentsBuilderMock; + private string _runner = "runner"; + private string[] _testRunnerArguments; + + public GivenATestRunner() + { + _testRunnerArguments = new[] {"assembly.dll", "--list", "--designtime"}; + + _commandMock = new Mock(); + _commandMock.Setup(c => c.CommandName).Returns(_runner); + _commandMock.Setup(c => c.CommandArgs).Returns(string.Join(" ", _testRunnerArguments)); + _commandMock.Setup(c => c.OnOutputLine(It.IsAny>())).Returns(_commandMock.Object); + + _argumentsBuilderMock = new Mock(); + _argumentsBuilderMock.Setup(a => a.BuildArguments()) + .Returns(_testRunnerArguments); + + _commandFactoryMock = new Mock(); + _commandFactoryMock.Setup(c => c.Create( + _runner, + _testRunnerArguments, + new NuGetFramework("DNXCore", Version.Parse("5.0")), + null)).Returns(_commandMock.Object).Verifiable(); + } + + [Fact] + public void It_creates_a_command_using_the_right_parameters() + { + var testRunner = new TestRunner(_runner, _commandFactoryMock.Object, _argumentsBuilderMock.Object); + + testRunner.RunTestCommand(); + + _commandFactoryMock.Verify(); + } + + [Fact] + public void It_executes_the_command() + { + var testRunner = new TestRunner(_runner, _commandFactoryMock.Object, _argumentsBuilderMock.Object); + + testRunner.RunTestCommand(); + + _commandMock.Verify(c => c.Execute(), Times.Once); + } + + [Fact] + public void It_throws_TestRunnerOperationFailedException_when_the_returns_return_an_error_code() + { + _commandMock.Setup(c => c.Execute()).Returns(new CommandResult(null, 1, null, null)); + + var testRunner = new TestRunner(_runner, _commandFactoryMock.Object, _argumentsBuilderMock.Object); + + Action action = () => testRunner.RunTestCommand(); + + action.ShouldThrow(); + } + + [Fact] + public void It_executes_the_command_when_RunTestCommand_is_called() + { + var testResult = new Message + { + MessageType = "Irrelevant", + Payload = JToken.FromObject("Irrelevant") + }; + + var testRunner = new TestRunner(_runner, _commandFactoryMock.Object, _argumentsBuilderMock.Object); + + testRunner.RunTestCommand(); + + _commandMock.Verify(c => c.Execute(), Times.Once); + } + + [Fact] + public void It_returns_a_ProcessStartInfo_object_with_the_right_parameters_to_execute_the_test_command() + { + var testRunner = new TestRunner(_runner, _commandFactoryMock.Object, _argumentsBuilderMock.Object); + + var testCommandProcessStartInfo = testRunner.GetProcessStartInfo(); + + testCommandProcessStartInfo.FileName.Should().Be(_runner); + testCommandProcessStartInfo.Arguments.Should().Be(string.Join(" ", _testRunnerArguments)); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestRunnerTestCompletedMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestRunnerTestCompletedMessageHandler.cs new file mode 100644 index 000000000..9c855c204 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestRunnerTestCompletedMessageHandler.cs @@ -0,0 +1,122 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestRunnerTestCompletedMessageHandler + { + private Mock _dotnetTestAtTestDiscoveryStartedMock; + private Mock _dotnetTestAtTestExecutionStartedMock; + private Mock _adapterChannelMock; + + private Message _validMessage; + private TestRunnerTestCompletedMessageHandler _testRunnerTestCompletedMessageHandler; + + public GivenATestRunnerTestCompletedMessageHandler() + { + _dotnetTestAtTestDiscoveryStartedMock = new Mock(); + _dotnetTestAtTestDiscoveryStartedMock.Setup(d => d.State).Returns(DotnetTestState.TestDiscoveryStarted); + + _dotnetTestAtTestExecutionStartedMock = new Mock(); + _dotnetTestAtTestExecutionStartedMock.Setup(d => d.State).Returns(DotnetTestState.TestExecutionStarted); + + _adapterChannelMock = new Mock(); + + _validMessage = new Message + { + MessageType = TestMessageTypes.TestRunnerTestCompleted + }; + + _testRunnerTestCompletedMessageHandler = + new TestRunnerTestCompletedMessageHandler(_adapterChannelMock.Object); + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_TestDiscoveryStarted_or_TestExecutionStarted() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testRunnerTestCompletedMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestRunnerTestCompleted_when_state_is_TestDiscoveryStarted() + { + var nextState = _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestDiscoveryStartedMock.Object, + new Message { MessageType = "Something different from TestDiscovery.Start" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestRunnerTestCompleted_when_state_is_TestExecutionStarted() + { + var nextState = _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestExecutionStartedMock.Object, + new Message { MessageType = "Something different from TestDiscovery.Start" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestDiscoveryCompleted_when_it_handles_the_message_and_current_state_is_TestDiscoveryStarted() + { + var nextState = _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestDiscoveryStartedMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestDiscoveryCompleted); + } + + [Fact] + public void It_sends_a_TestDiscoveryCompleted_when_it_handles_the_message_and_current_state_is_TestDiscoveryStarted() + { + _adapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestDiscoveryCompleted))) + .Verifiable(); + + _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestDiscoveryStartedMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + + [Fact] + public void It_returns_TestExecutionCompleted_when_it_handles_the_message_and_current_state_is_TestExecutionStarted() + { + var nextState = _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestExecutionStartedMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionCompleted); + } + + [Fact] + public void It_sends_a_TestExecutionCompleted_when_it_handles_the_message_and_current_state_is_TestExecutionStarted() + { + _adapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestExecutionCompleted))) + .Verifiable(); + + _testRunnerTestCompletedMessageHandler.HandleMessage( + _dotnetTestAtTestExecutionStartedMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestRunnerTestFoundMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestRunnerTestFoundMessageHandler.cs new file mode 100644 index 000000000..8a9c98c67 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestRunnerTestFoundMessageHandler.cs @@ -0,0 +1,84 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestRunnerTestFoundMessageHandler + { + private Mock _dotnetTestMock; + private Mock _adapterChannelMock; + + private Message _validMessage; + private TestRunnerTestFoundMessageHandler _testRunnerTestFoundMessageHandler; + + public GivenATestRunnerTestFoundMessageHandler() + { + _dotnetTestMock = new Mock(); + _dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.TestDiscoveryStarted); + + _adapterChannelMock = new Mock(); + + _validMessage = new Message + { + MessageType = TestMessageTypes.TestRunnerTestFound, + Payload = JToken.FromObject("testFound") + }; + + _testRunnerTestFoundMessageHandler = new TestRunnerTestFoundMessageHandler(_adapterChannelMock.Object); + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_TestDiscoveryStarted() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testRunnerTestFoundMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestRunnerTestFound() + { + var nextState = _testRunnerTestFoundMessageHandler.HandleMessage( + _dotnetTestMock.Object, + new Message { MessageType = "Something different from TestDiscovery.Start" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestDiscoveryStarted_when_it_handles_the_message() + { + var nextState = _testRunnerTestFoundMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestDiscoveryStarted); + } + + [Fact] + public void It_sends_the_payload_of_the_message_when_it_handles_the_message() + { + _adapterChannelMock.Setup(a => a.Send(It.Is(m => + m.MessageType == TestMessageTypes.TestDiscoveryTestFound && + m.Payload.ToObject() == _validMessage.Payload.ToObject()))).Verifiable(); + + _testRunnerTestFoundMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestRunnerTestResultMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestRunnerTestResultMessageHandler.cs new file mode 100644 index 000000000..11700dac9 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestRunnerTestResultMessageHandler.cs @@ -0,0 +1,84 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestRunnerTestResultMessageHandler + { + private Mock _dotnetTestMock; + private Mock _adapterChannelMock; + + private Message _validMessage; + private TestRunnerTestResultMessageHandler _testRunnerTestResultMessageHandler; + + public GivenATestRunnerTestResultMessageHandler() + { + _dotnetTestMock = new Mock(); + _dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.TestExecutionStarted); + + _adapterChannelMock = new Mock(); + + _validMessage = new Message + { + MessageType = TestMessageTypes.TestRunnerTestResult, + Payload = JToken.FromObject("testFound") + }; + + _testRunnerTestResultMessageHandler = new TestRunnerTestResultMessageHandler(_adapterChannelMock.Object); + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_TestExecutionStarted() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testRunnerTestResultMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestRunnerTestResult() + { + var nextState = _testRunnerTestResultMessageHandler.HandleMessage( + _dotnetTestMock.Object, + new Message { MessageType = "Something different from TestRunner.TestResult" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestExecutionStarted_when_it_handles_the_message() + { + var nextState = _testRunnerTestResultMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionStarted); + } + + [Fact] + public void It_sends_the_payload_of_the_message_when_it_handles_the_message() + { + _adapterChannelMock.Setup(a => a.Send(It.Is(m => + m.MessageType == TestMessageTypes.TestExecutionTestResult && + m.Payload.ToObject() == _validMessage.Payload.ToObject()))).Verifiable(); + + _testRunnerTestResultMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestRunnerTestStartedMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestRunnerTestStartedMessageHandler.cs new file mode 100644 index 000000000..1a894baa8 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestRunnerTestStartedMessageHandler.cs @@ -0,0 +1,112 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestRunnerTestStartedMessageHandler + { + private Mock _dotnetTestMock; + private Mock _adapterChannelMock; + + private Message _validMessage; + private TestRunnerTestStartedMessageHandler _testRunnerTestStartedMessageHandler; + + public GivenATestRunnerTestStartedMessageHandler() + { + _dotnetTestMock = new Mock(); + _dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.TestExecutionSentTestRunnerProcessStartInfo); + + _adapterChannelMock = new Mock(); + + _validMessage = new Message + { + MessageType = TestMessageTypes.TestRunnerTestStarted, + Payload = JToken.FromObject("testFound") + }; + + _testRunnerTestStartedMessageHandler = + new TestRunnerTestStartedMessageHandler(_adapterChannelMock.Object); + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_TestExecutionSentTestRunnerProcessStartInfo_or_TestExecutionTestStarted() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _testRunnerTestStartedMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_TestRunnerTestStarted() + { + var nextState = _testRunnerTestStartedMessageHandler.HandleMessage( + _dotnetTestMock.Object, + new Message { MessageType = "Something different from TestRunner.TestStart" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_TestExecutionStarted_when_it_handles_the_message_and_current_state_is_TestExecutionSentTestRunnerProcessStartInfo() + { + var nextState = _testRunnerTestStartedMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionStarted); + } + + [Fact] + public void It_returns_TestExecutionStarted_when_it_handles_the_message_and_current_state_is_TestExecutionTestStarted() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.TestExecutionStarted); + + var nextState = _testRunnerTestStartedMessageHandler.HandleMessage( + dotnetTestMock.Object, + _validMessage); + + nextState.Should().Be(DotnetTestState.TestExecutionStarted); + } + + [Fact] + public void It_sends_a_TestExecutionTestStarted_when_it_handles_the_message() + { + _adapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestExecutionStarted))) + .Verifiable(); + + _testRunnerTestStartedMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + + [Fact] + public void It_sends_the_payload_of_the_message_when_it_handles_the_message() + { + _adapterChannelMock.Setup(a => a.Send(It.Is(m => + m.MessageType == TestMessageTypes.TestExecutionStarted && + m.Payload.ToObject() == _validMessage.Payload.ToObject()))).Verifiable(); + + _testRunnerTestStartedMessageHandler.HandleMessage( + _dotnetTestMock.Object, + _validMessage); + + _adapterChannelMock.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenATestSessionTerminateMessageHandler.cs b/test/dotnet-test.UnitTests/GivenATestSessionTerminateMessageHandler.cs new file mode 100644 index 000000000..febfb3b9e --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenATestSessionTerminateMessageHandler.cs @@ -0,0 +1,42 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenATestSessionTerminateMessageHandler + { + private DotnetTestState _nextState; + private Mock _testMessagesCollectionMock; + + public GivenATestSessionTerminateMessageHandler() + { + var reportingChannel = new Mock(); + _testMessagesCollectionMock = new Mock(); + var dotnetTestMock = new Mock(); + var messageHandler = new TestSessionTerminateMessageHandler(_testMessagesCollectionMock.Object); + + _nextState = messageHandler.HandleMessage(dotnetTestMock.Object, new Message + { + MessageType = TestMessageTypes.TestSessionTerminate + }); + } + + [Fact] + public void It_always_returns_the_terminated_state_idependent_of_the_state_passed_to_it() + { + _nextState.Should().Be(DotnetTestState.Terminated); + } + + [Fact] + public void It_calls_drain_on_the_test_messages() + { + _testMessagesCollectionMock.Verify(tmc => tmc.Drain(), Times.Once); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenAUnknownMessageHandler.cs b/test/dotnet-test.UnitTests/GivenAUnknownMessageHandler.cs new file mode 100644 index 000000000..ff9200f37 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenAUnknownMessageHandler.cs @@ -0,0 +1,37 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Xunit; +using FluentAssertions; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenAUnknownMessageHandler + { + [Fact] + public void It_throws_InvalidOperationException_and_sends_an_error_when_the_message_is_not_handled() + { + const string expectedError = "No handler for message 'Test Message' when at state 'InitialState'"; + + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.InitialState); + + var reportingChannel = new Mock(); + reportingChannel.Setup(r => r.SendError(expectedError)).Verifiable(); + + var unknownMessageHandler = new UnknownMessageHandler(reportingChannel.Object); + + Action action = () => unknownMessageHandler.HandleMessage( + dotnetTestMock.Object, + new Message { MessageType = "Test Message" }); + + action.ShouldThrow().WithMessage(expectedError); + + reportingChannel.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenAVersionCheckMessageHandler.cs b/test/dotnet-test.UnitTests/GivenAVersionCheckMessageHandler.cs new file mode 100644 index 000000000..19bf77653 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenAVersionCheckMessageHandler.cs @@ -0,0 +1,83 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using FluentAssertions; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenAVersionCheckMessageHandler + { + private Mock _reportingChannelMock; + private VersionCheckMessageHandler _versionCheckMessageHandler; + private Message _validMessage; + private IDotnetTest _dotnetTestAtInitialState; + + public GivenAVersionCheckMessageHandler() + { + _reportingChannelMock = new Mock(); + _versionCheckMessageHandler = new VersionCheckMessageHandler(_reportingChannelMock.Object); + + _validMessage = new Message + { + MessageType = TestMessageTypes.VersionCheck, + Payload = JToken.FromObject(new ProtocolVersionMessage + { + Version = 99 + }) + }; + + var dotnetTestAtInitialStateMock = new Mock(); + dotnetTestAtInitialStateMock.Setup(d => d.State).Returns(DotnetTestState.InitialState); + _dotnetTestAtInitialState = dotnetTestAtInitialStateMock.Object; + } + + [Fact] + public void It_returns_NoOp_if_the_dotnet_test_state_is_not_initial() + { + var dotnetTestMock = new Mock(); + dotnetTestMock.Setup(d => d.State).Returns(DotnetTestState.Terminated); + + var nextState = _versionCheckMessageHandler.HandleMessage( + dotnetTestMock.Object, + new Message {MessageType = TestMessageTypes.VersionCheck}); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_NoOp_if_the_message_is_not_VersionCheck() + { + var nextState = _versionCheckMessageHandler.HandleMessage( + _dotnetTestAtInitialState, + new Message { MessageType = "Something different from ProtocolVersion" }); + + nextState.Should().Be(DotnetTestState.NoOp); + } + + [Fact] + public void It_returns_VersionCheckCompleted_when_it_handles_the_message() + { + var nextState = _versionCheckMessageHandler.HandleMessage(_dotnetTestAtInitialState, _validMessage); + + nextState.Should().Be(DotnetTestState.VersionCheckCompleted); + } + + [Fact] + public void It_returns_a_ProtocolVersion_with_the_SupportedVersion_when_it_handles_the_message() + { + _reportingChannelMock.Setup(r => + r.Send(It.Is(m => + m.MessageType == TestMessageTypes.VersionCheck && + m.Payload.ToObject().Version == 1))).Verifiable(); + + _versionCheckMessageHandler.HandleMessage(_dotnetTestAtInitialState, _validMessage); + + _reportingChannelMock.Verify(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenThatWeWantToDiscoverTests.cs b/test/dotnet-test.UnitTests/GivenThatWeWantToDiscoverTests.cs new file mode 100644 index 000000000..6ffb0b0c8 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenThatWeWantToDiscoverTests.cs @@ -0,0 +1,67 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenThatWeWantToDiscoverTests + { + [Fact] + public void Dotnet_test_handles_and_sends_all_the_right_messages() + { + var dotnetTestMessageScenario = new DotnetTestMessageScenario(); + + dotnetTestMessageScenario.TestRunnerMock + .Setup(t => t.RunTestCommand()) + .Callback(() => dotnetTestMessageScenario.TestRunnerChannelMock.Raise( + t => t.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestRunnerTestFound, + Payload = JToken.FromObject("testFound") + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.VersionCheck))) + .Callback(() => dotnetTestMessageScenario.AdapterChannelMock.Raise( + r => r.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestDiscoveryStart + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestDiscoveryTestFound))) + .Callback(() => dotnetTestMessageScenario.TestRunnerChannelMock.Raise( + t => t.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestRunnerTestCompleted + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestDiscoveryCompleted))) + .Callback(() => dotnetTestMessageScenario.AdapterChannelMock.Raise( + r => r.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestSessionTerminate + })) + .Verifiable(); + + dotnetTestMessageScenario.Run(); + } + } +} diff --git a/test/dotnet-test.UnitTests/GivenThatWeWantToRunTests.cs b/test/dotnet-test.UnitTests/GivenThatWeWantToRunTests.cs new file mode 100644 index 000000000..01da29141 --- /dev/null +++ b/test/dotnet-test.UnitTests/GivenThatWeWantToRunTests.cs @@ -0,0 +1,86 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using Microsoft.DotNet.Tools.Test; +using Microsoft.Extensions.Testing.Abstractions; +using Moq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.Dotnet.Tools.Test.Tests +{ + public class GivenThatWeWantToRunTests + { + [Fact] + public void Dotnet_test_handles_and_sends_all_the_right_messages() + { + var dotnetTestMessageScenario = new DotnetTestMessageScenario(); + + dotnetTestMessageScenario.TestRunnerMock + .Setup(t => t.GetProcessStartInfo()) + .Returns(new ProcessStartInfo()) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.VersionCheck))) + .Callback(() => dotnetTestMessageScenario.AdapterChannelMock.Raise( + r => r.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestExecutionGetTestRunnerProcessStartInfo + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send( + It.Is(m => m.MessageType == TestMessageTypes.TestExecutionTestRunnerProcessStartInfo))) + .Callback(() => dotnetTestMessageScenario.TestRunnerChannelMock.Raise( + t => t.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestRunnerTestStarted + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send( + It.Is(m => m.MessageType == TestMessageTypes.TestExecutionStarted))) + .Callback(() => dotnetTestMessageScenario.TestRunnerChannelMock.Raise( + t => t.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestRunnerTestResult + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send( + It.Is(m => m.MessageType == TestMessageTypes.TestExecutionTestResult))) + .Callback(() => dotnetTestMessageScenario.TestRunnerChannelMock.Raise( + t => t.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestRunnerTestCompleted + })) + .Verifiable(); + + dotnetTestMessageScenario.AdapterChannelMock + .Setup(a => a.Send(It.Is(m => m.MessageType == TestMessageTypes.TestExecutionCompleted))) + .Callback(() => dotnetTestMessageScenario.AdapterChannelMock.Raise( + r => r.MessageReceived += null, + dotnetTestMessageScenario.DotnetTestUnderTest, + new Message + { + MessageType = TestMessageTypes.TestSessionTerminate + })) + .Verifiable(); + + dotnetTestMessageScenario.Run(); + } + } +} diff --git a/test/dotnet-test.UnitTests/dotnet-test.UnitTests.xproj b/test/dotnet-test.UnitTests/dotnet-test.UnitTests.xproj new file mode 100644 index 000000000..ceb3b9bdd --- /dev/null +++ b/test/dotnet-test.UnitTests/dotnet-test.UnitTests.xproj @@ -0,0 +1,18 @@ + + + + 14.0.24720 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + 857274ac-e741-4266-a7fd-14dee0c1cc96 + Microsoft.Dotnet.Tools.Test.Tests + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + 2.0 + + + \ No newline at end of file diff --git a/test/dotnet-test.UnitTests/project.json b/test/dotnet-test.UnitTests/project.json new file mode 100644 index 000000000..1183f75f6 --- /dev/null +++ b/test/dotnet-test.UnitTests/project.json @@ -0,0 +1,23 @@ +{ + "version": "1.0.0-*", + + "dependencies": { + "Newtonsoft.Json": "7.0.1", + "NETStandard.Library": "1.0.0-rc2-23811", + + "dotnet": { "target": "project" }, + + "xunit": "2.1.0", + "dotnet-test-xunit": "1.0.0-dev-48273-16", + "moq.netcore": "4.4.0-beta8", + "FluentAssertions": "4.2.2" + }, + + "frameworks": { + "dnxcore50": { + "imports": "portable-net45+win8" + } + }, + + "testRunner": "xunit" +}