public TrxResultsParser(string filename)
        {
            // Deserialize
            _testRunType = DeserializeFile <TestRunType>(filename);

            // Parse Results collection and Times element from the report
            var resultsType     = new ResultsType();
            var testDefinitions = new TestRunTypeTestDefinitions();

            foreach (var item in _testRunType.Items)
            {
                TypeSwitch.Switch(item,
                                  TypeSwitch.Case <ResultsType>((results) => resultsType                    = results),
                                  TypeSwitch.Case <TestRunTypeTimes>((results) => _testRunTimes             = results),
                                  TypeSwitch.Case <TestRunTypeTestDefinitions>((results) => testDefinitions = results)
                                  );
            }

            _resultsFromReport = resultsType.Items.Select(item => (UnitTestResultType)item);

            // Extract the codebase (name of DLL from the first record)
            FileName =
                Path.GetFileNameWithoutExtension(
                    testDefinitions.Items[0] == null
                        ? string.Empty
                        : ((UnitTestType)testDefinitions.Items[0]).TestMethod.codeBase);
        }
Exemplo n.º 2
0
 public void AddResults(ref List <System.Drawing.Bitmap> imgs, ResultsType resType)
 {
     if (resType == ResultsType.WHITE_LIGHT)
     {
         imgs_White_Light = imgs;
     }
     else if (resType == ResultsType.N3_FL)
     {
         imgs_N3_FL = imgs;
     }
     else if (resType == ResultsType.PHOS)
     {
         imgs_PHOS = imgs;
     }
     else if (resType == ResultsType.DP_FL)
     {
         imgs_DP_FL = imgs;
     }
     else if (resType == ResultsType.DP_FL2)
     {
         imgs_DP_FL2 = imgs;
     }
     else if (resType == ResultsType.DARK_BG)
     {
         imgs_DARK_BG = imgs;
     }
 }
        /// <summary>
        /// Processes the StatLight result.
        /// </summary>
        /// <param name="testRun">The test run.</param>
        /// <returns>The test results.</returns>
        internal IEnumerable <TrxResult> ProcessStatLightResult(TestRunType testRun)
        {
            IEnumerable <TrxResult> trxResults = new List <TrxResult>();
            TestDefinitionType      definition = GetDefinitions(testRun);
            ResultsType             results    = GetResults(testRun);

            if (definition == null || results == null)
            {
                return(trxResults);
            }

            if (definition.Items == null || results.Items == null)
            {
                return(trxResults);
            }

            IEnumerable <UnitTestType>       unitTestDefinitions = definition.Items.OfType <UnitTestType>();
            IEnumerable <UnitTestResultType> items = results.Items.OfType <UnitTestResultType>();

            trxResults =
                from e in unitTestDefinitions
                from f in items
                from g in this.TestCases
                where e.id == f.testId && g.FullyQualifiedName == string.Concat(e.TestMethod.className, ".", e.TestMethod.name)
                select new TrxResult
            {
                UnitTest       = e,
                UnitTestResult = f,
                TestCase       = g
            };

            return(trxResults);
        }
Exemplo n.º 4
0
        public async Task <Result <LiveResultsResponse> > GetResults(ResultsType type, string location = null)
        {
            try
            {
                var liveResultsResponse = new LiveResultsResponse();

                var result = await GetResultsByType(type, location);

                if (result.IsFailure)
                {
                    return(Result.Failure <LiveResultsResponse>("Could not load results"));
                }
                var selectedResults = result.Value;
                var candidates      = ConvertCandidates(selectedResults);
                var counties        =
                    selectedResults.Candidates.FirstOrDefault()?.Counties.Select(c => new County
                {
                    Label = c.Key,
                    Id    = c.Key
                }).ToList();
                liveResultsResponse.Candidates = candidates;
                liveResultsResponse.Counties   = counties ?? new List <County>();

                return(Result.Ok(liveResultsResponse));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Encountered exception while retrieving results");
                throw;
            }
        }
Exemplo n.º 5
0
        private TestDefinitionType CreateTestDefinitions(ResultsType results)
        {
            var unitTestDefinitions = new List <UnitTestType>();

            foreach (var result in results.Items)
            {
                var r = result as UnitTestResultType;

                unitTestDefinitions.Add(new UnitTestType
                {
                    id    = r.testId,
                    name  = r.testName,
                    Items = new object[]
                    {
                        new BaseTestTypeExecution
                        {
                            id = r.executionId
                        },
                    },
                    TestMethod = new UnitTestTypeTestMethod
                    {
                        codeBase        = "...",
                        adapterTypeName = "Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter",
                        className       = r.testName
                    }
                });
            }

            return(new TestDefinitionType
            {
                Items = unitTestDefinitions.ToArray(),
                ItemsElementName = unitTestDefinitions.Select(u => ItemsChoiceType4.UnitTest).ToArray()
            });
        }
Exemplo n.º 6
0
        private async Task <Result <ElectionResultsData> > GetResultsByType(ResultsType type, string location)
        {
            try
            {
                string resultsType          = type.ConvertEnumToString();
                var    localResultsResponse = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

                var diasporaResultsResponse = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

                if (localResultsResponse.IsFailure || diasporaResultsResponse.IsFailure)
                {
                    return(Result.Failure <ElectionResultsData>("Failed to retrieve data"));
                }
                var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResultsResponse.Value.StatisticsJson);
                var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResultsResponse.Value.StatisticsJson);
                var electionResultsData = StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData);

                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g1").Votes  = 3485292;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g2").Votes  = 527098;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g3").Votes  = 1384450;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g4").Votes  = 357014;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g5").Votes  = 2051725;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g6").Votes  = 32787;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g7").Votes  = 30884;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g8").Votes  = 30850;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g9").Votes  = 27769;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g10").Votes = 815201;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g11").Votes = 39192;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g12").Votes = 244275;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g13").Votes = 48662;
                electionResultsData.Candidates.FirstOrDefault(c => c.Id == "g14").Votes = 141316;
                _totalCounted = electionResultsData.Candidates.Sum(c => c.Votes);
                if (string.IsNullOrWhiteSpace(location) == false)
                {
                    if (location == "TOTAL")
                    {
                        return(Result.Ok(electionResultsData));
                    }
                    if (location == "DSPR")
                    {
                        return(Result.Ok(diasporaResultsData));
                    }
                    if (location == "RO")
                    {
                        return(Result.Ok(localResultsData));
                    }
                    foreach (var candidate in electionResultsData.Candidates)
                    {
                        candidate.Votes = candidate.Counties[location];
                    }
                }
                return(Result.Ok(electionResultsData));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to retrieve results for type {type} and location {location}");
                return(Result.Failure <ElectionResultsData>(e.Message));
            }
        }
Exemplo n.º 7
0
        static TestReportBase ReadInputInternal(string path, ref ExitCode.ExitCodeData errorCode)
        {
            string xmlReportFile = path;

            if (!File.Exists(xmlReportFile))
            {
                // the input path could be a folder, try to detect it
                string dir = xmlReportFile;
                xmlReportFile = Path.Combine(dir, XMLReport_File);
                if (!File.Exists(xmlReportFile))
                {
                    // still not find, may be under "Report" sub folder? try it
                    xmlReportFile = Path.Combine(dir, XMLReport_SubDir_Report, XMLReport_File);
                    if (!File.Exists(xmlReportFile))
                    {
                        OutputWriter.WriteLine(Properties.Resources.ErrMsg_CannotFindXmlReportFile + " " + path);
                        errorCode = ExitCode.FileNotFound;
                        return(null);
                    }
                }
            }

            // load XML from file with the specified XML schema
            ResultsType root = XmlReportUtilities.LoadXmlFileBySchemaType <ResultsType>(xmlReportFile);

            if (root == null)
            {
                errorCode = ExitCode.CannotReadFile;
                return(null);
            }

            // try to load the XML data as a GUI test report
            GUITestReport guiReport = new GUITestReport(root, xmlReportFile);

            if (guiReport.TryParse())
            {
                return(guiReport);
            }

            // try to load as API test report
            APITestReport apiReport = new APITestReport(root, xmlReportFile);

            if (apiReport.TryParse())
            {
                return(apiReport);
            }

            // try to load as BP test report
            BPTReport bptReport = new BPTReport(root, xmlReportFile);

            if (bptReport.TryParse())
            {
                return(bptReport);
            }

            OutputWriter.WriteLine(Properties.Resources.ErrMsg_Input_InvalidFirstReportNode + " " + path);
            errorCode = ExitCode.InvalidInput;
            return(null);
        }
Exemplo n.º 8
0
 private static string ConvertEnumToString(ResultsType type)
 {
     return(type
            .GetType()
            .GetMember(type.ToString())
            .FirstOrDefault()
            ?.GetCustomAttribute <DescriptionAttribute>()
            ?.Description ?? type.ToString());
 }
Exemplo n.º 9
0
        /// <summary>
        /// Excute tests.
        /// </summary>
        /// <param name="test">
        /// A <see cref="TestInfo"/>.
        /// </param>
        /// <param name="variables">
        /// A <see cref="IDictionary{TKey,TValue}"/> variables.
        /// </param>
        /// <param name="previousTestResults">
        /// A <see cref="IDictionary{TKey,TValue}"/> of previous results.
        /// </param>
        /// <param name="resultsType">
        /// Results type.
        /// </param>
        /// <returns>
        /// Results dictionary.
        /// </returns>
        private IDictionary <string, object> ExecuteTest(
            TestInfo test,
            IDictionary <string, object> variables,
            IDictionary <string, object> previousTestResults,
            out ResultsType resultsType)
        {
            var allParameters = new Dictionary <string, object>();

            test.Parameters?.ToList().ForEach(kv => allParameters[kv.Key]    = kv.Value);
            previousTestResults.ToList().ForEach(kv => allParameters[kv.Key] = kv.Value);
            var newParameters = this.EvaluateParameters(allParameters, variables);

            var output  = this._methodProxy.Execute(test.Api, newParameters);
            var results = new Dictionary <string, object>()
            {
                { "resultType", this._methodProxy.ReturnType },
            };

            if (output == null)
            {
                if (this._methodProxy.ReturnType == null)
                {
                    resultsType = ResultsType.Void;
                    return(results);
                }

                resultsType       = ResultsType.Object;
                results["result"] = null;
                return(results);
            }

            if (output.GetType().IsPrimitive)
            {
                resultsType       = ResultsType.Primitive;
                results["result"] = output;
                return(results);
            }

            if (output is string)
            {
                resultsType       = ResultsType.String;
                results["result"] = output;
                return(results);
            }

            if (output is IDictionary <string, object> )
            {
                resultsType = ResultsType.Dictionary;
                return(output as IDictionary <string, object>);
            }

            resultsType       = ResultsType.Object;
            results["result"] = output;
            return(results);
        }
Exemplo n.º 10
0
        public TestReport(ResultsType root, string reportFile) : base(root, reportFile)
        {
            Iterations         = new ReportNodeCollection <IterationReport>(this, ReportNodeFactory.Instance);
            Groups             = new ReportNodeCollection <GroupReport>(this, ReportNodeFactory.Instance);
            Flows              = new ReportNodeCollection <FlowReport>(this, ReportNodeFactory.Instance);
            Branches           = new ReportNodeCollection <BranchReport>(this, ReportNodeFactory.Instance);
            BusinessComponents = new ReportNodeCollection <BusinessComponentReport>(this, ReportNodeFactory.Instance);
            RecoverySteps      = new ReportNodeCollection <RecoveryStepReport>(this, ReportNodeFactory.Instance);
            GeneralSteps       = new ReportNodeCollection <GeneralStepReport>(this, ReportNodeFactory.Instance);

            AllBCsEnumerator = new ReportNodeEnumerator <BusinessComponentReport>();
        }
Exemplo n.º 11
0
        public async Task <ElectionResultsData> GetResults(ResultsType type)
        {
            string resultsType = ConvertEnumToString(type);

            var localResults = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

            var diasporaResults = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

            var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResults.StatisticsJson);
            var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResults.StatisticsJson);

            return(StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData));
        }
Exemplo n.º 12
0
        public DataTable GetTestResultData()
        {
            string    fileName;
            DataTable testResultTable = null;

            try
            {
                // Construct DirectoryInfo for the folder path passed in as an argument
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                //baseDirectory = baseDirectory.Substring(0, baseDirectory.IndexOf("bin"));
                DirectoryInfo di          = new DirectoryInfo(baseDirectory);
                ResultTable   resultTable = new ResultTable();
                testResultTable = resultTable.CreateTestResultTable();
                // For each .trx file in the given folder process it
                foreach (FileInfo file in di.GetFiles("*.trx"))
                {
                    fileName = file.Name;
                    // Deserialize TestRunType object from the trx file
                    StreamReader  fileStreamReader = new StreamReader(file.FullName);
                    XmlSerializer xmlSer           = new XmlSerializer(typeof(TestRunType));
                    TestRunType   testRunType      = (TestRunType)xmlSer.Deserialize(fileStreamReader);
                    // Navigate to UnitTestResultType object and update the sheet with test result information
                    foreach (object itob1 in testRunType.Items)
                    {
                        ResultsType resultsType = itob1 as ResultsType;
                        if (resultsType != null)
                        {
                            foreach (object itob2 in resultsType.Items)
                            {
                                UnitTestResultType unitTestResultType = itob2 as UnitTestResultType;
                                if (unitTestResultType != null)
                                {
                                    DataRow row = testResultTable.NewRow();
                                    row[Constant.PROCESSEDFILENAME] = fileName;
                                    row[Constant.TESTID]            = unitTestResultType.testId;
                                    row[Constant.TESTNAME]          = unitTestResultType.testName;
                                    row[Constant.TESTOUTCOME]       = unitTestResultType.outcome;
                                    row[Constant.ERRORMESSAGE]      = ((System.Xml.XmlNode[])(((OutputType)(((TestResultType)(unitTestResultType)).Items[0])).ErrorInfo.Message))[0].Value;
                                    testResultTable.Rows.Add(row);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(testResultTable);
        }
Exemplo n.º 13
0
        private byte[] GetIndexLengthTypeAndId(int index, int totalLength, ResultsType resultsType, int id)
        {
            int length = totalLength - index;

            tmpBuffer[0] = (byte)resultsType;
            tmpBuffer[1] = (byte)id;
            tmpBuffer[2] = (byte)(index >> 24);
            tmpBuffer[3] = (byte)(index >> 16);
            tmpBuffer[4] = (byte)(index >> 8);
            tmpBuffer[5] = (byte)(index);
            tmpBuffer[6] = (byte)(length >> 24);
            tmpBuffer[7] = (byte)(length >> 16);
            tmpBuffer[8] = (byte)(length >> 8);
            tmpBuffer[9] = (byte)(length);
            return(tmpBuffer);
        }
Exemplo n.º 14
0
        private void Testresult()
        {
            var testRun             = new TestRunType();
            var resultContainer     = new ResultsType();
            var definitionContainer = new TestDefinitionType();

            resultContainer.Items     = results.ToArray();
            definitionContainer.Items = definitions.ToArray();

            resultContainer.ItemsElementName     = new ItemsChoiceType3[results.Count];
            definitionContainer.ItemsElementName = new ItemsChoiceType4[results.Count];
            for (int i = 0; i < results.Count; i++)
            {
                resultContainer.ItemsElementName[i]     = ItemsChoiceType3.UnitTestResult;
                definitionContainer.ItemsElementName[i] = ItemsChoiceType4.UnitTest;
            }
            testRun.Items = new List <object> {
                resultContainer, definitionContainer
            }.ToArray();

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "smoketestresult.trx");

            var x          = new XmlSerializer(testRun.GetType());
            var xmlnsEmpty = new XmlSerializerNamespaces();

            xmlnsEmpty.Add("x", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");
            xmlnsEmpty.Add("x1", "http://www.w3.org/2001/XMLSchema-instance");
            xmlnsEmpty.Add("x2", "http://www.w3.org/2001/XMLSchema");
            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                x.Serialize(fs, testRun, xmlnsEmpty);
                fs.Flush();
            }

            //Replace namespaces because on the publish test results to TFS, TFS doesnt accept the namespaces and we couldn't suppress them during serialization
            string text = File.ReadAllText(filePath);

            text = text.Replace("x:", "");
            text = text.Replace("x1:", "");
            text = text.Replace("x2:", "");
            text = text.Replace("xmlns:x=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"", "xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"");
            text = text.Replace("xmlns:x1=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
            text = text.Replace("xmlns:x2=\"http://www.w3.org/2001/XMLSchema\"", "");
            File.WriteAllText(filePath, text);
        }
Exemplo n.º 15
0
        private async Task <Result <ElectionResultsData> > GetResultsByType(ResultsType type, string location)
        {
            try
            {
                string resultsType          = type.ConvertEnumToString();
                var    localResultsResponse = await _resultsRepository.GetLatestResults(Consts.LOCAL, resultsType);

                var diasporaResultsResponse = await _resultsRepository.GetLatestResults(Consts.DIASPORA, resultsType);

                if (localResultsResponse.IsFailure || diasporaResultsResponse.IsFailure)
                {
                    return(Result.Failure <ElectionResultsData>("Failed to retrieve data"));
                }
                var localResultsData    = JsonConvert.DeserializeObject <ElectionResultsData>(localResultsResponse.Value.StatisticsJson);
                var diasporaResultsData = JsonConvert.DeserializeObject <ElectionResultsData>(diasporaResultsResponse.Value.StatisticsJson);
                var electionResultsData = StatisticsAggregator.CombineResults(localResultsData, diasporaResultsData);
                if (string.IsNullOrWhiteSpace(location) == false)
                {
                    if (location == "TOTAL")
                    {
                        return(Result.Ok(electionResultsData));
                    }
                    if (location == "DSPR")
                    {
                        return(Result.Ok(diasporaResultsData));
                    }
                    if (location == "RO")
                    {
                        return(Result.Ok(localResultsData));
                    }
                    foreach (var candidate in electionResultsData.Candidates)
                    {
                        candidate.Votes = candidate.Counties[location];
                    }
                }
                return(Result.Ok(electionResultsData));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to retrieve results for type {type} and location {location}");
                return(Result.Failure <ElectionResultsData>(e.Message));
            }
        }
Exemplo n.º 16
0
        private TestEntriesType1 CreateTestEntries(ResultsType results)
        {
            var entries = new TestEntryType[results.Items.Length];

            for (int n = 0; n < entries.Length; n++)
            {
                var r = results.Items[n] as UnitTestResultType;
                entries[n] = new TestEntryType
                {
                    executionId = r.executionId,
                    testId      = r.testId,
                    testListId  = r.testListId
                };
            }

            return(new TestEntriesType1
            {
                TestEntry = entries
            });
        }
Exemplo n.º 17
0
        public async Task <Result <LiveResultsResponse> > GetResults(ResultsType type, string location = null)
        {
            try
            {
                var liveResultsResponse = new LiveResultsResponse();

                var result = await GetResultsByType(type, location);

                if (result.IsFailure)
                {
                    return(Result.Failure <LiveResultsResponse>("Could not load results"));
                }
                var selectedResults = result.Value;
                var candidates      = ConvertCandidates(selectedResults);

                var counties =
                    selectedResults?.Candidates?.FirstOrDefault()?.Counties.Select(c => new County
                {
                    Label = c.Key,
                    Id    = c.Key
                }).ToList();
                liveResultsResponse.Candidates = candidates;
                liveResultsResponse.Counties   = counties ?? new List <County>();
                var voterTurnout = await GetVoterTurnout();

                if (voterTurnout.IsSuccess)
                {
                    decimal totalVotes = voterTurnout.Value.TotalNationalVotes;
                    var     percentage = Math.Round(_totalCounted / totalVotes, 2) * 100;
                    liveResultsResponse.PercentageCounted = percentage;
                    liveResultsResponse.VoterTurnout      = totalVotes;
                }
                return(Result.Ok(liveResultsResponse));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Encountered exception while retrieving results");
                throw;
            }
        }
Exemplo n.º 18
0
        public async Task <ActionResult <LiveResultsResponse> > GetLatestResults([FromQuery] ResultsType type, string location)
        {
            try
            {
                var key    = $"results-{type.ConvertEnumToString()}-{location}";
                var result = await _appCache.GetOrAddAsync(
                    key, () => _resultsAggregator.GetResults(type, location), DateTimeOffset.Now.AddMinutes(5));

                if (result.IsFailure)
                {
                    _appCache.Remove(key);
                    _logger.LogError(result.Error);
                    return(BadRequest(result.Error));
                }
                return(result.Value);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception encountered while retrieving results");
                throw;
            }
        }
        private static TestRunType GetVSTestRun(TestRunInfo testRunInfo)
        {
            var results = new ResultsType()
            {
                Items            = testRunInfo.Tests.Select(MapTestResult).ToArray(),
                ItemsElementName = testRunInfo.Tests.Select(_ => ItemsChoiceType3.UnitTestResult).ToArray()
            };
            var testDefinitions = new TestDefinitionType()
            {
                Items            = testRunInfo.Tests.Select(MapTestDefinition).ToArray(),
                ItemsElementName = testRunInfo.Tests.Select(_ => ItemsChoiceType4.UnitTest).ToArray()
            };
            var testEntries = new TestEntriesType1()
            {
                TestEntry = testRunInfo.Tests.Select(MapTestEntry).ToArray(),
            };
            var testLists = new TestRunTypeTestLists()
            {
                TestList = new[]
                {
                    new TestListType()
                    {
                        name = "Results Not in a List", id = TestListId
                    },
                    new TestListType()
                    {
                        name = "All Loaded Results", id = "19431567-8539-422a-85d7-44ee4e166bda"
                    }
                }
            };
            var resultsSummary = MapSummary(testRunInfo);

            return(new TestRunType()
            {
                id = Guid.NewGuid().ToString(),
                Items = new object[] { results, testDefinitions, testEntries, testLists, resultsSummary }
            });
        }
Exemplo n.º 20
0
 public static Results Create(ResultsType type, string message)
 {
     return(new Results {
         ResultType = type, Message = message
     });
 }
Exemplo n.º 21
0
 public async Task <ElectionResultsData> GetLatestResults([FromQuery] ResultsType type)
 {
     return(await _resultsAggregator.GetResults(type));
 }
Exemplo n.º 22
0
        public TestReport(ResultsType root, string reportFile) : base(root, reportFile)
        {
            Iterations = new ReportNodeCollection <IterationReport>(this, ReportNodeFactory.Instance);

            AllStepsEnumerator = new ReportNodeEnumerator <StepReport>();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Verifies the results of a test.
        /// </summary>
        /// <param name="test">
        /// A <see cref="TestInfo"/> of test.
        /// </param>
        /// <param name="resultsType">
        /// A <see cref="ResultsType"/> of result type.
        /// </param>
        /// <param name="results">
        /// A <see cref="IDictionary{TKey,TValue}"/> of results.
        /// </param>
        /// <param name="variables">
        /// A <see cref="IDictionary{TKey,TValue}"/> of variables.
        /// </param>
        private void VerifyResults(TestInfo test, ResultsType resultsType, IDictionary <string, object> results, IDictionary <string, object> variables)
        {
            try
            {
                if (resultsType == ResultsType.Primitive)
                {
                    var finalExpectedValue = this.EvaluateParameters(
                        new Dictionary <string, object>()
                    {
                        { "result", test.ReturnValue },
                    }, variables).First();
                    var result = results["result"];
                    this.Verify(test, () => result, finalExpectedValue.Value);
                }
                else if (resultsType == ResultsType.Void)
                {
                    // Nothing to verify.
                }
                else if (resultsType == ResultsType.Object)
                {
                    var evaluatedExpectedValues = this.EvaluateParameters(test.GetExpectedResults(), variables);
                    if (evaluatedExpectedValues.Any())
                    {
                        var returnObject = results["result"];
                        var output       = JsonConvert.SerializeObject(returnObject, Formatting.Indented);
                        File.WriteAllText(@"c:\temp\test.json", output);
                        var expectedObjectJson = JsonConvert.SerializeObject(evaluatedExpectedValues.First().Value);
                        var returnType         = results["resultType"];
                        var expectedObject     = JsonConvert.DeserializeObject(expectedObjectJson?.ToString(), returnType as Type);

                        // Verify dictionary.
                        this.SendVerificationTraceInfo(test, returnObject, expectedObject);
                        returnObject.Should().BeEquivalentTo(expectedObject, test.Name);
                    }
                }
                else
                {
                    var evaluatedExpectedValues = this.EvaluateParameters(test.GetExpectedResults(true), variables);
                    if (evaluatedExpectedValues.Any())
                    {
                        // Verify dictionary.
                        results.Remove("resultType");
                        this.SendVerificationTraceInfo(test, results, evaluatedExpectedValues);
                        results.Should().BeEquivalentTo(evaluatedExpectedValues, test.Name);
                    }
                }
            }
            catch (Exception e)
            {
                var expectedObjectJson = JsonConvert.DeserializeObject <ExpectedExceptionInfo>(
                    JsonConvert.SerializeObject(test.GetExpectedResults()));
                if (expectedObjectJson.Exception)
                {
                    this.VerifyException(test, expectedObjectJson, e);
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 24
0
        public override void SaveReport(IList <MutationDocumentResult> mutations, TimeSpan exectutionTime)
        {
            Log.Info("Saving TRX report..");

            if (!mutations.Any())
            {
                Log.Info("No mutations to report.");
                return;
            }

            try
            {
                var unitTestResults = CreateUnitTestResults(mutations);

                var results = new ResultsType
                {
                    Items = new List <UnitTestResultType>(unitTestResults).ToArray(),
                };

                results.ItemsElementName = new ItemsChoiceType3[results.Items.Length];
                for (int n = 0; n < results.Items.Length; n++)
                {
                    results.ItemsElementName[n] = ItemsChoiceType3.UnitTestResult;
                }

                var testRunType = new TestRunType
                {
                    id    = Guid.NewGuid().ToString(),
                    name  = "mutation",
                    Items = new object[]
                    {
                        new TestRunTypeTimes
                        {
                            creation = DateTime.Now.ToString(),
                            finish   = DateTime.Now.ToString(),
                            start    = DateTime.Now.ToString()
                        },
                        new TestRunTypeResultSummary
                        {
                            outcome = mutations.All(m => !m.Survived) ? "Passed" : "Failed",
                            Items   = new object[]
                            {
                                new CountersType
                                {
                                    passed    = mutations.Count(s => !s.Survived && s.CompilationResult != null && s.CompilationResult.IsSuccess),
                                    failed    = mutations.Count(s => s.Survived && s.CompilationResult != null && s.CompilationResult.IsSuccess),
                                    completed = mutations.Count(s => s.CompilationResult != null && s.CompilationResult.IsSuccess),
                                    error     = mutations.Count(s => s.CompilationResult == null || !s.CompilationResult.IsSuccess)
                                }
                            }
                        },
                        results,
                        CreateTestDefinitions(results),
                        CreateTestEntries(results),
                        new TestRunTypeTestLists()
                        {
                            TestList = new TestListType[]
                            {
                                new TestListType()
                                {
                                    id   = results.Items.Any() ? ((UnitTestResultType)results.Items[0]).testListId : "No result found",
                                    name = "All Loaded Results"
                                }
                            }
                        }
                    }
                };

                var xmlSerializer = new XmlSerializer(typeof(TestRunType));
                using (var textWriter = new StringWriter())
                {
                    xmlSerializer.Serialize(textWriter, testRunType);
                    var xml = textWriter
                              .ToString()
                              .Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", string.Empty)
                              .Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", string.Empty)
                              .Replace(" xsi:type=\"xsd:string\"", string.Empty);

                    File.WriteAllText(SavePath, xml);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Failed to save TRX report", ex);
                throw;
            }

            Log.Info("TRX report saved successfully.");
        }