public void Add(object value) { if (this.value == null) { this.value = new ArrayList(); } string strType = value.GetType().ToString(); if (value is string) { this.value.Add((String)value.ToString()); } else if (value is int) { this.value.Add(new integer((int)value)); } else if (value is uint) { this.value.Add(new integer((int)(uint)value)); } else if (value is double) { this.value.Add(new Float((double)value)); } else { this.value.Add(value); } }
public void CanWrite_ReturnsFalse_IfValueIsAList() { object value = new ArrayList(); Assert.IsFalse(writer.CanWrite(value, value.GetType())); value = new List<int>(); Assert.IsFalse(writer.CanWrite(value, value.GetType())); }
internal ArrayListEnumeratorSimple(ArrayList list) { this.list = list; index = -1; version = list._version; isArrayList = (list.GetType() == typeof(ArrayList)); currentElement = dummyObject; }
public void ArrayListHoldsObjects() { ArrayList list = new ArrayList(); // list type = ArrayList, gets the method .Add() System.Reflection.MethodInfo method = list.GetType().GetMethod("Add"); // Gets method's first param (.Add()) and asks type of that param. Assert.Equal(typeof(object), method.GetParameters()[0].ParameterType); }
public bool AnySerialize(ArrayList Items) { if (Items.Count == 0) { File.Delete(FileName); return true; } try { SObj = new XmlSerializer(Items.GetType(), new Type[] { type.GetType() }); writer = new StreamWriter(@FileName); SObj.Serialize(writer, Items); writer.Close(); return true; } catch (Exception e) { writer.Close(); return false; } }
internal ArrayListEnumeratorSimple(ArrayList list) { _list = list; _index = -1; _version = list._version; _isArrayList = (list.GetType() == typeof(ArrayList)); _currentElement = s_dummyObject; }
internal ArrayListEnumeratorSimple(ArrayList list) { this.list = list; this.index = -1; version = list._version; isArrayList = (list.GetType() == typeof(ArrayList)); currentElement = dummyObject; }
public void ArrayListHoldsObjects() { ArrayList list = new ArrayList(); System.Reflection.MethodInfo method = list.GetType().GetMethod("Add"); Assert.Equal(typeof(object), method.GetParameters()[0].ParameterType); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { int beginTickCount = Environment.TickCount; try { this.tempFileCollection = new TempFileCollection(); Environment.SetEnvironmentVariable("WixUnitTempDir", this.tempFileCollection.BasePath, EnvironmentVariableTarget.Process); this.ParseCommandline(args); // get the assemblies Assembly wixUnitAssembly = this.GetType().Assembly; FileVersionInfo fv = FileVersionInfo.GetVersionInfo(wixUnitAssembly.Location); if (this.showHelp) { Console.WriteLine("WixUnit version {0}", fv.FileVersion); Console.WriteLine("Copyright (C) .NET Foundation and contributors. All rights reserved."); Console.WriteLine(); Console.WriteLine(" usage: WixUnit [-?] tests.xml"); Console.WriteLine(); Console.WriteLine(" -env:<var>=<value> Sets an environment variable to the value for the current process"); Console.WriteLine(" -notidy Do not delete temporary files (for checking results)"); Console.WriteLine(" -rf Re-run the failed test from the last run"); Console.WriteLine(" -st Run the tests on a single thread"); Console.WriteLine(" -test:<Test_name> Run only the specified test (may use wildcards)"); Console.WriteLine(" -update Prompt user to auto-update a test if expected and actual output files do not match"); Console.WriteLine(" -v Verbose output"); Console.WriteLine(" -val Run MSI validation for light unit tests"); return 0; } // set the environment variables for the process only foreach (KeyValuePair<string, string> environmentVariable in this.environmentVariables) { Environment.SetEnvironmentVariable(environmentVariable.Key, environmentVariable.Value, EnvironmentVariableTarget.Process); } // load the schema XmlReader schemaReader = null; XmlSchemaCollection schemas = null; try { schemas = new XmlSchemaCollection(); schemaReader = new XmlTextReader(wixUnitAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Unit.unitTests.xsd")); XmlSchema schema = XmlSchema.Read(schemaReader, null); schemas.Add(schema); } finally { if (schemaReader != null) { schemaReader.Close(); } } // load the unit tests XmlTextReader reader = null; XmlDocument doc = new XmlDocument(); try { reader = new XmlTextReader(this.unitTestsFile); XmlValidatingReader validatingReader = new XmlValidatingReader(reader); validatingReader.Schemas.Add(schemas); // load the xml into a DOM doc.Load(validatingReader); } catch (XmlException e) { SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber); SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber }); throw new WixException(WixErrors.InvalidXml(sourceLineNumbers, "unitTests", e.Message)); } catch (XmlSchemaException e) { SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber); SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber }); throw new WixException(WixErrors.SchemaValidationFailed(sourceLineNumbers, e.Message, e.LineNumber, e.LinePosition)); } finally { if (reader != null) { reader.Close(); } } // check the document element if ("UnitTests" != doc.DocumentElement.LocalName || XmlNamespace != doc.DocumentElement.NamespaceURI) { throw new InvalidOperationException("Unrecognized document element."); } // create a regular expression of the selected tests Regex selectedUnitTests = new Regex(String.Concat("^", String.Join("$|^", (string[])this.unitTests.ToArray(typeof(string))), "$"), RegexOptions.IgnoreCase | RegexOptions.Singleline); // find the unit tests foreach (XmlNode node in doc.DocumentElement) { if (XmlNodeType.Element == node.NodeType) { switch (node.LocalName) { case "UnitTest": XmlElement unitTestElement = (XmlElement)node; string unitTestName = unitTestElement.GetAttribute("Name"); if (selectedUnitTests.IsMatch(unitTestName)) { unitTestElement.SetAttribute("TempDirectory", this.tempFileCollection.BasePath); this.unitTestElements.Enqueue(node); } break; } } } if (this.unitTests.Count > 0) { this.totalUnitTests = this.unitTestElements.Count; int numThreads; if (this.updateTests || this.singleThreaded) { // If the tests are running with the -update switch, they must run on one thread // so that all execution is paused when the user is prompted to update a test. numThreads = 1; } else { // create a thread for each processor numThreads = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"), CultureInfo.InvariantCulture); } Thread[] threads = new Thread[numThreads]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ThreadStart(this.RunUnitTests)); threads[i].Start(); } // wait for all threads to finish foreach (Thread thread in threads) { thread.Join(); } // report the results Console.WriteLine(); int elapsedTime = (Environment.TickCount - beginTickCount) / 1000; if (0 < this.failedUnitTests.Count) { Console.WriteLine("Summary of failed tests:"); Console.WriteLine(); // Put the failed tests into an ArrayList, which will get serialized ArrayList serializedFailedTests = new ArrayList(); foreach (string failedTest in this.failedUnitTests.Keys) { serializedFailedTests.Add(failedTest); Console.WriteLine("{0}. {1}", this.failedUnitTests[failedTest], failedTest); } Console.WriteLine(); Console.WriteLine("Re-run the failed tests with the -rf option"); Console.WriteLine(); Console.WriteLine("Failed {0} out of {1} unit test{2} ({3} seconds).", this.failedUnitTests.Count, this.totalUnitTests, (1 != this.completedUnitTests ? "s" : ""), elapsedTime); using (XmlWriter writer = XmlWriter.Create(this.failedTestsFile)) { XmlSerializer serializer = new XmlSerializer(serializedFailedTests.GetType()); serializer.Serialize(writer, serializedFailedTests); writer.Close(); } } else { Console.WriteLine("Successful unit tests: {0} ({1} seconds).", this.completedUnitTests, elapsedTime); } Console.WriteLine(); } else { Console.WriteLine("No unit tests were selected."); } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException) { throw; } } finally { if (this.noTidy) { Console.WriteLine(); Console.WriteLine("The notidy option was specified, temporary files can be found at:"); Console.WriteLine(this.tempFileCollection.BasePath); } else { // try three times and give up with a warning if the temp files aren't gone by then const int RetryLimit = 3; for (int i = 0; i < RetryLimit; i++) { try { Directory.Delete(this.tempFileCollection.BasePath, true); // toast the whole temp directory break; // no exception means we got success the first time } catch (UnauthorizedAccessException) { if (0 == i) // should only need to unmark readonly once - there's no point in doing it again and again { RecursiveFileAttributes(this.tempFileCollection.BasePath, FileAttributes.ReadOnly, false); // toasting will fail if any files are read-only. Try changing them to not be. } else { break; } } catch (DirectoryNotFoundException) { // if the path doesn't exist, then there is nothing for us to worry about break; } catch (IOException) // directory in use { if (i == (RetryLimit - 1)) // last try failed still, give up { break; } Thread.Sleep(300); // sleep a bit before trying again } } } } return this.failedUnitTests.Count; }
////[email protected] adds for capture return value for regression assertion //public override string ToCSharpCode(ReadOnlyCollection<string> arguments, string newValueName, string return_val) //{ // return ToCSharpCode(arguments, newValueName); //} public override bool Execute(out ResultTuple ret, ResultTuple[] parameters, Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull) { contractViolated = false; ArrayList a = new ArrayList(); for (int i = 0; i < length; i++) { Plan.ParameterChooser pair = parameterMap[i]; if (forbidNull) Util.Assert(parameters[pair.planIndex].tuple[pair.resultIndex] != null); a.Add(parameters[pair.planIndex].tuple[pair.resultIndex]); } exceptionThrown = null; ret = new ResultTuple(this, a); executionLog.WriteLine("execute arraylistconstructor type " + a.GetType().ToString());//[email protected] adds return true; }
protected BaseOptions(SerializationInfo info, StreamingContext context) : base(info, context) { if(info == null) throw new ArgumentNullException("info"); LoadFileName(); ArrayList tmp = new ArrayList(); heapNames = (ArrayList)info.GetValue("HeapNames", tmp.GetType()); heapValues = (ArrayList)info.GetValue("HeapValues", tmp.GetType()); }
public static IEnumerable<TestCaseData> TestCases2() { var r = new Random(); yield return new TestCaseData(r.Next(),typeof(int)); yield return new TestCaseData(Math.Round(r.NextDouble(), 15), typeof(double)); yield return new TestCaseData("test string",typeof(string)); yield return new TestCaseData(DateTime.UtcNow,typeof(DateTime)); var len = r.Next(5, 30); var array = Enumerable.Repeat(0, len).Select(a => r.Next()).ToArray(); yield return new TestCaseData(array,typeof(int[])); var list = new List<int>(array); yield return new TestCaseData(list,list.GetType()); var list2 = new ArrayList(array); yield return new TestCaseData(list2,list2.GetType()); var hashset = new HashSet<double>(); hashset.UnionWith(Enumerable.Repeat(0,r.Next(5,50)).Select(a => Math.Round(r.NextDouble(), 15))); yield return new TestCaseData(hashset,typeof(HashSet<double>)); var hashset2 = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); hashset2.UnionWith(Enumerable.Repeat(0,r.Next(5,30)).Select(i => RandomString(r.Next(5,10)))); yield return new TestCaseData(hashset2,typeof(HashSet<string>)); var dic = new Dictionary<string,int>(); var entries = r.Next(3, 10); for (int i = 0; i < entries; i++) { string key; do { key = RandomString(6); } while (dic.ContainsKey(key)); dic.Add(key,r.Next()); } yield return new TestCaseData(dic,typeof(Dictionary<string, int>)); var dic2 = new Dictionary<string,int>(StringComparer.InvariantCultureIgnoreCase); var entries2 = r.Next(3, 10); for (int i = 0; i < entries2; i++) { string key; do { key = RandomString(6); } while (dic2.ContainsKey(key)); dic2.Add(key, r.Next()); } yield return new TestCaseData(dic2, typeof(Dictionary<string, int>)); }