/// <summary>
 /// Returns C# source code for the given plan.
 /// The code is returns as a list of strings, one
 /// per line (each line contains a statement).
 /// </summary>
 public static ReadOnlyCollection<string> AsCSharpCode(Plan p)
 {
     if (p == null) throw new ArgumentNullException();
     CSharpGenVisitor v = new CSharpGenVisitor();
     v.Visit(p);
     return v.Code;
 }
Exemple #2
0
        internal void AddPlan(Plan p, ResultTuple resultTuple)
        {
            if (p == null) throw new ArgumentNullException();
            if (resultTuple == null) throw new ArgumentNullException();

            AddplanInternal(p, resultTuple);
        }
Exemple #3
0
 public void Move(Plan p, Exception exceptionThrown)
 {
     string dirName;
     MakeExceptionDirIfNotExists(exceptionThrown, out dirName);
     string className = this.testPrefix + p.TestCaseId;
     string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs";
     string newTestFileName = dirName + "\\" + className + ".cs";
     TestWriterHelperMethods.WritePlanToFile(p, newTestFileName, exceptionThrown.GetType(), className);
     new FileInfo(oldTestFileName).Delete();
 }
Exemple #4
0
        public void MoveNormalTermination(Plan p)
        {
            if (numNormalTerminationPlansWritten % 1000 == 0)
                newSubDir();

            string className = this.testPrefix + p.TestCaseId;
            string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs";
            string newTestFileName = normalTerminationCurrentDir + "\\" + className + ".cs";
            TestWriterHelperMethods.WritePlanToFile(p, newTestFileName, null, className);
            new FileInfo(oldTestFileName).Delete();
            numNormalTerminationPlansWritten++;
        }
        public static void WritePlanToFile(Plan p, string fileName, Type exceptionThrown, string className)
        {


            TestCase code;
            try
            {
                code = p.ToTestCase(exceptionThrown, false, className);
            }
            catch (Exception)
            {
                code = TestCase.Dummy(className);
            }

            code.WriteToFile(fileName, true);
        }
        public static void WritePlanToFile(Plan p, string fileName, Type exceptionThrown, string className)
        {
            TestCase code;
            bool writeTest = true; //[email protected] -- added for avoid writing "dummy" code
            try
            {
                code = p.ToTestCase(exceptionThrown, true, className); //[email protected] -- if the middle parameter is set to "true", print plan for debugging
            }
            catch (Exception)
            {
                code = TestCase.Dummy(className);
                writeTest = false;
            }

            if(writeTest)
                code.WriteToFile(fileName, true);
        }
 private void HandleDummy(Plan p, Collection<int> path)
 {
     // Dummy transformer has no associated code.
 }
            protected override void Visit(Plan p, Collection<int> path)
            {
                base.Visit(p, path);

                if (p.transformer is MethodCall)
                {
                    HandleMethod(p, path);
                }
                else if ((p.transformer is ConstructorCallTransformer))
                {
                    HandleConstructor(p, path);
                }
                else if (p.transformer is ArrayOrArrayListBuilderTransformer)
                {
                    HandleArray(p, path);
                }
                else if (p.transformer is DummyTransformer)
                {
                    HandleDummy(p, path);
                }
                else if (p.transformer is PrimitiveValueTransformer)
                {
                    HandlePrimitive(p, path);
                }
                else //TODO: do this 
                {
                    Util.Assert(p.transformer is FieldSettingTransformer);
                    HandleField(p, path);
                }

            }
 protected virtual void Visit(Plan p, Collection<int> path)
 {
     for (int i = 0; i < p.parentPlans.Length; i++)
     {
         Plan p2 = p.parentPlans[i];
         path.Add(i);
         Visit(p2, path);
         path.RemoveAt(path.Count - 1);
     }
     nameManager.ProcessPlan(p, path);
 }
            private void MapOutputPortsMethod(Plan p, Collection<int> path, string freshvar)
            {
                // Map receiver.
                Plan.ParameterChooser c = p.parameterChoosers[0];
                OutPortId pOutputPort = new OutPortId(path, 0);
                path.Add(c.planIndex);
                OutPortId recPort = new OutPortId(path, c.resultIndex);
                path.RemoveAt(path.Count - 1);
                foobar.set(pOutputPort, foobar.Get(recPort));

                // Map return value.
                MethodCall mct = p.transformer as MethodCall;
                if (!mct.method.ReturnType.Equals(typeof(void)))
                {
                    OutPortId newObjPort = new OutPortId(path, 1);
                    foobar.set(newObjPort, freshvar);
                }

                // Map mutated parameters.
                // Start from 1 because already handled receiver.
                for (int i = 1; i < p.parameterChoosers.Length; i++)
                {
                    c = p.parameterChoosers[i];
                    pOutputPort = new OutPortId(path, i + 1); // Add 1 because of retval.
                    path.Add(c.planIndex);
                    OutPortId paramPort = new OutPortId(path, c.resultIndex);
                    path.RemoveAt(path.Count - 1);
                    foobar.set(pOutputPort, foobar.Get(paramPort));
                }
            }
 private void MapOutputPortsFieldSetter(Plan p, Collection<int> path, string freshvar)
 {
     // Map receiver.
     Plan.ParameterChooser c = p.parameterChoosers[0];
     OutPortId pOutputPort = new OutPortId(path, 0);
     path.Add(c.planIndex);
     OutPortId recPort = new OutPortId(path, c.resultIndex);
     path.RemoveAt(path.Count - 1);
     foobar.set(pOutputPort, foobar.Get(recPort));
 }
 private void MapOutputPortsDummy(Plan p, Collection<int> path, string freshvar)
 {
     OutPortId newObjPort = new OutPortId(path, 0);
     foobar.set(newObjPort, freshvar);
 }
Exemple #13
0
 public RandomPlansResult(Plan[] plans, Plan.ParameterChooser[] parameterMap)
 {
     this.fplans = plans;
     this.fparameterChoosers = parameterMap;
 }
Exemple #14
0
 public virtual void Accept(Plan p)
 {
     // Empty body.
 }
            private void HandleArray(Plan p, Collection<int> path)
            {
                OutPortId newObjPort = new OutPortId(path, 0);
                string newObjName = nameManager.foobar.Get(newObjPort);

                Collection<string> args = new Collection<string>();
                for (int i = 0; i < p.parameterChoosers.Length; i++)
                {
                    Plan.ParameterChooser c = p.parameterChoosers[i];
                    path.Add(c.planIndex);
                    OutPortId paramPort = new OutPortId(path, c.resultIndex);
                    path.RemoveAt(path.Count - 1);
                    args.Add(nameManager.foobar.Get(paramPort));
                }
                b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(args), nameManager.foobar.Get(newObjPort)));
            }
Exemple #16
0
        /// <summary>
        /// Adds (if not already present) p to either fplanDB or fexceptionThrowingPlanDB,
        /// by executing the plan to determine if it throws exceptions.
        /// </summary>
        /// <param name="v"></param>
        public void AddMaybeExecutingIfNeeded(Plan plan, StatsManager stats)
        {
            if (builderPlans.Containsplan(plan))
            {
                redundantAdds++;
                stats.CreatedNew(CreationResult.Redundant);
            }
            else if (exceptionPlans.Containsplan(plan))
            {
                redundantAdds++;
                stats.CreatedNew(CreationResult.Redundant);
            }
            else
            {
                addCounter++;
                if (addCounter % 1000 == 0)
                {
                    Console.Write(".");
                }

                stats.CreatedNew(CreationResult.New);
                ResultTuple execResult;

                TextWriter writer = new StringWriter();
                ////[email protected] changes for debuglog
                //TextWriter writer
                //    = new StreamWriter("..\\..\\TestRandoopBare\\1ab1qkwm.jbd\\debug.log");

                Exception exceptionThrown;
                bool      contractViolated;
                bool      preconditionViolated;

                testFileWriter.WriteTest(plan);

                if (config.executionmode == ExecutionMode.DontExecute)
                {
                    builderPlans.AddPlan(plan);
                    stats.ExecutionResult("normal");
                }
                else
                {
                    Util.Assert(config.executionmode == ExecutionMode.Reflection);

                    //TextWriter executionLog = new StreamWriter(config.executionLog);
                    TextWriter executionLog = new StreamWriter(config.executionLog + addCounter.ToString() + ".log"); //[email protected] changes
                    executionLog.WriteLine("LASTPLANID:" + plan.UniqueId);

                    long startTime = 0;
                    Timer.QueryPerformanceCounter(ref startTime);

                    bool execSucceeded = plan.Execute(out execResult,
                                                      executionLog, writer, out preconditionViolated, out exceptionThrown,
                                                      out contractViolated, config.forbidnull,
                                                      config.useRandoopContracts);

                    long endTime = 0;
                    Timer.QueryPerformanceCounter(ref endTime);
                    TimeTracking.timeSpentExecutingTestedCode += (endTime - startTime);

                    executionLog.Close();

                    if (!execSucceeded)
                    {
                        if (preconditionViolated)
                        {
                            stats.ExecutionResult("precondition violated");
                            testFileWriter.Remove(plan);
                        }

                        if (exceptionThrown != null)
                        {
                            stats.ExecutionResult(exceptionThrown.GetType().FullName);
                            plan.exceptionThrown = exceptionThrown;
                            testFileWriter.Move(plan, exceptionThrown);

                            if (exceptionThrown is AccessViolationException)
                            {
                                Logger.Error("SECOND-CHANCE ACCESS VIOLATION EXCEPTION.");
                                Environment.Exit(1);
                            }
                        }


                        //string exceptionMessage = writer.ToString(); //no use? [email protected] comments out

                        Util.Assert(plan.exceptionThrown != null || contractViolated || preconditionViolated);

                        if (config.monkey)
                        {
                            builderPlans.AddPlan(plan);
                        }
                        else if (exceptionThrown != null)
                        {
                            exceptionPlans.AddPlan(plan);
                        }
                    }
                    else
                    {
                        stats.ExecutionResult("normal");

                        if (config.outputnormalinputs)
                        {
                            testFileWriter.MoveNormalTermination(plan);
                        }
                        else
                        {
                            testFileWriter.Remove(plan);
                        }

                        // If forbidNull, then make inactive any result tuple elements that are null.
                        if (config.forbidnull)
                        {
                            Util.Assert(plan.NumTupleElements == execResult.tuple.Length);
                            for (int i = 0; i < plan.NumTupleElements; i++)
                            {
                                if (execResult.tuple[i] == null)
                                {
                                    plan.SetActiveTupleElement(i, false);
                                }
                            }
                            //Util.Assert(!allNull); What is the motivation behind this assertion?
                        }


                        //only allow the receivers to be arguments to future methods
                        if (config.forbidparamobj)
                        {
                            Util.Assert(plan.NumTupleElements == execResult.tuple.Length);
                            for (int i = 1; i < plan.NumTupleElements; i++)
                            {
                                plan.SetActiveTupleElement(i, false);
                            }
                        }

                        builderPlans.AddPlan(plan, execResult);
                    }
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// Selects random plans (from planDB) that yield results specified
        /// in typesDesired. Only consider plans for which filter returns true.
        /// </summary>
        private bool RandomPlans(out RandomPlansResult result, Type[] typesDesired, PlanFilter filter,
            PlanDataBase planDB, bool forbidNull, MethodInfo method)
        {
            List<Plan> plans = new List<Plan>();
            Plan.ParameterChooser[] parameterMap = new Plan.ParameterChooser[typesDesired.Length];

            for (int i = 0; i < typesDesired.Length; i++)
            {
                Type typeDesired = typesDesired[i];

                if (typeDesired.IsArray || typeDesired.Equals(typeof(ArrayList)))
                {
                    int randArrayLength = Common.Enviroment.Random.Next(this.arrayMaxSize + 1);

                    Transformer t;
                    Type baseType = null;
                    if (typeDesired.IsArray)
                    {
                        baseType = typeDesired.GetElementType();
                        t = ArrayBuilderTransformer.Get(baseType, randArrayLength);
                    }
                    else
                    {
                        baseType = typeof(object);
                        t = ArrayListBuilderTransformer.Get(typeof(object), randArrayLength);
                    }

                    RandomPlansResult arrayResult;

                    PlanFilter f;

                    if (forbidNull)
                    {
                        f = delegate(Plan p, int x)
                        {
                            // Non-null heuristic
                            if (baseType.IsValueType && (p.transformer is PrimitiveValueTransformer)
                                && (p.transformer as PrimitiveValueTransformer).IsNull)
                                return false;

                            return true;
                        };
                    }
                    else
                        f = delegate(Plan dontCareP, int dontCareInt) { return true; };

                    if (!RandomPlans(out arrayResult, t.ParameterTypes, f, planDB, forbidNull, null))
                    {
                        //Util.Warning("\tNo array plans for type " + typeDesired.Name + " created");
                        result = null;
                        return false;
                    }

                    plans.Add(new Plan(t, arrayResult.fplans, arrayResult.fparameterChoosers));
                    parameterMap[i] = new Plan.ParameterChooser(i, 0);

                }
                else
                {
                    // Types for which default plans are not created
                    // Don't want to create a plan for a value type which is just a type defn.
                    if (typeDesired.IsValueType && typeDesired.IsGenericTypeDefinition)
                    {
                        result = null; return false;
                    }

                    //Array.createInstance can't create arrays of these types
                    if (typeDesired.Name.Equals("TypedReference") ||
                        typeDesired.Name.Equals("ArgIterator") ||
                        typeDesired.Name.Equals("ByRef") ||
                        typeDesired.Name.Equals("RuntimeArgumentHandle"))
                    {
                        result = null;
                        return false;
                    }

                    if (typeDesired.IsPointer)
                    {
                        result = null;
                        return false;
                    }

                    Plan chosenplan;
                    if (i == 0 && method != null && method.IsStatic)
                    {
                        chosenplan = new Plan(DummyTransformer.Get(typeDesired), new Plan[0], new Randoop.Plan.ParameterChooser[0]);
                    }
                    else
                    {

                        chosenplan = planDB.RandomPlan(typeDesired);
                        if (chosenplan == null)
                        {
                            // No plans for type typeDesired created.
                            result = null;
                            return false;
                        }

                        if (!filter(chosenplan, i))
                        {
                            result = null;
                            return false;
                        }

                        // If plan represents "null" return false.
                        if (forbidNull && (chosenplan.transformer is PrimitiveValueTransformer)
                                       && (chosenplan.transformer as PrimitiveValueTransformer).IsNull)
                        {
                            result = null;
                            return false;
                        }

                    }
                    plans.Add(chosenplan);

                    Collection<int> possibleResultIndices = PossibleResultTupleIndices(chosenplan, typeDesired);
                    if (possibleResultIndices.Count == 0)
                    {
                        result = null;
                        return false;
                    }

                    parameterMap[i] =
                        new Plan.ParameterChooser(i, possibleResultIndices[Common.Enviroment.Random.Next(possibleResultIndices.Count)]);

                }
            }

            result = new RandomPlansResult(plans.ToArray(), parameterMap);
            return true;
        }
            public void ProcessPlan(Plan p, Collection<int> path)
            {
                // Create new name for p's result.
                string freshvar = "v" + nameCounter++;

                if (p.transformer is MethodCall)
                {
                    MapOutputPortsMethod(p, path, freshvar);
                }
                else if ((p.transformer is ConstructorCallTransformer))
                {
                    MapOutputPortsConstructor(p, path, freshvar);
                }
                else if (p.transformer is ArrayOrArrayListBuilderTransformer)
                {
                    MapOutputPortsArray(p, path, freshvar);
                }
                else if (p.transformer is DummyTransformer)
                {
                    MapOutputPortsDummy(p, path, freshvar);
                }
                else if (p.transformer is PrimitiveValueTransformer)
                {
                    MapOutputPortsPrimitive(p, path, freshvar);
                }
                else //TODO: do this 
                {
                    Util.Assert(p.transformer is FieldSettingTransformer);
                    MapOutputPortsFieldSetter(p, path, freshvar);
                }
            }
Exemple #19
0
        private Collection<int> PossibleResultTupleIndices(Plan chosenplan, Type typeDesired)
        {
            // Now, figure out the result element that we'll pick from this plan.
            Collection<int> possibleResultIndices = new Collection<int>();
            for (int j = 0; j < chosenplan.transformer.TupleTypes.Length; j++)
            {
                Type resultType = chosenplan.transformer.TupleTypes[j];

                if (typeDesired.IsInterface)
                {
                    if (resultType.IsInterface && typeDesired.Equals(resultType))
                        possibleResultIndices.Add(j);
                    else
                    {
                        foreach (Type interfaceType in resultType.GetInterfaces())
                            if (interfaceType.Equals(typeDesired))
                            {
                                possibleResultIndices.Add(j);
                                break;
                            }
                    }
                }
                else
                {
                    if (resultType.Equals(typeDesired) || ReflectionUtils.IsSubclassOrEqual(resultType, typeDesired))
                        possibleResultIndices.Add(j);
                }
            }

            Util.Assert(possibleResultIndices.Count > 0);

            Collection<int> activePossible = new Collection<int>();
            foreach (int i in possibleResultIndices)
                if (chosenplan.IsActiveTupleElement(i))
                    activePossible.Add(i);

            //Util.Assert(activePossible.Count > 0);

            return activePossible;
        }
 private void MapOutputPortsPrimitive(Plan p, Collection<int> path, string freshvar)
 {
     // Map primitive.
     OutPortId newObjPort = new OutPortId(path, 0);
     foobar.set(newObjPort, freshvar);
 }
Exemple #21
0
 public override bool Execute(out ResultTuple ret, ResultTuple[] results,
     Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull)
 {
     contractViolated = false;
     exceptionThrown = null;
     ret = new ResultTuple(ftype, new object[] { null });
     return true;
 }
            private void MapOutputPortsConstructor(Plan p, Collection<int> path, string freshvar)
            {
                // Map new object.
                OutPortId newObjPort = new OutPortId(path, 0);
                foobar.set(newObjPort, freshvar);

                // Map mutated parameters.
                for (int i = 0; i < p.parameterChoosers.Length; i++)
                {
                    Plan.ParameterChooser c = p.parameterChoosers[i];
                    OutPortId pOutputPort = new OutPortId(path, i + 1);
                    path.Add(c.planIndex);
                    OutPortId paramPort = new OutPortId(path, c.resultIndex);
                    path.RemoveAt(path.Count - 1);
                    foobar.set(pOutputPort, foobar.Get(paramPort));
                }
            }
Exemple #23
0
        public override bool Execute(out ResultTuple ret, ResultTuple[] parameters,
            Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull)
        {
            this.timesExecuted++;
            long startTime = 0;
            Timer.QueryPerformanceCounter(ref startTime);

            object[] objects = new object[method.GetParameters().Length];
            // Get the actual objects from the results using parameterIndices;
            object receiver = parameters[parameterMap[0].planIndex].tuple[parameterMap[0].resultIndex];
            for (int i = 0; i < method.GetParameters().Length; i++)
            {
                Plan.ParameterChooser pair = parameterMap[i + 1];
                objects[i] = parameters[pair.planIndex].tuple[pair.resultIndex];
            }

            // FIXME This should be true! It currently isn't.
            //if (!this.coverageInfo.methodInfo.IsStatic)
            //    Util.Assert(receiver != null);

            if (forbidNull)
                foreach (object o in objects)
                    Util.Assert(o != null);

            CodeExecutor.CodeToExecute call;

            object returnValue = null;
            contractViolated = false; //default value of contract violation

            call = delegate() { returnValue = method.Invoke(receiver, objects); };

            bool retval = true;

            executionLog.WriteLine("execute method " + this.method.Name);
            executionLog.Flush();

            if (!CodeExecutor.ExecuteReflectionCall(call, debugLog, out exceptionThrown))
            {
                //for exns we can ony add the class to faulty classes when its a guideline violation
                if (Util.GuidelineViolation(exceptionThrown.GetType()))
                {

                    PlanManager.numDistinctContractViolPlans++;

                    KeyValuePair<MethodBase, Type> k = new KeyValuePair<MethodBase, Type>(this.method, exceptionThrown.GetType());
                    if (!exnViolatingMethods.ContainsKey(k))
                    {
                        PlanManager.numContractViolatingPlans++;
                        exnViolatingMethods[k] = true;
                    }

                    //add this class to the faulty classes
                    contractExnViolatingClasses[method.DeclaringType] = true;
                    contractExnViolatingMethods[method] = true;
                }

                ret = null;
                return false;
            }
            else
                ret = new ResultTuple(method, receiver, returnValue, objects);

            //check if the objects in the output tuple violated basic contracts
            if (ret != null)
            {
                foreach (object o in ret.tuple)
                {
                    if (o == null) continue;

                    bool toStrViol, hashCodeViol, equalsViol;
                    int count;
                    if (Util.ViolatesContracts(o, out count, out toStrViol, out hashCodeViol, out equalsViol))
                    {
                        contractViolated = true;
                        contractExnViolatingMethods[method] = true;

                        PlanManager.numDistinctContractViolPlans++;

                        bool newcontractViolation = false;

                        if (toStrViol)
                        {

                            if (!toStrViolatingMethods.ContainsKey(method))
                                newcontractViolation = true;
                            toStrViolatingMethods[method] = true;
                        }
                        if (hashCodeViol)
                        {
                            if (!hashCodeViolatingMethods.ContainsKey(method))
                                newcontractViolation = true;

                            hashCodeViolatingMethods[method] = true;
                        }
                        if (equalsViol)
                        {
                            if (!equalsViolatingMethods.ContainsKey(method))
                                newcontractViolation = true;

                            equalsViolatingMethods[method] = true;
                        }

                        if (newcontractViolation)
                            PlanManager.numContractViolatingPlans++;

                        //add this class to the faulty classes
                        contractExnViolatingClasses[method.DeclaringType] = true;

                        retval = false;
                    }

                }
            }

            long endTime = 0;
            Timer.QueryPerformanceCounter(ref endTime);
            executionTimeAccum += ((double)(endTime - startTime)) / ((double)(Timer.PerfTimerFrequency));

            return retval;
        }
 public void Visit(Plan p)
 {
     nameManager = new NameManager();
     Visit(p, new Collection<int>());
 }
        public override bool Execute(out ResultTuple ret, ResultTuple[] results,
            Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull)
        {
            contractViolated = false;

            this.timesExecuted++;
            long startTime = 0;
            Timer.QueryPerformanceCounter(ref startTime);

            object[] objects = new object[fconstructor.GetParameters().Length];
            // Get the actual objects from the results using parameterIndices;
            for (int i = 0; i < fconstructor.GetParameters().Length; i++)
            {
                Plan.ParameterChooser pair = parameterMap[i];
                objects[i] = results[pair.planIndex].tuple[pair.resultIndex];
            }

            if (forbidNull)
                foreach (object o in objects)
                    Util.Assert(o != null);

            object newObject = null;

            CodeExecutor.CodeToExecute call =
                delegate() { newObject = fconstructor.Invoke(objects); };

            executionLog.WriteLine("execute constructor " + this.fconstructor.DeclaringType);
            executionLog.Flush();

            bool retval = true;
            if (!CodeExecutor.ExecuteReflectionCall(call, debugLog, out exceptionThrown))
            {
                ret = null;

                if (exceptionThrown is AccessViolationException)
                {
                    //Console.WriteLine("SECOND CHANCE AV!" + this.ToString());
                    //Logging.LogLine(Logging.GENERAL, "SECOND CHANCE AV!" + this.ToString());
                }

                //for exns we can ony add the class to faulty classes when its a guideline violation
                if (Util.GuidelineViolation(exceptionThrown.GetType()))
                {
                    PlanManager.numDistinctContractViolPlans++;

                    KeyValuePair<MethodBase, Type> k = new KeyValuePair<MethodBase, Type>(this.fconstructor, exceptionThrown.GetType());
                    if (!exnViolatingMethods.ContainsKey(k))
                    {
                        PlanManager.numContractViolatingPlans++;
                        exnViolatingMethods[k] = true;
                    }

                    //add this class to the faulty classes
                    contractExnViolatingClasses[fconstructor.GetType()] = true;
                    contractExnViolatingMethods[fconstructor] = true;
                }


                return false;
            }
            else
                ret = new ResultTuple(fconstructor, newObject, objects);


            //check if the objects in the output tuple violated basic contracts
            if (ret != null)
            {
                foreach (object o in ret.tuple)
                {
                    if (o == null) continue;

                    bool toStrViol, hashCodeViol, equalsViol;
                    int count;
                    if (Util.ViolatesContracts(o, out count, out toStrViol, out hashCodeViol, out equalsViol))
                    {
                        contractViolated = true;
                        contractExnViolatingMethods[fconstructor] = true;

                        bool newcontractViolation = false;
                        PlanManager.numDistinctContractViolPlans++;

                        if (toStrViol)
                        {

                            if (!toStrViolatingMethods.ContainsKey(fconstructor))
                                newcontractViolation = true;
                            toStrViolatingMethods[fconstructor] = true;
                        }
                        if (hashCodeViol)
                        {
                            if (!hashCodeViolatingMethods.ContainsKey(fconstructor))
                                newcontractViolation = true;

                            hashCodeViolatingMethods[fconstructor] = true;
                        }
                        if (equalsViol)
                        {
                            if (!equalsViolatingMethods.ContainsKey(fconstructor))
                                newcontractViolation = true;

                            equalsViolatingMethods[fconstructor] = true;
                        }

                        if (newcontractViolation)
                            PlanManager.numContractViolatingPlans++;

                        //add this class to the faulty classes
                        contractExnViolatingClasses[fconstructor.DeclaringType] = true;

                        retval = false;
                    }

                }
            }

            long endTime = 0;
            Timer.QueryPerformanceCounter(ref endTime);
            executionTimeAccum += ((double)(endTime - startTime)) / ((double)(Timer.PerfTimerFrequency));

            return retval;
        }
            protected override void Visit(Plan p, Collection<int> path)
            {
                base.Visit(p, path);

            }
        ////[email protected] adds for capture return value for regression assertion
        //public override string ToCSharpCode(ReadOnlyCollection<string> arguments, string newValueName, string return_val)
        //{
        //    return ToCSharpCode(arguments, newValueName);
        //}


        public override bool Execute(out ResultTuple ret, ResultTuple[] results,
            Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull)
        {
            contractViolated = false;

            Util.Assert(parameterMap.Length == 2);

            object receiver = results[parameterMap[0].planIndex].tuple[parameterMap[0].resultIndex];
            object val = results[parameterMap[1].planIndex].tuple[parameterMap[1].resultIndex];

            if (!this.coverageInfo.IsStatic)
                Util.Assert(receiver != null);

            if (forbidNull)
                Util.Assert(val != null);

            CodeExecutor.CodeToExecute call = delegate() { ffield.SetValue(receiver, val); };

            executionLog.WriteLine("set field " + ffield.Name);
            debugLog.WriteLine("set field " + ffield.Name); //[email protected] adds
            executionLog.Flush();

            if (!CodeExecutor.ExecuteReflectionCall(call, debugLog, out exceptionThrown))
            {
                ret = null;
                return false;
            }

            ret = new ResultTuple(ffield, receiver);
            return true;
        }
 private void HandlePrimitive(Plan p, Collection<int> path)
 {
     OutPortId newPort = new OutPortId(path, 0);
     string newName = nameManager.foobar.Get(newPort);
     b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(new List<string>()), newName));
 }
Exemple #29
0
 /// <summary>
 /// Returns false when the execution fails due to exception
 /// Returns true even when some contracts are violated
 /// </summary>
 /// <param name="ret"></param>
 /// <param name="results"></param>
 /// <param name="parameterMap"></param>
 /// <param name="writer"></param>
 /// <param name="exceptionThrown"></param>
 /// <param name="contractViolated"></param>
 /// <param name="forbidNull"></param>
 /// <returns></returns>
 public abstract bool Execute(out ResultTuple ret,
     ResultTuple[] results, Plan.ParameterChooser[] parameterMap, TextWriter executionLog,
     TextWriter writer, out Exception exceptionThrown, out bool contractViolated, bool forbidNull);
            private void HandleMethod(Plan p, Collection<int> path)
            {
                MethodCall mct = p.transformer as MethodCall;
                string freshvar = null;
                if (!mct.method.ReturnType.Equals(typeof(void)))
                {
                    OutPortId newObjPort = new OutPortId(path, 1);
                    freshvar = nameManager.foobar.Get(newObjPort);
                }


                Collection<string> arguments = new Collection<string>();

                for (int i = 0; i < p.parameterChoosers.Length; i++)
                {
                    if (i == 0 && mct.method.IsStatic)
                    {
                        arguments.Add(null);
                        continue;
                    }
                    Plan.ParameterChooser c = p.parameterChoosers[i];
                    path.Add(c.planIndex);
                    OutPortId paramPort = new OutPortId(path, c.resultIndex);
                    path.RemoveAt(path.Count - 1);
                    arguments.Add(nameManager.foobar.Get(paramPort));
                }
                b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(arguments), freshvar));
            }
Exemple #31
0
 public void WriteTest(Plan p)
 {
     string className = this.testPrefix + p.TestCaseId;
     string fileName = outputDir + "\\" + "temp" + "\\" + className + ".cs";
     TestWriterHelperMethods.WritePlanToFile(p, fileName, null, className);
 }
Exemple #32
0
 public void Remove(Plan p)
 {
     string className = this.testPrefix + p.TestCaseId;
     string oldTestFileName = outputDir + "\\" + "temp" + "\\" + className + ".cs";
     new FileInfo(oldTestFileName).Delete();
 }
Exemple #33
0
        /// <summary>
        /// Selects random plans (from planDB) that yield results specified
        /// in typesDesired. Only consider plans for which filter returns true.
        /// </summary>
        private bool RandomPlans(out RandomPlansResult result, Type[] typesDesired, PlanFilter filter,
                                 PlanDataBase planDB, bool forbidNull, MethodInfo method)
        {
            List <Plan> plans = new List <Plan>();

            Plan.ParameterChooser[] parameterMap = new Plan.ParameterChooser[typesDesired.Length];

            for (int i = 0; i < typesDesired.Length; i++)
            {
                Type typeDesired = typesDesired[i];

                //if (typeDesired.IsArray || typeDesired.Equals(typeof(ArrayList))) //[email protected] changes as below to add List input generation
                if (typeDesired.IsArray || typeDesired.Equals(typeof(ArrayList)) || (!string.IsNullOrEmpty(typeDesired.FullName) && typeDesired.FullName.Contains("System.Collections.Generic.List")))
                {
                    int randArrayLength = Common.Enviroment.Random.Next(this.arrayMaxSize + 1);

                    Transformer t;
                    Type        baseType = null;
                    if (typeDesired.IsArray)
                    {
                        baseType = typeDesired.GetElementType();
                        t        = ArrayBuilderTransformer.Get(baseType, randArrayLength);
                    }
                    else //[email protected] addes -- start
                    {
                        if (typeDesired.FullName.Contains("System.Collections.Generic.List"))
                        {
                            //string fullType = typeDesired.ToString();
                            //string elementType = fullType.Substring(fullType.IndexOf('[') + 1, fullType.IndexOf(']') - fullType.IndexOf('[') - 1);
                            //baseType = System.Type.GetType(elementType);

                            baseType = typeDesired.GetProperty("Item").PropertyType;

                            if (baseType == null)
                            {
                                baseType = typeof(object);
                            }

                            t = ListBuilderTransformer.Get(baseType, randArrayLength);
                        }
                        //[email protected] addes -- end
                        else
                        {
                            baseType = typeof(object);
                            t        = ArrayListBuilderTransformer.Get(typeof(object), randArrayLength);
                        }
                    }

                    RandomPlansResult arrayResult;

                    PlanFilter f;

                    if (forbidNull)
                    {
                        f = delegate(Plan p, int x)
                        {
                            // Non-null heuristic
                            if (baseType.IsValueType && (p.transformer is PrimitiveValueTransformer) &&
                                (p.transformer as PrimitiveValueTransformer).IsNull)
                            {
                                return(false);
                            }

                            return(true);
                        };
                    }
                    else
                    {
                        f = delegate(Plan dontCareP, int dontCareInt) { return(true); }
                    };

                    if (!RandomPlans(out arrayResult, t.ParameterTypes, f, planDB, forbidNull, null))
                    {
                        //Util.Warning("\tNo array plans for type " + typeDesired.Name + " created");
                        result = null;
                        return(false);
                    }

                    plans.Add(new Plan(t, arrayResult.fplans, arrayResult.fparameterChoosers));
                    parameterMap[i] = new Plan.ParameterChooser(i, 0);
                }
                else
                {
                    // Types for which default plans are not created
                    // Don't want to create a plan for a value type which is just a type defn.
                    if (typeDesired.IsValueType && typeDesired.IsGenericTypeDefinition)
                    {
                        result = null; return(false);
                    }

                    //Array.createInstance can't create arrays of these types
                    if (typeDesired.Name.Equals("TypedReference") ||
                        typeDesired.Name.Equals("ArgIterator") ||
                        typeDesired.Name.Equals("ByRef") ||
                        typeDesired.Name.Equals("RuntimeArgumentHandle"))
                    {
                        result = null;
                        return(false);
                    }

                    if (typeDesired.IsPointer)
                    {
                        result = null;
                        return(false);
                    }

                    Plan chosenplan;
                    if (i == 0 && method != null && method.IsStatic)
                    {
                        chosenplan = new Plan(DummyTransformer.Get(typeDesired), new Plan[0], new Randoop.Plan.ParameterChooser[0]);
                    }
                    else
                    {
                        chosenplan = planDB.RandomPlan(typeDesired);

                        if (chosenplan == null)
                        {
                            // No plans for type typeDesired created.
                            result = null;
                            return(false);
                        }

                        //if ((method != null) && method.Name.Contains("heapSort") && !(chosenplan.transformer is PrimitiveValueTransformer)) //[email protected]
                        //    Console.WriteLine("debug.");

                        if (!filter(chosenplan, i))
                        {
                            result = null;
                            return(false);
                        }

                        // If plan represents "null" return false.
                        if (forbidNull && (chosenplan.transformer is PrimitiveValueTransformer) &&
                            (chosenplan.transformer as PrimitiveValueTransformer).IsNull)
                        {
                            result = null;
                            return(false);
                        }
                    }
                    plans.Add(chosenplan);

                    Collection <int> possibleResultIndices = PossibleResultTupleIndices(chosenplan, typeDesired);
                    if (possibleResultIndices.Count == 0)
                    {
                        result = null;
                        return(false);
                    }

                    parameterMap[i] =
                        new Plan.ParameterChooser(i, possibleResultIndices[Common.Enviroment.Random.Next(possibleResultIndices.Count)]);
                }
            }

            result = new RandomPlansResult(plans.ToArray(), parameterMap);
            return(true);
        }