Пример #1
0
		public void ReadLiftFile_CurrentVersion_Happy()
		{
			using (TempFile f = new TempFile(string.Format("<lift version='{0}'></lift>", Validator.LiftVersion)))
			{
				_parser.ReadLiftFile(f.Path);
			}
		}
Пример #2
0
        public void FileSystemWatcher_Renamed_Negative()
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
            using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
            using (var watcher = new FileSystemWatcher(testDirectory.Path))
            {
                // put everything in our own directory to avoid collisions
                watcher.Path = Path.GetFullPath(dir.Path);
                watcher.Filter = "*.*";
                AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Renamed);

                watcher.EnableRaisingEvents = true;

                // run all scenarios together to avoid unnecessary waits, 
                // assert information is verbose enough to trace to failure cause

                // create a file
                using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
                using (var testDir = new TempDirectory(Path.Combine(dir.Path, "dir")))
                {
                    // change a file
                    File.WriteAllText(testFile.Path, "changed");

                    // deleting a file & directory by leaving the using block
                }

                ExpectNoEvent(eventOccurred, "created");
            }
        }
Пример #3
0
 public void Should_create_temporary_file()
 {
     using( var file = new TempFile() )
     {
         Assert.IsTrue(file.FileInfo.Exists);
     }
 }
        public void Creating_thumbnail_creates_new_entry_in_cache()
        {
            var cache = generator.Cache as ThumbnailCache;
            Assert.IsNotNull(cache);
            Assert.AreEqual(0, cache.CacheDirectory.GetFiles().Length);

            using( var thumb = new TempFile()) // This will be the location of the thumbnail
            using (var image = new TempFile("{0}.jpg")) // This is the test image we will make a thumb out of
            using (var destStream = image.FileInfo.OpenWrite()) // Writes the test image data to the test image file
            using (var imageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Foundation.Tests.Resources.TestImage.jpg"))
            {
                var buffer = new byte[9012];
                var bytesRead = imageStream.Read(buffer, 0, buffer.Length);
                while (bytesRead > 0)
                {
                    destStream.Write(buffer, 0, bytesRead);
                    bytesRead = imageStream.Read(buffer, 0, buffer.Length);
                }

                destStream.Close();
                imageStream.Close();

                // Create thumbnail
                generator.Generate(image.FileInfo.FullName, thumb.FileInfo.FullName);
            }

            Assert.AreEqual(1, ((ThumbnailCache) generator.Cache).CacheDirectory.GetFiles().Length);
        }
Пример #5
0
		public void IsMigrationNeeded_ReturnsTrue()
		{
			using (TempFile f = new TempFile("<lift version='0.10'></lift>"))
			{
				Assert.IsTrue(Migrator.IsMigrationNeeded(f.Path));
			}
		}
Пример #6
0
		public void IsMigrationNeeded_Latest_ReturnsFalse()
		{
			using (TempFile f = new TempFile(string.Format("<lift version='{0}'></lift>", Validator.LiftVersion)))
			{
				Assert.IsFalse(Migrator.IsMigrationNeeded(f.Path));
			}
		}
Пример #7
0
        public void DataShared()
        {
            // Create a new file and load it into an MMF
            using (TempFile file = new TempFile(GetTestFilePath(), 4096))
            using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, fs.Length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
            using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
            {
                // Write some known data to the map
                long capacity = acc.Capacity;
                for (int i = 0; i < capacity; i++)
                {
                    acc.Write(i, (byte)i);
                }
                acc.Flush();

                // Spawn and then wait for the other process, which will verify the data and write its own known pattern
                RemoteInvoke("DataShared_OtherProcess", file.Path).Dispose();

                // Now verify we're seeing the data from the other process
                for (int i = 0; i < capacity; i++)
                {
                    Assert.Equal((byte)(capacity - i - 1), acc.ReadByte(i));
                }
            }
        }
 internal void AddBytes(byte[] data, int offset, int length)
 {
     if (this._completed)
     {
         throw new InvalidOperationException();
     }
     if (length > 0)
     {
         if (this._file == null)
         {
             if ((this._length + length) <= this._data.Length)
             {
                 Array.Copy(data, offset, this._data, this._length, length);
                 this._length += length;
                 return;
             }
             if ((this._length + length) <= this._fileThreshold)
             {
                 byte[] destinationArray = new byte[this._fileThreshold];
                 if (this._length > 0)
                 {
                     Array.Copy(this._data, 0, destinationArray, 0, this._length);
                 }
                 Array.Copy(data, offset, destinationArray, this._length, length);
                 this._data = destinationArray;
                 this._length += length;
                 return;
             }
             this._file = new TempFile();
             this._file.AddBytes(this._data, 0, this._length);
         }
         this._file.AddBytes(data, offset, length);
         this._length += length;
     }
 }
		public void DeleteWritingSystemId(string id)
		{
			var fileToBeWrittenTo = new IO.TempFile();
			var reader = XmlReader.Create(_liftFilePath, Xml.CanonicalXmlSettings.CreateXmlReaderSettings());
			var writer = XmlWriter.Create(fileToBeWrittenTo.Path, Xml.CanonicalXmlSettings.CreateXmlWriterSettings());
			//System.Diagnostics.Process.Start(fileToBeWrittenTo.Path);
			try
			{
				bool readerMovedByXmlDocument = false;
				while (readerMovedByXmlDocument || reader.Read())
				{
					readerMovedByXmlDocument = false;
					var xmldoc = new XmlDocument();
					if (reader.NodeType == XmlNodeType.Element && reader.Name == "entry")
					{
						var entryFragment = xmldoc.ReadNode(reader);
						readerMovedByXmlDocument = true;
						var nodesWithLangId = entryFragment.SelectNodes(String.Format("//*[@lang='{0}']", id));
						if (nodesWithLangId != null)
						{
							foreach (XmlNode node in nodesWithLangId)
							{
								var parent = node.SelectSingleNode("parent::*");
								if (node.Name == "gloss")
								{
									parent.RemoveChild(node);
								}
								else
								{
									var siblingNodes =
										node.SelectNodes("following-sibling::form | preceding-sibling::form");
									if (siblingNodes.Count == 0)
									{
										var grandParent = parent.SelectSingleNode("parent::*");
										grandParent.RemoveChild(parent);
									}
									else
									{
										parent.RemoveChild(node);
									}
								}
							}
						}
						entryFragment.WriteTo(writer);
					}
					else
					{
						writer.WriteNodeShallow(reader);
					}
					//writer.Flush();
				}
			}
			finally
			{
				reader.Close();
				writer.Close();
			}
			File.Delete(_liftFilePath);
			fileToBeWrittenTo.MoveTo(_liftFilePath);
		}
Пример #10
0
		public void SenseLiteralDefinition_WasOnSense_MovedToEntry()
		{
			using (TempFile f = new TempFile("<lift version='0.12' producer='tester'>" +
				"<entry>" +
				"<sense>" +
				"<field type='LiteralMeaning' dateCreated='2009-03-31T08:28:37Z'><form lang='en'><text>trial</text></form></field>" +
				"<trait name='SemanticDomainDdp4' value='6.1.2.9 Opportunity'/>" +
				"</sense>" +
				"</entry>" +
				"</lift>"))
			{
				var path = Migrator.MigrateToLatestVersion(f.Path);
				try
				{
					Assert.AreEqual(Validator.LiftVersion, Validator.GetLiftVersion(path));
					AssertXPathAtLeastOne("//lift[@producer='tester']", path);
					AssertXPathAtLeastOne("//entry/field[@type='literal-meaning']", path);
					AssertXPathNotFound("//entry/sense/field", path);
					AssertXPathAtLeastOne("//entry/sense/trait[@name='semantic-domain-ddp4']", path);
					AssertXPathNotFound("//entry/sense/trait[@name='SemanticDomainDdp4']", path);
				}
				finally
				{
					File.Delete(path);
				}
			}
		}
			public TestEnvironment(string rfctag, string rfctag2)
			{
				_folder = new TemporaryFolder("WritingSystemsInoptionListFileHelper");
				var pathtoOptionsListFile1 = Path.Combine(_folder.Path, "test1.xml");
				_optionListFile = new IO.TempFile(String.Format(_optionListFileContent, rfctag, rfctag2));
				_optionListFile.MoveTo(pathtoOptionsListFile1);
			}
Пример #12
0
		public void MigrateToLatestVersion_HasCurrentVersion_Throws()
		{
			using (TempFile f = new TempFile(string.Format("<lift version='{0}'></lift>", Validator.LiftVersion)))
			{
				Migrator.MigrateToLatestVersion(f.Path);
			}
		}
Пример #13
0
		public void MigrateToLatestVersion_VersionWithoutMigrationXsl_Throws()
		{
			using (TempFile f = new TempFile("<lift version='0.5'></lift>"))
			{
				Migrator.MigrateToLatestVersion(f.Path);
			}
		}
Пример #14
0
		public void ReadLiftFile_OldVersion_Throws()
		{
			using (TempFile f = new TempFile(string.Format("<lift version='{0}'></lift>", /*Validator.LiftVersion*/ "0.0")))
			{
				_parser.ReadLiftFile(f.Path);
			}
		}
			public TestEnvironment(string liftFileContent)
			{
				_folder = new TemporaryFolder("WritingSystemsInLiftFileHelper");
				var pathtoLiftFile1 = Path.Combine(_folder.Path, "test1.lift");
				_liftFile1 = new IO.TempFile(liftFileContent);
				_liftFile1.MoveTo(pathtoLiftFile1);
				Helper = new WritingSystemsInLiftFileHelper(WritingSystems, _liftFile1.Path);
			}
Пример #16
0
 public void Can_read_and_write_text()
 {
     using( var file = new TempFile() )
     {
         var text = TestStrings.Internationalisation;
         file.WriteAllText(text);
         Assert.AreEqual(text, file.ReadAllText());
     }
 }
Пример #17
0
 public void Allows_constructor_argument_to_choose_filename()
 {
     using( var file = new TempFile("{0}.gif"))
     {
         file.FileInfo.Refresh();
         Assert.IsTrue(file.FileInfo.Name.EndsWith(".gif", StringComparison.OrdinalIgnoreCase));
         Assert.IsTrue(file.FileInfo.Exists);
     }
 }
Пример #18
0
        public void GetMappingCollection_returns_mapping()
        {
            var edmxContents = @"<?xml version='1.0'?>
<Edmx Version='3.0' xmlns='http://schemas.microsoft.com/ado/2009/11/edmx'>
  <Runtime>
    <ConceptualModels>
      <Schema Namespace='Model' Alias='Self' annotation:UseStrongSpatialTypes='false' xmlns:annotation='http://schemas.microsoft.com/ado/2009/02/edm/annotation' xmlns='http://schemas.microsoft.com/ado/2009/11/edm'>
        <EntityContainer Name='DatabaseEntities' annotation:LazyLoadingEnabled='true'>
          <EntitySet Name='Entities' EntityType='Model.Entity' />
        </EntityContainer>
        <EntityType Name='Entity'>
          <Key>
            <PropertyRef Name='Id' />
          </Key>
          <Property Name='Id' Type='Int32' Nullable='false' annotation:StoreGeneratedPattern='Identity' />
        </EntityType>
      </Schema>
    </ConceptualModels>
    <Mappings>
      <Mapping Space='C-S' xmlns='http://schemas.microsoft.com/ado/2009/11/mapping/cs'>
        <EntityContainerMapping StorageEntityContainer='ModelStoreContainer' CdmEntityContainer='DatabaseEntities'>
          <EntitySetMapping Name='Entities'>
            <EntityTypeMapping TypeName='Model.Entity'>
              <MappingFragment StoreEntitySet='Entities'>
                <ScalarProperty Name='Id' ColumnName='Id' />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>
        </EntityContainerMapping>
      </Mapping>
    </Mappings>
    <StorageModels>
      <Schema Namespace='Model.Store' Alias='Self' Provider='System.Data.SqlClient' ProviderManifestToken='2008' xmlns:store='http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator' xmlns='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'>
        <EntityContainer Name='ModelStoreContainer'>
          <EntitySet Name='Entities' EntityType='Model.Store.Entities' store:Type='Tables' Schema='dbo' />
        </EntityContainer>
        <EntityType Name='Entities'>
          <Key>
            <PropertyRef Name='Id' />
          </Key>
          <Property Name='Id' Type='int' Nullable='false' StoreGeneratedPattern='Identity' />
        </EntityType>
      </Schema>
    </StorageModels>
  </Runtime>
</Edmx>";
            StorageMappingItemCollection mappingCollection;

            using (var edmx = new TempFile(edmxContents))
            {
                mappingCollection = new EdmxUtility(edmx.FileName)
                    .GetMappingCollection();
            }

            Assert.True(mappingCollection.Contains("DatabaseEntities"));
        }
Пример #19
0
 public void AddNewPath_PathExists_PathAtTopOfList()
 {
     using (TempFile existingFile = new TempFile())
     {
         _MostRecentPathsList.AddNewPath(existingFile.FileName);
         string[] mruPaths = _MostRecentPathsList.Paths;
         Assert.AreEqual(1, mruPaths.Length);
         Assert.AreEqual(existingFile.FileName, mruPaths[0]);
     }
 }
Пример #20
0
 public void WrapScriptBlockWithScriptTag()
 {
     using (var tempFile = new TempFile())
     {
         Assert.Equal(
           String.Format(ScriptResources.ScriptIncludeFormat, tempFile.FileName),
           new ScriptInclude(tempFile.FileName).ToScriptFragment()
         );
     }
 }
Пример #21
0
 public void Add_takes_filename_and_dimensions_and_creates_new_file_in_cache()
 {
     using( var temp = new TempFile())
     {
         File.WriteAllText( temp.FileInfo.FullName, "Test Data");
         cache.Add(temp.FileInfo.FullName, 100, 100);
         var cached = cache.GetCacheFile(temp.FileInfo.FullName, 100, 100);
         Assert.IsNotNull(cached);
         Assert.AreEqual("Test Data", File.ReadAllText(cached.FullName));
     }
 }
Пример #22
0
 public void SetPaths_InitializeWithValues_ValuesWereInitialized()
 {
     using (TempFile file1 = new TempFile(), file2 = new TempFile(), file3 = new TempFile())
     {
         _MostRecentPathsList.Paths = new string[] {file1.FileName, file2.FileName, file3.FileName};
         Assert.AreEqual(3, _MostRecentPathsList.Paths.Length);
         Assert.AreEqual(file1.FileName, _MostRecentPathsList.Paths[0]);
         Assert.AreEqual(file2.FileName, _MostRecentPathsList.Paths[1]);
         Assert.AreEqual(file3.FileName, _MostRecentPathsList.Paths[2]);
     }
 }
Пример #23
0
 public void CreateFromFile(int capacity)
 {
     // Note that the test results will include the disposal overhead of both the MemoryMappedFile
     // as well as the Accessor for it
     foreach (var iteration in Benchmark.Iterations)
         using (TempFile file = new TempFile(GetTestFilePath(), capacity))
         using (iteration.StartMeasurement())
         using (MemoryMappedFile mmfile = MemoryMappedFile.CreateFromFile(file.Path))
         using (mmfile.CreateViewAccessor(capacity / 4, capacity / 2))
         { }
 }
Пример #24
0
        public void CanImplicitlyConvertToString()
        {
            using (var tempFile = new TempFile())
            {
                var scriptInclude = new ScriptInclude(tempFile.FileName);

                String script = scriptInclude;

                Assert.Equal(scriptInclude.ToScriptFragment(), script);
            }
        }
Пример #25
0
        public void FileSystemWatcher_EmptyAction_TriggersNothing()
        {
            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)))
            {
                Action action = () => { };

                ExpectEvent(watcher, 0, action, expectedPath: file.Path);
            }
        }
Пример #26
0
		public void CanProvideChangeRecord_AfterReset_True()
		{
			using (TempFile working = new TempFile("<lift version='0.12'/>"))
			{
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);
					detector.Reset();
					Assert.IsTrue(detector.CanProvideChangeRecord);
				}
			}
		}
Пример #27
0
 public void FileSystemWatcher_Renamed_FileInNestedDirectory()
 {
     TestNestedDirectoriesHelper(GetTestFilePath(), WatcherChangeTypes.Renamed | WatcherChangeTypes.Created, (AutoResetEvent are, TempDirectory ttd) =>
     {
         using (var nestedFile = new TempFile(Path.Combine(ttd.Path, "nestedFile")))
         {
             ExpectEvent(are, "file created");
             File.Move(nestedFile.Path, nestedFile.Path + "_2");
             ExpectEvent(are, "renamed");
         }
     });
 }
Пример #28
0
        public void Should_delete_temporary_file_when_finished()
        {
            string filename;

            using( var file = new TempFile() )
            {
                filename = file.FileInfo.FullName;
                Assert.IsTrue(file.FileInfo.Exists);
            }

            Assert.IsFalse(File.Exists(filename));
        }
Пример #29
0
        public void FileSystemWatcher_FileInfoGetter_TriggersNothing()
        {
            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)))
            {
                FileAttributes res;
                Action action = () => res = new FileInfo(file.Path).Attributes;

                ExpectEvent(watcher, 0, action, expectedPath: file.Path);
            }
        }
Пример #30
0
		public void GetChangeReport_NoChanges_PerformanceTest()
		{
			using (TempFile working = new TempFile(_originalLift))
			{
				int howManyEntries = 10000;
				Debug.WriteLine("running test using "+howManyEntries.ToString()+" entries");
				using (XmlWriter w = XmlWriter.Create(working.Path))
				{
					w.WriteStartElement("lift");
					for (int i = 0; i < howManyEntries; i++)
					{
						w.WriteStartElement("entry");
						w.WriteAttributeString("id", i.ToString());
						w.WriteElementString("lexical-unit", "<form lang='x'><text>"
															 + Path.GetRandomFileName()
															 //just a way to get some random text
															 + "</text></form>");
						w.WriteElementString("gloss", "<form lang='y'><text>"
													  + Path.GetRandomFileName() //just a way to get some random text
													  + "</text></form>");
						w.WriteEndElement();
					}
					w.WriteEndElement();
				}
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);

					System.Diagnostics.Stopwatch timer = new Stopwatch();
					timer.Start();
					detector.Reset();
					timer.Stop();
					Debug.WriteLine("reset took "+timer.Elapsed.TotalSeconds+" seconds");

					timer.Reset();
					timer.Start();
					ILiftChangeReport report = detector.GetChangeReport(null);
					timer.Stop();
					Debug.WriteLine("getting report took " + timer.Elapsed.TotalSeconds + " seconds");

					timer.Reset();
					timer.Start();
					for (int i = 0; i < howManyEntries; i++)
					{
						report.GetChangeType(i.ToString());
					}
				   timer.Stop();
				   Debug.WriteLine("Time to inquire about each entry " + timer.Elapsed.TotalSeconds + " seconds");

				}
			}
		}