public void LoadingAndSavingResultsFileTest1_1()
        {
            using (var settingsFile = new TempFile(SettingsFileAccessor1_1Test.Xml))
            using (var resultsFile = new TempFile(ResultsFileAccessor1_1Test.Xml, StreamOptions.GZip))
            {
                var userInfo = EPuzzleUserInfo.Load(settingsFile.Name, resultsFile.Name);

                Assert.AreEqual(Guid.Parse("fd48c0a4-95fc-4797-94a1-adcfd38fbdc2"), userInfo.UserId);
                Assert.AreEqual("User01", userInfo.UserName);

                CollectionAssert.AreEquivalent(new []
                {
                    new MondaiResult("mondai001", DateTime.Parse("2012-10-06T18:23:46.199375+09:00"), TimeSpan.FromMinutes(1.5d), Difficulty.Normal),
                    new MondaiResult("mondai002", DateTime.Parse("2012-10-07T18:23:46.199375+09:00"), TimeSpan.FromMinutes(1.5d), Difficulty.Hard),
                }, userInfo.MondaiResults);

                Assert.AreEqual(3, userInfo.Medals.Count());
                Assert.AreEqual(Difficulty.Normal, userInfo.Medals.First(x => x.MondaiId == "fc8dd6ac-5e91-4bb3-a455-98d49c2bce5f").Difficulty);
                Assert.AreEqual(Difficulty.Normal, userInfo.Medals.First(x => x.MondaiId == "ed437ba5-95db-4bd8-80b9-46f9454e758c").Difficulty);
                Assert.AreEqual(Difficulty.Hard, userInfo.Medals.First(x => x.MondaiId == "0fd20539-9964-40e2-ab00-12373796a950").Difficulty);

                using (var savedFile = new TempFile())
                {
                    userInfo.SaveResultsFile(savedFile.Name, "1.1");
                    FileAssert.AreEqual(resultsFile.Name, savedFile.Name);
                }
            }
        }
Esempio n. 2
0
		public void Save_UsingStream_RoundTripsUtf8File()
		{
			// ŋ (velar nasal)--> ŋ
			// β (greek beta) (03B2) --> β
			using (var input = TempFile.CreateAndGetPathButDontMakeTheFile())
			{
				var source = "<!DOCTYPE html><html><head> <meta charset='UTF-8'></head><body>ŋ β</body></html>";
				
				using(var stream = new MemoryStream(Encoding.UTF8.GetBytes(source)))
				using (var tidy = Document.FromStream(stream))
				{
					tidy.CharacterEncoding = EncodingType.Utf8; 
//					tidy.InputCharacterEncoding = EncodingType.Utf8;
//					tidy.OutputCharacterEncoding = EncodingType.Utf8;

					tidy.CleanAndRepair();
					using (var output = new TempFile())
					{
						tidy.Save(output.Path);
						var newContents = File.ReadAllText(output.Path);
						Assert.IsTrue(newContents.Contains("ŋ"), newContents);
					}
				}
			}
		}
        public void op_Execute_IEnumerable()
        {
            using (var file = new TempFile())
            {
                using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"Cavity.Build.MSBuildCompliance.xml"))
                {
                    if (null != resource)
                    {
                        using (var reader = new StreamReader(resource))
                        {
                            file.Info.Append(reader.ReadToEnd());
                        }
                    }
                }

                var obj = new MSBuildCompliance
                              {
                                  BuildEngine = new Mock<IBuildEngine>().Object,
                                  Projects = new ITaskItem[]
                                                 {
                                                     new TaskItem(file.Info.FullName)
                                                 },
                                  XPath = "0=count(/b:Project/b:PropertyGroup[@Condition][not(b:WarningLevel[text()='4'])])"
                              };

                Assert.True(obj.Execute());
            }
        }
Esempio n. 4
0
        public void op_Execute_IEnumerable()
        {
            using (var file = new TempFile())
            {
                file.Info.AppendLine("CANONICAL,SYNONYMS");
                file.Info.AppendLine("1,One");
                file.Info.AppendLine("1,Unit");

                var obj = new LexiconTidy
                {
                    BuildEngine = new Mock<IBuildEngine>().Object,
                    Paths = new ITaskItem[]
                    {
                        new TaskItem(file.Info.FullName)
                    }
                };

                Assert.True(obj.Execute());

                file.Info.Refresh();
                Assert.True(file.Info.Exists);

                Assert.True(File.ReadAllText(file.Info.FullName).Contains("1,One;Unit"));
            }
        }
        public void AnkimonTest()
        {
            using (var tempFile = new TempFile())
            {
                FileUtility.Save(tempFile.Value, TestResources.Mondai03);
                var mondaiDocument = MondaiDocument.Load(tempFile.Value);

                // Daimonの親はMondaiDocument
                var daimon = mondaiDocument.GetItem("daimon3");
                Assert.AreSame(mondaiDocument, daimon.Parent);

                var chumon = mondaiDocument.GetItem("3-3");
                Assert.AreEqual(4, chumon.Items.Count());
                var ankimon = (Ankimon)mondaiDocument.GetItem("3-3-1");
                Assert.AreSame(chumon, ankimon.Parent);
                Assert.IsInstanceOf<Ankimon>(ankimon);
                var ankimonItem = ankimon.AnkimonItems[0];
                Assert.IsInstanceOf<AnkimonItem>(ankimonItem);
                Assert.AreEqual("泳ぐ", ankimonItem.Name);
                CollectionAssert.AreEqual(new [] { "swim", "swam", "swum", }, ankimonItem.MondaiWords.Select(x => x.Text));

                Assert.IsInstanceOf<Shomon>(mondaiDocument.GetItem("3-3-2"));
                CollectionAssert.AreEqual(new [] { "3-3-1", "3-3-2", "3-3-3", "3-3-4", }, chumon.Items.Select(x => x.Id));
            }
        }
Esempio n. 6
0
        public void Process(Crawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            using (TempFile tempFile = new TempFile())
            {
                using (FileStream fs = new FileStream(tempFile.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000))
                using (Stream input = propertyBag.GetResponse())
                {
                    input.CopyToStream(fs);
                }

                UltraID3 id3 = new UltraID3();
                id3.Read(tempFile.FileName);

                propertyBag["MP3_Album"].Value = id3.Album;
                propertyBag["MP3_Artist"].Value = id3.Artist;
                propertyBag["MP3_Comments"].Value = id3.Comments;
                propertyBag["MP3_Duration"].Value = id3.Duration;
                propertyBag["MP3_Genre"].Value = id3.Genre;
                propertyBag["MP3_Title"].Value = id3.Title;
            }
        }
Esempio n. 7
0
 public void ctor_FileInfo()
 {
     using (var temp = new TempFile())
     {
         Assert.NotNull(new ExcelWorksheet(temp.Info));
     }
 }
 public void LoadingAndSavingTest()
 {
     var text = @"version = 1.1
     document
     {
     prop1 = a
     obj1
     {
     prop2 = b
     obj2
     {
     prop3 = c
     }
     }
     }
     ";
     using (var tempFile = new TempFile(text))
     {
         var doc = FishDocument.Load(tempFile.Name);
         using (var savedFile = new TempFile())
         {
             doc.Save(savedFile.Name);
     //					TestUtility.CompareWithWinMerge(tempFile.Name, savedFile.Name);
             FileAssert.AreEqual(tempFile.Name, savedFile.Name);
         }
     }
 }
Esempio n. 9
0
		public void Construct_FileDoesExistButEmpty_OK()
		{
			using (var f = new TempFile())
			{
				var x = AudioFactory.CreateAudioSession(f.Path);
			}
		}
Esempio n. 10
0
 public void ctor_FileInfo()
 {
     using (var temp = new TempFile())
     {
         Assert.NotNull(new TsvDataFile(temp.Info));
     }
 }
Esempio n. 11
0
        public void Process(Crawler crawler, PropertyBag propertyBag)
        {
            if (propertyBag.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            string extension = MapContentTypeToExtension(propertyBag.ContentType);
            if (extension.IsNullOrEmpty())
            {
                return;
            }

            propertyBag.Title = propertyBag.Step.Uri.PathAndQuery;
            using (TempFile temp = new TempFile())
            {
                temp.FileName += "." + extension;
                File.WriteAllBytes(temp.FileName, propertyBag.Response);
                using (FilterReader filterReader = new FilterReader(temp.FileName))
                {
                    string content = filterReader.ReadToEnd();
                    propertyBag.Text = content.Trim();
                }
            }
        }
Esempio n. 12
0
 public void ctor()
 {
     using (var file = new TempFile())
     {
         Assert.NotNull(file);
     }
 }
        public void OneAddedOneTranslationOtherEditedFormText()
        {
            const string ancestor = @"<?xml version='1.0' encoding='utf-8'?>
            <lift version='0.10' producer='WeSay 1.0.0.0'>
            <entry id='test'  guid='F169EB3D-16F2-4eb0-91AA-FDB91636F8F6'>
            <sense id='123'>
             <example>
            <form lang='chorus'>
              <text>This is my example sentence.</text>
            </form>
              </example>
            </sense>
            </entry>
            </lift>";
            var ours = ancestor.Replace(@"This is my example", @"This was your example");
            var theirs = ancestor.Replace(@"</example>", @"<form lang='en'><text>hello new entry</text></form></example>");

            using (var oursTemp = new TempFile(ours))
            using (var theirsTemp = new TempFile(theirs))
            using (var ancestorTemp = new TempFile(ancestor))
            {
                var listener = new ListenerForUnitTests();
                var situation = new NullMergeSituation();
                var mergeOrder = new MergeOrder(oursTemp.Path, ancestorTemp.Path, theirsTemp.Path, situation) { EventListener = listener };
                XmlMergeService.Do3WayMerge(mergeOrder, new LiftEntryMergingStrategy(mergeOrder),
                    false,
                    "header",
                    "entry", "guid");
                var result = File.ReadAllText(mergeOrder.pathToOurs);
                XmlTestHelper.AssertXPathMatchesExactlyOne(result, "//example");
                AssertThatXmlIn.String(result).HasSpecifiedNumberOfMatchesForXpath("//example/form", 2);
            }
        }
Esempio n. 14
0
 public void prop_Info()
 {
     using (var file = new TempFile())
     {
         Assert.True(file.Info.Exists);
     }
 }
        public void TestTransactionLogOptions()
        {
            using (TempFile temp = new TempFile())
            {
                temp.Delete();
                var opt = new TransactionLogOptions<int, string>(temp.TempPath,
                                                              PrimitiveSerializer.Int32,
                                                              PrimitiveSerializer.String);
                //FileName
                Assert.AreEqual(temp.TempPath, opt.FileName);
                //Key/Value serializers
                Assert.IsTrue(ReferenceEquals(opt.KeySerializer, PrimitiveSerializer.Int32));
                Assert.IsTrue(ReferenceEquals(opt.ValueSerializer, PrimitiveSerializer.String));
                //FileOptions
                Assert.AreEqual(FileOptions.WriteThrough, opt.FileOptions);
                Assert.AreEqual(FileOptions.WriteThrough | FileOptions.Asynchronous, opt.FileOptions |= FileOptions.Asynchronous);
                //Read Only
                Assert.AreEqual(false, opt.ReadOnly);
                Assert.AreEqual(true, opt.ReadOnly = true);
                //File Buffer
                Assert.AreEqual(8, opt.FileBuffer);
                Assert.AreEqual(0x40000, opt.FileBuffer = 0x40000);
                //Clone
                Assert.IsFalse(ReferenceEquals(opt, opt.Clone()));

                using(TransactionLog<int, string> log = new TransactionLog<int,string>(opt))
                    Assert.AreEqual(0, log.Size);
            }
        }
Esempio n. 16
0
		public void Process(Crawler crawler, PropertyBag propertyBag)
		{
			if (propertyBag.StatusCode != HttpStatusCode.OK)
			{
				return;
			}

			string extension = MapContentTypeToExtension(propertyBag.ContentType);
			if (extension.IsNullOrEmpty())
			{
				return;
			}

			propertyBag.Title = propertyBag.Step.Uri.PathAndQuery;
			using (TempFile temp = new TempFile())
			{
				temp.FileName += "." + extension;
				using (FileStream fs = new FileStream(temp.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000))
				using (Stream input = propertyBag.GetResponse())
				{
					input.CopyToStream(fs);
				}

				using (FilterReader filterReader = new FilterReader(temp.FileName))
				{
					string content = filterReader.ReadToEnd();
					propertyBag.Text = content.Trim();
				}
			}
		}
Esempio n. 17
0
 public void ctor_string()
 {
     using (var temp = new TempFile())
     {
         Assert.NotNull(new TsvDataSheet(temp.Info.FullName));
     }
 }
        public void SaveLoadTest()
        {
            using (var tempFile = new TempFile(_xml))
            {
                Assert.Throws<ApplicationException>(() =>
                {
                    FishSettingsBase.Load(tempFile.Name, "badName");
                });
                var settings = FishSettingsBase.Load(tempFile.Name, "name0");
                Assert.AreEqual("name0", settings.Name);
                Assert.AreEqual("version0", settings.Version);

                Assert.IsInstanceOf<System.Int32>(settings["a"]);
                Assert.AreEqual(typeof(System.Int32), settings.GetType_TESTONLY("a"));
                Assert.AreEqual(2, settings["a"]);
                Assert.AreEqual(1, settings.GetDefaultValue("a"));

                Assert.IsInstanceOf<int[]>(settings["b"]);
                Assert.AreEqual(typeof(int[]), settings.GetType_TESTONLY("b"));
                CollectionAssert.AreEqual(new [] { 3, 4, 5 }, (int[])settings["b"]);
                CollectionAssert.AreEqual(new [] { 1, 2 }, (int[])settings.GetDefaultValue("b"));

                using (var tempFile2 = new TempFile())
                {
                    settings.Save(tempFile2.Name);
                    Assert.AreEqual(tempFile.Text, tempFile2.Text);
                    FileAssert.AreEqual(tempFile.Name, tempFile2.Name);
                }
            }
        }
        public void InvalidArguments_Mode()
        {
            // FileMode out of range
            Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
            Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
            Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
            Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));

            // FileMode.Append never allowed
            Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
            Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
            Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
            Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));

            // FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
            Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
            Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
            Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));

            // FileMode.Truncate can't be used with default capacity, as resulting file will be empty
            using (TempFile file = new TempFile(GetTestFilePath()))
            {
                Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
            }
        }
        public void BothModifiedExampleFormTextWorksWithConflict()
        {
            const string ancestor = @"<?xml version='1.0' encoding='utf-8'?>
            <lift version='0.10' producer='WeSay 1.0.0.0'>
            <entry id='test'  guid='F169EB3D-16F2-4eb0-91AA-FDB91636F8F6'>
            <sense id='123'>
             <example>
            <form lang='chorus'>
              <text>This is my example sentence.</text>
            </form>
              </example>
            </sense>
            </entry>
            </lift>";
            var ours = ancestor.Replace(@"This is my example", @"This was your example");
            var theirs = ancestor.Replace(@"This is my example", @"It's mine don't touch it.");

            using (var oursTemp = new TempFile(ours))
            using (var theirsTemp = new TempFile(theirs))
            using (var ancestorTemp = new TempFile(ancestor))
            {
                var listener = new ListenerForUnitTests();
                var situation = new NullMergeSituation();
                var mergeOrder = new MergeOrder(oursTemp.Path, ancestorTemp.Path, theirsTemp.Path, situation) { EventListener = listener };
                XmlMergeService.Do3WayMerge(mergeOrder, new LiftEntryMergingStrategy(mergeOrder),
                    false,
                    "header",
                    "entry", "guid");
                var result = File.ReadAllText(mergeOrder.pathToOurs);
                Assert.AreEqual(1, listener.Conflicts.Count);
                var warning = listener.Conflicts[0];
                Assert.AreEqual(typeof(XmlTextBothEditedTextConflict), warning.GetType(), warning.ToString());
                XmlTestHelper.AssertXPathMatchesExactlyOne(result, "//example/form");
            }
        }
Esempio n. 21
0
        public void SymLinkLength()
        {
            string path = GetTestFilePath();
            string linkPath = GetTestFilePath();

            const int FileSize = 2000;
            using (var tempFile = new TempFile(path, FileSize))
            {
                Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false));

                var info = new FileInfo(path);
                Assert.Equal(FileSize, info.Length);

                var linkInfo = new FileInfo(linkPath);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On Windows, symlinks have length 0.
                    Assert.Equal(0, linkInfo.Length);
                }
                else
                {
                    // On Unix, a symlink contains the path to the target, and thus has that length.
                    // But the length could actually be longer if it's not just ASCII characters.
                    // We just verify it's at least that big, but also verify that we're not accidentally
                    // getting the target file size.
                    Assert.InRange(linkInfo.Length, path.Length, FileSize - 1);
                }

                // On both, FileStream should however open the target such that its length is the target length
                using (FileStream linkFs = File.OpenRead(linkPath))
                {
                    Assert.Equal(FileSize, linkFs.Length);
                }
            }
        }
        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);
            }
        }
		public void DeleteWritingSystemId(string id)
		{
			var fileToBeWrittenTo = new TempFile();
			var reader = XmlReader.Create(_liftFilePath, CanonicalXmlSettings.CreateXmlReaderSettings());
			var writer = XmlWriter.Create(fileToBeWrittenTo.Path, 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);
		}
Esempio n. 24
0
 public void ctor_FileInfo()
 {
     using (var file = new TempFile())
     {
         Assert.NotNull(new CsvLexiconStorage(file.Info));
     }
 }
        public void LoadingTest()
        {
            var text = @"
            element1
            {
            element2
            {
            text2
            }

            element3 = ""text3""
            }
            ";

            using (var tempFile = new TempFile(text))
            {
                var doc = FishDocument.Load(tempFile.Name);
                var element = doc.Items.First();

                Assert.AreEqual("element1", element.Name);
                Assert.AreEqual(2, element.Items.Count());
                int i = 0;
                {
                    var item = element.Items[i++];
                    Assert.AreEqual("element2", item.Name);
                    Assert.AreEqual("text2", item.Value);
                }
                {
                    var item = element.Items[i++];
                    Assert.AreEqual("element3", item.Name);
                    Assert.AreEqual(@"""text3""", item.Value);
                }
            }
        }
Esempio n. 26
0
        public void ClickAllControlsOnPage_UsingReflection_Succeeds()
        {
            //Arrange
            using (TempFile tempFile = new TempFile(
            @"<html>
            <head>
            <title>test</title>
            </head>
            <body>
            <a href=""#"">test</a>
            <button>test</button>
            <input type=""text"" value=""test""/>
            </body>
            </html>"))
            {
                BrowserWindow.Launch(tempFile.FilePath);
                var window = new BrowserWindowUnderTest("test");

                IControlBase a = window.Get<HtmlHyperlink>("InnerText=test");
                a.Click();

                List<Type> list = new List<Type>();
                list.Add(typeof(HtmlHyperlink));
                list.Add(typeof(HtmlButton));
                list.Add(typeof(HtmlEdit));

                MethodInfo getMethodInfo = typeof(BrowserWindowUnderTest).GetMethod("Get");

                foreach(Type t in list)
                {
                    MethodInfo test = getMethodInfo.MakeGenericMethod(t);

                    IControlBase control;

                    if ((t == typeof(HtmlEdit)) || (t == typeof(HtmlTextArea)))
                    {
                        control = (IControlBase)test.Invoke(window, new object[] { "Value=test" });
                    }
                    else
                    {
                        //window.Get<t>("InnerText=test");
                        control = (IControlBase)test.Invoke(window, new object[] { "InnerText=test" });
                    }

                    //Act
                    control.Click();

                    if (control is HtmlEdit)
                    {
                        (control as HtmlEdit).SetText("text");
                    }
                    else if (control is HtmlTextArea)
                    {
                        (control as HtmlTextArea).SetText("text");
                    }
                }

                window.Close();
            }
        }
        public void LoadAndSaveSettingsFileTest()
        {
            using (var settingsFile = new TempFile(Xml1))
            using (var resultsFile = new TempFile(ResultsFileAccessor1_0Test.Xml1, StreamOptions.GZip))
            {
                var userInfo = EPuzzleUserInfo.Load(settingsFile.Name, resultsFile.Name);
                Assert.AreEqual(Guid.Parse("fd48c0a4-95fc-4797-94a1-adcfd38fbdc2"), userInfo.UserId);
                Assert.AreEqual("User01", userInfo.UserName);

                Assert.AreEqual(Difficulty.Hard, userInfo.Difficulty);

                var lastDaimonInfos = userInfo.GetLastDaimonInfos();
                CollectionAssert.AreEqual(new [] { "document0", "document1", }, lastDaimonInfos.Select(x => x.DocumentId));
                CollectionAssert.AreEqual(new [] { "daimonA1", "daimonA2", }, lastDaimonInfos.Select(x => x.DaimonId));
                CollectionAssert.AreEqual(new [] { DateTime.Parse("2012-11-22T10:09:57+09:00"), DateTime.Parse("2012-11-23T10:09:57+09:00"), }, lastDaimonInfos.Select(x => x.CreationTime));

                Assert.AreEqual(1, userInfo.MondaiResults.Count());
                var result = userInfo.MondaiResults.First();
                Assert.AreEqual("mondai001", result.MondaiId);
                Assert.AreEqual(DateTime.Parse("2012-10-06T18:23:46.199375+09:00"), result.StartTime);
                Assert.AreEqual(TimeSpan.FromMinutes(1.5d), result.所要時間);
                Assert.AreEqual(Difficulty.Hard, result.Difficulty);

                using (var settingsFile2 = new TempFile())
                using (var resultsFile2 = new TempFile())
                {
                    userInfo.SaveSettingsFile(settingsFile2.Name, "1.0");
                    userInfo.SaveResultsFile(resultsFile2.Name, "1.0");

                    FileAssert.AreEqual(settingsFile.Name, settingsFile2.Name);
                    FileAssert.AreEqual(resultsFile.Name, resultsFile2.Name);
                }
            }
        }
Esempio n. 28
0
        public IEnumerable<LogFileLine> ReadLogFileLines()
        {
            using (var tmp = new TempFile())
            {
                StreamReader reader;

                try
                {
                    var stream = File.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    reader = new StreamReader(stream);
                }
                catch (IOException)
                {
                    File.CopyTo(tmp.File.FullName);
                    reader = new StreamReader(tmp.File.OpenRead());
                }

                using (reader)
                    foreach (var l in reader.ReadLines().Select((l, i) =>
                        new LogFileLine
                        {
                            Text = l,
                            LineNumber = i + 1,
                            LogFile = this
                        }))
                        yield return l;
            }
        }
Esempio n. 29
0
        public void BothAddedHeaderButWithDifferentContentInEach()
        {
            const string ancestor = @"<?xml version='1.0' encoding='utf-8'?>
                    <lift version='0.10' producer='WeSay 1.0.0.0'>
                        <entry id='parent' guid='c1ed1fa3-e382-11de-8a39-0800200c9a66' >
                            <lexical-unit>
                                <form lang='a'>
                                    <text>form parent</text>
                                </form>
                            </lexical-unit>
                         </entry>
                    </lift>";
            var alpha = ancestor.Replace("<entry id", "<header><description>alphastuff</description></header><entry id");
            var beta = ancestor.Replace("<entry id", "<header><ranges>betastuff</ranges></header><entry id");

            using (var oursTemp = new TempFile(alpha))
            using (var theirsTemp = new TempFile(beta))
            using (var ancestorTemp = new TempFile(ancestor))
            {
                var listener = new ListenerForUnitTests();
                var situation = new NullMergeSituation();
                var mergeOrder = new MergeOrder(oursTemp.Path, ancestorTemp.Path, theirsTemp.Path, situation) { EventListener = listener };
                XmlMergeService.Do3WayMerge(mergeOrder, new LiftEntryMergingStrategy(mergeOrder),
                    false,
                    "header",
                    "entry",
                    "guid");
                var result = File.ReadAllText(mergeOrder.pathToOurs);
                Assert.IsTrue(result.Contains("<header>"));
                Assert.IsTrue(result.Contains("<description>"));
                Assert.IsTrue(result.Contains("<ranges>"));
                listener.AssertExpectedChangesCount(2);
            }
        }
        public ChorusNotesMergeEventListener(string path)
        {
            _path = path;

            try
            {
                if (!File.Exists(path))
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(string.Format("<notes version='{0}'/>", FormatVersionNumber.ToString()));
                    using (var fileWriter = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings()))
                    {
                        doc.Save(fileWriter);
                    }
                }
            }
            catch (Exception error)
            {
                Debug.Fail("Something went wrong trying to create a blank ChorusNotes file :"+error.Message);
                //todo log that the xml was the wrong format
            }

            _tempFile = new TempFile();
            _readerStream = new FileStream(path, FileMode.Open);
            _reader = XmlReader.Create(_readerStream, CanonicalXmlSettings.CreateXmlReaderSettings());
            _writer = XmlWriter.Create(_tempFile.Path, CanonicalXmlSettings.CreateXmlWriterSettings());
            StreamToInsertionPoint(_reader, _writer);
        }
Esempio n. 31
0
        public void CreateZipFile_NonAsciiEntryNames()
        {
            // this test is to make sure non-ascii file names are being stored and retrieved correctly

            const string fileName     = "मराठी मैथिली संस्कृत हिन्.htm";
            const string fileContents = @"File contents.";

            using (var tempFile = TempFile.WithFilenameInTempFolder(fileName))
            {
                RobustFile.WriteAllText(tempFile.Path, fileContents);

                using (var bookZip = TempFile.WithExtension(".zip"))
                {
                    var zip = new BloomZipFile(bookZip.Path);
                    zip.AddTopLevelFile(tempFile.Path);
                    zip.Save();

                    using (var zip2 = new ZipFile(bookZip.Path))
                    {
                        foreach (ZipEntry zipEntry in zip2)
                        {
                            Console.Out.WriteLine(zipEntry.Name);
                            Assert.That(zipEntry.Name, Is.EqualTo(fileName));

                            using (var inStream = zip2.GetInputStream(zipEntry))
                            {
                                byte[] buffer = new byte[zipEntry.Size];
                                ICSharpCode.SharpZipLib.Core.StreamUtils.ReadFully(inStream, buffer);

                                var testStr = Encoding.Default.GetString(buffer);
                                Assert.That(testStr, Is.EqualTo(fileContents));
                            }
                        }
                    }
                }
            }
        }
        public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
            FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
        {
            // Test each of the four path-based CreateFromFile overloads

            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
                {
                    ValidateMemoryMappedFile(mmf, capacity);
                }

            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
                {
                    ValidateMemoryMappedFile(mmf, capacity);
                }

            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
                {
                    ValidateMemoryMappedFile(mmf, capacity);
                }

            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
                {
                    ValidateMemoryMappedFile(mmf, capacity);
                }

            // Finally, re-test the last overload, this time with an empty file to start

            using (TempFile file = new TempFile(GetTestFilePath()))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
                {
                    ValidateMemoryMappedFile(mmf, capacity);
                }
        }
Esempio n. 33
0
        public static void Install()
        {
            SaveCmdTools.SaveOpenBat();

            var baseDir     = AppContext.EncodingContext.BaseDir;
            var batFullName = Path.Combine(baseDir, "Libs\\startnecmd.bat");
            var iconName    = Path.Combine(baseDir, "NEbin\\ne.ico");

            var regName     = "installnecmdtools.reg";
            var regFullName = Path.Combine(baseDir, regName);

            var regContent = "Windows Registry Editor Version 5.00\n" +
                             "\n" +
                             "[HKEY_CLASSES_ROOT\\Directory\\shell\\NegativeEncoder]\n" +
                             "@=\"启动消极压制工具包命令行\"\n" +
                             "\"Icon\"=\"" + DoubleSlash(iconName) + "\"\n" +
                             "\n" +
                             "[HKEY_CLASSES_ROOT\\Directory\\shell\\NegativeEncoder\\command]\n" +
                             "@=\"cmd.exe /s /k \\\"\\\"" + DoubleSlash(batFullName) + "\\\" \\\"%V\\\"\\\"\"\n" +
                             "\n" +
                             "[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\NegativeEncoder]\n" +
                             "@=\"启动消极压制工具包命令行\"\n" +
                             "\"Icon\"=\"" + DoubleSlash(iconName) + "\"\n" +
                             "\n" +
                             "[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\NegativeEncoder\\command]\n" +
                             "@=\"cmd.exe /s /k \\\"\\\"" + DoubleSlash(batFullName) + "\\\" \\\"%V\\\"\\\"\"\n";

            TempFile.SaveTempFileUTF16LE(regFullName, regContent);

            var psi = new ProcessStartInfo("regedit.exe")
            {
                Arguments       = "/s \"" + regFullName + "\"",
                UseShellExecute = true
            };

            Process.Start(psi);
        }
Esempio n. 34
0
        public void Validate_MemoryRangeStartBelowRange_ShouldThrow()
        {
            using var configFile = new TempFile(@"
{
  ""Logos"": [
    {
      ""MemoryRanges"": [
        {
          ""LocalVariableMemoryStart"": -1,
        }
      ]
    }
  ]
}");
            var config = new Config();

            config.Read(configFile.Path);

            var ex = Assert.Throws <ArgumentOutOfRangeException>(() => config.Validate());

            ex.ParamName.Should().Be(nameof(MemoryRangeConfig.LocalVariableMemoryStart));
            ex.ActualValue.Should().Be(-1);
            ex.Message.Should().Contain("0..850");
        }
Esempio n. 35
0
        public void SymLinkLength()
        {
            string path     = GetTestFilePath();
            string linkPath = GetTestFilePath();

            const int FileSize = 2000;

            using (var tempFile = new TempFile(path, FileSize))
            {
                Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false));

                var info = new FileInfo(path);
                Assert.Equal(FileSize, info.Length);

                var linkInfo = new FileInfo(linkPath);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On Windows, symlinks have length 0.
                    Assert.Equal(0, linkInfo.Length);
                }
                else
                {
                    // On Unix, a symlink contains the path to the target, and thus has that length.
                    // But the length could actually be longer if it's not just ASCII characters.
                    // We just verify it's at least that big, but also verify that we're not accidentally
                    // getting the target file size.
                    Assert.InRange(linkInfo.Length, path.Length, FileSize - 1);
                }

                // On both, FileStream should however open the target such that its length is the target length
                using (FileStream linkFs = File.OpenRead(linkPath))
                {
                    Assert.Equal(FileSize, linkFs.Length);
                }
            }
        }
Esempio n. 36
0
        private void FileMove_WithNotifyFilter(WatcherChangeTypes eventType)
        {
            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 = NotifyFilters.FileName;
                        string sourcePath = file.Path;
                        string targetPath = Path.Combine(testDirectory.Path, "target");

                        // Move the testFile to a different name under the same directory with active notifyfilters
                        Action action  = () => File.Move(sourcePath, targetPath);
                        Action cleanup = () => File.Move(targetPath, sourcePath);

                        if ((eventType & WatcherChangeTypes.Deleted) > 0)
                        {
                            ExpectEvent(watcher, eventType, action, cleanup, sourcePath);
                        }
                        else
                        {
                            ExpectEvent(watcher, eventType, action, cleanup, targetPath);
                        }
                    }
        }
Esempio n. 37
0
        public async Task UpdateAddFile()
        {
            //add file
            using (TempFile testArchive = CreateTempCopyFile(zfile("normal.zip"), GetTestFilePath()))
            {
                using (ZipArchive archive = ZipFile.Open(testArchive.Path, ZipArchiveMode.Update))
                {
                    await UpdateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
                }
                await IsZipSameAsDirAsync(testArchive.Path, zmodified("addFile"), ZipArchiveMode.Read);
            }

            //add file and read entries before
            using (TempFile testArchive = CreateTempCopyFile(zfile("normal.zip"), GetTestFilePath()))
            {
                using (ZipArchive archive = ZipFile.Open(testArchive.Path, ZipArchiveMode.Update))
                {
                    var x = archive.Entries;

                    await UpdateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
                }
                await IsZipSameAsDirAsync(testArchive.Path, zmodified("addFile"), ZipArchiveMode.Read);
            }

            //add file and read entries after
            using (TempFile testArchive = CreateTempCopyFile(zfile("normal.zip"), GetTestFilePath()))
            {
                using (ZipArchive archive = ZipFile.Open(testArchive.Path, ZipArchiveMode.Update))
                {
                    await UpdateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");

                    var x = archive.Entries;
                }
                await IsZipSameAsDirAsync(testArchive.Path, zmodified("addFile"), ZipArchiveMode.Read);
            }
        }
Esempio n. 38
0
        public static ExecutionResult Run(string commandLine, string fromDirectory)
        {
            ExecutionResult result = new ExecutionResult();
            Process         p      = new Process();

            p.StartInfo.UseShellExecute  = false;
            p.StartInfo.WorkingDirectory = fromDirectory;
            p.StartInfo.FileName         = "WrapShellCall";
            using (TempFile tempOut = new TempFile())
            {
                using (TempFile tempErr = new TempFile())
                {
                    p.StartInfo.Arguments      = "\"" + tempOut.Path + "\" " + "\"" + tempErr.Path + "\" " + commandLine;
                    p.StartInfo.CreateNoWindow = true;
                    p.Start();
                    p.WaitForExit();

                    result.StandardOutput = File.ReadAllText(tempOut.Path);
                    result.StandardError  = File.ReadAllText(tempErr.Path);
                    result.ExitCode       = p.ExitCode;
                }
            }
            return(result);
        }
Esempio n. 39
0
        public void GetFilesInRevision_MultipleRevisionsInRepo_GivesCorrectFiles()
        {
            using (var testRoot = new TemporaryFolder("ChorusRetrieveTest"))
            {
                var temp = testRoot.Combine("filename with spaces");
                File.WriteAllText(temp, "one");
                using (var f = TempFile.TrackExisting(temp))
                {
                    HgRepository.CreateRepositoryInExistingDir(testRoot.Path, _progress);
                    var repo = new HgRepository(testRoot.Path, _progress);

                    repo.AddAndCheckinFile(f.Path);
                    repo.Commit(true, "initial");
                    File.WriteAllText(f.Path, "one two");
                    repo.Commit(true, "second");

                    var revisions = repo.GetAllRevisions();
                    Assert.AreEqual(2, revisions.Count);
                    var files = repo.GetFilesInRevision(revisions[0]);
                    Assert.AreEqual(1, files.Count());
                    Assert.AreEqual(f.Path, files.First().FullPath);
                }
            }
        }
Esempio n. 40
0
        public void ModifiedFileIsNotReloadedIfOneFileIsMissing()
        {
            using (var file1 = TempFile.Create())
            {
                using (var file2 = TempFile.Create())
                {
                    factory.FilePaths(file1.Path, file2.Path)
                    .AutoUpdate(true);
                    file1.SetContentFromPath(TestUtils.TestFilePath("flag-only.json"));
                    file2.SetContent("{}");
                    using (var fp = MakeDataSource())
                    {
                        fp.Start();
                        var initData = _updateSink.Inits.ExpectValue();
                        AssertJsonEqual(DataSetAsJson(ExpectedDataSetForFlagOnlyFile(1)), DataSetAsJson(initData));

                        file2.Delete();
                        file1.SetContentFromPath(TestUtils.TestFilePath("segment-only.json"));

                        _updateSink.Inits.ExpectNoValue();
                    }
                }
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Starts the application using the instance fields.
        /// </summary>
        private void StartApplication()
        {
            // Handle the special case where an earlier run of this application was
            // not stopped because the developer was debugging and interrupted the
            // the unit tests before the fixture was disposed or an application with
            // the same name is already running for some other reason.

            StopApplication(ApplicationName, customContainerNames);

            // Start the application.  Note that we're going to write the compose file
            // to a temporary file to accomplish this.

            using (var tempFile = new TempFile(".yml"))
            {
                File.WriteAllText(tempFile.Path, composeFile);

                var result = NeonHelper.ExecuteCapture(NeonHelper.DockerComposeCli, new string[] { "-f", tempFile.Path, "--project-name", ApplicationName, "up", "--detach" });

                if (result.ExitCode != 0)
                {
                    throw new Exception($"Cannot launch application [{ApplicationName}] - [exitcode={result.ExitCode}]: {result.ErrorText}");
                }
            }
        }
Esempio n. 42
0
        public void Validate_MemoryRangePollingCycleSmaller100_ShouldThrow()
        {
            using var configFile = new TempFile(@"
{
  ""Logos"": [
    {
      ""MemoryRanges"": [
        {
          ""LocalVariableMemoryPollingCycleMilliseconds"": 99,
        }
      ]
    }
  ]
}");
            var config = new Config();

            config.Read(configFile.Path);

            var ex = Assert.Throws <ArgumentOutOfRangeException>(() => config.Validate());

            ex.ParamName.Should().Be(nameof(MemoryRangeConfig.LocalVariableMemoryPollingCycleMilliseconds));
            ex.ActualValue.Should().Be(99);
            ex.Message.Should().Contain("Polling cycle should be greater than 100");
        }
Esempio n. 43
0
 public void SplitConfigurationsByPublication_ConfigWithAllPublicationIsIn()
 {
     using (var helper = new UndoableUnitOfWorkHelper(Cache.ActionHandlerAccessor, "doit", "undoit"))
     {
         var allPubsConfig = ConfigurationTemplateWithAllPublications;
         using (var docView = new TestXhtmlDocView())
             using (var tempConfigFile = TempFile.WithFilename(Path.Combine(Path.GetTempPath(),
                                                                            "AllPubsConf" + DictionaryConfigurationModel.FileExtension)))
             {
                 docView.SetConfigObjectName("Dictionary");
                 docView.SetMediator(m_mediator);
                 File.WriteAllText(tempConfigFile.Path, allPubsConfig);
                 IDictionary <string, string> configsWithPub;
                 IDictionary <string, string> configsWithoutPub;
                 var configurations = new Dictionary <string, string>();
                 configurations["AConfigPubtest"] = tempConfigFile.Path;
                 // SUT
                 docView.SplitConfigurationsByPublication(configurations,
                                                          "TestPub", out configsWithPub, out configsWithoutPub);
                 CollectionAssert.Contains(configsWithPub.Values, tempConfigFile.Path);
                 CollectionAssert.DoesNotContain(configsWithoutPub.Values, tempConfigFile.Path);
             }
     }
 }
        public void ThrowsExceptionOnLockTimeout()
        {
            using (var tmp = new TempFile())
            {
                using (var db = new LiteDatabase($"filename={tmp.Filename};timeout=00:00:01"))
                {
                    var transactionStarted = new AutoResetEvent(false);
                    var transactionBlock   = new AutoResetEvent(false);
                    var blockTask          = Task.Run(() =>
                    {
                        using (db.BeginTrans())
                        {
                            transactionStarted.Set();
                            transactionBlock.WaitOne(TimeSpan.FromSeconds(10));
                        }
                    });

                    transactionStarted.WaitOne(TimeSpan.FromSeconds(10));
                    LiteException lockException = null;
                    try
                    {
                        using (db.BeginTrans())
                        {
                        }
                    }
                    catch (LiteException e)
                    {
                        lockException = e;
                        transactionBlock.Set();
                    }
                    blockTask.Wait();
                    Assert.IsNotNull(lockException);
                    Assert.AreEqual(LiteException.LOCK_TIMEOUT, lockException.ErrorCode);
                }
            }
        }
        public static void DuplicateSignedAssembliesDifferentVersions()
        {
            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_SimpleSignedVersioned200Image))
                            {
                                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());

                                    // Using simple name will find first assembly that matches.
                                    Assembly a1 = lc.LoadFromAssemblyName(TestData.s_SimpleVersionedShortName);
                                    Assembly a2 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned100FullName);
                                    Assembly a3 = lc.LoadFromAssemblyName(TestData.s_SimpleSignedVersioned200FullName);
                                    Assert.True(object.ReferenceEquals(a1, a2) || object.ReferenceEquals(a1, a3));

                                    Assert.Equal(3, lc.GetAssemblies().Count());
                                }
                            }
        }
Esempio n. 46
0
        public void DeletionReport_Not_ProducedForDeletionInParentAndChild()
        {
            const string parent = @"<?xml version='1.0' encoding='utf-8'?>
					<lift version='0.10' producer='WeSay 1.0.0.0'>
						<entry id='old1' dateDeleted='2009-06-16T06:14:20Z'/>
						<entry id='old2'/>
					</lift>"                    ;
            const string child  = @"<?xml version='1.0' encoding='utf-8'?>
					<lift version='0.10' producer='WeSay 1.0.0.0'>
						<entry	id='old1'	dateDeleted='2009-06-16T06:14:20Z'/>
						<entry id='old2'/>
					</lift>"                    ;

            using (var parentTempFile = new TempFile(parent))
                using (var childTempFile = new TempFile(child))
                {
                    var listener = new ListenerForUnitTests();
                    var differ   = Xml2WayDiffer.CreateFromFiles(parentTempFile.Path, childTempFile.Path, listener,
                                                                 "header", "entry", "id");
                    differ.ReportDifferencesToListener();
                    listener.AssertExpectedChangesCount(0);
                    listener.AssertExpectedConflictCount(0);
                }
        }
Esempio n. 47
0
        public async Task Basic()
        {
            using (TempFile tmp = new TempFile())
            {
                File.WriteAllText(tmp.File.FullName, C_HelloWorld, Encoding.UTF8);
                using CLIExecutor cli = new CLIExecutor(new CLIExecutorSettings(Utils.GetShell(), new string[] { "-c", $"python {tmp.File.FullName}" })
                {
                    CollectOutput = true
                });
                ExecutorResult res = await cli.Run();

                Assert.AreEqual(0, res.ExitCode);
                StringAssert.Contains(res.Output, "Hello World!");
                _ = await Assert.ThrowsExceptionAsync <Exception>(async() => await cli.Run());
            }
            using (TempFile tmp = new TempFile())
            {
                File.WriteAllText(tmp.File.FullName, C_Exit1, Encoding.UTF8);
                using CLIExecutor cli = new CLIExecutor(new CLIExecutorSettings(Utils.GetShell(), new string[] { "-c", $"python {tmp.File.FullName}" }));
                ExecutorResult res = await cli.Run();

                Assert.AreEqual(1, res.ExitCode);
            }
        }
Esempio n. 48
0
        public DblBundleTextCorpus(ITokenizer <string, int> wordTokenizer, string fileName)
        {
            using (ZipArchive archive = ZipFile.OpenRead(fileName))
            {
                ZipArchiveEntry metadataEntry = archive.GetEntry("metadata.xml");
                using (Stream stream = metadataEntry.Open())
                {
                    var doc = XDocument.Load(stream);
                    if (!SupportedVersions.Contains((string)doc.Root.Attribute("version")))
                    {
                        throw new InvalidOperationException("Unsupported version of DBL bundle.");
                    }

                    ZipArchiveEntry versificationEntry = archive.Entries
                                                         .FirstOrDefault(e => e.Name == "versification.vrs");
                    if (versificationEntry != null)
                    {
                        using (var tempFile = TempFile.CreateAndGetPathButDontMakeTheFile())
                        {
                            versificationEntry.ExtractToFile(tempFile.Path);
                            var abbr = (string)doc.Root.Elements("identification").Elements("abbreviation")
                                       .FirstOrDefault();
                            Versification = Scripture.Versification.Table.Implementation.Load(tempFile.Path, abbr);
                        }
                    }

                    foreach (XElement contentElem in doc.Root.Elements("publications").Elements("publication")
                             .Where(pubElem => (bool?)pubElem.Attribute("default") ?? false).Elements("structure")
                             .Elements("content"))
                    {
                        AddText(new DblBundleText(wordTokenizer, (string)contentElem.Attribute("role"), fileName,
                                                  (string)contentElem.Attribute("src"), Versification));
                    }
                }
            }
        }
Esempio n. 49
0
        public void Engine_Insert_Documents()
        {
            using (var file = new TempFile())
            {
                using (var db = new LiteEngine(file.Filename))
                {
                    db.Insert("col", new BsonDocument {
                        { "_id", 1 }, { "name", "John" }
                    });
                    db.Insert("col", new BsonDocument {
                        { "_id", 2 }, { "name", "Doe" }
                    });
                }

                using (var db = new LiteEngine(file.Filename))
                {
                    var john = db.Find("col", Query.EQ("_id", 1)).FirstOrDefault();
                    var doe  = db.Find("col", Query.EQ("_id", 2)).FirstOrDefault();

                    Assert.AreEqual("John", john["name"].AsString);
                    Assert.AreEqual("Doe", doe["name"].AsString);
                }
            }
        }
Esempio n. 50
0
        public void GetRepostoryNames_TwoItemsInHubFolder_GetTwoItems()
        {
            using (var testRoot = new TemporaryFolder("ChorusHubCloneTest_" + Guid.NewGuid()))
                using (var chorusHubSourceFolder = new TemporaryFolder(testRoot, "ChorusHub"))
                    using (var repo1 = new TemporaryFolder(chorusHubSourceFolder, "repo1"))
                        using (var tempFile1 = TempFile.WithExtension("ext1"))
                            using (var repo2 = new TemporaryFolder(chorusHubSourceFolder, "repo2"))
                                using (var tempFile2 = TempFile.WithExtension("ext2"))
                                {
                                    tempFile1.MoveTo(Path.Combine(repo1.Path, Path.GetFileName(tempFile1.Path)));
                                    tempFile2.MoveTo(Path.Combine(repo2.Path, Path.GetFileName(tempFile2.Path)));
                                    RepositorySetup.MakeRepositoryForTest(repo1.Path, "bob", new ConsoleProgress());
                                    RepositorySetup.MakeRepositoryForTest(repo2.Path, "bob", new ConsoleProgress());

                                    var r1 = HgRepository.CreateOrUseExisting(repo1.Path, new ConsoleProgress());
                                    r1.AddAndCheckinFile(tempFile1.Path); // need this to create store/data/files
                                    var r2 = HgRepository.CreateOrUseExisting(repo2.Path, new ConsoleProgress());
                                    r2.AddAndCheckinFile(tempFile2.Path); // need this to create store/data/files

                                    ChorusHubOptions.RootDirectory = chorusHubSourceFolder.Path;
                                    using (var service = new ChorusHubServer())
                                    {
                                        // hg server side is now involved in deciding what repos are available
                                        Assert.IsTrue(service.Start(true));
                                        var chorusHubServerInfo = ChorusHubServerInfo.FindServerInformation();
                                        Assert.NotNull(chorusHubServerInfo);
                                        var client   = new ChorusHubClient(chorusHubServerInfo);
                                        var repoInfo = client.GetRepositoryInformation(string.Empty);
                                        Assert.AreEqual(2, repoInfo.Count());
                                        var info1 = repoInfo.First();
                                        var info2 = repoInfo.Last();
                                        Assert.IsTrue(info1.RepoName == "repo1");
                                        Assert.IsTrue(info2.RepoName == "repo2");
                                    }
                                }
        }
Esempio n. 51
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                    components = null;
                }

                if (_savedOriginalImage != null)
                {
                    _savedOriginalImage.Dispose();
                    _savedOriginalImage = null;
                }

                if (_croppingImage != null)
                {
                    _croppingImage.Dispose();
                    _croppingImage = null;
                }
            }
            base.Dispose(disposing);
        }
Esempio n. 52
0
        public void PathsAreOnSameVolume_TwoVolumesLinux()
        {
            // On Linux, /tmp is typically a ram disk and therefore a different partition from
            // /var/tmp which is supposed to persist across reboots.
            // On Mac, /tmp isn't usually a ram disk. However, it's possible to create and mount
            // loop filesystems (disk images) without root privileges. So it would be possible
            // to extend this when porting to Mac.
            if (PathUtilities.GetDeviceNumber("/tmp") == PathUtilities.GetDeviceNumber("/var/tmp"))
            {
                Assert.Ignore("For this test /tmp and /var/tmp have to be on different partitions");
            }

            var tempFile1 = Path.Combine("/tmp", Path.GetRandomFileName());
            var tempFile2 = Path.Combine("/var/tmp", Path.GetRandomFileName());

            using (File.Create(tempFile1))
                using (File.Create(tempFile2))
                    using (TempFile.TrackExisting(tempFile1))
                        using (TempFile.TrackExisting(tempFile2))
                        {
                            Assert.That(PathUtilities.PathsAreOnSameVolume(tempFile1, tempFile2),
                                        Is.False);
                        }
        }
Esempio n. 53
0
        public void FilenamesAreRelativeToTheProjectLocation()
        {
            string xml = @"<xunit2>" + Environment.NewLine +
                         @"    <assembly filename='AssemblyFilename' config-filename='ConfigFilename' />" + Environment.NewLine +
                         @"    <output type='xml' filename='XmlFilename' />" + Environment.NewLine +
                         @"</xunit2>";

            XunitProject project;
            string       directory;

            using (var tempFile = new TempFile(xml))
            {
                directory = Path.GetDirectoryName(tempFile.Filename);
                project   = XunitProject.Load(tempFile.Filename);
            }

            var assembly = Assert.Single(project.Assemblies);

            Assert.Equal(Path.Combine(directory, "AssemblyFilename"), assembly.AssemblyFilename);
            Assert.Equal(Path.Combine(directory, "ConfigFilename"), assembly.ConfigFilename);
            var output = Assert.Single(project.Output);

            Assert.Equal(Path.Combine(directory, "XmlFilename"), output.Value);
        }
        public void Constructor()
        {
            String extension;

            using (TempFile tempFile = new TempFile())
            {
                Assert.IsNotNull(tempFile);
                Assert.IsTrue(tempFile.DirectoryPath.IsNotEmpty());
                Assert.IsTrue(tempFile.FileName.IsNotEmpty());
                Assert.IsTrue(tempFile.FilePath.IsNotEmpty());
                Assert.AreEqual(tempFile.FilePath, tempFile.DirectoryPath + tempFile.FileName);
            }

            extension = "txt";
            using (TempFile tempFile = new TempFile(extension))
            {
                Assert.IsNotNull(tempFile);
                Assert.IsTrue(tempFile.DirectoryPath.IsNotEmpty());
                Assert.IsTrue(tempFile.FileName.IsNotEmpty());
                Assert.IsTrue(tempFile.FilePath.IsNotEmpty());
                Assert.AreEqual(tempFile.FilePath, tempFile.DirectoryPath + tempFile.FileName);
                Assert.AreEqual(extension, tempFile.FileName.Substring(tempFile.FileName.IndexOf(".") + 1));
            }
        }
Esempio n. 55
0
        private void FileMove_SameDirectory(WatcherChangeTypes eventType)
        {
            using (var testDirectory = new TempDirectory(GetTestFilePath()))
                using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
                    using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
                        using (var watcher = new FileSystemWatcher(dir.Path, "*"))
                        {
                            string sourcePath = testFile.Path;
                            string targetPath = testFile.Path + "_" + eventType.ToString();

                            // Move the testFile to a different name in the same directory
                            Action action  = () => File.Move(sourcePath, targetPath);
                            Action cleanup = () => File.Move(targetPath, sourcePath);

                            if ((eventType & WatcherChangeTypes.Deleted) > 0)
                            {
                                ExpectEvent(watcher, eventType, action, cleanup, new string[] { sourcePath, targetPath });
                            }
                            else
                            {
                                ExpectEvent(watcher, eventType, action, cleanup, targetPath);
                            }
                        }
        }
Esempio n. 56
0
        public void SentSpecialLengthMailAttachment_Base64Decode_Success()
        {
            // The special length follows pattern: (3N - 1) * 0x4400 + 1
            // This length will trigger WriteState.Padding = 2 & count = 1 (byte to write)
            // The smallest number to match the pattern is 34817.
            int specialLength = 34817;

            string stringLength34817 = new string('A', specialLength - 1) + 'Z';

            byte[] toBytes = Encoding.ASCII.GetBytes(stringLength34817);

            using (var tempFile = TempFile.Create(toBytes))
            {
                var message = new MailMessage("*****@*****.**", "*****@*****.**", "testSubject", "testBody");
                message.Attachments.Add(new Attachment(tempFile.Path));

                string attachment        = DecodeSentMailMessage(message).Attachment;
                string decodedAttachment = Encoding.UTF8.GetString(Convert.FromBase64String(attachment));

                // Make sure last byte is not encoded twice.
                Assert.Equal(specialLength, decodedAttachment.Length);
                Assert.Equal("AAAAAAAAAAAAAAAAZ", decodedAttachment.Substring(34800));
            }
        }
Esempio n. 57
0
        public void TestRepeatingColsRows()
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Test Print Titles");

            IRow row = sheet.CreateRow(0);

            ICell cell = row.CreateCell(1);

            cell.SetCellValue(new HSSFRichTextString("hi"));


            workbook.SetRepeatingRowsAndColumns(0, 0, 1, 0, 0);

            string filepath = TempFile.GetTempFilePath("TestPrintTitles", ".xls");

            FileStream fileOut = new FileStream(filepath, FileMode.OpenOrCreate);

            workbook.Write(fileOut);
            fileOut.Close();

            Assert.IsTrue(File.Exists(filepath), "file exists");
        }
Esempio n. 58
0
        public static TempFile GetLibSubFolderPackage()
        {
            var file = new TempFile();

            using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create))
            {
                zip.AddEntry("lib/net40/test40.dll", ZeroContent);
                zip.AddEntry("lib/net40/x86/testx86.dll", ZeroContent);

                zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?>
                            <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
                              <metadata>
                                <id>packageA</id>
                                <version>2.0.3</version>
                                <authors>Author1, author2</authors>
                                <description>Sample description</description>
                                <language>en-US</language>
                                <projectUrl>http://www.nuget.org/</projectUrl>
                                <licenseUrl>http://www.nuget.org/license</licenseUrl>
                                <dependencies>
                                   <group>
                                      <dependency id=""RouteMagic"" version=""1.1.0"" />
                                   </group>
                                   <group targetFramework=""net40"">
                                      <dependency id=""jQuery"" />
                                      <dependency id=""WebActivator"" />
                                   </group>
                                   <group targetFramework=""sl30"">
                                   </group>
                                </dependencies>
                              </metadata>
                            </package>", Encoding.UTF8);
            }

            return(file);
        }
Esempio n. 59
0
        public void Thread_Insert_Query()
        {
            const int N       = 3000;
            var       running = true;

            using (var file = new TempFile())
                using (var db = new LiteEngine(file.Filename))
                {
                    db.Insert("col", new BsonDocument());

                    // insert basic document
                    var ta = Task.Factory.StartNew(() =>
                    {
                        for (var i = 0; i < N; i++)
                        {
                            db.Insert("col", new BsonDocument {
                                { "_id", i }
                            });
                        }
                        running = false;
                    });

                    // query while insert
                    var tb = Task.Factory.StartNew(() =>
                    {
                        while (running)
                        {
                            db.Find("col", Query.All()).ToList();
                        }
                    });

                    Task.WaitAll(ta, tb);

                    Assert.AreEqual(N + 1, db.Count("col", Query.All()));
                }
        }
        public void GetMode_ZipFileWithMultipleTypesInList_ReturnsCorrectMetsList()
        {
            ZipFile zipFile = new ZipFile();

            zipFile.AddEntry("blah.mp3", "whatever");
            zipFile.AddEntry("blah.doc", "whatever");
            zipFile.AddEntry("blah.niff", "whatever");
            var tempFile = TempFile.WithExtension("zip");

            try
            {
                zipFile.Save(tempFile.Path);
                var mode = _helper.GetMode(new[] { zipFile.Name });
                Assert.AreEqual("\"" + RampArchivingDlgViewModel.kFileTypeModeList + "\":[\"" +
                                RampArchivingDlgViewModel.kModeSpeech + "\",\"" +
                                RampArchivingDlgViewModel.kModeText + "\",\"" +
                                RampArchivingDlgViewModel.kModeMusicalNotation + "\"]", mode);
            }
            finally
            {
                zipFile.Dispose();
                tempFile.Dispose();
            }
        }