Exemplo n.º 1
0
        public static string GetTestFolder <T>(DnxSdk sdk, [CallerMemberName] string testName = null)
        {
            var tempFolderPath = Path.Combine(RootTestFolder, $"{typeof(T).Name}.{testName}", sdk.FullName);

            Directory.CreateDirectory(tempFolderPath);
            return(tempFolderPath);
        }
Exemplo n.º 2
0
        public void Restore_PackageOverProjectTarget(DnxSdk sdk)
        {
            var solution = TestUtils.GetSolution<DnuRestoreTests2>(sdk, "DependencyTargets");
            var bOutputPath = Path.Combine(solution.ArtifactsPath, "B");

            // Build a package for B
            sdk.Dnu.Restore(solution.GetProject("A")).EnsureSuccess();
            sdk.Dnu.Restore(solution.GetProject("B")).EnsureSuccess();
            sdk.Dnu.Pack(
                solution.GetProject("B").ProjectDirectory,
                bOutputPath,
                configuration: "package").EnsureSuccess();
            sdk.Dnu.PackagesAdd(
                Path.Combine(bOutputPath, "package", "B.1.0.0.nupkg"),
                solution.LocalPackagesDir).EnsureSuccess();

            // Restore the app, it'll work but it will choose the package over the project
            sdk.Dnu.Restore(solution.GetProject("App")).EnsureSuccess();

            // Run the app
            var result = sdk.Dnx.Execute(solution.GetProject("App"));

            Assert.Equal(@"A: This is Project A
            B: This is Package B
            ", result.StandardOutput);
        }
Exemplo n.º 3
0
        public static DnxSdk GetRuntime(string flavor, string os, string arch)
        {
            var dnxSolutionRoot      = ProjectRootResolver.ResolveRootDirectory(Directory.GetCurrentDirectory());
            var runtimeHome          = Path.Combine(dnxSolutionRoot, "artifacts", "test", DnxSdk.GetRuntimeName(flavor, os, arch));
            var buildVersion         = Environment.GetEnvironmentVariable("DNX_BUILD_VERSION");
            var sdkVersionForTesting = Environment.GetEnvironmentVariable(TestEnvironmentNames.TestSdkVersion);

            DnxSdk sdk = null;

            if (string.IsNullOrEmpty(sdkVersionForTesting) &&
                Directory.Exists(runtimeHome) &&
                !string.IsNullOrEmpty(buildVersion))
            {
                sdk = DnxSdk.GetRuntime(runtimeHome, $"1.0.0-{buildVersion}", flavor, os, arch);
            }
            else
            {
                sdk = DnxSdk.GetRuntime(SdkVersionForTesting, flavor, os, arch);
            }

            if (!Directory.Exists(sdk.Location))
            {
                throw new InvalidOperationException($"Unable to locate DNX at ${sdk.Location}");
            }

            return(sdk);
        }
Exemplo n.º 4
0
        public void DnuPack_ClientProfile(DnxSdk sdk)
        {
            const string ProjectName = "ClientProfileProject";
            var projectStructure = new Dir
            {
                [ProjectName] = new Dir
                {
                    ["project.json"] = new JObject
                    {
                        ["frameworks"] = new JObject
                        {
                            ["net40-client"] = new JObject(),
                            ["net35-client"] = new JObject()
                        }
                    }
                },
                ["Output"] = new Dir()
            };

            var baseDir = TestUtils.GetTestFolder<DnuPackTests>(sdk);
            var projectDir = Path.Combine(baseDir, ProjectName);
            var outputDir = Path.Combine(baseDir, "Output");
            projectStructure.Save(baseDir);

            sdk.Dnu.Restore(projectDir).EnsureSuccess();
            var result = sdk.Dnu.Pack(projectDir, outputDir);

            Assert.Equal(0, result.ExitCode);
        }
Exemplo n.º 5
0
        public void Restore_ProjectOverPackageTarget(DnxSdk sdk)
        {
            var solution = TestUtils.GetSolution<DnuRestoreTests2>(sdk, "DependencyTargets");
            var aOutputPath = Path.Combine(solution.ArtifactsPath, "A");

            sdk.Dnu.Restore(solution.GetProject("B")).EnsureSuccess();

            // Build a package for A
            sdk.Dnu.Restore(solution.GetProject("A")).EnsureSuccess();
            sdk.Dnu.Pack(
                solution.GetProject("A").ProjectDirectory,
                aOutputPath,
                configuration: "package").EnsureSuccess();
            sdk.Dnu.PackagesAdd(
                Path.Combine(aOutputPath, "package", "A.1.0.0.nupkg"),
                solution.LocalPackagesDir).EnsureSuccess();

            // Delete the project A
            CommonTestUtils.TestUtils.DeleteFolder(solution.GetProject("A").ProjectDirectory);

            // Restore the app, it should fail because the project is gone!
            var result = sdk.Dnu.Restore(solution.GetProject("App"));

            Assert.NotEqual(0, result.ExitCode);
            Assert.Contains("Unable to locate Project A", result.StandardError);
        }
Exemplo n.º 6
0
        public void UnresolvedProjectDoesNotThrow(DnxSdk sdk)
        {
            const string solutionName = "BootstrapperSolution";
            var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName);

            var result = sdk.Dnx.Execute($"--project {solution.RootPath} run");

            Assert.NotEqual(0, result.ExitCode);
            Assert.Equal($"Error: Unable to resolve project from {solution.RootPath}{Environment.NewLine}", result.StandardError);
        }
Exemplo n.º 7
0
        public static Solution GetSolution <TTest>(
            DnxSdk sdk,
            string solutionName,
            [CallerMemberName] string testName  = null,
            bool appendSolutionNameToTestFolder = false)
        {
            var originalSolutionPath = Path.Combine(GetTestSolutionsDirectory(), solutionName);
            var tempSolutionPath     = GetTestFolder <TTest>(sdk, Path.Combine(testName, appendSolutionNameToTestFolder ? solutionName : string.Empty));

            CopyFolder(originalSolutionPath, tempSolutionPath);
            return(new Solution(tempSolutionPath));
        }
        public DnxSdkFunctionalTestFixtureBase()
        {
            Console.WriteLine($@"
Environment information:
  DNX_HOME: {Environment.GetEnvironmentVariable(EnvironmentNames.Home)}
  DNX_TEST_SDK_VERSION: {Environment.GetEnvironmentVariable(TestEnvironmentNames.TestSdkVersion)}

Information of DNX under testing:
  DNX Home: {DnxSdk.GetRuntimeHome()}
  DNX Version: {DnxSdkFunctionalTestBase.SdkVersionForTesting}
");
        }
Exemplo n.º 9
0
        public static void CleanUpTestDir <T>(DnxSdk sdk, [CallerMemberName] string testName = null)
        {
            var saveFilesBehaviour = Environment.GetEnvironmentVariable(TestEnvironmentNames.SaveFiles);

            if (string.IsNullOrEmpty(saveFilesBehaviour) || !saveFilesBehaviour.Equals(TestConstants.SaveFilesAll, StringComparison.OrdinalIgnoreCase))
            {
                var testFolder = GetTestFolder <T>(sdk, testName);
                if (Directory.Exists(testFolder))
                {
                    Directory.Delete(testFolder, recursive: true);
                }
            }
        }
Exemplo n.º 10
0
        public void UserExceptionsThrows(DnxSdk sdk)
        {
            const string solutionName = "BootstrapperSolution";
            const string projectName = "TesterProgram";
            var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName);
            var project = solution.GetProject(projectName);

            sdk.Dnu.Restore(project).EnsureSuccess();
            var result = sdk.Dnx.Execute($"--project {project.ProjectDirectory} run");

            Assert.NotEqual(0, result.ExitCode);
            Assert.Contains("System.Exception: foo", result.StandardError);
        }
Exemplo n.º 11
0
        public IDisposable CreateDisposableTestProject(string projectName, DnxSdk sdk, out string testProjectDir)
        {
            var source = Path.Combine(TestUtils.GetTestSolutionsDirectory(), "DthTestProjects", projectName);
            if (!Directory.Exists(source))
            {
                throw new ArgumentException($"Test project {source} doesn't exist.", nameof(projectName));
            }

            var disposableDir = new DisposableDir();
            CreateDisposableTestProject(sdk, disposableDir, source);

            testProjectDir = Path.Combine(disposableDir, projectName);
            return disposableDir;
        }
Exemplo n.º 12
0
        public void UnknownCommandDoesNotThrow(DnxSdk sdk)
        {
            const string solutionName = "BootstrapperSolution";
            const string projectName = "TesterProgram";
            const string unknownCommand = "unknownCommand";
            const string testerCommand = "TesterProgram";
            var solution = TestUtils.GetSolution<BootstrapperTests>(sdk, solutionName);
            var project = solution.GetProject(projectName);

            var result = sdk.Dnx.Execute($"--project {project.ProjectDirectory} {unknownCommand}");

            Assert.NotEqual(0, result.ExitCode);
            Assert.Equal($"Error: Unable to load application or execute command '{unknownCommand}'. Available commands: {testerCommand}.{Environment.NewLine}", result.StandardError);
        }
Exemplo n.º 13
0
        public void P2PDifferentFrameworks(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DnuPackTests>(sdk, "ProjectToProject");
            var project = solution.GetProject("P1");

            sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

            // Act
            var result = sdk.Dnu.Pack(project.ProjectDirectory);

            // Assert
            Assert.Equal(0, result.ExitCode);
        }
Exemplo n.º 14
0
        public void CompileModuleWithDeps(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DnuPackTests>(sdk, "CompileModuleWithDependencies");
            var project = solution.GetProject("A");

            sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

            // Act
            var result = sdk.Dnu.Pack(project.ProjectDirectory);

            // Assert
            Assert.Equal(0, result.ExitCode);
        }
Exemplo n.º 15
0
        public static string CreateLocalFeed <TTest>(DnxSdk sdk, Solution solution, [CallerMemberName] string testName = null)
        {
            var feed       = GetTestFolder <TTest>(sdk, Path.Combine(testName, Path.GetRandomFileName()));
            var packOutput = GetTestFolder <TTest>(sdk, Path.Combine(testName, Path.GetRandomFileName()));

            sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();
            foreach (var project in solution.Projects)
            {
                var output = sdk.Dnu.Pack(project.ProjectDirectory, packOutput);
                output.EnsureSuccess();
                sdk.Dnu.PackagesAdd(output.PackagePath, feed).EnsureSuccess();
            }

            return(feed);
        }
Exemplo n.º 16
0
        public void CompileModuleWithDeps(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<AppHostTests2>(sdk, "CompileModuleWithDependencies");
            var project = solution.GetProject("A");

            sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

            // Act
            var result = sdk.Dnx.Execute(project);

            // Assert
            Assert.Equal(0, result.ExitCode);
            Assert.Contains($"Hello from generated code", result.StandardOutput);
        }
Exemplo n.º 17
0
        public void ApplicationWithEcmaEntryPoint(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<AppHostTests2>(sdk, "EcmaEntryPoint");
            var project = solution.GetProject("EcmaEntryPoint");

            sdk.Dnu.Restore(project.ProjectDirectory).EnsureSuccess();

            // Act
            var result = sdk.Dnx.Execute(project);

            // Assert
            Assert.Equal(0, result.ExitCode);
            Assert.Contains($"EntryPoint: Main", result.StandardOutput);
        }
Exemplo n.º 18
0
        public void RunP2PDifferentFrameworks(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<AppHostTests2>(sdk, "ProjectToProject");
            var project = solution.GetProject("P1");

            sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

            // Act
            var result = sdk.Dnx.Execute(project);

            // Assert
            Assert.Equal(0, result.ExitCode);
            Assert.Contains("BaseClass.Test()", result.StandardOutput);
            Assert.Contains("Derived.Test", result.StandardOutput);
        }
Exemplo n.º 19
0
        private static void CreateDisposableTestProject(DnxSdk sdk, string targetDir, string sourceDir)
        {
            // Find the misc project to copy
            var targetProjectDir = Path.Combine(targetDir, Path.GetFileName(sourceDir));
            Testing.TestUtils.CopyFolder(sourceDir, targetProjectDir);

            // Make sure package restore can be successful
            var currentDnxSolutionRootDir = ProjectRootResolver.ResolveRootDirectory(Directory.GetCurrentDirectory());

            File.Copy(
                Path.Combine(currentDnxSolutionRootDir, "NuGet.config"),
                Path.Combine(targetProjectDir, "NuGet.config"));

            // Use the newly built runtime to generate lock files for samples
            sdk.Dnu.Restore(targetProjectDir);
        }
Exemplo n.º 20
0
        public void LibraryExporterGetExports(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<AppHostTests2>(sdk, "AppHostServicesProjects");
            var project = solution.GetProject("GetExports");

            sdk.Dnu.Restore(project.ProjectDirectory).EnsureSuccess();

            // Act
            var result = sdk.Dnx.Execute(project);

            // Assert
            Assert.Equal(0, result.ExitCode);
            Assert.Contains($"Project: {project.Name}", result.StandardOutput);
            Assert.Contains($"Package: Microsoft.Dnx.Compilation.Abstractions", result.StandardOutput);
        }
Exemplo n.º 21
0
        public void DthStartup_GetProjectInformation(DnxSdk sdk)
        {
            var projectName = "EmptyConsoleApp";
            var testProject = _fixture.GetTestProjectPath(projectName);

            using (var server = DthTestServer.Create(sdk))
            using (var client = new DthTestClient(server))
            {
                client.Initialize(testProject);

                var projectInformation = client.DrainAllMessages()
                                               .RetrieveSingleMessage("ProjectInformation")
                                               .EnsureSource(server, client)
                                               .RetrievePayloadAs<JObject>()
                                               .AssertProperty("Name", projectName);

                projectInformation.RetrievePropertyAs<JArray>("Configurations")
                                  .AssertJArrayCount(2)
                                  .AssertJArrayContains("Debug")
                                  .AssertJArrayContains("Release");

                var frameworkShortNames = projectInformation.RetrievePropertyAs<JArray>("Frameworks")
                                                            .AssertJArrayCount(2)
                                                            .Select(f => f["ShortName"].Value<string>());

                Assert.Contains("dnxcore50", frameworkShortNames);
                Assert.Contains("dnx451", frameworkShortNames);
            }
        }
Exemplo n.º 22
0
        public void PublishedAppWithWebRootFailsIfIISCommandInvalid(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DnuPublishTests2>(sdk, "HelloWorldWithWebRoot");
            var outputPath = Path.Combine(solution.RootPath, "Output");
            var project = solution.GetProject("HelloWorldWithWebRoot");

            // Act
            sdk.Dnu.Restore(project).EnsureSuccess();
            var result = sdk.Dnu.Publish(project.ProjectDirectory, outputPath, $"--iis-command SomethingRandom");

            Assert.NotEqual(0, result.ExitCode);
        }
Exemplo n.º 23
0
        public static DthTestServer Create(DnxSdk sdk, TimeSpan timeout)
        {
            var bootstraperExe = Path.Combine(sdk.Location, "bin", Constants.BootstrapperExeName);

            var dthPath = Path.Combine(sdk.Location, "bin", "lib", DthName, $"{DthName}.dll");
            if (!File.Exists(dthPath))
            {
                throw new InvalidOperationException($"Can't find {DthName} at {dthPath}.");
            }

            var port = FindFreePort();
            var hostId = Guid.NewGuid().ToString();
            var processStartInfo = new ProcessStartInfo()
            {
                UseShellExecute = false,
                WorkingDirectory = sdk.Location,
                FileName = bootstraperExe,
                Arguments = $"--appbase \"{sdk.Location}\" \"{dthPath}\" {port} {Process.GetCurrentProcess().Id} {hostId}",
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            var wait = new ManualResetEvent(false);
            var success = false;
            var successOuput = $"Listening on port {port}";

            var process = Process.Start(processStartInfo);
            process.EnableRaisingEvents = true;

            var stdout = new StringBuilder();
            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    stdout.AppendLine(Exec.RemoveAnsiColorCodes(args.Data));

                    if (string.Equals(args.Data, successOuput, StringComparison.Ordinal))
                    {
                        success = true;
                        wait.Set();
                    }
                }
            };

            var stderr = new StringBuilder();
            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    stderr.AppendLine(Exec.RemoveAnsiColorCodes(args.Data));
                }
            };

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (wait.WaitOne(timeout))
            {
                if (!success)
                {
                    Console.WriteLine(stdout);
                    Console.WriteLine(stderr);

                    throw new InvalidOperationException($"Failed to start DesignTime host.");
                }
                else
                {
                    return new DthTestServer(process, port, hostId);
                }
            }
            else
            {
                throw new InvalidOperationException($"Timeout after {timeout.TotalSeconds}. Expected message {successOuput} from STDOUT to indicate that DTH is started successfully.");
            }
        }
Exemplo n.º 24
0
 public static DthTestServer Create(DnxSdk sdk)
 {
     return Create(sdk, TimeSpan.FromSeconds(10));
 }
Exemplo n.º 25
0
        public void PublishWrappedProjectForSpecificFramework(DnxSdk sdk)
        {
            var solutionName = Path.Combine("DnuWrapTestSolutions", "WrapAndPublish");
            var solution = TestUtils.GetSolution<DnuPublishTests2>(sdk, solutionName);

            // Restore the wrapper project
            sdk.Dnu.Restore(solution.GetWrapperProjectPath("ClassLibrary")).EnsureSuccess();
            sdk.Dnu.Restore(solution.GetProject("DnxConsoleApp")).EnsureSuccess();

            // Build the console app in Debug mode (we specify the config explicitly since dnx here defaults to a Debug
            // build but on the CI we might have the Configuration environment variable set so that MSBuild builds as Release by default).
            var msbuild = CommonTestUtils.TestUtils.ResolveMSBuildPath();
            Exec.Run(msbuild, "/p:Configuration=Debug", workingDir: Path.Combine(solution.SourcePath, "ClassLibrary")).EnsureSuccess(); ;

            // Publish the console app
            sdk.Dnu.Publish(solution.GetProject("DnxConsoleApp").ProjectFilePath, solution.ArtifactsPath, "--framework dnx451").EnsureSuccess();

            // Get an SDK we can use the RUN the wrapped project (it has to be CLR because the project only supports dnx451)
            var clrSdk = GetRuntime("clr", "win", "x86");

            // Run it
            var outputPath = Path.Combine(solution.ArtifactsPath, "approot", "src", "DnxConsoleApp");
            var result = clrSdk.Dnx.Execute(
                commandLine: $"--project \"{outputPath}\" --configuration Debug DnxConsoleApp run")
                .EnsureSuccess();
            Assert.Contains($"Hello from the wrapped project{Environment.NewLine}", result.StandardOutput);
        }
Exemplo n.º 26
0
        public void GlobalJsonInProjectDir(DnxSdk sdk)
        {
            const string solutionName = "GlobalJsonInProjectDir";

            var solution = TestUtils.GetSolution<DnuPublishTests>(sdk, solutionName);
            var projectPath = Path.Combine(solution.RootPath, "Project");
            var outputPath = Path.Combine(solution.RootPath, "Output");

            var expectedOutputProjectJson = new JObject
            {
                ["dependencies"] = new JObject { },
                ["frameworks"] = new JObject
                {
                    ["dnx451"] = new JObject { },
                    ["dnxcore50"] = new JObject { }
                }
            };

            var expectedOutputGlobalJson = new JObject
            {
                ["sdk"] = new JObject
                {
                    ["version"] = "1.0.0-beta7"
                },
                ["projects"] = new JArray("src"),
                ["packages"] = "packages"
            };

            var expectedOutputLockFile = new JObject
            {
                ["locked"] = false,
                ["version"] = Constants.LockFileVersion,
                ["targets"] = new JObject
                {
                    ["DNX,Version=v4.5.1"] = new JObject { },
                    ["DNXCore,Version=v5.0"] = new JObject { },
                },
                ["libraries"] = new JObject { },
                ["projectFileDependencyGroups"] = new JObject
                {
                    [""] = new JArray(),
                    ["DNX,Version=v4.5.1"] = new JArray(),
                    ["DNXCore,Version=v5.0"] = new JArray()
                }
            };
            var expectedOutputStructure = new Dir
            {
                ["approot"] = new Dir
                {
                    [$"src/Project"] = new Dir
                    {
                        ["project.json"] = expectedOutputProjectJson,
                        ["project.lock.json"] = expectedOutputLockFile
                    },
                    [$"global.json"] = expectedOutputGlobalJson
                }
            };

            var result = sdk.Dnu.Publish(
                projectPath,
                outputPath);
            result.EnsureSuccess();

            var actualOutputStructure = new Dir(outputPath);
            DirAssert.Equal(expectedOutputStructure, actualOutputStructure);
        }
Exemplo n.º 27
0
 public static string GetTempTestFolder <T>(DnxSdk sdk, [CallerMemberName] string testName = null)
 {
     return(GetTestFolder <T>(sdk, Path.Combine(testName, Path.GetRandomFileName())));
 }
Exemplo n.º 28
0
        public void DthStartup_ProtocolNegotiation_ZeroIsNoAllowed(DnxSdk sdk)
        {
            var projectName = "EmptyConsoleApp";
            var testProject = _fixture.GetTestProjectPath(projectName);

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                client.SetProtocolVersion(0);

                Assert.Throws<TimeoutException>(() =>
                {
                    client.DrainTillFirst(ProtocolManager.NegotiationMessageTypeName);
                });
            }
        }
Exemplo n.º 29
0
        public void DthStartup_ProtocolNegotiation(DnxSdk sdk, int requestVersion, int expectVersion)
        {
            var projectName = "EmptyConsoleApp";
            var testProject = _fixture.GetTestProjectPath(projectName);

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                client.SetProtocolVersion(requestVersion);

                var response = client.DrainTillFirst(ProtocolManager.NegotiationMessageTypeName);
                response.EnsureSource(server, client);

                Assert.Equal(expectVersion, response.Payload["Version"]?.Value<int>());
            }
        }
Exemplo n.º 30
0
        public void DthNegative_BrokenProjectPathInLockFile_V2(DnxSdk sdk)
        {
            var testProject = _fixture.GetTestProjectPath("BrokenProjectPathSample");

            using (var disposableDir = new DisposableDir())
            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                // copy the project to difference location so that the project path in its lock file is invalid
                var targetPath = Path.Combine(disposableDir, "BrokenProjectPathSample");
                Testing.TestUtils.CopyFolder(testProject, targetPath);

                client.Initialize(targetPath, protocolVersion: 2);
                var messages = client.DrainAllMessages()
                                     .AssertDoesNotContain("Error");

                messages.RetrieveSingleMessage("DependencyDiagnostics")
                        .RetrieveDependencyDiagnosticsCollection()
                        .RetrieveDependencyDiagnosticsErrorAt(0)
                        .AssertProperty<string>("FormattedMessage", message => message.Contains("error NU1001: The dependency EmptyLibrary  could not be resolved."))
                        .RetrievePropertyAs<JObject>("Source")
                        .AssertProperty("Name", "EmptyLibrary");

                messages.RetrieveSingleMessage("Dependencies")
                        .RetrieveDependency("EmptyLibrary")
                        .AssertProperty<JArray>("Errors", errorsArray => errorsArray.Count == 1)
                        .AssertProperty<JArray>("Warnings", warningsArray => warningsArray.Count == 0)
                        .AssertProperty("Name", "EmptyLibrary")
                        .AssertProperty("Resolved", false);
            }
        }
Exemplo n.º 31
0
        public void DthDependencies_UpdateGlobalJson_RefreshDependencies(DnxSdk sdk)
        {
            using (var disposableDir = new DisposableDir())
            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                Testing.TestUtils.CopyFolder(
                    _fixture.GetTestProjectPath("UpdateSearchPathSample"),
                    Path.Combine(disposableDir, "UpdateSearchPathSample"));

                var root = Path.Combine(disposableDir, "UpdateSearchPathSample", "home");
                sdk.Dnu.Restore(root).EnsureSuccess();

                var testProject = Path.Combine(root, "src", "MainProject");

                client.Initialize(testProject, protocolVersion: 2);
                var messages = client.DrainAllMessages();

                messages.RetrieveSingleMessage("ProjectInformation")
                        .RetrievePayloadAs<JObject>()
                        .RetrievePropertyAs<JArray>("ProjectSearchPaths")
                        .AssertJArrayCount(2);

                messages.RetrieveSingleMessage("Dependencies")
                        .RetrieveDependency("Newtonsoft.Json")
                        .AssertProperty("Type", "Project")
                        .AssertProperty("Resolved", true)
                        .AssertProperty<JArray>("Errors", array => array.Count == 0, _ => "Dependency shouldn't contain any error.");

                messages.RetrieveSingleMessage("DependencyDiagnostics")
                        .RetrievePayloadAs<JObject>()
                        .AssertProperty<JArray>("Errors", array => array.Count == 0)
                        .AssertProperty<JArray>("Warnings", array => array.Count == 0);

                // Overwrite the global.json to remove search path to ext
                File.WriteAllText(
                    Path.Combine(root, GlobalSettings.GlobalFileName),
                    JsonConvert.SerializeObject(new { project = new string[] { "src" } }));

                client.SendPayLoad(testProject, "RefreshDependencies");
                messages = client.DrainAllMessages();

                messages.RetrieveSingleMessage("ProjectInformation")
                        .RetrievePayloadAs<JObject>()
                        .RetrievePropertyAs<JArray>("ProjectSearchPaths")
                        .AssertJArrayCount(1)
                        .AssertJArrayElement(0, Path.Combine(root, "src"));

                messages.RetrieveSingleMessage("Dependencies")
                        .RetrieveDependency("Newtonsoft.Json")
                        .AssertProperty("Type", LibraryTypes.Unresolved)
                        .AssertProperty("Resolved", false)
                        .RetrievePropertyAs<JArray>("Errors")
                        .AssertJArrayCount(1)
                        .RetrieveArraryElementAs<JObject>(0)
                        .AssertProperty("ErrorCode", "NU1010");

                messages.RetrieveSingleMessage("DependencyDiagnostics")
                        .RetrieveDependencyDiagnosticsCollection()
                        .RetrieveDependencyDiagnosticsErrorAt<JObject>(0)
                        .AssertProperty("ErrorCode", "NU1010");
            }
        }
Exemplo n.º 32
0
        public void DthCompilation_RestoreComplete_OnEmptyLibrary(DnxSdk sdk, int protocolVersion)
        {
            var projectName = "EmptyLibrary";

            string testProject;
            using (_fixture.CreateDisposableTestProject(projectName, sdk, out testProject))
            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                // Drain the inital messages
                client.Initialize(testProject, protocolVersion);

                client.DrainTillFirst("Dependencies")
                      .EnsureSource(server, client)
                      .EnsureNotContainDependency("System.Console");

                File.Copy(Path.Combine(testProject, "project-update.json"),
                          Path.Combine(testProject, "project.json"),
                          overwrite: true);

                sdk.Dnu.Restore(testProject).EnsureSuccess();

                client.SendPayLoad(testProject, "RestoreComplete");

                client.DrainTillFirst("Dependencies")
                       .EnsureSource(server, client)
                       .RetrieveDependency("System.Console");
            }
        }
Exemplo n.º 33
0
        public void DthCompilation_Initialize_UnresolvedDependency(DnxSdk sdk, int protocolVersion, string referenceType, string testProjectName,
                                                                   string expectedUnresolvedDependency, string expectedUnresolvedType)
        {
            var testProject = _fixture.GetTestProjectPath(testProjectName);

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                client.Initialize(testProject, protocolVersion);

                var messages = client.DrainAllMessages();

                var unresolveDependency = messages.RetrieveSingleMessage("Dependencies")
                                                  .EnsureSource(server, client)
                                                  .RetrieveDependency(expectedUnresolvedDependency);
                unresolveDependency.AssertProperty("Name", expectedUnresolvedDependency)
                                   .AssertProperty("DisplayName", expectedUnresolvedDependency)
                                   .AssertProperty("Resolved", false)
                                   .AssertProperty("Type", expectedUnresolvedType);

                if (expectedUnresolvedType == "Project")
                {
                    unresolveDependency.AssertProperty(
                        "Path",
                        Path.Combine(Path.GetDirectoryName(testProject), expectedUnresolvedDependency, Project.ProjectFileName));
                }
                else
                {
                    Assert.False(unresolveDependency["Path"].HasValues);
                }

                var referencesMessage = messages.RetrieveSingleMessage("References")
                                                .EnsureSource(server, client);

                if (referenceType == "Project")
                {
                    var expectedUnresolvedProjectPath = Path.Combine(Path.GetDirectoryName(testProject), expectedUnresolvedDependency, Project.ProjectFileName);

                    referencesMessage.RetrievePayloadAs<JObject>()
                                     .RetrievePropertyAs<JArray>("ProjectReferences")
                                     .AssertJArrayCount(1)
                                     .RetrieveArraryElementAs<JObject>(0)
                                     .AssertProperty("Name", expectedUnresolvedDependency)
                                     .AssertProperty("Path", expectedUnresolvedProjectPath)
                                     .AssertProperty<JToken>("WrappedProjectPath", prop => !prop.HasValues);
                }
                else if (referenceType == "Package")
                {
                    referencesMessage.RetrievePayloadAs<JObject>()
                                     .RetrievePropertyAs<JArray>("ProjectReferences")
                                     .AssertJArrayCount(0);
                }
            }
        }
Exemplo n.º 34
0
        public void DthCompilation_GetDiagnostics_OnEmptyConsoleApp(DnxSdk sdk, int protocolVersion)
        {
            var projectName = "EmptyConsoleApp";
            var testProject = _fixture.GetTestProjectPath(projectName);

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                // Drain the inital messages
                client.Initialize(testProject, protocolVersion);
                client.SendPayLoad(testProject, "GetDiagnostics");

                var diagnosticsGroup = client.DrainTillFirst("AllDiagnostics")
                                             .EnsureSource(server, client)
                                             .RetrievePayloadAs<JArray>()
                                             .AssertJArrayCount(3);

                foreach (var group in diagnosticsGroup)
                {
                    group.AsJObject()
                         .AssertProperty<JArray>("Errors", errorsArray => !errorsArray.Any())
                         .AssertProperty<JArray>("Warnings", warningsArray => !warningsArray.Any());
                }
            }
        }
Exemplo n.º 35
0
        public void CompileModuleWithDeps(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DthStartupTests>(sdk, "CompileModuleWithDependencies");
            var project = solution.GetProject("A");

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

                client.Initialize(project.ProjectDirectory);

                client.SendPayLoad(project, "GetDiagnostics");

                var messages = client.DrainAllMessages();

                // Assert
                messages.AssertDoesNotContain("Error");

                var diagnosticsPerFramework = messages.RetrieveSingleMessage("AllDiagnostics")
                                                      .RetrievePayloadAs<JArray>()
                                                      .AssertJArrayCount(3);

                foreach (var frameworkDiagnostics in diagnosticsPerFramework)
                {
                    var errors = frameworkDiagnostics.Value<JArray>("Errors");
                    var warnings = frameworkDiagnostics.Value<JArray>("Warnings");
                    Assert.Equal(0, errors.Count);
                    Assert.Equal(0, warnings.Count);
                }
            }
        }
Exemplo n.º 36
0
        public void AddDepsReturnsReferences(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DthStartupTests>(sdk, "HelloWorld");
            var project = solution.GetProject("HelloWorld");

            using (var server = DthTestServer.Create(sdk))
            using (var client = server.CreateClient())
            {
                sdk.Dnu.Restore(solution.RootPath).EnsureSuccess();

                client.SetProtocolVersion(3);

                client.Initialize(project.ProjectDirectory);

                var messages = client.DrainAllMessages();

                foreach (var frameworkInfo in project.GetTargetFrameworks())
                {
                    var messagesByFramework = messages.GetMessagesByFramework(frameworkInfo.FrameworkName);

                    messagesByFramework.RetrieveSingleMessage("Dependencies")
                                       .RetrieveDependency("Newtonsoft.Json")
                                       .AssertProperty("Type", LibraryTypes.Package);

                    var references = messagesByFramework.RetrieveSingleMessage("References")
                                                        .RetrievePayloadAs<JObject>()
                                                        .RetrievePropertyAs<JArray>("FileReferences");

                    Assert.NotEmpty(references);
                    Assert.Contains("Newtonsoft.Json", references.Select(r => Path.GetFileNameWithoutExtension(r.Value<string>())));
                }

                // Update dependencies
                project = project.UpdateProjectFile(json =>
                {
                    json["dependencies"]["DoesNotExist"] = "1.0.0";
                });

                client.SendPayLoad(project, "FilesChanged");

                messages = client.DrainAllMessages();

                foreach (var frameworkInfo in project.GetTargetFrameworks())
                {
                    var messagesByFramework = messages.GetMessagesByFramework(frameworkInfo.FrameworkName);

                    var dependencies = messagesByFramework.RetrieveSingleMessage("Dependencies");

                    dependencies.RetrieveDependency("Newtonsoft.Json")
                                .AssertProperty("Type", LibraryTypes.Package);

                    dependencies.RetrieveDependency("DoesNotExist")
                                .AssertProperty("Type", LibraryTypes.Unresolved);

                    // The references should not have changed
                    messagesByFramework.AssertDoesNotContain("References");
                }

                client.SendPayLoad(project, "GetDiagnostics");

                messages = client.DrainAllMessages();

                var diagnosticsPerFramework = messages.RetrieveSingleMessage("AllDiagnostics")
                                                      .RetrievePayloadAs<JArray>()
                                                      .AssertJArrayCount(3);

                foreach (var frameworkDiagnostics in diagnosticsPerFramework)
                {
                    if (!frameworkDiagnostics["Framework"].HasValues)
                    {
                        continue;
                    }

                    var errors = frameworkDiagnostics.Value<JArray>("Errors");
                    var warnings = frameworkDiagnostics.Value<JArray>("Warnings");
                    Assert.Equal(2, errors.Count);
                    Assert.Equal(0, warnings.Count);

                    var error1 = errors[0];
                    var error2 = errors[1];

                    Assert.Equal("NU1006", error1.Value<string>("ErrorCode"));
                    Assert.Equal("NU1001", error2.Value<string>("ErrorCode"));
                    Assert.Equal("DoesNotExist", error2["Source"].Value<string>("Name"));
                }
            }
        }
Exemplo n.º 37
0
        public void PublishedAppWithWebRootDefaults(DnxSdk sdk)
        {
            // Arrange
            var solution = TestUtils.GetSolution<DnuPublishTests2>(sdk, "HelloWorldWithWebRoot");
            var outputPath = Path.Combine(solution.RootPath, "Output");
            var project = solution.GetProject("HelloWorldWithWebRoot");

            // Act
            sdk.Dnu.Restore(project).EnsureSuccess();
            sdk.Dnu.Publish(project.ProjectDirectory, outputPath).EnsureSuccess();

            var config = File.ReadAllText(Path.Combine(outputPath, project.WebRoot, "web.config"));

            var expected = @"<configuration>
              <system.webServer>
            <handlers>
              <add name=""httpplatformhandler"" path=""*"" verb=""*"" modules=""httpPlatformHandler"" resourceType=""Unspecified"" />
            </handlers>
            <httpPlatform processPath=""..\approot\HelloWorld.cmd"" arguments="""" stdoutLogEnabled=""true"" stdoutLogFile=""..\logs\stdout.log""></httpPlatform>
              </system.webServer>
            </configuration>";

            Assert.Equal(RemoveWhitespace(expected), RemoveWhitespace(config));
        }