Exemple #1
0
        public async Task FrontendBackendAzureFunctionTest()
        {
            // Install to directory
            using var tmp = TempDirectory.Create();
            await ProcessUtil.RunAsync("npm", "install azure-functions-core-tools@3`", workingDirectory : tmp.DirectoryPath);

            using var projectDirectory = CopyTestProjectDirectory("azure-functions");

            var content = @$ "
# tye application configuration file
# read all about it at https://github.com/dotnet/tye
name: frontend-backend
services:
- name: backend
  azureFunction: backend/
  pathToFunc: {tmp.DirectoryPath}/node_modules/azure-functions-core-tools/bin/func.dll
Exemple #2
0
        public void ExecuteScriptActionTest(ScriptLanguage language, string script)
        {
            using (var tempDir = TempDirectory.Create())
            {
                var game = new Game()
                {
                    InstallDirectory = tempDir.TempPath
                };

                var editor = new GamesEditor(null, new GameControllerFactory(null), new PlayniteSettings(), null, null, null);
                editor.ExecuteScriptAction(language, script, game);
                var testPath = Path.Combine(tempDir.TempPath, executeScriptActionTestFileName);
                var content  = File.ReadAllText(testPath);
                Assert.AreEqual(language.ToString(), content.Trim());
            }
        }
        public void ExecuteScriptActionTest(PowerShellRuntime runtime, string script)
        {
            using (var tempDir = TempDirectory.Create())
            {
                var game = new Game()
                {
                    InstallDirectory = tempDir.TempPath
                };

                var editor = new GamesEditor(null, new GameControllerFactory(null), new PlayniteSettings(), null, null, new TestPlayniteApplication());
                editor.ExecuteScriptAction(runtime, script, game, true, false, GameScriptType.None);
                var testPath = Path.Combine(tempDir.TempPath, executeScriptActionTestFileName);
                var content  = File.ReadAllText(testPath);
                Assert.AreEqual("PowerShell", content.Trim());
            }
        }
        public void BasicTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                db.Games.Add(new List <Game>
                {
                    new Game("Game 1"),
                    new Game("Steam game 1")
                    {
                        IsInstalled = true,
                        Hidden      = true
                    },
                    new Game("Origin game 1")
                    {
                    },
                    new Game("GOG game 1")
                    {
                        Hidden = true
                    },
                    new Game("GOG game 2")
                    {
                        Hidden = false
                    }
                });

                var stats = new DatabaseStats(db);

                Assert.AreEqual(5, stats.Total);
                Assert.AreEqual(1, stats.Installed);
                Assert.AreEqual(2, stats.Hidden);
                Assert.AreEqual(0, stats.Favorite);

                var newGame = new Game("Game 2")
                {
                    Favorite = true
                };
                db.Games.Add(newGame);
                Assert.AreEqual(6, stats.Total);
                Assert.AreEqual(1, stats.Favorite);

                newGame.IsInstalled = true;
                db.Games.Update(newGame);
                Assert.AreEqual(2, stats.Installed);
            }
        }
Exemple #5
0
    public async Task ShadowCopyCleansUpOlderFolders()
    {
        using var directory = TempDirectory.Create();
        var deploymentParameters = Fixture.GetBaseDeploymentParameters();

        deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
        deploymentParameters.HandlerSettings["shadowCopyDirectory"]          = directory.DirectoryPath;
        var deploymentResult = await DeployAsync(deploymentParameters);

        // Start with a bunch of junk
        DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "1"), copySubDirs: true);
        DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "3"), copySubDirs: true);
        DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "10"), copySubDirs: true);

        var response = await deploymentResult.HttpClient.GetAsync("Wow!");

        Assert.True(response.IsSuccessStatusCode);

        using var secondTempDir = TempDirectory.Create();

        // copy back and forth to cause file change notifications.
        DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
        DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true);

        response = await deploymentResult.HttpClient.GetAsync("Wow!");

        Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "0")), "Expected 0 shadow copy directory to be skipped");

        // Depending on timing, this could result in a shutdown failure, but sometimes it succeeds, handle both situations
        if (!response.IsSuccessStatusCode)
        {
            Assert.True(response.ReasonPhrase == "Application Shutting Down" || response.ReasonPhrase == "Server has been shutdown");
        }

        // This shutdown should trigger a copy to the next highest directory, which will be 11
        await deploymentResult.AssertRecycledAsync();

        Assert.True(Directory.Exists(Path.Combine(directory.DirectoryPath, "11")), "Expected 11 shadow copy directory");

        response = await deploymentResult.HttpClient.GetAsync("Wow!");

        Assert.True(response.IsSuccessStatusCode);

        // Verify old directories were cleaned up
        Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "1")), "Expected 1 shadow copy directory to be deleted");
        Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "3")), "Expected 3 shadow copy directory to be deleted");
    }
        public void ImageReplaceTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var game = new Game()
                {
                    GameId = "testid",
                    Name   = "Test Game"
                };

                var origIcon       = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                var origImage      = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                var origBackground = db.AddFile(PlayniteTests.GenerateFakeFile(), game.Id);
                game.Icon            = origIcon;
                game.CoverImage      = origImage;
                game.BackgroundImage = origBackground;
                db.Games.Add(game);

                var newIcon       = PlayniteTests.GenerateFakeFile();
                var newImage      = PlayniteTests.GenerateFakeFile();
                var newBackground = PlayniteTests.GenerateFakeFile();
                File.WriteAllBytes(Path.Combine(temp.TempPath, newIcon.FileName), newIcon.Content);
                File.WriteAllBytes(Path.Combine(temp.TempPath, newImage.FileName), newImage.Content);
                File.WriteAllBytes(Path.Combine(temp.TempPath, newBackground.FileName), newBackground.Content);

                // Images are replaced
                var model = new GameEditViewModel(game, db, new MockWindowFactory(), new MockDialogsFactory(), new MockResourceProvider(), null);
                model.EditingGame.Icon            = Path.Combine(temp.TempPath, newIcon.FileName);
                model.EditingGame.CoverImage      = Path.Combine(temp.TempPath, newImage.FileName);
                model.EditingGame.BackgroundImage = Path.Combine(temp.TempPath, newBackground.FileName);
                model.ConfirmDialog();

                Assert.AreNotEqual(game.Icon, origIcon);
                Assert.AreNotEqual(game.CoverImage, origImage);
                Assert.AreNotEqual(game.BackgroundImage, origBackground);

                var dbFiles = Directory.GetFiles(db.GetFileStoragePath(game.Id));
                Assert.AreEqual(3, dbFiles.Count());
                CollectionAssert.AreEqual(newIcon.Content, File.ReadAllBytes(db.GetFullFilePath(game.Icon)));
                CollectionAssert.AreEqual(newImage.Content, File.ReadAllBytes(db.GetFullFilePath(game.CoverImage)));
                CollectionAssert.AreEqual(newBackground.Content, File.ReadAllBytes(db.GetFullFilePath(game.BackgroundImage)));
            }
        }
Exemple #7
0
        public async Task FrontendBackendPurgeTest()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "frontend-backend"));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile   = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));
            var tyeDir        = new DirectoryInfo(Path.Combine(tempDirectory.DirectoryPath, ".tye"));
            var outputContext = new OutputContext(_sink, Verbosity.Debug);
            var application   = await ApplicationFactory.CreateAsync(outputContext, projectFile);

            var host = new TyeHost(application.ToHostingApplication(), Array.Empty <string>())
            {
                Sink = _sink,
            };

            try
            {
                await TestHelpers.StartHostAndWaitForReplicasToStart(host);

                try
                {
                    var pids = GetAllAppPids(host.Application);

                    Assert.True(Directory.Exists(tyeDir.FullName));
                    Assert.Subset(new HashSet <int>(GetAllPids()), new HashSet <int>(pids));

                    await TestHelpers.PurgeHostAndWaitForGivenReplicasToStop(host,
                                                                             GetAllReplicasNames(host.Application));

                    var runningPids = new HashSet <int>(GetAllPids());
                    Assert.True(pids.All(pid => !runningPids.Contains(pid)));
                }
                finally
                {
                    await host.StopAsync();
                }
            }
            finally
            {
                host.Dispose();
                Assert.False(Directory.Exists(tyeDir.FullName));
            }
        }
Exemple #8
0
        public void SingleProjectInitTest()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "single-project", "test-project"));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            File.Delete(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "test-project.csproj"));

            var(content, _) = InitHost.CreateTyeFileContent(projectFile, force: false);
            var expectedContent = File.ReadAllText("testassets/init/single-project.yaml");

            output.WriteLine(content);

            Assert.Equal(expectedContent.NormalizeNewLines(), content.NormalizeNewLines());
        }
        public void ExecuteFileTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new PowerShellRuntime("ExecuteFileTest"))
                {
                    var filePath = Path.Combine(tempDir.TempPath, "ExecuteFileTest.ps1");
                    File.WriteAllText(filePath, @"
param($FileArgs)
return $FileArgs.Arg1 + $FileArgs.Arg2
");
                    var res = runtime.ExecuteFile(filePath, null, new Dictionary <string, object>
                    {
                        { "Arg1", 2 },
                        { "Arg2", 3 }
                    });
                    Assert.AreEqual(5, res);
                }
        }
        public void CreateTempFileInConcreteDirectoryTest()
        {
            var    extension = ".dwg";
            string path;

            using (var tempDir = TempDirectory.Create())
            {
                using (var tempFile = TempFile.Create(extension: extension, content: new byte[0], parentDir: tempDir.Path))
                {
                    path = tempFile.Path;
                    Assert.That(File.Exists(path));
                    Assert.That(Path.GetExtension(path), Is.EqualTo(extension));
                    Assert.That(Path.GetDirectoryName(path), Is.EqualTo(tempDir.Path));
                }
            }

            Assert.That(File.Exists(path), Is.False);
        }
Exemple #11
0
        public void EventsInvokeCountNonBufferedTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var itemUpdates = 0;
                var colUpdates  = 0;
                var col         = new ItemCollection <DatabaseObject>(temp.TempPath);
                col.ItemUpdated           += (e, args) => itemUpdates++;
                col.ItemCollectionChanged += (e, args) => colUpdates++;

                var item = new DatabaseObject();
                col.Add(item);
                col.Update(item);
                col.Remove(item);
                Assert.AreEqual(1, itemUpdates);
                Assert.AreEqual(2, colUpdates);
            }
        }
Exemple #12
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new PowerShellRuntime("ExecuteWorkDirTest"))
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt");
                    FileAssert.Exists(outPath);

                    outPath = Path.Combine(tempDir.TempPath, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt", tempDir.TempPath);
                    FileAssert.Exists(outPath);
                }
        }
Exemple #13
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new BatchRuntime())
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"echo test> workDirTest.txt");
                    FileAssert.Exists(outPath);

                    outPath = Path.Combine(tempDir.TempPath, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"echo test> workDirTest.txt", tempDir.TempPath);
                    FileAssert.Exists(outPath);
                }
        }
Exemple #14
0
        public async Task FrontendBackendGenerateTest()
        {
            await DockerAssert.DeleteDockerImagesAsync(output, "test/backend");

            await DockerAssert.DeleteDockerImagesAsync(output, "test/frontend");

            var projectName = "frontend-backend";
            var environment = "production";

            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", projectName));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));

            var application = ConfigFactory.FromFile(projectFile);

            // Need to add docker registry for generate
            application.Registry = "test";

            try
            {
                await GenerateHost.ExecuteGenerateAsync(new OutputContext(sink, Verbosity.Debug), application, environment, interactive : false);

                // name of application is the folder
                var content         = File.ReadAllText(Path.Combine(tempDirectory.DirectoryPath, $"{projectName}-generate-{environment}.yaml"));
                var expectedContent = File.ReadAllText($"testassets/generate/{projectName}.yaml");

                Assert.Equal(expectedContent, content);

                await BuildHost.ExecuteBuildAsync(new OutputContext(sink, Verbosity.Debug), application, environment, interactive : false);

                await DockerAssert.AssertImageExistsAsync(output, "test/backend");

                await DockerAssert.AssertImageExistsAsync(output, "test/frontend");
            }
            finally
            {
                await DockerAssert.DeleteDockerImagesAsync(output, "test/backend");

                await DockerAssert.DeleteDockerImagesAsync(output, "test/frontend");
            }
        }
        public void GetFunctionTest()
        {
            using (var tempDir = TempDirectory.Create())
            {
                using (var ps = new PowerShellRuntime("GetFunctionTest"))
                {
                    Assert.IsTrue(ps.GetFunction("TestFunc") == null);
                    var path = Path.Combine(tempDir.TempPath, "GetFunctionTest.psm1");
                    File.WriteAllText(path, @"
function TestFunc()
{
    return 4 + 4
}
");
                    ps.ImportModule(path);
                    Assert.IsTrue(ps.GetFunction("TestFunc") != null);
                }
            }
        }
Exemple #16
0
        public void FrontendBackendTest()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "frontend-backend"));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            // delete already present yaml
            File.Delete(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "frontend-backend.sln"));

            var(content, _) = InitHost.CreateTyeFileContent(projectFile, force: false);
            var expectedContent = File.ReadAllText("testassets/init/frontend-backend.yaml");

            output.WriteLine(content);

            Assert.Equal(expectedContent.NormalizeNewLines(), content.NormalizeNewLines());
        }
Exemple #17
0
        public async Task <MutationTestResult> Run(Config config)
        {
            var baseTempDirectory = TempDirectory.Create();

            try
            {
                CreateTempDirectories(baseTempDirectory, config);

                var mutationJobs = await MutationJobList.Create(config, coverageAnalysisResult);

                var survivingMutants = await mutationJobs.RunAll(testRunner, baseTempDirectory, eventListener);

                return(new MutationTestResult().WithSurvivingMutants(survivingMutants));
            }
            finally
            {
                Directory.Delete(baseTempDirectory, recursive: true);
            }
        }
Exemple #18
0
        public async Task MultipleProjectBuildTest()
        {
            await DockerAssert.DeleteDockerImagesAsync(output, "test/backend");

            await DockerAssert.DeleteDockerImagesAsync(output, "test/frontend");

            await DockerAssert.DeleteDockerImagesAsync(output, "test/worker");

            var projectName = "multi-project";
            var environment = "production";

            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", projectName));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));

            var outputContext = new OutputContext(sink, Verbosity.Debug);
            var application   = await ApplicationFactory.CreateAsync(outputContext, projectFile);

            application.Registry = new ContainerRegistry("test");

            try
            {
                await BuildHost.ExecuteBuildAsync(outputContext, application, environment, interactive : false);

                await DockerAssert.AssertImageExistsAsync(output, "test/backend");

                await DockerAssert.AssertImageExistsAsync(output, "test/frontend");

                await DockerAssert.AssertImageExistsAsync(output, "test/worker");
            }
            finally
            {
                await DockerAssert.AssertImageExistsAsync(output, "test/backend");

                await DockerAssert.AssertImageExistsAsync(output, "test/frontend");

                await DockerAssert.AssertImageExistsAsync(output, "test/worker");
            }
        }
        public void PlatformRemovalTest()
        {
            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                var platform = new Platform("Test");
                db.Platforms.Add(platform);
                var game = new Game("Test")
                {
                    PlatformId = platform.Id
                };

                db.Games.Add(game);
                db.Platforms.Remove(platform);
                var dbGame = db.Games[game.Id];
                Assert.AreEqual(Guid.Empty, dbGame.PlatformId);
                Assert.IsNull(db.Platforms.FirstOrDefault(a => a.Name == "Test"));
            }
        }
Exemple #20
0
        public async Task CertificateDirectoryStructure()
        {
            using (var dir = TempDirectory.Create())
            {
                var store = new DirectoryStore(dir.Name, createLocalCertificateIfNotExist: true);

                var app = new ApplicationDescription
                {
                    ApplicationUri = "http://hostname/appname",
                };

                await store.GetLocalCertificateAsync(app);

                Directory.EnumerateFiles(dir.Name + @"/own/certs")
                .Should().HaveCount(1);

                Directory.EnumerateFiles(dir.Name + @"/own/private")
                .Should().HaveCount(1);
            }
        }
 private void buttonOpenAttachment_Click(object sender, EventArgs e)
 {
     try
     {
         string fpath = Path.Combine(tempdir.Path, File.Name);
         fileUpdatePairs.Remove(fpath);
         tempdir.Create(fpath, File.Data);
         if (!fileSystemWatcher.EnableRaisingEvents)
         {
             fileSystemWatcher.Path                = tempdir.Path;
             fileSystemWatcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.Size;
             fileSystemWatcher.EnableRaisingEvents = true;
         }
         fileUpdatePairs[fpath] = Card;
         Process.Start(fpath);
     }
     catch (IOException)
     {
     }
 }
Exemple #22
0
        public async Task FrontendBackendRunTestWithDocker()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "frontend-backend"));

            using var tempDirectory = TempDirectory.Create(preferUserDirectoryOnMacOS: true);
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile   = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "tye.yaml"));
            var outputContext = new OutputContext(sink, Verbosity.Debug);
            var application   = await ApplicationFactory.CreateAsync(outputContext, projectFile);

            using var host = new TyeHost(application.ToHostingApplication(), new[] { "--docker" })
                  {
                      Sink = sink,
                  };

            await host.StartAsync();

            try
            {
                // Make sure we're runningn containers
                Assert.True(host.Application.Services.All(s => s.Value.Description.RunInfo is DockerRunInfo));

                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (a, b, c, d) => true,
                    AllowAutoRedirect = false
                };

                var client = new HttpClient(new RetryHandler(handler));

                var dashboardUri = new Uri(host.DashboardWebApplication !.Addresses.First());

                await CheckServiceIsUp(host.Application, client, "backend", dashboardUri, timeout : TimeSpan.FromSeconds(60));
                await CheckServiceIsUp(host.Application, client, "frontend", dashboardUri, timeout : TimeSpan.FromSeconds(60));
            }
            finally
            {
                await host.StopAsync();
            }
        }
        public async Task ShadowCopyE2EWorksWithOldFoldersPresent()
        {
            using var directory = TempDirectory.Create();
            var deploymentParameters = Fixture.GetBaseDeploymentParameters();

            deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
            deploymentParameters.HandlerSettings["shadowCopyDirectory"]          = directory.DirectoryPath;
            var deploymentResult = await DeployAsync(deploymentParameters);

            // Start with 1 to exercise the incremental logic
            DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "1"), copySubDirs: true);

            var response = await deploymentResult.HttpClient.GetAsync("Wow!");

            Assert.True(response.IsSuccessStatusCode);

            using var secondTempDir = TempDirectory.Create();

            // copy back and forth to cause file change notifications.
            DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
            DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true);

            response = await deploymentResult.HttpClient.GetAsync("Wow!");

            Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "0")), "Expected 0 shadow copy directory to be skipped");

            // Depending on timing, this could result in a shutdown failure, but sometimes it succeeds, handle both situations
            if (!response.IsSuccessStatusCode)
            {
                Assert.Equal("Application Shutting Down", response.ReasonPhrase);
            }

            // This shutdown should trigger a copy to the next highest directory, which will be 2
            await deploymentResult.AssertRecycledAsync();

            Assert.True(Directory.Exists(Path.Combine(directory.DirectoryPath, "2")), "Expected 2 shadow copy directory");

            response = await deploymentResult.HttpClient.GetAsync("Wow!");

            Assert.True(response.IsSuccessStatusCode);
        }
Exemple #24
0
        public async Task DockerHostVolumeTest()
        {
            using var projectDirectory = CopyTestProjectDirectory("volume-test");
            var projectFile = new FileInfo(Path.Combine(projectDirectory.DirectoryPath, "tye.yaml"));

            var outputContext = new OutputContext(_sink, Verbosity.Debug);
            var application   = await ApplicationFactory.CreateAsync(outputContext, projectFile);

            // Add a volume
            var project = (ProjectServiceBuilder)application.Services[0];

            using var tempDir = TempDirectory.Create(preferUserDirectoryOnMacOS: true);

            project.Volumes.Clear();
            project.Volumes.Add(new VolumeBuilder(source: tempDir.DirectoryPath, name: null, target: "/data"));

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (a, b, c, d) => true,
                AllowAutoRedirect = false
            };

            await File.WriteAllTextAsync(Path.Combine(tempDir.DirectoryPath, "file.txt"), "This content came from the host");

            var client  = new HttpClient(new RetryHandler(handler));
            var options = new HostOptions()
            {
                Docker = true,
            };

            await RunHostingApplication(application, options, async (app, serviceApi) =>
            {
                var serviceUri = await GetServiceUrl(client, serviceApi, "volume-test");

                Assert.NotNull(serviceUri);

                // The volume has data the host mapped data
                Assert.Equal("This content came from the host", await client.GetStringAsync(serviceUri));
            });
        }
Exemple #25
0
        public async Task NullDebugTargetsDoesNotThrow()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "single-project", "test-project"));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "test-project.csproj"));

            // Debug targets can be null if not specified, so make sure calling host.Start does not throw.
            var outputContext = new OutputContext(sink, Verbosity.Debug);
            var application   = await ApplicationFactory.CreateAsync(outputContext, projectFile);

            using var host = new TyeHost(application.ToHostingApplication(), Array.Empty <string>())
                  {
                      Sink = sink,
                  };

            await host.StartAsync();

            await host.StopAsync();
        }
Exemple #26
0
        public async Task LoadCertificate()
        {
            using (var dir = TempDirectory.Create())
            {
                var store = new DirectoryStore(dir.Name, createLocalCertificateIfNotExist: true);

                var app = new ApplicationDescription
                {
                    ApplicationUri = "urn:hostname:appname",
                };

                var(cert1, key1) = await store.GetLocalCertificateAsync(app);

                var(cert2, key2) = await store.GetLocalCertificateAsync(app);

                cert1
                .Should().Be(cert2);

                key1
                .Should().Be(key2);
            }
        }
Exemple #27
0
        public async Task CreateCertificate()
        {
            using (var dir = TempDirectory.Create())
            {
                var store = new DirectoryStore(dir.Name, createLocalCertificateIfNotExist: true);

                var app = new ApplicationDescription
                {
                    ApplicationUri = "http://hostname/appname",
                };

                var(cert, key) = await store.GetLocalCertificateAsync(app);

                cert
                .Should().NotBeNull();
                key
                .Should().NotBeNull();

                cert.SubjectDN.ToString()
                .Should().Be("CN=appname,DC=hostname");
            }
        }
Exemple #28
0
        public void PlatformRemovalTest()
        {
            using (var temp = TempDirectory.Create())
                using (var db = new GameDatabase(temp.TempPath))
                {
                    db.OpenDatabase();
                    var platform = new Platform("Test");
                    db.Platforms.Add(platform);
                    var game = new Game("Test")
                    {
                        PlatformIds = new List <Guid> {
                            platform.Id
                        }
                    };

                    db.Games.Add(game);
                    db.Platforms.Remove(platform);
                    var dbGame = db.Games[game.Id];
                    CollectionAssert.IsEmpty(dbGame.PlatformIds);
                    Assert.IsNull(db.Platforms.FirstOrDefault(a => a.Name == "Test"));
                }
        }
Exemple #29
0
        public void EventsInvokeCountBufferedTest()
        {
            using (var temp = TempDirectory.Create())
                using (var col = new ItemCollection <DatabaseObject>(Path.Combine(temp.TempPath, "db"), null))
                {
                    var itemUpdates = 0;
                    var colUpdates  = 0;
                    col.ItemUpdated           += (e, args) => itemUpdates++;
                    col.ItemCollectionChanged += (e, args) => colUpdates++;

                    var item = new DatabaseObject();
                    col.BeginBufferUpdate();
                    col.Add(item);
                    col.Update(item);
                    col.Remove(item);
                    Assert.AreEqual(0, itemUpdates);
                    Assert.AreEqual(0, colUpdates);
                    col.EndBufferUpdate();
                    Assert.AreEqual(1, itemUpdates);
                    Assert.AreEqual(1, colUpdates);
                }
        }
Exemple #30
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new IronPythonRuntime())
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"f = open('workDirTest.txt', 'w')
f.write('test')
f.close()");
                    FileAssert.Exists(outPath);

                    outPath = Path.Combine(tempDir.TempPath, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute(@"f = open('workDirTest.txt', 'w')
f.write('test')
f.close()", tempDir.TempPath);
                    FileAssert.Exists(outPath);
                }
        }