public void GetOrAdd_IgnoresCachedValue_IfGlobalFileWasChangedSinceCacheWasCreated( RazorFileInfo viewStartRazorFileInfo, IFileInfo globalFileInfo) { // Arrange var expectedType = typeof(RuntimeCompileDifferent); var lastModified = DateTime.UtcNow; var viewStartLastModified = DateTime.UtcNow; var content = "some content"; var fileInfo = new TestFileInfo { Length = 1020, Content = content, LastModified = lastModified, PhysicalPath = "Views\\home\\index.cshtml" }; var fileProvider = new TestFileProvider(); fileProvider.AddFile(fileInfo.PhysicalPath, fileInfo); fileProvider.AddFile(viewStartRazorFileInfo.RelativePath, globalFileInfo); var viewCollection = new ViewCollection(); var cache = new CompilerCache(new[] { viewCollection }, TestLoadContext, fileProvider); // Act var result = cache.GetOrAdd(fileInfo.PhysicalPath, compile: _ => CompilationResult.Successful(expectedType)); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result); var actual = result.CompilationResult; Assert.NotNull(actual); Assert.Equal(expectedType, actual.CompiledType); }
public void GetOrAdd_UsesFilesFromCache_IfTimestampDiffers_ButContentAndLengthAreTheSame(long fileTimeUTC) { // Arrange var instance = new RuntimeCompileIdentical(); var length = Encoding.UTF8.GetByteCount(instance.Content); var fileProvider = new TestFileProvider(); var cache = new CompilerCache(new[] { new ViewCollection() }, TestLoadContext, fileProvider); var fileInfo = new TestFileInfo { Length = length, LastModified = DateTime.FromFileTimeUtc(fileTimeUTC), Content = instance.Content }; fileProvider.AddFile(ViewPath, fileInfo); // Act var result = cache.GetOrAdd(ViewPath, compile: _ => { throw new Exception("Shouldn't be called."); }); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result); var actual = result.CompilationResult; Assert.NotNull(actual); Assert.Equal(typeof(PreCompile), actual.CompiledType); }
public void UpdateContent(string subpath, string content) { var old = _content[subpath]; old.TokenSource.Cancel(); _content[subpath] = new TestFileInfo(content); }
static void Main(string[] args) { // 构造例子类. 演示 文本文件写入与读取 TextFile textFile = new TextFile(); // 写入文件 textFile.TestWrite(); // 读取文件. textFile.TestRead(); // 构造例子类. 演示 二进制文件写入与读取 BinFile binFile = new BinFile(); // 写入文件 binFile.TestWrite(); // 读取文件. binFile.TestRead(); // 测试 FileInfo. TestFileInfo.DoTest(TextFile.TEXT_FILE_NAME); TestFileInfo.DoTest(BinFile.BIN_FILE_NAME); Console.ReadLine(); }
public void GetOrAdd_DoesNotCacheCompiledContent_OnCallsAfterInitial() { // Arrange var lastModified = DateTime.UtcNow; var fileProvider = new TestFileProvider(); var cache = new CompilerCache(Enumerable.Empty <RazorFileInfoCollection>(), TestLoadContext, fileProvider); var fileInfo = new TestFileInfo { PhysicalPath = "test", LastModified = lastModified }; fileProvider.AddFile("test", fileInfo); var type = GetType(); var uncachedResult = UncachedCompilationResult.Successful(type, "hello world"); // Act cache.GetOrAdd("test", _ => uncachedResult); var result1 = cache.GetOrAdd("test", _ => { throw new Exception("shouldn't be called."); }); var result2 = cache.GetOrAdd("test", _ => { throw new Exception("shouldn't be called."); }); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result1); Assert.NotSame(CompilerCacheResult.FileNotFound, result2); var actual1 = Assert.IsType <CompilationResult>(result1.CompilationResult); var actual2 = Assert.IsType <CompilationResult>(result2.CompilationResult); Assert.NotSame(uncachedResult, actual1); Assert.NotSame(uncachedResult, actual2); Assert.Same(type, actual1.CompiledType); Assert.Same(type, actual2.CompiledType); }
public IEnumerable <PathContentPair> Generate(string source) { if (source == null) { throw new ArgumentException("Source shouldn't be null"); } List <PathContentPair> resultList = new List <PathContentPair>(); TestFileInfo fileInfo = codeAnalyzer.Analyze(source); List <UsingDirectiveSyntax> commonUsings = fileInfo.Usings.Select((usingStr) => UsingDirective(IdentifierName(usingStr))).ToList(); commonUsings.Add(UsingDirective(IdentifierName("Microsoft.VisualStudio.TestTools.UnitTesting"))); commonUsings.Add(UsingDirective(IdentifierName("Moq"))); foreach (TestClassInfo typeInfo in fileInfo.Classes) { resultList.Add(new PathContentPair(typeInfo.Name + "Test.cs", CompilationUnit() .WithUsings( List <UsingDirectiveSyntax>( CreateClassUsings(typeInfo, commonUsings))) .WithMembers( SingletonList <MemberDeclarationSyntax>( CreateTestClassWithNamespaceDeclaration(typeInfo))) .NormalizeWhitespace().ToFullString())); } return(resultList); }
public void GetOrAdd_RecompilesFile_IfContentAndLengthAreChanged( Type resultViewType, long fileTimeUTC) { // Arrange var instance = (View)Activator.CreateInstance(resultViewType); var length = Encoding.UTF8.GetByteCount(instance.Content); var fileProvider = new TestFileProvider(); var cache = new CompilerCache(new[] { new ViewCollection() }, TestLoadContext, fileProvider); var fileInfo = new TestFileInfo { Length = length, LastModified = DateTime.FromFileTimeUtc(fileTimeUTC), Content = instance.Content }; fileProvider.AddFile(ViewPath, fileInfo); // Act var result = cache.GetOrAdd(ViewPath, compile: _ => CompilationResult.Successful(resultViewType)); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result); var actual = result.CompilationResult; Assert.NotNull(actual); Assert.Equal(resultViewType, actual.CompiledType); }
public IFileInfo GetFileInfo(string subpath) { if (!_content.TryGetValue(subpath, out var fileInfo)) { fileInfo = new TestFileInfo(null); } return(fileInfo); }
private static RazorProjectItem GetProjectItem(string basePath, string path, string content) { var testFileInfo = new TestFileInfo { Content = content, }; return(new FileProviderRazorProjectItem(testFileInfo, basePath, path)); }
protected override void SetupData() { base.SetupData(); _episodesToDelete = new IFileInfo[4]; _episodesToDelete[0] = TestFileInfo.GenerateFile(Path.Combine(_rootFolder, _podcastInfo.Folder), "2010_04_30_1611_title_.mp3"); _episodesToDelete[1] = TestFileInfo.GenerateFile(Path.Combine(_rootFolder, _podcastInfo.Folder), "2010_04_26_1611_title_.mp3"); _episodesToDelete[2] = TestFileInfo.GenerateFile(Path.Combine(_rootFolder, _podcastInfo.Folder), "2010_04_26_1609_title_.mp3"); _episodesToDelete[3] = TestFileInfo.GenerateFile(Path.Combine(_rootFolder, _podcastInfo.Folder), "2010_04_20_1611_title_.mp3"); // note - we do not mark the state.xml or thumbs.db file as being one to delete }
public void GetHash_ThrowsIfHashAlgorithmVersionIsUnknown(int hashAlgorithmVersion) { // Arrange var file = new TestFileInfo(); // Act and Assert ExceptionAssert.ThrowsArgument(() => RazorFileHash.GetHash(file, hashAlgorithmVersion), "hashAlgorithmVersion", "Unsupported hash algorithm."); }
private void OnButtonDownloadClick(object sender, System.EventArgs e) { TestFileInfo selectedFile = (TestFileInfo)cboxFiles.SelectedValue; DownloadFile(selectedFile); // Запуск загрузки в отдельном потоке "сломает" EAP механизм и мы снова начнем получать исключения // InvalidOperationException в методах OnDownloadProgressChanged/OnDownloadDataCompleted //Thread dnldThread = new Thread(DownloadFile); //dnldThread.Start(selectedFile); }
private void DownloadFile(TestFileInfo fileToDownload) { WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += OnDownloadProgressChanged; webClient.DownloadDataCompleted += OnDownloadDataCompleted; // Вызов *Async метода на экземпляре WebClient'a заставляет его "запомнить" поток где был произведен этот вызов // и выполнять делегаты своих событий в этом потоке. Если вызов идет из UI потока, то у нас отпадает // необходимость в использовании метода Invoke или других способов выполнения кода в UI потоке. webClient.DownloadDataAsync(new Uri("http://ftp.byfly.by/test/" + fileToDownload.FileName), fileToDownload); }
public IEnumerator <IFileInfo> GetEnumerator() { var file = new TestFileInfo("@page" + Environment.NewLine + "Original content") { Name = "UpdateablePage.cshtml" }; var files = new List <IFileInfo> { file }; return(files.GetEnumerator()); }
public void GetOrAdd_UsesValueFromCache_IfGlobalHasNotChanged() { // Arrange var instance = new PreCompile(); var length = Encoding.UTF8.GetByteCount(instance.Content); var fileProvider = new TestFileProvider(); var lastModified = DateTime.UtcNow; var fileInfo = new TestFileInfo { Length = length, LastModified = lastModified, Content = instance.Content }; fileProvider.AddFile(ViewPath, fileInfo); var globalContent = "global-content"; var globalFileInfo = new TestFileInfo { Content = globalContent, LastModified = DateTime.UtcNow }; fileProvider.AddFile("_ViewImports.cshtml", globalFileInfo); var globalRazorFileInfo = new RazorFileInfo { Hash = Crc32.Calculate(GetMemoryStream(globalContent)).ToString(CultureInfo.InvariantCulture), HashAlgorithmVersion = 1, LastModified = globalFileInfo.LastModified, Length = globalFileInfo.Length, RelativePath = "_ViewImports.cshtml", FullTypeName = typeof(RuntimeCompileIdentical).FullName }; var precompiledViews = new ViewCollection(); precompiledViews.Add(globalRazorFileInfo); var cache = new CompilerCache(new[] { precompiledViews }, TestLoadContext, fileProvider); // Act var result = cache.GetOrAdd(ViewPath, compile: _ => { throw new Exception("shouldn't be invoked"); }); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result); var actual = result.CompilationResult; Assert.NotNull(actual); Assert.Equal(typeof(PreCompile), actual.CompiledType); }
public TestFileInfo AddFile(string path, string contents) { var fileInfo = new TestFileInfo { Content = contents, PhysicalPath = Path.Combine(Root, NormalizeAndEnsureValidPhysicalPath(path)), Name = Path.GetFileName(path), LastModified = DateTime.UtcNow, }; AddFile(path, fileInfo); return(fileInfo); }
public TestFileInfo AddFile(string path, string contents) { var fileInfo = new TestFileInfo { Content = contents, PhysicalPath = path, Name = Path.GetFileName(path), LastModified = DateTime.UtcNow, }; AddFile(path, fileInfo); return fileInfo; }
public TestFileInfo Analyze(string code) { TestFileInfo testFileInfo = new TestFileInfo(); CompilationUnitSyntax root = CSharpSyntaxTree.ParseText(code).GetCompilationUnitRoot(); foreach (UsingDirectiveSyntax usingEntry in root.Usings) { testFileInfo.Usings.Add(usingEntry.Name.ToString()); } foreach (ClassDeclarationSyntax classDeclaration in root.DescendantNodes().OfType <ClassDeclarationSyntax>()) { testFileInfo.Classes.Add(CreateClassInfo(classDeclaration)); } return(testFileInfo); }
public void GetOrAdd_IgnoresCachedValueIfFileIsIdentical_ButViewImportsWasAdedSinceTheCacheWasCreated() { // Arrange var expectedType = typeof(RuntimeCompileDifferent); var fileProvider = new TestFileProvider(); var collection = new ViewCollection(); var precompiledFile = collection.FileInfos[0]; precompiledFile.RelativePath = "Views\\home\\index.cshtml"; var cache = new CompilerCache(new[] { collection }, TestLoadContext, fileProvider); var testFile = new TestFileInfo { Content = new PreCompile().Content, LastModified = precompiledFile.LastModified, PhysicalPath = precompiledFile.RelativePath }; fileProvider.AddFile(precompiledFile.RelativePath, testFile); var relativeFile = new RelativeFileInfo(testFile, testFile.PhysicalPath); // Act 1 var result1 = cache.GetOrAdd(testFile.PhysicalPath, compile: _ => { throw new Exception("should not be called"); }); // Assert 1 Assert.NotSame(CompilerCacheResult.FileNotFound, result1); var actual1 = result1.CompilationResult; Assert.NotNull(actual1); Assert.Equal(typeof(PreCompile), actual1.CompiledType); // Act 2 var globalTrigger = fileProvider.GetTrigger("Views\\_ViewImports.cshtml"); globalTrigger.IsExpired = true; var result2 = cache.GetOrAdd(testFile.PhysicalPath, compile: _ => CompilationResult.Successful(expectedType)); // Assert 2 Assert.NotSame(CompilerCacheResult.FileNotFound, result2); var actual2 = result2.CompilationResult; Assert.NotNull(actual2); Assert.Equal(expectedType, actual2.CompiledType); }
private TestFileInfo AddToFiles(string directory, TestFileInfo fileInfo) { if (!String.IsNullOrEmpty(directory)) { directory = directory.ToLower(); AddToFolders(directory); List <TestFileInfo> files; if (!_Files.TryGetValue(directory, out files)) { files = new List <TestFileInfo>(); _Files.Add(directory, files); } files.Add(fileInfo); } return(fileInfo); }
public void GetOrAdd_DoesNotReadFileFromFileSystemAfterPrecompiledViewIsVerified() { // Arrange var precompiledViews = new ViewCollection(); var mockFileProvider = new Mock <TestFileProvider> { CallBase = true }; var fileProvider = mockFileProvider.Object; var precompiledView = precompiledViews.FileInfos[0]; var fileInfo = new TestFileInfo { Length = precompiledView.Length, LastModified = precompiledView.LastModified, }; fileProvider.AddFile(ViewPath, fileInfo); var cache = new CompilerCache(new[] { precompiledViews }, TestLoadContext, fileProvider); // Act 1 var result1 = cache.GetOrAdd(ViewPath, compile: _ => { throw new Exception("shouldn't be invoked"); }); // Assert 1 Assert.NotSame(CompilerCacheResult.FileNotFound, result1); var actual1 = result1.CompilationResult; Assert.NotNull(actual1); Assert.Equal(typeof(PreCompile), actual1.CompiledType); mockFileProvider.Verify(v => v.GetFileInfo(ViewPath), Times.Once()); // Act 2 var result2 = cache.GetOrAdd(ViewPath, compile: _ => { throw new Exception("shouldn't be invoked"); }); // Assert 2 Assert.NotSame(CompilerCacheResult.FileNotFound, result2); var actual2 = result2.CompilationResult; Assert.NotNull(actual2); Assert.Equal(typeof(PreCompile), actual2.CompiledType); mockFileProvider.Verify(v => v.GetFileInfo(ViewPath), Times.Once()); }
private void OnDownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { progressDownload.Value = progressDownload.Maximum; progressDownload.Update(); TestFileInfo requestedFile = (TestFileInfo)e.UserState; byte[] data = e.Result; // Вычисляем MD5 хеш скачанных данных чтобы убедиться что файл скачался без ошибок MD5CryptoServiceProvider md5svc = new MD5CryptoServiceProvider(); byte[] hashBytes = md5svc.ComputeHash(data); string hash = ByteArrayToString(hashBytes); if (requestedFile.MD5Hash.Equals(hash, StringComparison.OrdinalIgnoreCase)) { MessageBox.Show("Успех!", "Загрузка файла", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Ошибка!", "Загрузка файла", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void TestInitialise() { _ClassFactorySnapshot = Factory.TakeSnapshot(); _Clock = new ClockMock() { UtcNowValue = _StandardDate }; Factory.RegisterInstance <IClock>(_Clock.Object); CreateBackgroundWorkerMock(); _HeartbeatService = TestUtilities.CreateMockSingleton <IHeartbeatService>(); _Log = TestUtilities.CreateMockSingleton <ILog>(); _Log.Setup(g => g.WriteLine(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Callback(() => { throw new InvalidOperationException("Log was unexpectedly written"); }); _CacheChangedEvent = new EventRecorder <EventArgs>(); _LastModifiedUtc = new DateTime(2009, 8, 7, 6, 5, 4, 321); _Files = new Dictionary <string, List <TestFileInfo> >(); _Folders = new List <string>(); _Provider = new Mock <IDirectoryCacheProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); _Provider.Setup(p => p.FolderExists(It.IsAny <string>())).Returns((string folder) => { if (folder != null && folder.EndsWith(@"\")) { folder = folder.Substring(0, folder.Length - 1); } return(_Folders.Contains(folder.ToLower())); }); _Provider.Setup(p => p.GetSubFoldersInFolder(It.IsAny <string>())).Returns((string folder) => { if (folder != null && !folder.EndsWith(@"\")) { folder += '\\'; } var subFolders = _Folders.Where(r => r.StartsWith(folder, StringComparison.OrdinalIgnoreCase) && r.IndexOf('\\', folder.Length) == -1) .Select(r => Path.GetFileName(r)) .ToList(); return(subFolders); }); _Provider.Setup(p => p.GetFilesInFolder(It.IsAny <string>())).Returns((string folder) => { List <TestFileInfo> files; if (folder != null && folder.EndsWith(@"\")) { folder = folder.Substring(0, folder.Length - 1); } _Files.TryGetValue(folder.ToLower(), out files); return((IEnumerable <TestFileInfo>)files ?? new TestFileInfo[0]); }); _Provider.Setup(p => p.GetFileInfo(It.IsAny <string>())).Returns((string fullPath) => { TestFileInfo result = null; var folder = (Path.GetDirectoryName(fullPath) ?? "").ToLower(); var fileName = Path.GetFileName(fullPath); List <TestFileInfo> files; if (_Files.TryGetValue(folder, out files)) { result = files.FirstOrDefault(r => r.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase)); } return(result); }); _DirectoryCache = Factory.Resolve <IDirectoryCache>(); _DirectoryCache.Provider = _Provider.Object; }
public void GetOrAdd_IgnoresCachedValueIfFileIsIdentical_ButGlobalWasDeletedSinceCacheWasCreated() { // Arrange var expectedType = typeof(RuntimeCompileDifferent); var lastModified = DateTime.UtcNow; var fileProvider = new TestFileProvider(); var viewCollection = new ViewCollection(); var precompiledView = viewCollection.FileInfos[0]; precompiledView.RelativePath = "Views\\Index.cshtml"; var viewFileInfo = new TestFileInfo { Content = new PreCompile().Content, LastModified = precompiledView.LastModified, PhysicalPath = precompiledView.RelativePath }; fileProvider.AddFile(viewFileInfo.PhysicalPath, viewFileInfo); var globalFileInfo = new TestFileInfo { PhysicalPath = "Views\\_ViewImports.cshtml", Content = "viewstart-content", LastModified = lastModified }; var globalFile = new RazorFileInfo { FullTypeName = typeof(RuntimeCompileIdentical).FullName, RelativePath = globalFileInfo.PhysicalPath, LastModified = globalFileInfo.LastModified, Hash = RazorFileHash.GetHash(globalFileInfo, hashAlgorithmVersion: 1), HashAlgorithmVersion = 1, Length = globalFileInfo.Length }; fileProvider.AddFile(globalFileInfo.PhysicalPath, globalFileInfo); viewCollection.Add(globalFile); var cache = new CompilerCache(new[] { viewCollection }, TestLoadContext, fileProvider); // Act 1 var result1 = cache.GetOrAdd(viewFileInfo.PhysicalPath, compile: _ => { throw new Exception("should not be called"); }); // Assert 1 Assert.NotSame(CompilerCacheResult.FileNotFound, result1); var actual1 = result1.CompilationResult; Assert.NotNull(actual1); Assert.Equal(typeof(PreCompile), actual1.CompiledType); // Act 2 var trigger = fileProvider.GetTrigger(globalFileInfo.PhysicalPath); trigger.IsExpired = true; var result2 = cache.GetOrAdd(viewFileInfo.PhysicalPath, compile: _ => CompilationResult.Successful(expectedType)); // Assert 2 Assert.NotSame(CompilerCacheResult.FileNotFound, result2); var actual2 = result2.CompilationResult; Assert.NotNull(actual2); Assert.Equal(expectedType, actual2.CompiledType); }