public void FileSystemWatcher_Directory_Delete_DeepDirectoryStructure()
        {
            // List of created directories
            List<TempDirectory> lst = new List<TempDirectory>();

            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
            using (var watcher = new FileSystemWatcher(dir.Path, "*"))
            {
                watcher.IncludeSubdirectories = true;
                watcher.NotifyFilter = NotifyFilters.DirectoryName;

                // Priming directory
                lst.Add(new TempDirectory(Path.Combine(dir.Path, "dir")));

                // Create a deep directory structure and expect things to work
                for (int i = 1; i < 20; i++)
                {
                    // Test that the creation triggers an event correctly
                    string dirPath = Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i));
                    Action action = () => Directory.Delete(dirPath);
                    Action cleanup = () => Directory.CreateDirectory(dirPath);
                    cleanup();

                    ExpectEvent(watcher, WatcherChangeTypes.Deleted, action, cleanup);

                    // Create the directory so subdirectories may be created from it.
                    lst.Add(new TempDirectory(dirPath));
                }
            }
        }
 public void ctor_string_bool()
 {
     using (var temp = new TempDirectory())
     {
         Assert.NotNull(new DirectoryCreateCommand(temp.Info.FullName, true));
     }
 }
        public void transaction_Complete()
        {
            try
            {
                using (var temp = new TempDirectory())
                {
                    var path = temp.Info.ToDirectory("example").FullName;
                    Recovery.MasterDirectory = temp.Info.ToDirectory("Recovery");
                    using (var scope = new TransactionScope())
                    {
                        var obj = new DerivedDurableEnlistmentNotification(Guid.NewGuid(), EnlistmentOptions.None);
                        obj.Operation.Commands.Add(new DirectoryCreateCommand(path));

                        scope.Complete();
                    }

                    Assert.True(new DirectoryInfo(path).Exists);
                    Thread.Sleep(1000);
                }
            }
            finally
            {
                Recovery.MasterDirectory = null;
            }
        }
Exemplo n.º 4
0
        public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName)
        {
            var analyzerSource = @"
            using System;
            using System.Collections.Immutable;
            using Microsoft.CodeAnalysis;
            using Microsoft.CodeAnalysis.Diagnostics;

            [DiagnosticAnalyzer(LanguageNames.CSharp)]
            public class TestAnalyzer : DiagnosticAnalyzer
            {
            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } }
            public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); }
            }";

            dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location);
            var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location);
            var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location);
            dir.CopyFile(Path.Combine(Path.GetDirectoryName(typeof(CSharpCompilation).Assembly.Location), "System.IO.FileSystem.dll"));

            var analyzerCompilation = CSharpCompilation.Create(
                assemblyName,
                new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
                new MetadataReference[]
                {
                    TestReferences.NetStandard13.SystemRuntime,
                    MetadataReference.CreateFromFile(immutable.Path),
                    MetadataReference.CreateFromFile(analyzer.Path)
                },
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray());
        }
        public void FileSystemWatcher_File_NotifyFilter_Attributes(NotifyFilters filter)
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
            using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
            {
                watcher.NotifyFilter = filter;
                var attributes = File.GetAttributes(file.Path);

                Action action = () => File.SetAttributes(file.Path, attributes | FileAttributes.ReadOnly);
                Action cleanup = () => File.SetAttributes(file.Path, attributes);

                WatcherChangeTypes expected = 0;
                if (filter == NotifyFilters.Attributes)
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ((filter & LinuxFiltersForAttribute) > 0))
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & OSXFiltersForModify) > 0))
                    expected |= WatcherChangeTypes.Changed;
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && ((filter & NotifyFilters.Security) > 0))
                    expected |= WatcherChangeTypes.Changed; // Attribute change on OSX is a ChangeOwner operation which passes the Security NotifyFilter.
                
                ExpectEvent(watcher, expected, action, cleanup, file.Path);
            }
        }
Exemplo n.º 6
0
        public void SetUp()
        {
            kernel = new StandardKernel();

            tmp = new TempDirectory();
            rootDir = new LocalFileSystemDirectory(tmp);
            using (var writer = rootDir.CreateTextFile("file1"))
                writer.WriteLine("Contents of file 1");
            using (var writer = rootDir.CreateTextFile("file2"))
                writer.WriteLine("Contents of file 2");
            using (var writer = rootDir.CreateTextFile("file3"))
                writer.WriteLine("Contents of file 3");

            sourceSet1 = new SourceSet("test1");
            sourceSet1.Add(new SuiteRelativePath("file1"));
            sourceSet1.Add(new SuiteRelativePath("file2"));

            sourceSet2 = new SourceSet("test2");
            sourceSet2.Add(new SuiteRelativePath("file1"));
            sourceSet2.Add(new SuiteRelativePath("file3"));

            kernel.Bind<IFileSystemDirectory>().ToConstant(rootDir).WhenTargetHas<SuiteRootAttribute>();

            var factoryMock = new Mock<ISourceSetFingerprintFactory>();
            factoryMock.Setup(
                f =>
                f.CreateSourceSetFingerprint(It.IsAny<IEnumerable<SuiteRelativePath>>(), It.IsAny<Func<string, bool>>(), It.IsAny<bool>()))
                       .Returns<IEnumerable<SuiteRelativePath>, Func<string, bool>, bool>(
                            (files, exclusions, fullDependency) => new SourceSetFingerprint(rootDir, files, exclusions, fullDependency));
            fingerprintFactory = factoryMock.Object;
        }
Exemplo n.º 7
0
 public void ctor()
 {
     using (var directory = new TempDirectory())
     {
         Assert.NotNull(directory);
     }
 }
Exemplo n.º 8
0
        public void op_Do()
        {
            try
            {
                using (var temp = new TempDirectory())
                {
                    Recovery.MasterDirectory = temp.Info.ToDirectory("Recovery");
                    var path1 = temp.Info.ToDirectory("1").FullName;
                    var path2 = temp.Info.ToDirectory("2").FullName;
                    var obj = new Operation(Guid.NewGuid())
                                  {
                                      Info = Guid.NewGuid().ToString()
                                  };
                    obj.Commands.Add(new DirectoryCreateCommand(path1));
                    obj.Commands.Add(new DirectoryCreateCommand(path2));

                    Assert.True(obj.Do());
                    Assert.True(new DirectoryInfo(path1).Exists);
                    Assert.True(new DirectoryInfo(path2).Exists);
                }
            }
            finally
            {
                Recovery.MasterDirectory = null;
            }
        }
        public FileSystemWatchingBundleRebuilder_Tests()
        {
            tempDirectory = new TempDirectory();
            Directory.CreateDirectory(Path.Combine(tempDirectory, "cache"));
            var settings = new CassetteSettings
            {
                SourceDirectory = new FileSystemDirectory(tempDirectory),
                CacheDirectory = new FileSystemDirectory(Path.Combine(tempDirectory, "cache")),
                IsFileSystemWatchingEnabled = true
            };
            bundles = new BundleCollection(settings, Mock.Of<IFileSearchProvider>(), Mock.Of<IBundleFactoryProvider>());
            bundleConfiguration = new Mock<IConfiguration<BundleCollection>>();

            var bundle = new TestableBundle("~");
            var asset1 = new StubAsset("~/test.js");
            var asset2 = new StubAsset("~/sub/test2.js");
            asset1.AddRawFileReference("~/image.png");
            bundle.Assets.Add(asset1);
            bundle.Assets.Add(asset2);
            bundles.Add(bundle);

            fileSearch = new Mock<IFileSearch>();
            fileSearch
                .Setup(s => s.IsMatch(It.IsAny<string>()))
                .Returns<string>(path => path.EndsWith(".js"));

            var initializer = new BundleCollectionInitializer(new[] { bundleConfiguration.Object }, new ExternalBundleGenerator(Mock.Of<IBundleFactoryProvider>(), settings));
            rebuilder = new FileSystemWatchingBundleRebuilder(settings, bundles, initializer, new[] { fileSearch.Object });
        }
 private void CopyProjectToTempDir(string projectDir, TempDirectory tempDir)
 {
     foreach (var file in Directory.EnumerateFiles(projectDir))
     {
         tempDir.CopyFile(file);
     }
 }
        public void ItPersistsArgumentsInFile(
            string containerDirectory, string machineIp, string syslogHostIp, string syslogPort, string machineName)
        {
            using(var tempDirectory = new TempDirectory())
            {
                var configurationManager = new ConfigurationManagerTest();
                var context = new InstallContext();
                context.Parameters.Add("CONTAINER_DIRECTORY", containerDirectory);
                context.Parameters.Add("MACHINE_IP", machineIp);
                context.Parameters.Add("SYSLOG_HOST_IP", syslogHostIp);
                context.Parameters.Add("SYSLOG_PORT", syslogPort);
                context.Parameters.Add("assemblypath", tempDirectory.ToString());
                context.Parameters.Add("MACHINE_NAME", machineName);
                configurationManager.Context = context;
                configurationManager.OnBeforeInstall(null);

                var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var jsonString = File.ReadAllText(Path.Combine(tempDirectory.ToString(), @"..\parameters.json"));
                var hash = javaScriptSerializer.Deserialize<Dictionary<string, string>>(jsonString);
                Assert.Equal(hash["CONTAINER_DIRECTORY"], containerDirectory);
                Assert.Equal(hash["MACHINE_IP"], machineIp);
                Assert.Equal(hash["SYSLOG_HOST_IP"], syslogHostIp);
                Assert.Equal(hash["SYSLOG_PORT"], syslogPort);
                Assert.Equal(hash["MACHINE_NAME"], machineName);
            }
        }
Exemplo n.º 12
0
 public void Constructor_NoParent_CreatesTempDirectory()
 {
     using (var tempDir = new TempDirectory())
     {
         Assert.IsTrue(Directory.Exists(tempDir));
     }
 }
Exemplo n.º 13
0
        public void op_Run_DirectoryInfo_TextWriter()
        {
            using (var temp = new TempDirectory())
            {
                var log = temp.Info.ToFile("log.txt");
                using (var stream = File.Open(log.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        var mock = new Mock<IRunTest>();

                        // ReSharper disable AccessToDisposedClosure
                        mock
                            .Setup(x => x.Run(temp.Info, writer))
                            .Returns(true)
                            .Verifiable();

                        // ReSharper restore AccessToDisposedClosure
                        Assert.True(mock.Object.Run(temp.Info, writer));

                        mock.VerifyAll();
                    }
                }
            }
        }
Exemplo n.º 14
0
 public void ctor_DirectoryInfo()
 {
     using (var directory = new TempDirectory(new DirectoryInfo("C:\\").Root))
     {
         Assert.NotNull(directory);
     }
 }
        public BundleCollectionCache_Write_Tests()
        {
            path = new TempDirectory();
            directory = new FileSystemDirectory(path);

            var bundles = new BundleCollection(new CassetteSettings(), Mock.Of<IFileSearchProvider>(), Mock.Of<IBundleFactoryProvider>());
            scriptBundle = new Mock<ScriptBundle>("~/test1");
            scriptBundle.CallBase = true;
            scriptBundle.Object.Hash = new byte[] { 1, 2, 3 };
            scriptBundle.Object.Assets.Add(new StubAsset("~/test/asset.js", "script-bundle-content"));
            scriptBundle.Object.Renderer = new ScriptBundleHtmlRenderer(Mock.Of<IUrlGenerator>());
            scriptBundle.Setup(b => b.Render()).Returns("");
            bundles.Add(scriptBundle.Object);

            stylesheetBundle = new Mock<StylesheetBundle>("~/test2");
            stylesheetBundle.CallBase = true;
            stylesheetBundle.Object.Hash = new byte[] { 4, 5, 6 };
            stylesheetBundle.Object.Assets.Add(new StubAsset("~/test2/asset.css", "stylesheet-bundle-content"));
            stylesheetBundle.Object.Renderer = new StylesheetHtmlRenderer(Mock.Of<IUrlGenerator>());
            stylesheetBundle.Setup(b => b.Render()).Returns("");
            bundles.Add(stylesheetBundle.Object);

            var cache = new BundleCollectionCache(directory, b => null);
            cache.Write(new Manifest(bundles, "VERSION"));
        }
 public void ctor_DirectoryInfo_bool()
 {
     using (var temp = new TempDirectory())
     {
         Assert.NotNull(new DirectoryCreateCommand(temp.Info, true));
     }
 }
Exemplo n.º 17
0
 public void ctor_DirectoryInfo_string_SearchOption()
 {
     using (var temp = new TempDirectory())
     {
         Assert.NotNull(new DerivedFileReceiverTask(temp.Info, "*.txt", SearchOption.TopDirectoryOnly));
     }
 }
        public void FileSystemWatcher_File_Delete_DeepDirectoryStructure()
        {
            // List of created directories
            List<TempDirectory> lst = new List<TempDirectory>();

            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
            using (var watcher = new FileSystemWatcher(dir.Path, "*"))
            {
                watcher.IncludeSubdirectories = true;
                watcher.NotifyFilter = NotifyFilters.FileName;

                // Create a deep directory structure
                lst.Add(new TempDirectory(Path.Combine(dir.Path, "dir")));
                for (int i = 1; i < 20; i++)
                {
                    string dirPath = Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i));
                    lst.Add(new TempDirectory(dirPath));
                }

                // Put a file at the very bottom and expect it to raise an event
                string fileName = Path.Combine(lst[lst.Count - 1].Path, "file");
                Action action = () => File.Delete(fileName);
                Action cleanup = () => File.Create(fileName).Dispose();
                cleanup();

                ExpectEvent(watcher, WatcherChangeTypes.Deleted, action, cleanup, fileName);
            }
        }
Exemplo n.º 19
0
 public void op_Dispose_whenContainsDirectory()
 {
     using (var directory = new TempDirectory())
     {
         var example = directory.Info.CreateSubdirectory("example");
         example.CreateSubdirectory(Guid.NewGuid().ToString());
     }
 }
        public void TempDirectory_FullName_ReturnsExistingDirectory()
        {
            var tempDirectory = new TempDirectory();

            var directory = tempDirectory.FullName;

            Assert.IsTrue(Directory.Exists(directory));
        }
Exemplo n.º 21
0
 public void GetRandomDirectory(IsolatedStorageScope scope)
 {
     using (var temp = new TempDirectory())
     {
         string randomDir = Helper.GetRandomDirectory(temp.Path, scope);
         Assert.True(Directory.Exists(randomDir));
     }
 }
 public void op_ToCsvFile_DirectoryInfo_stringEmpty()
 {
     using (var temp = new TempDirectory())
     {
         // ReSharper disable once AccessToDisposedClosure
         Assert.Throws<ArgumentOutOfRangeException>(() => temp.Info.ToCsvFile(string.Empty));
     }
 }
Exemplo n.º 23
0
        public ScriptExecutorTests()
        {
            _root = Temp.CreateDirectory();

            var sourceTestProjectPath = Path.Combine(s_testProjectRoot, "TestApp");
            binTestProjectPath = _root.CopyDirectory(sourceTestProjectPath).Path;
            project = ProjectContext.Create(binTestProjectPath, NuGetFramework.Parse("netstandardapp1.5")).ProjectFile;
        }
 public void op_ToCsvFile_DirectoryInfo_stringNull()
 {
     using (var temp = new TempDirectory())
     {
         // ReSharper disable once AccessToDisposedClosure
         Assert.Throws<ArgumentNullException>(() => temp.Info.ToCsvFile(null as string));
     }
 }
        public void op_Load_FileInfoNotFound()
        {
            using (var temp = new TempDirectory())
            {
                var file = temp.Info.ToFile("sabc.csv");

                Assert.Throws<FileNotFoundException>(() => BritishTelephoneNumberPlan.Load(file));
            }
        }
Exemplo n.º 26
0
        public void op_PackageReference_PackageNull()
        {
            using (var temp = new TempDirectory())
            {
                var obj = ProjectFile.Create(temp.Info.ToFile("example.csproj"));

                Assert.Throws<ArgumentNullException>(() => obj.PackageReference(null));
            }
        }
        public void TempDirectory_CallingDispose_DeletesDirectory()
        {
            var tempDirectory = new TempDirectory();
            var directory = tempDirectory.FullName;

            tempDirectory.Dispose();

            Assert.IsFalse(Directory.Exists(directory));
        }
Exemplo n.º 28
0
 public void ctor_FileInfoMissing()
 {
     using (var temp = new TempDirectory())
     {
         // ReSharper disable AccessToDisposedClosure
         Assert.Throws<FileNotFoundException>(() => new TsvDataFile(temp.Info.ToFile("missing.txt")));
         // ReSharper restore AccessToDisposedClosure
     }
 }
        public void TempDirectory_FullNameCalledTwice_ReturnsSameName()
        {
            var tempDirectory = new TempDirectory();

            var directory1 = tempDirectory.FullName;
            var directory2 = tempDirectory.FullName;

            Assert.AreEqual(directory1, directory2);
        }
Exemplo n.º 30
0
 void it_creates_and_deletes_a_temporary_directory_accessible_as_path_string()
 {
     string path;
     using (var tmp = new TempDirectory())
     {
         path = tmp.PathString();
         Directory.Exists(path).should_be_true();
     }
     Directory.Exists(path).should_be_false();
 }
        public void FileSystemWatcher_File_NotifyFilter_Security(NotifyFilters filter)
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
                using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
                    using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
                    {
                        watcher.NotifyFilter = filter;
                        Action action = () =>
                        {
                            // ACL support is not yet available, so pinvoke directly.
                            uint result = SetSecurityInfoByHandle(file.Path,
                                                                  SE_FILE_OBJECT,
                                                                  DACL_SECURITY_INFORMATION, // Only setting the DACL
                                                                  owner: IntPtr.Zero,
                                                                  group: IntPtr.Zero,
                                                                  dacl: IntPtr.Zero, // full access to everyone
                                                                  sacl: IntPtr.Zero);
                            Assert.Equal(ERROR_SUCCESS, result);
                        };
                        Action cleanup = () =>
                        {
                            // Recreate the file.
                            File.Delete(file.Path);
                            File.AppendAllText(file.Path, "text");
                        };

                        WatcherChangeTypes expected = 0;
                        if (filter == NotifyFilters.Security)
                        {
                            expected |= WatcherChangeTypes.Changed;
                        }
                        else if (PlatformDetection.IsWindows7 && filter == NotifyFilters.Attributes) // win7 FSW Security change passes the Attribute filter
                        {
                            expected |= WatcherChangeTypes.Changed;
                        }
                        ExpectEvent(watcher, expected, action, expectedPath: file.Path);
                    }
        }
        public CreateBundlesWithRawFilesTests()
        {
            root = new TempDirectory();

            CreateDirectory("source");
            CreateDirectory("source\\bin");
            CreateDirectory("output");

            WriteFile("source\\test.css", @"p { background: url(test.png); } .other { background: url(notfound.png); }");
            WriteFile("source\\test.png", "image");

            var configurationDll = CompileConfigurationDll();

            File.Move(configurationDll, PathUtilities.Combine(root, "source", "bin", "test.dll"));
            File.Copy("Cassette.dll", PathUtilities.Combine(root, "source", "bin", "Cassette.dll"));
            File.Copy("Cassette.pdb", PathUtilities.Combine(root, "source", "bin", "Cassette.pdb"));
            File.Copy("AjaxMin.dll", PathUtilities.Combine(root, "source", "bin", "AjaxMin.dll"));
#if NET35
            File.Copy("Iesi.Collections.dll", PathUtilities.Combine(root, "source", "bin", "Iesi.Collections.dll"));
#endif
            buildEngine = new BuildEngineStub();
            var task = new CreateBundles
            {
                BuildEngine = buildEngine
            };

            var taskLoggingHelper = new TaskLoggingHelper(task);

            var command = new CreateBundlesCommand(
                PathUtilities.Combine(root, "source"),
                PathUtilities.Combine(root, "source", "bin"),
                PathUtilities.Combine(root, "output"),
                true,
                taskLoggingHelper
                );

            CreateBundlesCommand.ExecuteInSeparateAppDomain(command);
        }
        public async Task ProxyMetadata_WhenProxyFileChanges_IsRefreshed()
        {
            using (var tempDirectory = new TempDirectory())
            {
                var testProxiesPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Proxies");
                var options         = new OptionsWrapper <ScriptJobHostOptions>(new ScriptJobHostOptions
                {
                    RootScriptPath = tempDirectory.Path
                });

                var environment  = new TestEnvironment();
                var eventManager = new ScriptEventManager();

                var provider = new ProxyFunctionProvider(options, environment, eventManager, NullLoggerFactory.Instance);

                // Get metadata before proxies exist
                ImmutableArray <FunctionMetadata> proxyMetadata1 = await provider.GetFunctionMetadataAsync();

                ImmutableArray <FunctionMetadata> proxyMetadata2 = await provider.GetFunctionMetadataAsync();

                Assert.True(proxyMetadata2.IsDefaultOrEmpty);
                Assert.True(proxyMetadata1.IsDefaultOrEmpty);

                // Update our proxies definition
                FileUtility.CopyDirectory(testProxiesPath, tempDirectory.Path);

                // Simulate a file change notification
                eventManager.Publish(new FileEvent(EventSources.ScriptFiles,
                                                   new FileSystemEventArgs(WatcherChangeTypes.Changed, tempDirectory.Path, ScriptConstants.ProxyMetadataFileName)));

                ImmutableArray <FunctionMetadata> proxyMetadata3 = await provider.GetFunctionMetadataAsync();

                var proxyClient = (proxyMetadata3.FirstOrDefault() as ProxyFunctionMetadata).ProxyClient;

                Assert.True(proxyMetadata3.Select(p => (p as ProxyFunctionMetadata).ProxyClient).All(c => c.Equals(proxyClient)));
                Assert.Equal(20, proxyMetadata3.Length);
            }
        }
Exemplo n.º 34
0
        public async Task GetFunctiontSecrets_WhenNonDecryptedSecrets_SavesAndRefreshes()
        {
            using (var directory = new TempDirectory())
            {
                string functionName         = "testfunction";
                string expectedTraceMessage = string.Format(Resources.TraceNonDecryptedFunctionSecretRefresh, functionName);
                string functionSecretsJson  =
                    @"{
    'keys': [
        {
            'name': 'Key1',
            'value': 'cryptoError',
            'encrypted': true
        },
        {
            'name': 'Key2',
            'value': '1234',
            'encrypted': false
        }
    ]
}";
                File.WriteAllText(Path.Combine(directory.Path, functionName + ".json"), functionSecretsJson);
                Mock <IKeyValueConverterFactory> mockValueConverterFactory = GetConverterFactoryMock(true, false);
                IDictionary <string, string>     functionSecrets;
                ISecretsRepository repository = new FileSystemSecretsRepository(directory.Path);

                using (var secretManager = new SecretManager(repository, mockValueConverterFactory.Object, null))
                {
                    functionSecrets = await secretManager.GetFunctionSecretsAsync(functionName);
                }

                Assert.NotNull(functionSecrets);
                Assert.Equal(functionSecrets["Key1"], "cryptoError");
                var result = JsonConvert.DeserializeObject <FunctionSecrets>(File.ReadAllText(Path.Combine(directory.Path, functionName + ".json")));
                Assert.Equal(result.GetFunctionKey("Key1", functionName).Value, "!cryptoError");
                Assert.Equal(1, Directory.GetFiles(directory.Path, $"{functionName}.{ScriptConstants.Snapshot}*").Length);
            }
        }
Exemplo n.º 35
0
        public void PlaytimeImportTest()
        {
            var gameId       = "tesId";
            var libPlugin    = new Mock <ILibraryPlugin>();
            var timeToImport = 500;

            libPlugin.Setup(a => a.Id).Returns(Guid.NewGuid());
            libPlugin.Setup(a => a.GetGames()).Returns(() => new List <Game>
            {
                new Game()
                {
                    GameId   = gameId,
                    Playtime = timeToImport,
                    PluginId = libPlugin.Object.Id
                }
            });

            using (var temp = TempDirectory.Create())
            {
                var db = new GameDatabase(temp.TempPath);
                db.OpenDatabase();
                GameLibrary.ImportGames(libPlugin.Object, db, true);
                Assert.AreEqual(timeToImport, db.Games.First().Playtime);

                timeToImport = 600;
                GameLibrary.ImportGames(libPlugin.Object, db, false);
                Assert.AreEqual(500, db.Games.First().Playtime);
                GameLibrary.ImportGames(libPlugin.Object, db, true);
                Assert.AreEqual(timeToImport, db.Games.First().Playtime);

                var g = db.Games.First();
                g.Playtime = 0;
                db.Games.Update(g);
                Assert.AreEqual(0, db.Games.First().Playtime);
                GameLibrary.ImportGames(libPlugin.Object, db, false);
                Assert.AreEqual(timeToImport, db.Games.First().Playtime);
            }
        }
Exemplo n.º 36
0
        public void Add_Directory(TarFormat format, bool withContents)
        {
            using TempDirectory root = new TempDirectory();
            string dirName = "dir";
            string dirPath = Path.Join(root.Path, dirName);

            Directory.CreateDirectory(dirPath);

            if (withContents)
            {
                // Add a file inside the directory, we need to ensure the contents
                // of the directory are ignored when using AddFile
                File.Create(Path.Join(dirPath, "file.txt")).Dispose();
            }

            using MemoryStream archive = new MemoryStream();
            using (TarWriter writer = new TarWriter(archive, format, leaveOpen: true))
            {
                writer.WriteEntry(fileName: dirPath, entryName: dirName);
            }

            archive.Seek(0, SeekOrigin.Begin);
            using (TarReader reader = new TarReader(archive))
            {
                Assert.Equal(TarFormat.Unknown, reader.Format);
                TarEntry entry = reader.GetNextEntry();
                Assert.Equal(format, reader.Format);

                Assert.NotNull(entry);
                Assert.Equal(dirName, entry.Name);
                Assert.Equal(TarEntryType.Directory, entry.EntryType);
                Assert.Null(entry.DataStream);

                VerifyPlatformSpecificMetadata(dirPath, entry);

                Assert.Null(reader.GetNextEntry()); // If the dir had contents, they should've been excluded
            }
        }
Exemplo n.º 37
0
        public void Add_Fifo(TarEntryFormat format)
        {
            RemoteExecutor.Invoke((string strFormat) =>
            {
                TarEntryFormat expectedFormat = Enum.Parse <TarEntryFormat>(strFormat);

                using TempDirectory root = new TempDirectory();
                string fifoName          = "fifofile";
                string fifoPath          = Path.Join(root.Path, fifoName);

                Interop.CheckIo(Interop.Sys.MkFifo(fifoPath, (int)DefaultMode));

                using MemoryStream archive = new MemoryStream();
                using (TarWriter writer = new TarWriter(archive, expectedFormat, leaveOpen: true))
                {
                    writer.WriteEntry(fileName: fifoPath, entryName: fifoName);
                }

                archive.Seek(0, SeekOrigin.Begin);
                using (TarReader reader = new TarReader(archive))
                {
                    PosixTarEntry entry = reader.GetNextEntry() as PosixTarEntry;
                    Assert.Equal(expectedFormat, entry.Format);

                    Assert.NotNull(entry);
                    Assert.Equal(fifoName, entry.Name);
                    Assert.Equal(DefaultLinkName, entry.LinkName);
                    Assert.Equal(TarEntryType.Fifo, entry.EntryType);
                    Assert.Null(entry.DataStream);

                    VerifyPlatformSpecificMetadata(fifoPath, entry);

                    Assert.Null(reader.GetNextEntry());
                }
            }, format.ToString(), new RemoteInvokeOptions {
                RunAsSudo = true
            }).Dispose();
        }
Exemplo n.º 38
0
        public async Task SpecialFile_Unelevated_Throws_Async()
        {
            using TempDirectory root = new TempDirectory();
            using MemoryStream ms    = GetTarMemoryStream(CompressionMethod.Uncompressed, TestTarFormat.ustar, "specialfiles");

            TarReader reader = new TarReader(ms);

            await using (reader)
            {
                string path = Path.Join(root.Path, "output");

                // Block device requires elevation for writing
                PosixTarEntry blockDevice = await reader.GetNextEntryAsync() as PosixTarEntry;

                Assert.NotNull(blockDevice);
                await Assert.ThrowsAsync <UnauthorizedAccessException>(() => blockDevice.ExtractToFileAsync(path, overwrite: false));

                Assert.False(File.Exists(path));

                // Character device requires elevation for writing
                PosixTarEntry characterDevice = await reader.GetNextEntryAsync() as PosixTarEntry;

                Assert.NotNull(characterDevice);
                await Assert.ThrowsAsync <UnauthorizedAccessException>(() => characterDevice.ExtractToFileAsync(path, overwrite: false));

                Assert.False(File.Exists(path));

                // Fifo does not require elevation, should succeed
                PosixTarEntry fifo = await reader.GetNextEntryAsync() as PosixTarEntry;

                Assert.NotNull(fifo);
                await fifo.ExtractToFileAsync(path, overwrite : false);

                Assert.True(File.Exists(path));

                Assert.Null(await reader.GetNextEntryAsync());
            }
        }
Exemplo n.º 39
0
        public async Task MultiRepo_WorksWithCloning()
        {
            using var projectDirectory = TempDirectory.Create(preferUserDirectoryOnMacOS: true);

            var content  = @"
name: VotingSample
services:
- name: vote
  repository: https://github.com/jkotalik/TyeMultiRepoVoting
- name: results
  repository: https://github.com/jkotalik/TyeMultiRepoResults";
            var yamlFile = Path.Combine(projectDirectory.DirectoryPath, "tye.yaml");
            await File.WriteAllTextAsync(yamlFile, content);

            // 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, new FileInfo(yamlFile));

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

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

            await RunHostingApplication(application, Array.Empty <string>(), async (app, uri) =>
            {
                var votingUri = await GetServiceUrl(client, uri, "vote");
                var workerUri = await GetServiceUrl(client, uri, "worker");

                var votingResponse = await client.GetAsync(votingUri);
                var workerResponse = await client.GetAsync(workerUri);

                Assert.True(votingResponse.IsSuccessStatusCode);
                Assert.Equal(HttpStatusCode.NotFound, workerResponse.StatusCode);
            });
        }
        public async Task GetFunctiontSecrets_AddsMetrics()
        {
            using (var directory = new TempDirectory())
            {
                string functionName        = "testfunction";
                string functionSecretsJson =
                    @"{
    'keys': [
        {
            'name': 'Key1',
            'value': 'cryptoError',
            'encrypted': true
        },
        {
            'name': 'Key2',
            'value': '1234',
            'encrypted': false
        }
    ]
}";
                File.WriteAllText(Path.Combine(directory.Path, functionName + ".json"), functionSecretsJson);
                Mock <IKeyValueConverterFactory> mockValueConverterFactory = GetConverterFactoryMock(true, false);
                IDictionary <string, string>     functionSecrets;
                ISecretsRepository repository    = new FileSystemSecretsRepository(directory.Path);
                TestMetricsLogger  metricsLogger = new TestMetricsLogger();

                using (var secretManager = new SecretManager(repository, mockValueConverterFactory.Object, null, metricsLogger))
                {
                    functionSecrets = await secretManager.GetFunctionSecretsAsync(functionName);
                }

                string eventName = string.Format(MetricEventNames.SecretManagerGetFunctionSecrets, repository.GetType().Name.ToLower());
                metricsLogger.EventsBegan.Single(e => e.StartsWith(eventName));
                metricsLogger.EventsBegan.Single(e => e.Contains("testfunction"));
                metricsLogger.EventsEnded.Single(e => e.ToString().StartsWith(eventName));
                metricsLogger.EventsEnded.Single(e => e.ToString().Contains("testfunction"));
            }
        }
Exemplo n.º 41
0
        public void FileSystemWatcher_File_Rename_NotAffectEachOther()
        {
            ExecuteWithRetry(() =>
            {
                using (var testDirectory = new TempDirectory(GetTestFilePath()))
                    using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
                        using (var watcher1 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
                            using (var watcher2 = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
                            {
                                AutoResetEvent autoResetEvent1_created = WatchCreated(watcher1, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured;
                                AutoResetEvent autoResetEvent1_deleted = WatchDeleted(watcher1, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured;
                                AutoResetEvent autoResetEvent2_created = WatchCreated(watcher2, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured;
                                AutoResetEvent autoResetEvent2_deleted = WatchDeleted(watcher2, new[] { Path.Combine(testDirectory.Path, "file") }).EventOccured;

                                watcher1.EnableRaisingEvents = true;
                                watcher2.EnableRaisingEvents = true;

                                string filePath        = file.Path;
                                string filePathRenamed = file.Path + "_renamed";

                                File.Move(filePath, filePathRenamed);
                                Assert.True(WaitHandle.WaitAll(
                                                new[] { autoResetEvent1_created, autoResetEvent1_deleted, autoResetEvent2_created, autoResetEvent2_deleted },
                                                WaitForExpectedEventTimeout_NoRetry));

                                File.Move(filePathRenamed, filePath);
                                watcher1.EnableRaisingEvents = false;

                                File.Move(filePath, filePathRenamed);
                                Assert.False(WaitHandle.WaitAll(
                                                 new[] { autoResetEvent1_created, autoResetEvent1_deleted },
                                                 WaitForUnexpectedEventTimeout));
                                Assert.True(WaitHandle.WaitAll(
                                                new[] { autoResetEvent2_created, autoResetEvent2_deleted },
                                                WaitForExpectedEventTimeout_NoRetry));
                            }
            });
        }
Exemplo n.º 42
0
        public async Task ShadowCopySingleFileChangedWorks()
        {
            using var directory = TempDirectory.Create();
            var deploymentParameters = Fixture.GetBaseDeploymentParameters();

            deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
            deploymentParameters.HandlerSettings["shadowCopyDirectory"]          = directory.DirectoryPath;

            var deploymentResult = await DeployAsync(deploymentParameters);

            DirectoryCopy(deploymentResult.ContentRoot, directory.DirectoryPath, copySubDirs: true);

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

            Assert.True(response.IsSuccessStatusCode);
            // Rewrite file
            var dirInfo = new DirectoryInfo(deploymentResult.ContentRoot);

            string dllPath = "";

            foreach (var file in dirInfo.EnumerateFiles())
            {
                if (file.Extension == ".dll")
                {
                    dllPath = file.FullName;
                    break;
                }
            }
            var fileContents = File.ReadAllBytes(dllPath);

            File.WriteAllBytes(dllPath, fileContents);

            await deploymentResult.AssertRecycledAsync();

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

            Assert.True(response.IsSuccessStatusCode);
        }
        public void Save_throws_when_existing_files()
        {
            using (var directory = new TempDirectory())
            {
                var contextPath = Path.Combine(directory.Path, "TestContext.cs");
                File.WriteAllText(contextPath, "// Old");

                var entityTypePath = Path.Combine(directory.Path, "TestEntity.cs");
                File.WriteAllText(entityTypePath, "// Old");

                var scaffolder      = CreateScaffolder();
                var scaffoldedModel = new ScaffoldedModel
                {
                    ContextFile = new ScaffoldedFile
                    {
                        Path = "TestContext.cs",
                        Code = "// TestContext"
                    },
                    AdditionalFiles =
                    {
                        new ScaffoldedFile
                        {
                            Path = "TestEntity.cs",
                            Code = "// TestEntity"
                        }
                    }
                };

                var ex = Assert.Throws <OperationException>(
                    () => scaffolder.Save(scaffoldedModel, directory.Path, overwriteFiles: false));

                Assert.Equal(
                    DesignStrings.ExistingFiles(
                        directory.Path,
                        string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, "TestContext.cs", "TestEntity.cs")),
                    ex.Message);
            }
        }
Exemplo n.º 44
0
        public async Task FrontendBackendRunTest()
        {
            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 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();

            try
            {
                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);
                await CheckServiceIsUp(host.Application, client, "frontend", dashboardUri);
            }
            finally
            {
                await host.StopAsync();
            }
        }
Exemplo n.º 45
0
        public async Task CachedSecrets_UsedWhenPresent()
        {
            using (var directory = new TempDirectory())
            {
                string startupContextPath = Path.Combine(directory.Path, Guid.NewGuid().ToString());
                _testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteStartupContextCache, startupContextPath);
                _testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.WebSiteAuthEncryptionKey, TestEncryptionKey);

                WriteStartContextCache(startupContextPath);

                using (var secretManager = CreateSecretManager(directory.Path))
                {
                    var functionSecrets = await secretManager.GetFunctionSecretsAsync("function1", true);

                    Assert.Equal(4, functionSecrets.Count);
                    Assert.Equal("function1value", functionSecrets["test-function-1"]);
                    Assert.Equal("function2value", functionSecrets["test-function-2"]);
                    Assert.Equal("hostfunction1value", functionSecrets["test-host-function-1"]);
                    Assert.Equal("hostfunction2value", functionSecrets["test-host-function-2"]);

                    var hostSecrets = await secretManager.GetHostSecretsAsync();

                    Assert.Equal("test-master-key", hostSecrets.MasterKey);
                    Assert.Equal(2, hostSecrets.FunctionKeys.Count);
                    Assert.Equal("hostfunction1value", hostSecrets.FunctionKeys["test-host-function-1"]);
                    Assert.Equal("hostfunction2value", hostSecrets.FunctionKeys["test-host-function-2"]);
                    Assert.Equal(2, hostSecrets.SystemKeys.Count);
                    Assert.Equal("system1value", hostSecrets.SystemKeys["test-system-1"]);
                    Assert.Equal("system2value", hostSecrets.SystemKeys["test-system-2"]);
                }

                var logs = _loggerProvider.GetAllLogMessages();
                Assert.Equal($"Sentinel watcher initialized for path {directory.Path}", logs[0].FormattedMessage);
                Assert.Equal($"Loading startup context from {startupContextPath}", logs[1].FormattedMessage);
                Assert.Equal($"Loaded keys for 2 functions from startup context", logs[2].FormattedMessage);
                Assert.Equal($"Loaded host keys from startup context", logs[3].FormattedMessage);
            }
        }
Exemplo n.º 46
0
        public void PlaytimeImportTest()
        {
            var   gameId       = "tesId";
            var   libPlugin    = new Mock <LibraryPlugin>(MockBehavior.Loose, null);
            ulong timeToImport = 500;

            libPlugin.Setup(a => a.Id).Returns(Guid.NewGuid());
            libPlugin.Setup(a => a.GetGames(It.IsAny <LibraryGetGamesArgs>())).Returns(() => new List <GameMetadata>
            {
                new GameMetadata()
                {
                    GameId   = gameId,
                    Playtime = timeToImport
                }
            });

            using (var temp = TempDirectory.Create())
                using (var db = new GameDatabase(temp.TempPath))
                    using (var token = new CancellationTokenSource())
                    {
                        db.OpenDatabase();
                        db.ImportGames(libPlugin.Object, true, token.Token);
                        Assert.AreEqual(timeToImport, db.Games.First().Playtime);

                        timeToImport = 600;
                        db.ImportGames(libPlugin.Object, false, token.Token);
                        Assert.AreEqual(500, db.Games.First().Playtime);
                        db.ImportGames(libPlugin.Object, true, token.Token);
                        Assert.AreEqual(timeToImport, db.Games.First().Playtime);

                        var g = db.Games.First();
                        g.Playtime = 0;
                        db.Games.Update(g);
                        Assert.AreEqual(0, db.Games.First().Playtime);
                        db.ImportGames(libPlugin.Object, false, token.Token);
                        Assert.AreEqual(timeToImport, db.Games.First().Playtime);
                    }
        }
Exemplo n.º 47
0
        public async Task GetSecretSnapshots_ReturnsExpected(SecretsRepositoryType repositoryType, ScriptSecretsType secretsType)
        {
            using (var directory = new TempDirectory())
            {
                await _fixture.TestInitialize(repositoryType, directory.Path);

                ScriptSecrets secrets = null;
                if (secretsType == ScriptSecretsType.Host)
                {
                    secrets = new HostSecrets()
                    {
                        MasterKey = new Key("master", "test")
                    };
                }
                else
                {
                    secrets = new FunctionSecrets()
                    {
                        Keys = new List <Key>()
                        {
                            new Key(KeyName, "test")
                        }
                    };
                }
                string testFunctionName = secretsType == ScriptSecretsType.Host ? null : functionName;

                var target = _fixture.GetNewSecretRepository();
                await target.WriteAsync(secretsType, testFunctionName, secrets);

                for (int i = 0; i < 5; i++)
                {
                    await target.WriteSnapshotAsync(secretsType, testFunctionName, secrets);
                }
                string[] files = await target.GetSecretSnapshots(secretsType, testFunctionName);

                Assert.True(files.Length > 0);
            }
        }
Exemplo n.º 48
0
        public void Save_throws_when_readonly_files()
        {
            using var directory = new TempDirectory();
            var contextPath = Path.Combine(directory.Path, "TestContext.cs");

            File.WriteAllText(contextPath, "// Old");

            var entityTypePath = Path.Combine(directory.Path, "TestEntity.cs");

            File.WriteAllText(entityTypePath, "// Old");

            var originalAttributes = File.GetAttributes(contextPath);

            File.SetAttributes(contextPath, originalAttributes | FileAttributes.ReadOnly);
            File.SetAttributes(entityTypePath, originalAttributes | FileAttributes.ReadOnly);
            try
            {
                var scaffolder      = CreateScaffolder();
                var scaffoldedModel = new ScaffoldedModel(new ScaffoldedFile("TestContext.cs", "// TestContext"))
                {
                    AdditionalFiles = { new ScaffoldedFile("TestEntity.cs", "// TestEntity") }
                };

                var ex = Assert.Throws <OperationException>(
                    () => scaffolder.Save(scaffoldedModel, directory.Path, overwriteFiles: true));

                Assert.Equal(
                    DesignStrings.ReadOnlyFiles(
                        directory.Path,
                        string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, "TestContext.cs", "TestEntity.cs")),
                    ex.Message);
            }
            finally
            {
                File.SetAttributes(contextPath, originalAttributes);
                File.SetAttributes(entityTypePath, originalAttributes);
            }
        }
Exemplo n.º 49
0
        public async Task UsePollingFileWatcher_UseActivePolling_HasChanged_SymbolicLink_TargetDeleted(bool useWildcard)
        {
            // Arrange
            using var rootOfFile = new TempDirectory(GetTestFilePath());

            string filePath = Path.Combine(rootOfFile.Path, GetTestFileName());

            File.WriteAllText(filePath, "v1.1");

            using var rootOfLink = new TempDirectory(GetTestFilePath());
            string linkName = GetTestFileName();
            string linkPath = Path.Combine(rootOfLink.Path, linkName);

            File.CreateSymbolicLink(linkPath, filePath);

            string filter = useWildcard ? "*" : linkName;

            using var provider = new PhysicalFileProvider(rootOfLink.Path)
                  {
                      UsePollingFileWatcher = true, UseActivePolling = true
                  };
            IChangeToken token = provider.Watch(filter);

            var tcs = new TaskCompletionSource <bool>();

            token.RegisterChangeCallback(_ => { tcs.TrySetResult(true); }, null);

            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

            cts.Token.Register(() => tcs.TrySetCanceled());

            // Act
            File.Delete(linkPath);

            // Assert
            Assert.True(await tcs.Task,
                        $"Change event was not raised - current time: {DateTime.UtcNow:O}, file LastWriteTimeUtc: {File.GetLastWriteTimeUtc(filePath):O}.");
        }
Exemplo n.º 50
0
        public void Save_works_when_overwriteFiles()
        {
            using (var directory = new TempDirectory())
            {
                var path = Path.Combine(directory.Path, "Test.cs");
                File.WriteAllText(path, "// Old");

                var scaffolder      = CreateScaffolder();
                var scaffoldedModel = new ScaffoldedModel
                {
                    ContextFile = new ScaffoldedFile
                    {
                        Path = "Test.cs",
                        Code = "// Test"
                    }
                };

                var result = scaffolder.Save(scaffoldedModel, directory.Path, outputDir: null, overwriteFiles: true);

                Assert.Equal(path, result.ContextFile);
                Assert.Equal("// Test", File.ReadAllText(path));
            }
        }
Exemplo n.º 51
0
        public void XSDValidationGeneratesInvalidError_2()
        {
            using (var tempDirectory = new TempDirectory())
            {
                Initialize();
                CreateSchema2(tempDirectory.Path);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.XmlResolver         = new XmlUrlResolver();
                settings.Schemas.XmlResolver = new XmlUrlResolver();
                // TempDirectory path must end with a DirectorySeratorChar, otherwise it will throw in the Xml validation.
                settings.Schemas.Add("mainschema", XmlReader.Create(new StringReader(xsd), null, EnsureTrailingSlash(tempDirectory.Path)));
                settings.ValidationType = ValidationType.Schema;
                XmlReader   reader = XmlReader.Create(new StringReader(xml), settings);
                XmlDocument doc    = new XmlDocument();

                doc.Load(reader);

                ValidationEventHandler valEventHandler = new ValidationEventHandler(ValidationCallback);
                doc.Validate(valEventHandler);
                Assert.Equal(0, warningCount);
                Assert.Equal(0, errorCount);
            }
        }
Exemplo n.º 52
0
 public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock()
 {
     // Check the case where Stop or Dispose (they do the same thing) is called from
     // a FSW event callback and make sure we don't Thread.Join to deadlock
     using (var dir = new TempDirectory(GetTestFilePath()))
     {
         string filePath = Path.Combine(dir.Path, "testfile.txt");
         File.Create(filePath).Dispose();
         AutoResetEvent         are      = new AutoResetEvent(false);
         FileSystemWatcher      watcher  = new FileSystemWatcher(Path.GetFullPath(dir.Path), "*");
         FileSystemEventHandler callback = (sender, arg) =>
         {
             watcher.Dispose();
             are.Set();
         };
         watcher.NotifyFilter        = NotifyFilters.FileName | NotifyFilters.LastWrite;
         watcher.Changed            += callback;
         watcher.EnableRaisingEvents = true;
         File.SetLastWriteTime(filePath, File.GetLastWriteTime(filePath).AddDays(1));
         Assert.True(are.WaitOne(10000));
         Assert.Throws <ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
     }
 }
Exemplo n.º 53
0
        public void GivenAssetWithReferenceToUrl_WhenSaveContainer_ThenXmlHasReferenceElementWithUrlAsPath()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings("")
                {
                    SourceDirectory = Mock.Of <IDirectory>(),
                    CacheDirectory  = new FileSystemDirectory(cacheDir)
                };
                var cache     = new BundleCache("VERSION", settings);
                var bundle    = new TestableBundle("~/bundle-1");
                var asset     = StubAsset();
                var reference = new AssetReference("http://test.com", asset.Object, -1, AssetReferenceType.Url);
                asset.SetupGet(a => a.References)
                .Returns(new[] { reference });
                bundle.Assets.Add(asset.Object);

                cache.SaveBundleContainer(new BundleContainer(new Bundle[] { bundle, new ExternalScriptBundle("http://test.com"), }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldContain("<Reference Path=\"http://test.com\" />");
            }
        }
Exemplo n.º 54
0
        public void GivenAssetWithRawFilenameReference_WhenSaveContainer_ThenXmlHasFileElement()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings("")
                {
                    SourceDirectory = Mock.Of <IDirectory>(),
                    CacheDirectory  = new FileSystemDirectory(cacheDir)
                };
                var cache     = new BundleCache("VERSION", settings);
                var bundle    = new TestableBundle("~/bundle-1");
                var asset     = StubAsset();
                var reference = new AssetReference("~/images/test.png", asset.Object, -1, AssetReferenceType.RawFilename);
                asset.SetupGet(a => a.References)
                .Returns(new[] { reference });
                bundle.Assets.Add(asset.Object);

                cache.SaveBundleContainer(new BundleContainer(new[] { bundle }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldContain("<File Path=\"~/images/test.png\" />");
            }
        }
        public static void DuplicateSignedAndUnsignedAssemblies()
        {
            using (TempDirectory dir = new TempDirectory())
                using (TempDirectory dir2 = new TempDirectory())
                    using (TempFile core = new TempFile(Path.Combine(dir.Path, TestData.s_PhonyCoreAssemblySimpleName), TestData.s_PhonyCoreAssemblyImage))
                        using (TempFile tf1 = new TempFile(Path.Combine(dir.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleSignedVersioned100Image))
                            using (TempFile tf2 = new TempFile(Path.Combine(dir2.Path, TestData.s_SimpleVersionedShortName), TestData.s_SimpleUnsignedVersioned100Image))
                            {
                                var resolver = new PathAssemblyResolver(new string[] { core.Path, tf1.Path, tf2.Path });

                                using (var lc = new MetadataLoadContext(resolver, TestData.s_PhonyCoreAssemblyFullName))
                                {
                                    Assert.Equal(1, lc.GetAssemblies().Count());

                                    // These are treated as different since one contains a PublicKeyToken and one does not.
                                    Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleUnsignedVersioned100FullName);
                                    Assembly a2 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned100FullName);
                                    Assert.NotSame(a1, a2);

                                    Assert.Equal(3, lc.GetAssemblies().Count());
                                }
                            }
        }
Exemplo n.º 56
0
        public async Task PurgeOldSecrets_RemovesOldAndKeepsCurrentSecrets()
        {
            using (var directory = new TempDirectory())
            {
                Func <int, string> getFilePath = i => Path.Combine(directory.Path, $"{i}.json");

                var sequence = Enumerable.Range(0, 10);
                var files    = sequence.Select(i => getFilePath(i)).ToList();

                // Create files
                files.ForEach(f => File.WriteAllText(f, "test"));

                var target = new FileSystemSecretsRepository(directory.Path);

                // Purge, passing even named files as the existing functions
                var currentFunctions = sequence.Where(i => i % 2 == 0).Select(i => i.ToString()).ToList();

                await target.PurgeOldSecretsAsync(currentFunctions, new TestTraceWriter(TraceLevel.Off));

                // Ensure only expected files exist
                Assert.True(sequence.All(i => (i % 2 == 0) == File.Exists(getFilePath(i))));
            }
        }
        public async Task RenamedInIndexFile_False_Async()
        {
            using (var tempDir = new TempDirectory())
                using (var repo = CreateRepository(tempDir))
                {
                    var service         = CreatePullRequestService(repo);
                    var repositoryModel = CreateLocalRepositoryModel(repo);
                    var path            = "file.txt";
                    var renamedPath     = "renamed.txt";
                    var file            = Path.Combine(repo.Info.WorkingDirectory, path);
                    var renamedFile     = Path.Combine(repo.Info.WorkingDirectory, renamedPath);
                    File.WriteAllText(file, "contents");
                    Commands.Stage(repo, path);
                    repo.Commit("foo", Author, Author);
                    File.Move(file, renamedFile);
                    Commands.Stage(repo, path);
                    Commands.Stage(repo, renamedPath);

                    var count = await service.CountSubmodulesToSync(repositoryModel).FirstAsync();

                    Assert.That(0, Is.EqualTo(count));
                }
        }
Exemplo n.º 58
0
        public async Task ShouldExposeVideoPath()
        {
            using var tempDirectory = new TempDirectory();
            var context = await Browser.NewContextAsync(
                recordVideo : new RecordVideoOptions
            {
                Dir  = tempDirectory.Path,
                Size = new ViewportSize {
                    Width = 100, Height = 100
                }
            });

            var page = await context.NewPageAsync();

            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");

            string path = await page.Video.GetPathAsync();

            Assert.Contains(tempDirectory.Path, path);
            await context.CloseAsync();

            Assert.True(new FileInfo(path).Exists);
        }
Exemplo n.º 59
0
        public async Task LocalBehindRemote_ReturnRemoteCommitSha()
        {
            using (var temp = new TempDirectory())
            {
                string expectSha;
                var    dir = temp.Directory.FullName;
                using (var repo = new Repository(Repository.Init(dir)))
                {
                    AddCommit(repo); // First commit
                    var commit1 = AddCommit(repo);
                    var commit2 = AddCommit(repo);
                    repo.Reset(ResetMode.Hard, commit1);
                    expectSha = commit1.Sha;
                    AddTrackedBranch(repo, repo.Head, commit2);
                }

                var target = new GitService(new RepositoryFacade());

                var sha = await target.GetLatestPushedSha(dir).ConfigureAwait(false);

                Assert.That(sha, Is.EqualTo(expectSha));
            }
        }
Exemplo n.º 60
0
        public async Task GetExtensions_ReturnsNewlyAddedExtension()
        {
            using (var testDir = new TempDirectory())
            {
                var manager = GetExtensionsManager(testDir.Path);

                var extension = new ExtensionPackageReference
                {
                    Id      = "Microsoft.Azure.WebJobs.Samples.Extension",
                    Version = "1.0.0"
                };

                await manager.AddExtensions(extension);

                IEnumerable <ExtensionPackageReference> extensions = await manager.GetExtensions();

                Assert.Equal(1, extensions.Count());

                var reference = extensions.FirstOrDefault(p => string.Equals(p.Id, extensions.First().Id));
                Assert.NotNull(reference);
                Assert.Equal(extension.Version, reference.Version);
            }
        }