예제 #1
0
        public override List <string> GetColumns(string tableName)
        {
            // Somewhat heavy, this could be improved, right now I simply
            // read the table in then check the columns...
            try
            {
                DataTable table = this.ReadTable(tableName, null);
                if (table != null)
                {
                    List <string> columnNames = new List <string>();
                    foreach (DataColumn column in table.Columns)
                    {
                        columnNames.Add(column.ColumnName);
                    }

                    return(columnNames);
                }
            }
            catch (Exception exception)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, exception.Message + " for CSV data source " + this.fileName);
            }

            return(null);
        }
예제 #2
0
        /// <summary>
        /// Sets context required for running tests.
        /// </summary>
        /// <param name="source">
        /// source parameter used for setting context
        /// </param>
        private void SetContext(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return;
            }

            Exception setWorkingDirectoryException = null;

            this.currentDirectory = Environment.CurrentDirectory;

            try
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(source);
                EqtTrace.InfoIf(EqtTrace.IsInfoEnabled, "MSTestExecutor: Changed the working directory to {0}", Environment.CurrentDirectory);
            }
            catch (IOException ex)
            {
                setWorkingDirectoryException = ex;
            }
            catch (System.Security.SecurityException ex)
            {
                setWorkingDirectoryException = ex;
            }

            if (setWorkingDirectoryException != null)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "MSTestExecutor.SetWorkingDirectory: Failed to set the working directory to '{0}'. {1}", Path.GetDirectoryName(source), setWorkingDirectoryException);
            }
        }
예제 #3
0
        private DataSet LoadDataSet(bool schemaOnly)
        {
            try
            {
                DataSet dataSet = new DataSet();
                dataSet.Locale = CultureInfo.CurrentCulture;
                string path = this.FixPath(this.fileName) ?? Path.GetFullPath(this.fileName);
                if (schemaOnly)
                {
                    dataSet.ReadXmlSchema(path);
                }
                else
                {
                    dataSet.ReadXml(path);
                }

                return(dataSet);
            }
            catch (SecurityException securityException)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, securityException.Message + " for XML data source " + this.fileName);
            }
            catch (XmlException xmlException)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, xmlException.Message + " for XML data source " + this.fileName);
            }
            catch (Exception exception)
            {
                // Yes, we get other exceptions too!
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, exception.Message + " for XML data source " + this.fileName);
            }

            return(null);
        }
예제 #4
0
        /// <summary>
        /// Returns satellite assemblies. Returns full canonicalized paths.
        /// If the file is not an assembly returns empty list.
        /// </summary>
        /// <param name="assemblyPath"> The assembly to get satellites for. </param>
        /// <returns> List of satellite assemblies. </returns>
        internal virtual List <string> GetSatelliteAssemblies(string assemblyPath)
        {
            if (!this.IsAssemblyExtension(Path.GetExtension(assemblyPath)) || !this.IsAssembly(assemblyPath))
            {
                EqtTrace.ErrorIf(
                    EqtTrace.IsErrorEnabled,
                    "AssemblyUtilities.GetSatelliteAssemblies: the specified file '{0}' is not managed assembly.",
                    assemblyPath);
                Debug.Fail("AssemblyUtilities.GetSatelliteAssemblies: the file '" + assemblyPath + "' is not an assembly.");

                // If e.g. this is unmanaged dll, we don't care about the satellites.
                return(new List <string>());
            }

            assemblyPath = Path.GetFullPath(assemblyPath);
            var assemblyDir = Path.GetDirectoryName(assemblyPath);
            var satellites  = new List <string>();

            // Directory.Exists for 266 dirs takes 9ms while Path.GetDirectories can take up to 80ms on 10k dirs.
            foreach (string dir in Cultures.Keys)
            {
                var dirPath = Path.Combine(assemblyDir, dir);
                if (!Directory.Exists(dirPath))
                {
                    continue;
                }

                // Check if the satellite exists in this dir.
                // We check filenames like: MyAssembly.dll -> MyAssembly.resources.dll.
                // Suprisingly, but both DLL and EXE are found by resource manager.
                foreach (var extension in this.assemblyExtensions)
                {
                    // extension contains leading dot.
                    string satellite     = Path.ChangeExtension(Path.GetFileName(assemblyPath), "resources" + extension);
                    string satellitePath = Path.Combine(assemblyDir, Path.Combine(dir, satellite));

                    // We don't use Assembly.LoadFrom/Assembly.GetSatelliteAssebmlies because this is rather slow
                    // (1620ms for 266 cultures when directories do not exist).
                    if (File.Exists(satellitePath))
                    {
                        // If the satellite found is not a managed assembly we do not report it as a reference.
                        if (!this.IsAssembly(satellitePath))
                        {
                            EqtTrace.ErrorIf(
                                EqtTrace.IsErrorEnabled,
                                "AssemblyUtilities.GetSatelliteAssemblies: found assembly '{0}' installed as satellite but it's not managed assembly.",
                                satellitePath);
                            continue;
                        }

                        // If both .exe and .dll exist we return both silently.
                        satellites.Add(satellitePath);
                    }
                }
            }

            return(satellites);
        }
예제 #5
0
        /// <summary>
        /// Opens the image and reads information about the symbols file, associated
        /// to this image.
        /// </summary>
        /// <param name="imagePath">The full path to executable or DLL.</param>
        /// <returns>Full path to corresponding symbols file or null if the image does
        /// not contain symbols file information.</returns>
        public static string GetSymbolsFileName(string imagePath)
        {
            Debug.Assert(!string.IsNullOrEmpty(imagePath), "imagePath");

            IDiaDataSource source;

            try
            {
                source = (IDiaDataSource) new DiaSourceClass();
            }
            catch (COMException ex)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "DIA initialization threw:\n" + ex.ToString());

                // Let things go fine if we can find a local file, return
                // null if we can't.  This is needed to support xcopy deployment.
                string pdbFile = Path.ChangeExtension(imagePath, ".pdb");
                if (File.Exists(pdbFile))
                {
                    return(pdbFile);
                }

                return(null);
            }

            IDiaSession session = null;
            IDiaSymbol  global  = null;

            try
            {
                // Load the image:
                source.loadDataForExe(imagePath, null, null);

                // Extract the main symbol via session:
                source.openSession(out session);
                global = session.globalScope;

                Debug.Assert(global != null, "globalScope Symbol");
                return(global.symbolsFileName);
            }
            catch (COMException ex)
            {
                // If exception is thrown the image does not contain symbols or the symbols found
                // are not correct.
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "DIA thew in retrieving symbols: " + ex.ToString());
                return(null);
            }
            finally
            {
                // Ensure that the resources allocated by DIA get cleaned up.
                // In particular, after loadDataForExe, the PDB will be locked
                // until CDiaDataSource::~CDiaDataSource is called.
                ReleaseComObject(global);
                ReleaseComObject(session);
                ReleaseComObject(source);
            }
        }
예제 #6
0
 public virtual void DeleteDirectories(string filePath)
 {
     Validate.IsFalse(string.IsNullOrWhiteSpace(filePath), "Invalid filePath provided");
     try
     {
         var root = new DirectoryInfo(filePath);
         root.Delete(true);
     }
     catch (Exception ex)
     {
         EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "DeploymentManager.DeleteDirectories failed for the directory '{0}': {1}", filePath, ex);
     }
 }
예제 #7
0
        internal virtual void DeleteDirectories(string filePath)
        {
            Debug.Assert(filePath != null, "filePath");

            try
            {
                var root = new DirectoryInfo(filePath);
                root.Delete(true);
            }
            catch (Exception ex)
            {
                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "DeploymentManager.DeleteDirectories failed for the directory '{0}': {1}", filePath, ex);
            }
        }
예제 #8
0
        private static object SafeInvoke <T>(Func <T> action, string messageFormatOnException = null)
        {
            try
            {
                return(action.Invoke());
            }
            catch (Exception exception)
            {
                if (string.IsNullOrEmpty(messageFormatOnException))
                {
                    messageFormatOnException = "{0}";
                }

                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, messageFormatOnException, exception.Message);
            }

            return(null);
        }
 /// <summary>
 /// Log an error in a given format.
 /// </summary>
 /// <param name="format"> The format. </param>
 /// <param name="args"> The args. </param>
 public void LogError(string format, params object[] args)
 {
     EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, format, args);
 }
예제 #10
0
        /// <summary>
        /// Run a data driven test. Test case is executed once for each data row.
        /// </summary>
        /// <param name="testContext">
        /// The test Context.
        /// </param>
        /// <param name="testMethodInfo">
        /// The test Method Info.
        /// </param>
        /// <param name="testMethod">
        /// The test Method.
        /// </param>
        /// <param name="executor">
        /// The default test method executor.
        /// </param>
        /// <returns>
        /// The results after running all the data driven tests.
        /// </returns>
        public UTF.TestResult[] RunDataDrivenTest(UTF.TestContext testContext, UTF.ITestMethod testMethodInfo, ITestMethod testMethod, UTF.TestMethodAttribute executor)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();

            // Figure out where (as well as the current directory) we could look for data files
            // for unit tests this means looking at the the location of the test itself
            List <string> dataFolders = new List <string>();

            dataFolders.Add(Path.GetDirectoryName(new Uri(testMethodInfo.MethodInfo.Module.Assembly.CodeBase).LocalPath));

            List <UTF.TestResult> dataRowResults = new List <UTF.TestResult>();

            // Connect to data source.
            TestDataConnectionFactory factory = new TestDataConnectionFactory();

            string providerNameInvariant;
            string connectionString;
            string tableName;

            UTF.DataAccessMethod dataAccessMethod;

            try
            {
                this.GetConnectionProperties(testMethodInfo.GetAttributes <UTF.DataSourceAttribute>(false)[0], out providerNameInvariant, out connectionString, out tableName, out dataAccessMethod);
            }
            catch (Exception ex)
            {
                watch.Stop();
                var result = new UTF.TestResult();
                result.Outcome = UTF.UnitTestOutcome.Failed;
                result.TestFailureException = ex;
                result.Duration             = watch.Elapsed;
                return(new UTF.TestResult[] { result });
            }

            try
            {
                using (TestDataConnection connection = factory.Create(providerNameInvariant, connectionString, dataFolders))
                {
                    DataTable table = connection.ReadTable(tableName, null);
                    DataRow[] rows  = table.Select();
                    Debug.Assert(rows != null, "rows should not be null.");

                    if (rows.Length == 0)
                    {
                        watch.Stop();
                        var inconclusiveResult = new UTF.TestResult();
                        inconclusiveResult.Outcome  = UTF.UnitTestOutcome.Inconclusive;
                        inconclusiveResult.Duration = watch.Elapsed;
                        return(new UTF.TestResult[] { inconclusiveResult });
                    }

                    IEnumerable <int>         permutation     = this.GetPermutation(dataAccessMethod, rows.Length);
                    TestContextImplementation testContextImpl = testContext as TestContextImplementation;

                    try
                    {
                        testContextImpl.SetDataConnection(connection.Connection);

                        // For each data row...
                        foreach (int rowIndex in permutation)
                        {
                            watch.Reset();
                            watch.Start();

                            testContextImpl.SetDataRow(rows[rowIndex]);

                            UTF.TestResult[] currentResult = new UTF.TestResult[1];

                            try
                            {
                                currentResult = executor.Execute(testMethodInfo);
                            }
                            catch (Exception ex)
                            {
                                currentResult[0].Outcome = UTF.UnitTestOutcome.Failed;

                                // Trace whole exception but do not show call stack to the user, only show message.
                                EqtTrace.ErrorIf(EqtTrace.IsErrorEnabled, "Unit Test Adapter threw exception: {0}", ex);
                            }

                            currentResult[0].DatarowIndex = rowIndex;

                            watch.Stop();
                            currentResult[0].Duration = watch.Elapsed;

                            Debug.Assert(currentResult[0] != null, "current result should not be null.");
                            dataRowResults.Add(currentResult[0]);

                            // Clear the testContext's internal string writer to start afresh for the next datarow iteration
                            testContextImpl.ClearMessages();
                        }
                    }
                    finally
                    {
                        testContextImpl.SetDataConnection(null);
                        testContextImpl.SetDataRow(null);
                    }
                }
            }
            catch (Exception ex)
            {
                string         message      = ExceptionExtensions.GetExceptionMessage(ex);
                UTF.TestResult failedResult = new UTF.TestResult();
                failedResult.Outcome = UTF.UnitTestOutcome.Error;
                failedResult.TestFailureException = new Exception(string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorDataConnectionFailed, ex.Message), ex);
                return(new UTF.TestResult[] { failedResult });
            }

            return(dataRowResults.ToArray());
        }