示例#1
0
        public void AfterExploration(IPexExplorationComponent host, object data)
        {
            var graph = host.ExplorationServices.Searcher.ExecutionGraphBuilder as IVisualExecutionGraph;

            log = host.GetService <ProblemTrackDatabase>().SimpleLog;
            AppendLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            foreach (var rootNode in graph.ExecutionRootNodes)
            {
                LogRootNode(host, log, rootNode);
            }
            AppendLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            AppendLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            IFiniteMap <TypeName, StackFrameTree <PexStackFrameTag> .ExceptionNode> exceptions = host.Log.ExceptionFrameTree.GetExceptions();

            foreach (var exception in exceptions)
            {
                AppendLine("TypeName: " + exception.Key);
                IIndexable <PexGeneratedTestName> indexable = exception.Value.Tag.Tests;
                foreach (var name in indexable)
                {
                    AppendLine("ExceptionNode.Tag.Test: id: " + name.ID + " method: " + name.TestMethodName);
                }

                AppendLine("ExceptionNode.Tag.ExceptionState: " + exception.Value.Tag.ExceptionState);
            }
            AppendLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            return;
        }
示例#2
0
 public TargetBranchAnalyzer(PexMeDynamicDatabase pmd, IPexComponentServices services, IPexExplorationComponent explorationComponent)
 {
     this.pmd                  = pmd;
     this.host                 = pmd;
     this.services             = services;
     this.explorationComponent = explorationComponent;
 }
示例#3
0
        private static string prettyPrintPathCondition(IPexExplorationComponent host, Term[] pathConditions)
        {
            var writer     = new SafeStringWriter();
            var codeWriter = host.Services.TestManager.Language.CreateBodyWriter(
                writer,
                VisibilityContext.Private,
                100);
            var emitter = new TermEmitter(
                host.ExplorationServices.TermManager,
                new NameCreator());

            for (int i = pathConditions.Length - 1; i >= 0; i--)
            {
                var pathCondition = pathConditions[i];
                if (!emitter.TryEvaluate(
                        new Term[] { pathCondition },
                        10000,  // bound on size of expression we are going to pretty-print
                        codeWriter))
                {
                    writer.WriteLine("(expression too big; consider using environment variable {0})",
                                     ExtendedReflectionEnvironmentSettings.NoCodeEmitterSizeLimit.Name);
                }
                else
                {
                    codeWriter.Return(SystemTypes.Bool);
                }
            }
            return(writer.ToString());
        }
示例#4
0
        private static string prettyPrintTerm(IPexExplorationComponent host, Term term, TypeEx type)
        {
            var writer     = new SafeStringWriter();
            var codeWriter = host.Services.TestManager.Language.CreateBodyWriter(
                writer,
                VisibilityContext.Private,
                100);
            var emitter = new TermEmitter(
                host.ExplorationServices.TermManager,
                new NameCreator());

            if (!emitter.TryEvaluate(
                    new Term[] { term },
                    10000, // bound on size of expression we are going to pretty-print
                    codeWriter))
            {
                writer.WriteLine("(expression too big; consider using environment variable {0})",
                                 ExtendedReflectionEnvironmentSettings.NoCodeEmitterSizeLimit.Name);
            }
            else
            {
                codeWriter.Return(type);
            }
            return(writer.ToString());
        }
示例#5
0
        public object BeforeExploration(IPexExplorationComponent host)
        {
            MessageBox.Show("BeforeExploration");

            // Subscribing to constraint problem handler
            host.Log.ProblemHandler += (problemEventArgs) =>
            {
                var location = problemEventArgs.FlippedLocation.Method == null ?
                               "" :
                               (problemEventArgs.FlippedLocation.Method.FullName + ":" + problemEventArgs.FlippedLocation.Offset);

                Z3CallLocations.Add(location);
            };

            // Subscribing to test emitting handler
            host.Log.GeneratedTestHandler += (generatedTestEventArgs) =>
            {
                // Getting the number of the corresponding run
                var run = generatedTestEventArgs.GeneratedTest.Run;

                // Storing the result of the test (this is called before AfterRun)
                EmittedTestResult.Add(run, new Tuple <bool, string>(generatedTestEventArgs.GeneratedTest.IsFailure, generatedTestEventArgs.GeneratedTest.MethodCode));
            };


            return(null);
        }
示例#6
0
        /// <summary>
        /// Gets invoked befor the state of the exploration
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        object IPexExplorationPackage.BeforeExploration(IPexExplorationComponent host)
        {
            this.pmd.CurrentPUTMethod = host.ExplorationServices.CurrentExploration.Exploration.Method;
            var currPUTSignature = MethodOrFieldAnalyzer.GetMethodSignature(pmd.CurrentPUTMethod);

            //Activate the methods of the current PUT from dormant
            foreach (var fss in pmd.FactorySuggestionsDictionary.Values)
            {
                foreach (var pucls in fss.locationStoreSpecificSequences.Values)
                {
                    if (pucls.IsDormat())
                    {
                        pucls.ActivateFromDormant(currPUTSignature);
                    }
                }
            }
            pmd.PendingExplorationMethods.Add(currPUTSignature);

            //This code includes MSeqGen related stuff, primarily for evaluating the combined approach
            //if (PexMeConstants.ENABLE_MSEQGEN_RECOMMENDER)
            //{
            //    var explorableManager = host.ExplorationServices.ExplorableManager;
            //    int numMethodsRecommended = 0;
            //    foreach (var explorableCandidate in mseqgen.GetExplorableCandidates())
            //    {
            //        explorableManager.AddExplorableCandidate(explorableCandidate);
            //        numMethodsRecommended++;
            //    }
            //
            //    host.Log.LogMessage("MSeqGenRecommender", "Recommended " + numMethodsRecommended + " factory methods");
            //}

            return(null);
        }
        public void AfterExploration(IPexExplorationComponent host, object data)
        {
            var graph = host.ExplorationServices.Searcher.ExecutionGraphBuilder as IVisualExecutionGraph;
            log = host.GetService<ProblemTrackDatabase>().SimpleLog;
            AppendLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            foreach (var rootNode in graph.ExecutionRootNodes)
            {

                LogRootNode(host, log, rootNode);
            }
            AppendLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            AppendLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            IFiniteMap<TypeName, StackFrameTree<PexStackFrameTag>.ExceptionNode> exceptions = host.Log.ExceptionFrameTree.GetExceptions();
            foreach (var exception in exceptions)
            {
                AppendLine("TypeName: " + exception.Key);
                IIndexable<PexGeneratedTestName> indexable = exception.Value.Tag.Tests;
                foreach (var name in indexable)
                {
                    AppendLine("ExceptionNode.Tag.Test: id: " + name.ID + " method: "+name.TestMethodName);
                }

                AppendLine("ExceptionNode.Tag.ExceptionState: " + exception.Value.Tag.ExceptionState);
            }
            AppendLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            return;
        }
 public TargetBranchAnalyzer(PexMeDynamicDatabase pmd, IPexComponentServices services, IPexExplorationComponent explorationComponent)
 {
     this.pmd = pmd;
     this.host = pmd;
     this.services = services;
     this.explorationComponent = explorationComponent;
 }
示例#9
0
 void IPexExplorationPackage.AfterExploration(IPexExplorationComponent host, object data)
 {
     if (this.iofo == null)
     {
         this.iofo = ServiceProviderHelper.GetService <InsufficientObjectFactoryObserver>(host.Site);
     }
     this.iofo.AfterExecution();
 }
        void IPexExplorationPackage.AfterExploration(
            IPexExplorationComponent host,
            object data)
        {
            var observer =
                ServiceProviderHelper.GetService <InsufficientObjectFactoryObserver>(host.Site);

            observer.Dump();
        }
示例#11
0
        protected override object BeforeExploration <TAbstractValue>(IPexExplorationComponent <TAbstractValue> host)
        {
            SafeDebug.AssumeNotNull(host, "host");

            host.ExplorationServices.ExceptionManager.AddAssumptionExceptionValidator(
                new Validator <TAbstractValue>(host)
                );
            return(null);
        }
示例#12
0
        /// <summary>
        /// Gets invoked after the exploration
        /// </summary>
        /// <param name="host"></param>
        /// <param name="data"></param>
        void IPexExplorationPackage.AfterExploration(IPexExplorationComponent host, object data)
        {
            if (this.explorationObserver == null)
            {
                this.explorationObserver = host.GetService <IFieldAccessExplorationObserver>();
            }

            this.explorationObserver.Dump();
        }
示例#13
0
        void IPexExplorationPackage.AfterExploration(
            IPexExplorationComponent host,
            object data)
        {
            FieldAccessObserver observer =
                ServiceProviderHelper.GetService <FieldAccessObserver>(host.Site);

            observer.Dump();
        }
        /// <summary>
        /// Method, which is called before each exploration.
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        protected override object BeforeExploration(IPexExplorationComponent host)
        {
            using (var gvWriter = new StreamWriter(outFileUrl, true))
            {
                gvWriter.WriteLine("digraph {");
                gvWriter.WriteLine("node [ fontsize = \"16\" shape = \"box\" fillcolor = \"white\"];");
            }

            using (var infoWriter = new StreamWriter(outFileUrl + ".info", true))
            {
                infoWriter.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                infoWriter.WriteLine("<GraphInfo>");
            }

            host.Log.ProblemHandler += (p1) => {
                try
                {
                    var nodeStorage = host.GetService <PexExecutionNodeStorageComponent>();
                    nodeStorage.Z3Locations.Add((p1.FlippedLocation.Method == null ? "" : (p1.FlippedLocation.Method.FullName + ":" + p1.FlippedLocation.Offset)));
                }
                catch (Exception ex)
                {
                    // TODO : Exception handling?
                }
            };

            using (var testWriter = new StreamWriter(outFileUrl + ".tests", true))
            {
                testWriter.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                testWriter.WriteLine("<Methods>");
            }

            host.Log.GeneratedTestHandler += (p1) =>
            {
                try
                {
                    var currentRun = p1.GeneratedTest.Run;
                    var runStorage = host.GetService <PexRunAndTestStorageComponent>();

                    using (var testWriter = new StreamWriter(outFileUrl + ".tests", true))
                    {
                        testWriter.WriteLine("<MethodCode Run=\"" + currentRun + "\" Exception=\"" + p1.GeneratedTest.ExceptionState + "\" Failed=\"" + p1.GeneratedTest.IsFailure + "\"><![CDATA[");
                        testWriter.WriteLine(p1.GeneratedTest.MethodCode);
                        testWriter.WriteLine("]]></MethodCode>");
                    }

                    runStorage.Runs.Add(new Tuple <int, int>(currentRun, p1.GeneratedTest.IsFailure ? 2 : 1));
                }
                catch (Exception ex)
                {
                    // TODO : Exception handling?
                }
            };

            return(null);
        }
示例#15
0
        /// <summary>
        /// simplifies the term based on the contents of the term. all
        /// </summary>
        /// <param name="host"></param>
        /// <param name="termManager"></param>
        /// <param name="condition"></param>
        /// <param name="binOp"></param>
        private static Term SimplifyTerm(IPexExplorationComponent host, TermManager termManager, Term condition)
        {
            Term           left, right;
            BinaryOperator binOp;

            if (!termManager.TryGetBinary(condition, out binOp, out left, out right))
            {
                return(condition);
            }

            if (!IsInteger(termManager, left) || !IsInteger(termManager, right))
            {
                return(condition);
            }

            //Check whether the term is of the form x > 20, where one side is a constant. then no simplification needs to be done
            if (termManager.IsValue(left))
            {
                //one side is constant. so just return over here
                return(condition);
            }

            if (termManager.IsValue(right))
            {
                //one side is constant. so just return over here
                return(condition);
            }


            //none of the sides are concrete. both sides are symbolic.
            //find out which side can be more controlled based on the variables
            //contained on that side
            SafeList <Field>  allFieldsInLeftCondition          = new SafeList <Field>();
            SafeList <TypeEx> allFieldTypes                     = new SafeList <TypeEx>();
            SafeDictionary <Field, FieldValueHolder> leftfields = new SafeDictionary <Field, FieldValueHolder>();

            VariablesCollector.Collect(termManager, left, leftfields, allFieldsInLeftCondition, allFieldTypes);

            //TODO: How to get the concrete value of the other side, could be either left
            //or right. and make a term out of the concrete value
            int lvalue;

            if (termManager.TryGetI4Constant(left, out lvalue))
            {
            }

            int rvalue;

            if (termManager.TryGetI4Constant(right, out rvalue))
            {
            }

            return(condition);
        }
示例#16
0
        private void LogNode(IExecutionNode rootNode, StringBuilder log, IPexExplorationComponent host)
        {
            var visualExecutionNode = rootNode as IVisualExecutionNode;
            IIndexable <PexPathExecutionResult> indexable = visualExecutionNode.AttachedPathExecutionResults;

            if (rootNode.CodeLocation != null && rootNode.CodeLocation.Method != null)
            {
                AppendLine("node CodeLocation: " + rootNode.CodeLocation.Method.FullName + ":" + rootNode.CodeLocation.Offset);
            }
            else
            {
                AppendLine("node CodeLocation: " + rootNode.CodeLocation);
            }

            if (rootNode.InCodeBranch != null && rootNode.InCodeBranch.Method != null)
            {
                CodeLocation location = rootNode.InCodeBranch.Method.GetBranchLabelSource(rootNode.InCodeBranch.BranchLabel);
                AppendLine("node InCodeBranch: " + location.Method.FullName + ":" + location.Offset.ToString("x") + " out: " + rootNode.InCodeBranch.BranchLabel);
                AppendLine("node InCodeBranch: " + rootNode.InCodeBranch);
            }
            else
            {
                AppendLine("node InCodeBranch: " + rootNode.InCodeBranch);
            }

            AppendLine("node Pathcondition: ");
            foreach (var term in rootNode.GetPathCondition().Conjuncts)
            {
                AppendLine(prettyPrintPathCondition(host, new[] { term }));
            }


            AppendLine("node OutCodeBranches: ");
            foreach (CodeBranch branch in rootNode.OutCodeBranches)
            {
                if (branch != null && branch.Method != null)
                {
                    CodeLocation location = branch.Method.GetBranchLabelSource(branch.BranchLabel);
                    AppendLine("node OutCodeBranch: " + location.Method.FullName + ":" + location.Offset.ToString("x") + " out: " + branch.BranchLabel);
                }
                else
                {
                    AppendLine("node OutCodeBranch: " + branch);
                }
            }
            foreach (PexPathExecutionResult result in indexable)
            {
                AppendLine("node result: " + result.Kind);
            }
            AppendLine("node Pathcondition: " + rootNode.ModelHints);
            AppendLine();
        }
示例#17
0
        private void LogRootNode(IPexExplorationComponent host, StringBuilder log, IExecutionNode rootNode)
        {
            AppendLine("node: ");
            LogNode(rootNode, log, host);
//                host.GetService<IssueTrackDatabase>().
            IFiniteMap <Term, IExecutionNode> successors = rootNode.Successors;

            AppendLine("Successors: ");
            foreach (SafeKeyValuePair <Term, IExecutionNode> keyValuePair in successors)
            {
                AppendLine("term: " + prettyPrintPathCondition(host, new[] { keyValuePair.Key }));
                LogRootNode(host, log, keyValuePair.Value);
            }
        }
示例#18
0
        public void AfterExploration(IPexExplorationComponent host, object data)
        {
            foreach (var vertex in Vertices.Values)
            {
                // Modifying shape based on Z3 calls
                if (Z3CallLocations.Contains(vertex.MethodName + ":" + vertex.ILOffset))
                {
                    vertex.Shape = SENode.NodeShape.Ellipse;
                }

                // Adding the path condition
                var t = PrettyPathConditionTasks[vertex.Id];
                t.Wait();
                vertex.PathCondition = t.Result;
            }

            foreach (var vertex in Vertices.Values)
            {
                // Adding the incremental path condition
                if (ParentNodes.ContainsKey(vertex.Id))
                {
                    vertex.IncrementalPathCondition = CalculateIncrementalPathCondition(vertex.PathCondition, Vertices[ParentNodes[vertex.Id]].PathCondition);
                }
                else
                {
                    // If the node is the first one (has no parents), then the incremental equals the full PC
                    vertex.IncrementalPathCondition = vertex.PathCondition;
                }
            }

            // Adding vertices and edges to the graph
            Graph.AddVertexRange(Vertices.Values);
            foreach (var edgeDictionary in Edges.Values)
            {
                Graph.AddEdgeRange(edgeDictionary.Values);
            }

            // Checking if temporary SEViz folder exists
            if (!Directory.Exists(Path.GetTempPath() + "SEViz"))
            {
                var dir = Directory.CreateDirectory(Path.GetTempPath() + "SEViz");
            }

            // Getting the temporary folder
            var tempDir = Path.GetTempPath() + "SEViz\\";

            // Serializing the graph into graphml
            SEGraph.Serialize(Graph, tempDir);
        }
        /// <summary>
        /// Method, which is called after each exploration.
        /// </summary>
        /// <param name="host"></param>
        /// <param name="data"></param>
        protected override void AfterExploration(IPexExplorationComponent host, object data)
        {
            base.AfterExploration(host, data);

            var runStorage = host.GetService <PexRunAndTestStorageComponent>();

            var nodeStorage = host.GetService <PexExecutionNodeStorageComponent>();

            using (var testWriter = new StreamWriter(outFileUrl + ".tests", true))
            {
                testWriter.WriteLine("</Methods>");
            }

            using (StreamWriter runWriter = new StreamWriter(outFileUrl + ".runs", true))
            {
                foreach (var run in runStorage.Runs.OrderBy(t => t.Item1))
                {
                    StringBuilder indexes = new StringBuilder();

                    foreach (var node in runStorage.NodesInPath[run.Item1])
                    {
                        indexes.Append(node);
                        indexes.Append(",");
                    }

                    indexes.Remove(indexes.Length - 1, 1);

                    runWriter.WriteLine(run.Item1 + "|" + run.Item2 + "|" + indexes.ToString());
                }
            }

            var gvStringBuilder = new StringBuilder();

            foreach (var node in nodeStorage.NodeLocations)
            {
                if (nodeStorage.Z3Locations.Contains(node.Value))
                {
                    gvStringBuilder.AppendLine(node.Key + " [shape=ellipse]");
                }
            }

            foreach (var run in runStorage.Runs.OrderBy(t => t.Item1))
            {
                int last = -1;

                if (runStorage.NodesInPath.ContainsKey(run.Item1))
                {
                    last = runStorage.NodesInPath[run.Item1].Last();
                }
                if (last != -1)
                {
                    gvStringBuilder.AppendLine(last + " [fillcolor=" + ((run.Item2 == 0) ? "orange" :  (run.Item2 == 1 ? "limegreen" : "firebrick")) + "]");
                }
            }

            gvStringBuilder.AppendLine("}");

            using (var gvWriter = new StreamWriter(outFileUrl, true))
            {
                gvWriter.WriteLine(gvStringBuilder.ToString());
            }

            using (var exhWriter = new StreamWriter(outFileUrl + ".exh", true))
            {
                foreach (var node in nodeStorage.NodeInstances)
                {
                    exhWriter.WriteLine(node.Key + "|" + node.Value.ExhaustedReason);
                }
            }

            using (var infoWriter = new StreamWriter(outFileUrl + ".info", true))
            {
                infoWriter.WriteLine("</GraphInfo>");
            }

            /*
             * using (var metaWriter = new StreamWriter(outFileUrl + ".metainfo"))
             * {
             *  metaWriter.WriteLine("maxdepth:"+nodeStorage.NodeInstances.Max(n => n.Value.Depth));
             *  metaWriter.WriteLine("nodecount:"+nodeStorage.NodeInstances.Count);
             * }*/

            // Invoking GraphViz
            string strCmdText = "/C dot -Tplain-ext -o " + outFileUrl + ".plain  " + outFileUrl;

            System.Diagnostics.Process.Start("CMD.exe", strCmdText);

            var    dir      = outFileUrl.TrimEnd(outFileUrl.Split('\\').Last().ToCharArray());
            string fileName = outFileUrl.Split('\\').Last();

            // Waiting GraphViz to complete... TODO
            Thread.Sleep(5000);

            using (ZipFile zip = new ZipFile())
            {
                zip.AddFile(dir + fileName, "files");
                zip.AddFile(dir + fileName + ".plain", "files");
                zip.AddFile(dir + fileName + ".info", "files");
                zip.AddFile(dir + fileName + ".runs", "files");
                zip.AddFile(dir + fileName + ".tests", "files");
                zip.AddFile(dir + fileName + ".exh", "files");

                zip.Save(dir + fileName + ".sviz");
            }

            // Deleting temporary files
            File.Delete(dir + fileName);
            File.Delete(dir + fileName + ".plain");
            File.Delete(dir + fileName + ".info");
            File.Delete(dir + fileName + ".runs");
            File.Delete(dir + fileName + ".tests");
            File.Delete(dir + fileName + ".exh");
        }
示例#20
0
        /// <summary>
        /// Solves a term and computes the actual and expected values of fields. There are various possibilites of the term. The actual
        /// fiels in a condition, returned by this function should be only from one side.
        ///
        /// a. One side of the term is concrete and not symbolic. It is easy to handle this case as one side is concrete
        /// b. Both the sides are symbolic. Pex assigns different values to both the sides, since both are symbolic, but this is not possible
        ///     in the context of ours. So, we treat one side as a concrete and other side as symbolic. We use heuristics in deciding which
        ///     side is concrete and which side is symbolic.
        /// </summary>
        /// <param name="host"></param>
        /// <param name="condition"></param>
        /// <param name="binOp"></param>
        /// <param name="actualFieldValues"></param>
        /// <param name="expectedFieldValues"></param>
        /// <param name="allFieldsInCondition"></param>
        /// <returns></returns>
        public static bool SolveTerm(IPexExplorationComponent host, Term condition, BinaryOperator binOp,
                                     out SafeDictionary <Field, FieldValueHolder> actualFieldValues,
                                     out SafeDictionary <Field, FieldValueHolder> expectedFieldValues,
                                     out SafeList <Field> allFieldsInCondition, out SafeList <TypeEx> allFieldTypes)
        {
            var termManager      = host.ExplorationServices.TermManager;
            var solverFactory    = host.ExplorationServices.SolverFactory;
            var solverStatistics = solverFactory.CreateStatistics();

            actualFieldValues   = new SafeDictionary <Field, FieldValueHolder>();
            expectedFieldValues = new SafeDictionary <Field, FieldValueHolder>();
            allFieldTypes       = new SafeList <TypeEx>();

            //Simplifies term based on the contents within the term. gathering a simplied form of condition
            condition = SimplifyTerm(host, termManager, condition);

            allFieldsInCondition = new SafeList <Field>();
            var variables = VariablesCollector.Collect(termManager, condition,
                                                       actualFieldValues, allFieldsInCondition, allFieldTypes);

            using (var solver = solverFactory.CreateSolver(solverStatistics))
            {
                var writer = new SafeStringWriter();
                foreach (var symbolIdWithType in variables)
                {
                    writer.WriteLine("variable: {0}", symbolIdWithType.Description);
                    solver.AddDomainVariable(0, symbolIdWithType);
                }
                writer.WriteLine("condition: {0}", prettyPrintTerm(host, condition, SystemTypes.Bool));

                solver.Assert("is satisfiable check", condition);
                IModel model;
                var    result = solver.TryGetModel(null, out model);
                writer.WriteLine("TryGetModel => {0}", result);
                if (result == TryGetModelResult.Success)
                {
                    foreach (var symbolIdWithType in variables)
                    {
                        writer.Write("{0} => ", symbolIdWithType.Description);
                        var variable = termManager.Symbol(symbolIdWithType);
                        var value    = model.GetValue(variable);
                        writer.WriteLine(prettyPrintTerm(host, value, symbolIdWithType.Type));

                        TypeEx type;

                        if (symbolIdWithType.Layout.Kind == LayoutKind.Ref &&
                            termManager.TryGetObjectType(value, out type) &&
                            type != SystemTypes.Null)
                        {
                            foreach (var field in type.InstanceFields)
                            {
                                var fieldVariable = termManager.SelectInstanceFieldInInitialState(variable, field);
                                var fieldValue    = model.GetValue(fieldVariable);

                                writer.Write("{0}.{1} => ", symbolIdWithType.Description, field.ShortName);
                                writer.WriteLine(prettyPrintTerm(host, fieldValue, field.Type));

                                TypeEx fieldValueType;
                                if (termManager.TryGetObjectType(fieldValue, out fieldValueType)) // is this an object, and if so, what’s its type?
                                {
                                    // do the same thing are before for the nested fields
                                    foreach (var nestedField in field.Type.InstanceFields)
                                    {
                                        var nestedFieldVariable = termManager.SelectInstanceFieldInInitialState(fieldValue, nestedField);
                                        var nestedFieldValue    = model.GetValue(nestedFieldVariable);
                                        writer.Write("{0}.{1}.{2} => ", symbolIdWithType.Description, field.ShortName, nestedField.ShortName);
                                        writer.WriteLine(prettyPrintTerm(host, nestedFieldValue, nestedField.Type));
                                    }
                                }

                                //stores the field value into expected field values
                                StoreFieldValue(termManager, field, fieldValue, expectedFieldValues, actualFieldValues, allFieldsInCondition, host, condition, binOp);
                            }
                        }
                    }
                }
                if (model != null)
                {
                    model.Dispose();
                }

                host.Log.Dump("Satisfiable Checker", "TermSolver", writer.ToString());
            }

            return(true);
        }
        private void LogNode(IExecutionNode rootNode, StringBuilder log, IPexExplorationComponent host)
        {
            var visualExecutionNode = rootNode as IVisualExecutionNode;
            IIndexable<PexPathExecutionResult> indexable = visualExecutionNode.AttachedPathExecutionResults;
            if (rootNode.CodeLocation != null && rootNode.CodeLocation.Method != null)
            {
                AppendLine("node CodeLocation: " + rootNode.CodeLocation.Method.FullName + ":" + rootNode.CodeLocation.Offset);
            }
            else
            {
                AppendLine("node CodeLocation: " + rootNode.CodeLocation);
            }

            if (rootNode.InCodeBranch != null && rootNode.InCodeBranch.Method != null)
            {
                CodeLocation location = rootNode.InCodeBranch.Method.GetBranchLabelSource(rootNode.InCodeBranch.BranchLabel);
                AppendLine("node InCodeBranch: " + location.Method.FullName + ":" + location.Offset.ToString("x") + " out: " + rootNode.InCodeBranch.BranchLabel);
                AppendLine("node InCodeBranch: " + rootNode.InCodeBranch);
            }
            else
            {
                AppendLine("node InCodeBranch: " + rootNode.InCodeBranch);
            }

            AppendLine("node Pathcondition: ");
            foreach (var term in rootNode.GetPathCondition().Conjuncts)
            {
                AppendLine(prettyPrintPathCondition(host, new[]{term}));
            }

            AppendLine("node OutCodeBranches: ");
            foreach (CodeBranch branch in rootNode.OutCodeBranches)
            {
                if (branch != null && branch.Method != null)
                {
                    CodeLocation location = branch.Method.GetBranchLabelSource(branch.BranchLabel);
                    AppendLine("node OutCodeBranch: " + location.Method.FullName + ":" + location.Offset.ToString("x") + " out: " + branch.BranchLabel);
                }
                else
                {
                    AppendLine("node OutCodeBranch: " + branch);
                }
            }
            foreach (PexPathExecutionResult result in indexable)
            {
                AppendLine("node result: " + result.Kind);
            }
            AppendLine("node Pathcondition: " + rootNode.ModelHints);
            AppendLine();
        }
 void IPexExplorationPackage.AfterExploration(IPexExplorationComponent host, object data)
 {
     if(this.iofo == null)
         this.iofo = ServiceProviderHelper.GetService<InsufficientObjectFactoryObserver>(host.Site);
     this.iofo.AfterExecution();
 }
示例#23
0
 public Validator(IPexExplorationComponent <TAbstractValue> host)
 {
     SafeDebug.AssumeNotNull(host, "host");
     this.host = host;
 }
 private static string prettyPrintPathCondition(IPexExplorationComponent host, Term[] pathConditions)
 {
     var writer = new SafeStringWriter();
     var codeWriter = host.Services.TestManager.Language.CreateBodyWriter(
         writer,
         VisibilityContext.Private,
         100);
     var emitter = new TermEmitter(
         host.ExplorationServices.TermManager,
         new NameCreator());
     for (int i = pathConditions.Length - 1; i >= 0; i--)
     {
         var pathCondition = pathConditions[i];
         if (!emitter.TryEvaluate(
                  new Term[] { pathCondition },
                  10000, // bound on size of expression we are going to pretty-print
                  codeWriter))
         {
             writer.WriteLine("(expression too big; consider using environment variable {0})",
                              ExtendedReflectionEnvironmentSettings.NoCodeEmitterSizeLimit.Name);
         }
         else
         {
             codeWriter.Return(SystemTypes.Bool);
         }
     }
     return writer.ToString();
 }
 public object BeforeExploration(IPexExplorationComponent host)
 {
     return null;
 }
示例#26
0
 object IPexExplorationPackage.BeforeExploration(
     IPexExplorationComponent host)
 {
     return(null);
 }
示例#27
0
        protected override bool TryCreateArithmeticSolver(
            IPexExplorationComponent host,
            out IArithmeticSolver solver)
        {
            int    fitnessEvals = Convert.ToInt32(GetEnvironmentVariable("pex_custom_arithmetic_solver_evals", "100000"));
            string customSolver = GetEnvironmentVariable("pex_custom_arithmetic_solver", "ES");

            currentExploration = host.ExplorationServices.CurrentExploration.Exploration.Method.FullName;

            if (customSolver != null && customSolver.Equals("AVM"))
            {
                solver = new PexAlternatingVariableHillClimbingArithmeticSolver(
                    currentExploration,
                    true,
                    false,
                    fitnessEvals,
                    host.ExplorationServices.CurrentExploration.Exploration.Method);
            }
            else if (customSolver != null && customSolver.Equals("ES"))
            {
                int parents   = Convert.ToInt32(GetEnvironmentVariable("es_solver_parents", "15"));
                int offspring = Convert.ToInt32(GetEnvironmentVariable("es_solver_offspring", "100"));
                PexEvolutionStrategyArithmeticSolver.RecombinationStrategy recombination;
                PexEvolutionStrategyArithmeticSolver.MutationStrategy      mutation;
                switch (GetEnvironmentVariable("es_solver_recomb", "GlobalDiscrete"))
                {
                case "Discrete":
                    recombination = PexEvolutionStrategyArithmeticSolver.RecombinationStrategy.Discrete;
                    break;

                case "GlobalDiscrete":
                    recombination = PexEvolutionStrategyArithmeticSolver.RecombinationStrategy.GlobalDiscrete;
                    break;

                case "GlobalIntermediate":
                    recombination = PexEvolutionStrategyArithmeticSolver.RecombinationStrategy.GlobalIntermediate;
                    break;

                case "Intermediate":
                    recombination = PexEvolutionStrategyArithmeticSolver.RecombinationStrategy.Intermediate;
                    break;

                case "None":
                default: recombination = PexEvolutionStrategyArithmeticSolver.RecombinationStrategy.None; break;
                }
                switch (GetEnvironmentVariable("es_solver_mut", "Single"))
                {
                case "Multi":
                    mutation = PexEvolutionStrategyArithmeticSolver.MutationStrategy.Multi;
                    break;

                case "Single":
                    mutation = PexEvolutionStrategyArithmeticSolver.MutationStrategy.Single;
                    break;

                case "None":
                default: mutation = PexEvolutionStrategyArithmeticSolver.MutationStrategy.None; break;
                }
                solver = new PexEvolutionStrategyArithmeticSolver(
                    currentExploration,
                    true,
                    false,
                    fitnessEvals,
                    parents,
                    offspring,
                    recombination,
                    mutation,
                    false,
                    host.ExplorationServices.CurrentExploration.Exploration.Method);
            }
            else
            {
                host.Log.LogMessage(PexLogCategories.ArithmeticSolver, "pex_custom_arithmetic_solver set to wrong value");
                solver = null;
                return(false);
            }
            return(true);
        }
示例#28
0
 public object BeforeExploration(IPexExplorationComponent host)
 {
     return(null);
 }
 object IPexExplorationPackage.BeforeExploration(IPexExplorationComponent host)
 {
     return null;
 }
 private void LogRootNode(IPexExplorationComponent host, StringBuilder log, IExecutionNode rootNode)
 {
     AppendLine("node: ");
     LogNode(rootNode, log,host);
     //                host.GetService<IssueTrackDatabase>().
     IFiniteMap<Term, IExecutionNode> successors = rootNode.Successors;
     AppendLine("Successors: ");
     foreach (SafeKeyValuePair<Term, IExecutionNode> keyValuePair in successors)
     {
         AppendLine("term: " + prettyPrintPathCondition(host, new[] {keyValuePair.Key}));
         LogRootNode(host, log, keyValuePair.Value);
     }
 }