Пример #1
0
        /// <summary> Serialization implementation. </summary>
        public override bool Serialize(XElement elem, object obj, ITypeData expectedType)
        {
            if (false == obj is ITestStep)
            {
                return(false);
            }

            var objp = Serializer.SerializerStack.OfType <ObjectSerializer>().FirstOrDefault();

            if (objp != null && objp.Object != null)
            {
                if (objp.CurrentMember.TypeDescriptor.DescendsTo(typeof(ITestStep)))
                {
                    elem.Attributes("type")?.Remove();
                    elem.Value = ((ITestStep)obj).Id.ToString();
                    return(true);
                }
                if (objp.CurrentMember.TypeDescriptor is TypeData tp)
                {
                    // serialize references in list<ITestStep>, only when they are declared by a test step and not a TestStepList.
                    if ((tp.ElementType?.DescendsTo(typeof(ITestStep)) ?? false) && objp.CurrentMember.DeclaringType.DescendsTo(typeof(ITestStep)))
                    {
                        if (tp != TypeData.FromType(typeof(TestStepList)))
                        {
                            elem.Attributes("type")?.Remove();
                            elem.Value = ((ITestStep)obj).Id.ToString();
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Пример #2
0
        public void NullInputTest()
        {
            Input <double> a = null;
            Input <double> b = null;

            Assert.IsTrue(a == b);
            a = new Input <double>()
            {
            };
            Assert.IsTrue(a != b);
            b = new Input <double>()
            {
            };

            var       prop  = TypeData.FromType(typeof(DelayStep)).GetMember(nameof(DelayStep.DelaySecs));
            DelayStep delay = new DelayStep();

            Assert.IsTrue(a == b);
            a.Step     = delay;
            a.Property = prop;
            Assert.IsTrue(a != b);
            b.Step     = delay;
            b.Property = prop;
            Assert.IsTrue(a == b);
        }
Пример #3
0
        public void SerializeNestedSweepLoopRange()
        {
            var tp = new TestPlan();
            var s1 = new SweepLoopRange();
            var s2 = new SweepLoopRange();
            var s3 = new DelayStep()
            {
                DelaySecs = 0
            };

            tp.ChildTestSteps.Add(s1);
            s1.ChildTestSteps.Add(s2);
            s2.ChildTestSteps.Add(s3);
            s1.SweepProperties = new List <IMemberData>()
            {
                TypeData.FromType(typeof(DelayStep)).GetMember(nameof(DelayStep.DelaySecs))
            };
            s2.SweepProperties = new List <IMemberData>()
            {
                TypeData.FromType(typeof(DelayStep)).GetMember(nameof(DelayStep.DelaySecs))
            };

            using (var st = new System.IO.MemoryStream())
            {
                tp.Save(st);
                st.Seek(0, 0);
                tp = TestPlan.Load(st, tp.Path);
            }
            s1 = tp.ChildTestSteps[0] as SweepLoopRange;
            s2 = s1.ChildTestSteps[0] as SweepLoopRange;

            Assert.AreEqual(1, s1.SweepProperties.Count);
            Assert.AreEqual(1, s2.SweepProperties.Count);
            Assert.AreEqual(s1.SweepPropertyName, s2.SweepPropertyName);
        }
Пример #4
0
        public void SweepLoopEnabledTest()
        {
            var plan  = new TestPlan();
            var sweep = new SweepLoop();
            var prog  = new ProcessStep();

            plan.ChildTestSteps.Add(sweep);
            sweep.ChildTestSteps.Add(prog);

            sweep.SweepParameters.Add(new SweepParam(new [] { TypeData.FromType(prog.GetType()).GetMember(nameof(ProcessStep.RegularExpressionPattern)) }));

            var a = AnnotationCollection.Annotate(sweep);

            a.Read();
            var a2   = a.GetMember(nameof(SweepLoop.SweepParameters));
            var col  = a2.Get <ICollectionAnnotation>();
            var new1 = col.NewElement();

            col.AnnotatedElements = col.AnnotatedElements.Append(col.NewElement(), new1);

            var enabledmem = new1.Get <IMembersAnnotation>().Members.Last();
            var boolmember = enabledmem.Get <IMembersAnnotation>().Members.First();
            var val        = boolmember.Get <IObjectValueAnnotation>();

            val.Value = true;

            a.Write();

            var sweepParam = sweep.SweepParameters.FirstOrDefault();
            var en         = (Enabled <string>)sweepParam.Values[1];

            Assert.IsTrue(en.IsEnabled); // from val.Value = true.
        }
Пример #5
0
        /// <summary> Serialization implementation. </summary>
        public override bool Serialize(XElement elem, object sourceObj, ITypeData expectedType)
        {
            if (sourceObj is IEnumerable == false || sourceObj is string)
            {
                return(false);
            }
            IEnumerable sourceEnumerable = (IEnumerable)sourceObj;
            Type        type             = sourceObj.GetType();
            Type        genericTypeArg   = type.GetEnumerableElementType();

            if (genericTypeArg.IsNumeric())
            {
                var parser = new NumberFormatter(CultureInfo.InvariantCulture)
                {
                    UseRanges = false
                };
                elem.Value = parser.FormatRange(sourceEnumerable);
                return(true);
            }

            object prevObj = this.Object;

            try
            {
                this.Object = sourceObj;
                bool isComponentSettings = sourceObj is ComponentSettings;
                foreach (object obj in sourceEnumerable)
                {
                    var step = new XElement(Element);
                    if (obj != null)
                    {
                        type      = obj.GetType();
                        step.Name = TapSerializer.TypeToXmlString(type);
                        if (isComponentSettings)
                        {
                            ComponentSettingsSerializing.Add(obj);
                        }
                        try
                        {
                            Serializer.Serialize(step, obj, expectedType: TypeData.FromType(genericTypeArg));
                        }
                        finally
                        {
                            if (isComponentSettings)
                            {
                                ComponentSettingsSerializing.Remove(obj);
                            }
                        }
                    }

                    elem.Add(step);
                }
            }
            finally
            {
                this.Object = prevObj;
            }

            return(true);
        }
        public void CustomConstructionTest()
        {
            var type      = TypeDefinitionData.FromType(typeof(List <>));
            var addMethod = type.GetMethod("Add");

            Assert.AreEqual("T", addMethod.Parameters[0].Type.Name);

            var constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>() });

            addMethod = constructedType.GetMethod("Add");
            Assert.AreEqual("TestTypeArgument", addMethod.Parameters[0].Type.Name);


            type            = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <>));
            constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>() });

            var constructor = (ConstructorData)constructedType.GetMember(".ctor");

            Assert.AreEqual("TestTypeArgument?", constructor.Parameters[0].Type.GetDisplayName(fullyQualify: false));
            var _event = (EventData)constructedType.GetMember("Event");

            Assert.AreEqual("EventHandler<TestTypeArgument>", _event.Type.GetDisplayName(fullyQualify: false));
            var field = (FieldData)constructedType.GetMember("Field");

            Assert.AreEqual("TestTypeArgument[]", field.Type.GetDisplayName(fullyQualify: false));
            var indexer = (IndexerData)constructedType.GetMember("Item");

            Assert.AreEqual("IList<TestTypeArgument>", indexer.Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("TestTypeArgument[]", indexer.Parameters[0].Type.GetDisplayName(fullyQualify: false));
            var method = (MethodData)constructedType.GetMember("Method");

            Assert.AreEqual("TestTypeArgument?", method.Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("TestTypeArgument", method.Parameters[0].Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("U", method.Parameters[1].Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("Dictionary<TestTypeArgument[], U[]>", method.Parameters[2].Type.GetDisplayName(fullyQualify: false));
            var _operator = (OperatorData)constructedType.GetMember("op_Addition");

            Assert.AreEqual("KeyValuePair<TestTypeArgument, object>", _operator.Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("TestGenericTypeDefinition<TestTypeArgument>", _operator.Parameters[0].Type.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("TestTypeArgument", _operator.Parameters[1].Type.GetDisplayName(fullyQualify: false));
            var property = (PropertyData)constructedType.GetMember("Property");

            Assert.AreEqual("IComparer<TestTypeArgument>", property.Type.GetDisplayName(fullyQualify: false));
            var nestedType = (ConstructedGenericTypeData)constructedType.GetMember("NestedType`1");

            Assert.IsNull(nestedType);

            type            = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <> .NestedType <>));
            constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <TestTypeArgument>(), TypeData.FromType <double>() });
            Assert.AreEqual("NestedType<double>", constructedType.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("BreakingChangesDetector.UnitTests.MetadataTypesTests.ConstructedGenericTypeDataTests.TestGenericTypeDefinition<TestTypeArgument>.NestedType<double>", constructedType.GetDisplayName());
            Assert.AreEqual("Tuple<int, TestTypeArgument[], double>", constructedType.BaseType.GetDisplayName(fullyQualify: false));

            type            = TypeDefinitionData.FromType(typeof(TestGenericTypeDefinition <> .NestedType <> .FurtherNestedType <>));
            constructedType = type.GetConstructedGenericTypeData(new[] { TypeData.FromType <int>(), TypeData.FromType <TestTypeArgument>(), TypeData.FromType <double>() });
            Assert.AreEqual("FurtherNestedType<double>", constructedType.GetDisplayName(fullyQualify: false));
            Assert.AreEqual("BreakingChangesDetector.UnitTests.MetadataTypesTests.ConstructedGenericTypeDataTests.TestGenericTypeDefinition<int>.NestedType<TestTypeArgument>.FurtherNestedType<double>", constructedType.GetDisplayName());
            Assert.AreEqual("Dictionary<int, Tuple<TestTypeArgument, double>>", constructedType.BaseType.GetDisplayName(fullyQualify: false));
        }
Пример #7
0
        ExpandedTypeData getExpandedTypeData(TestPlanReference step)
        {
            var expDesc = new ExpandedTypeData();

            expDesc.InnerDescriptor = TypeData.FromType(typeof(TestPlanReference));
            expDesc.Object          = step;
            return(expDesc);
        }
Пример #8
0
 public void ConstructedGenericTypeDataTests()
 {
     Assert.AreEqual("object", TypeData.FromType <object>().DisplayName);
     Assert.AreEqual("System.Collections.Generic.IEnumerable<out T>", TypeData.FromType(typeof(IEnumerable <>)).DisplayName);
     Assert.AreEqual("System.Collections.Generic.IEnumerable<int>", TypeData.FromType(typeof(IEnumerable <int>)).DisplayName);
     Assert.AreEqual("System.Collections.Generic.IEnumerable<List<int[]>>", TypeData.FromType(typeof(IEnumerable <List <int[]> >)).DisplayName);
     Assert.AreEqual("int?", TypeData.FromType <Nullable <int> >().DisplayName);
 }
Пример #9
0
        public void InputBasicTests()
        {
            var            prop  = TypeData.FromType(typeof(DelayStep)).GetMember(nameof(DelayStep.DelaySecs));
            DelayStep      delay = new DelayStep();
            Input <double> secs  = new Input <double>()
            {
                Step = delay, Property = prop
            };



            delay.DelaySecs = 2;
            Assert.AreEqual(secs.Value, delay.DelaySecs);

            Input <double> secs2 = new Input <double>()
            {
                Step = delay, Property = prop
            };

            Assert.AreEqual(secs, secs2);

            Input <double> secs3 = new Input <double>()
            {
                Step = delay, Property = null
            };
            Input <double> secs4 = new Input <double>()
            {
                Step = null, Property = prop
            };
            Input <double> secs5 = new Input <double>()
            {
                Step = null, Property = null
            };
            Input <double> secs6 = new Input <double>()
            {
                Step = delay, PropertyName = prop.Name
            };

            Assert.IsFalse(secs3 == secs4);
            Assert.IsFalse(secs4 == secs5);
            Assert.IsFalse(secs3 == secs5);
            Assert.IsTrue(secs == secs2);
            Assert.IsTrue(secs == secs6);

            { // test serialize
                var plan = new TestPlan();
                plan.ChildTestSteps.Add(delay);
                plan.ChildTestSteps.Add(new ReadInputStep()
                {
                    Input = secs
                });

                var      planxml = new TapSerializer().SerializeToString(plan);
                TestPlan plan2   = (TestPlan) new TapSerializer().DeserializeFromString(planxml);
                var      step2   = plan2.ChildTestSteps[1] as ReadInputStep;
                Assert.IsTrue(step2.Input.Step == plan2.ChildTestSteps[0]);
            }
        }
Пример #10
0
 internal static readonly DynamicMember DynamicMembers = new DynamicMembersMember()
 {
     Name           = "ForwardedMembers",
     DefaultValue   = null,
     DeclaringType  = TypeData.FromType((typeof(TestStepTypeData))),
     Attributes     = new Attribute[] { new XmlIgnoreAttribute(), new AnnotationIgnoreAttribute() },
     Writable       = true,
     Readable       = true,
     TypeDescriptor = TypeData.FromType(typeof((Object, IMemberData)[]))
Пример #11
0
        /// <summary> Gets the C# type info for a string.  </summary>
        public ITypeData GetTypeData(string identifier)
        {
            var type = PluginManager.LocateType(identifier);

            if (type != null)
            {
                return(TypeData.FromType(type));
            }
            return(null);
        }
Пример #12
0
        public void TestDisplayName()
        {
            var aType = TypeData.FromType(typeof(WrongAName));
            var bType = TypeData.FromType(typeof(WrongBName));

            var displayDataA = aType.GetAttribute <DisplayAttribute>();
            var displayDataB = bType.GetAttribute <DisplayAttribute>();

            Assert.IsTrue(displayDataA.Name.Equals("Real A Name"));
            Assert.IsTrue(displayDataB.Name.Equals("Real B Name"));
        }
Пример #13
0
        public void LocateSystemNetIPAddressTest()
        {
            // the plugin searcher does not always locate .NET assemblies if they are part of the framework.
            // However if they are ever mentioned in respect to a Type, then we must make sure it is correctly loaded.
            var type1 = TypeData.FromType(typeof(System.Net.IPAddress));
            var type2 = TypeData.GetTypeData("System.Net.IPAddress");

            Assert.AreEqual(type1, type2);
            Assert.IsNotNull(type1);
            Assert.IsNotNull(type2);
        }
Пример #14
0
        private static object ParseEnum(string name, string value, Type propertyType)
        {
            var obj = StringConvertProvider.FromString(value, TypeData.FromType(propertyType), null, System.Globalization.CultureInfo.InvariantCulture);

            if (obj == null)
            {
                throw new Exception(string.Format("Could not parse argument '{0}'. Argument given: '{1}'. Valid arguments: {2}", name, value, string.Join(", ", propertyType.GetEnumNames())));
            }

            return(obj);
        }
Пример #15
0
        public void VerifyPackageDependencies()
        {
            var tp = new TestPlan();

            tp.ChildTestSteps.Add(new DelayStep());
            var serializer = new TapSerializer();

            var str = serializer.SerializeToString(tp);

            Assert.IsTrue(str.Contains("<Package.Dependencies>"));
            Assert.IsTrue(serializer.GetUsedTypes().Any(x => x.DescendsTo(TypeData.FromType(typeof(DelayStep)))));
        }
Пример #16
0
        public CliActionTree()
        {
            var commands = TypeData.GetDerivedTypes(TypeData.FromType(typeof(ICliAction)))
                           .Where(t => t.CanCreateInstance && t.GetDisplayAttribute() != null).ToList();

            Name = "tap";
            Root = this;
            foreach (var item in commands)
            {
                ParseCommand(item, item.GetDisplayAttribute().Group, Root);
            }
        }
Пример #17
0
        public void TypeWithElementDataTest()
        {
            var method = typeof(TypeDisplayNameTests).GetMethod("Method1");

            Assert.AreEqual("int*", TypeData.FromType(method.GetParameters()[0].ParameterType).DisplayName);

            method = typeof(TypeDisplayNameTests).GetMethod("Method2");
            Assert.AreEqual("void*", TypeData.FromType(method.GetParameters()[0].ParameterType).DisplayName);

            method = typeof(TypeDisplayNameTests).GetMethod("Method3");
            Assert.AreEqual("byte***", TypeData.FromType(method.GetParameters()[0].ParameterType).DisplayName);
        }
Пример #18
0
        public bool Deserialize(XElement node, ITypeData t, Action <object> setter)
        {
            if (t == TypeData.FromType(typeof(IPAddress)) == false)
            {
                return(false);
            }
            IPAddress address;

            if (IPAddress.TryParse(node.Value, out address))
            {
                setter(address);
            }
            return(true);
        }
Пример #19
0
        public void RunRepeat()
        {
            // plan:
            //    repeat1 (count 3)
            //       repeat2 (count 3)
            //         setVer  - sets verdict to pass
            //         checkif - breaks repeat 2
            //         setVer2 - is never executed.
            // total number of step runs:
            // repeat1: 1
            // repeat2: 3
            // setVer: 3
            // checkif: 3
            // setVer2: 0
            // Total: 10

            var rlistener = new PlanRunCollectorListener();

            var repeat1 = new RepeatStep {
                Action = RepeatStep.RepeatStepAction.Fixed_Count, Count = 3
            };
            var repeat2 = new RepeatStep {
                Action = RepeatStep.RepeatStepAction.Fixed_Count, Count = 3
            };
            var setVer = new TestTestSteps.VerdictStep()
            {
                VerdictOutput = Verdict.Pass
            };
            var checkif = new IfStep()
            {
                Action = IfStep.IfStepAction.BreakLoop, TargetVerdict = setVer.VerdictOutput
            };
            var setVer2 = new TestTestSteps.VerdictStep(); // this one is never executed.

            repeat2.ChildTestSteps.AddRange(new ITestStep[] { setVer, checkif, setVer2 });
            repeat1.ChildTestSteps.Add(repeat2);
            var plan = new TestPlan();

            plan.ChildTestSteps.Add(repeat1);

            checkif.InputVerdict.Step     = setVer;
            checkif.InputVerdict.Property = TypeData.FromType(typeof(TestStep)).GetMember(nameof(TestStep.Verdict));



            var planrun = plan.Execute(new[] { rlistener });

            Assert.AreEqual(10, rlistener.StepRuns.Count);
            Assert.AreEqual(5, planrun.StepsWithPrePlanRun.Count);
        }
Пример #20
0
        public void Annotate(AnnotationCollection annotations)
        {
            var member = annotations.Get <IMemberAnnotation>()?.Member;

            if (member == null)
            {
                return;
            }
            if (member.TypeDescriptor == TypeData.FromType(typeof(IPAddress)) == false)
            {
                return;
            }

            // now its known that it is an IPAddress
            annotations.Add(new IPAnnotation(annotations));
        }
Пример #21
0
        /// <summary> Deserialization implementation. </summary>
        public override bool Deserialize(XElement element, ITypeData t, Action <object> setter)
        {
            if (t.DescendsTo(TypeData.FromType(typeof(IConstResourceProperty))))
            {
                if (element.IsEmpty)
                {
                    return(true);                 // Dont do anything with a <port/>
                }
                var name = element.Attribute("Name");
                if (name == null)
                {
                    return(true);
                }
                Serializer.Deserialize(element.Element("Device"), obj =>
                {
                    var resource = obj as IResource;

                    if (obj is ComponentSettings)
                    {  // for legacy support. type argument was a component settings, not a device. In this case used index to get the resource.
                        obj     = ComponentSettings.GetCurrent(obj.GetType());
                        var lst = (IList)obj;
                        var dev = element.Element("Device");
                        if (dev != null && int.TryParse(dev.Value, out int index) && index >= 0 && lst.Count > index)
                        {
                            resource = ((IList)obj)[index] as IResource;
                        }
                    }
                    if (resource == null)
                    {
                        return;
                    }


                    foreach (var resProp in resource.GetConstProperties())
                    {
                        if (TypeData.GetTypeData(resProp).DescendsTo(t) && resProp.Name == name.Value)
                        {
                            setter(resProp);
                            return;
                        }
                    }
                }, typeof(IResource));
                return(true);
            }
            return(false);
        }
Пример #22
0
        public void GetDirectImplicitConversionsTests()
        {
            var rank1ArrayType     = typeof(int[]);
            var rank1ArrayTypeData = ArrayTypeData.FromType(rank1ArrayType);

            var implicitConversions = new HashSet <TypeData>(rank1ArrayTypeData.GetDirectImplicitConversions(true));

            if (implicitConversions.Remove(TypeData.FromType(rank1ArrayType.BaseType)) == false)
            {
                Assert.Fail(string.Format("Base type {0} was not returned from GetDirectImplicitConversions of a rank-1 array.", rank1ArrayType.BaseType));
            }

            foreach (var implementedInterface in rank1ArrayType.GetInterfaces())
            {
                if (implicitConversions.Remove(TypeData.FromType(implementedInterface)) == false)
                {
                    Assert.Fail(string.Format("Implemented interface type {0} was not returned from GetDirectImplicitConversions of a rank-1 array.", implementedInterface.Name));
                }
            }

            Assert.AreEqual(0, implicitConversions.Count, "Extra interfaces were returned from GetDirectImplicitConversions of a rank-1 array.");

            // ----------------------------------------------------------------

            var rank2ArrayType     = typeof(int[, ]);
            var rank2ArrayTypeData = ArrayTypeData.FromType(rank2ArrayType);

            implicitConversions = new HashSet <TypeData>(rank2ArrayTypeData.GetDirectImplicitConversions(true));

            if (implicitConversions.Remove(TypeData.FromType(rank2ArrayType.BaseType)) == false)
            {
                Assert.Fail(string.Format("Base type {0} was not returned from GetDirectImplicitConversions of a rank-1 array.", rank2ArrayType.BaseType));
            }

            foreach (var implementedInterface in rank2ArrayType.GetInterfaces())
            {
                if (implicitConversions.Remove(TypeData.FromType(implementedInterface)) == false)
                {
                    Assert.Fail(string.Format("Implemented interface type {0} was not returned from GetDirectImplicitConversions of a rank-2 array.", implementedInterface.Name));
                }
            }

            Assert.AreEqual(0, implicitConversions.Count, "Extra interfaces were returned from GetDirectImplicitConversions of a rank-2 array.");
        }
Пример #23
0
        /// <summary> Serialization implementation. </summary>
        public override bool Serialize(XElement elem, object obj, ITypeData expectedType)
        {
            if (obj is IConstResourceProperty == false)
            {
                return(false);
            }
            if (checkRentry.Contains(obj))
            {
                return(false);
            }
            checkRentry.Add(obj);
            try
            {
                IConstResourceProperty port = (IConstResourceProperty)obj;

                elem.SetAttributeValue("Name", port.Name);
                IList settings = ComponentSettingsList.GetContainer(port.Device.GetType());
                if (port.Device != null && settings != null)
                {
                    XElement device = new XElement("Device");
                    device.SetAttributeValue("type", settings.GetType().Name);
                    if (Serializer.Serialize(device, port.Device, TypeData.FromType(port.GetType())))
                    {
                        elem.Add(device);
                    }
                }
                else
                {
                    elem.Add(new XElement("Device"));
                }
                return(true);
            }
            finally
            {
                checkRentry.Remove(obj);
            }
        }
        public void ImplicitNullableConversionsTests()
        {
            var result = TypeData.FromType <BStruct?>().IsAssignableFromNew(TypeData.FromType <CStruct?>());

            TestAssignability((a, b) => a.IsNullable() || b.IsNullable(),
                              typeof(byte),
                              typeof(sbyte),
                              typeof(ushort),
                              typeof(short),
                              typeof(uint),
                              typeof(int),
                              typeof(ulong),
                              typeof(long),
                              typeof(float),
                              typeof(double),
                              typeof(decimal),
                              typeof(char),
                              typeof(CStruct),
                              typeof(BStruct),
                              typeof(AStruct),
                              typeof(byte?),
                              typeof(sbyte?),
                              typeof(ushort?),
                              typeof(short?),
                              typeof(uint?),
                              typeof(int?),
                              typeof(ulong?),
                              typeof(long?),
                              typeof(float?),
                              typeof(double?),
                              typeof(decimal?),
                              typeof(char?),
                              typeof(CStruct?),
                              typeof(BStruct?),
                              typeof(AStruct?));
        }
Пример #25
0
        /// <summary>
        /// Executes the action with the given parameters.
        /// </summary>
        /// <param name="action">The action to be executed.</param>
        /// <param name="parameters">The parameters for the action.</param>
        /// <returns></returns>
        public static int PerformExecute(this ICliAction action, string[] parameters)
        {
            ArgumentsParser ap    = new ArgumentsParser();
            var             td    = TypeData.GetTypeData(action);
            var             props = td.GetMembers();

            ap.AllOptions.Add("help", 'h', false, "Write help information.");
            ap.AllOptions.Add("verbose", 'v', false, "Show verbose/debug-level log messages.");
            ap.AllOptions.Add("color", 'c', false, "Color messages according to their severity.");
            ap.AllOptions.Add("quiet", 'q', false, "Quiet console logging.");

            var argToProp        = new Dictionary <string, IMemberData>();
            var unnamedArgToProp = new List <IMemberData>();

            foreach (var prop in props)
            {
                if (prop.Readable == false || prop.Writable == false)
                {
                    continue;
                }

                if (prop.HasAttribute <UnnamedCommandLineArgument>())
                {
                    unnamedArgToProp.Add(prop);
                    continue;
                }

                if (!prop.HasAttribute <CommandLineArgumentAttribute>())
                {
                    continue;
                }

                var attr = prop.GetAttribute <CommandLineArgumentAttribute>();

                var needsArg = prop.TypeDescriptor != TypeData.FromType(typeof(bool));

                string description = "";
                if (prop.HasAttribute <ObsoleteAttribute>())
                {
                    var obsoleteAttribute = prop.GetAttribute <ObsoleteAttribute>();
                    description = $"[OBSOLETE: {obsoleteAttribute.Message}] {attr.Description}";
                }
                else
                {
                    description = attr.Description;
                }

                var arg = ap.AllOptions.Add(attr.Name, attr.ShortName == null ? '\0' : attr.ShortName.FirstOrDefault(), needsArg, description);
                arg.IsVisible = attr.Visible;
                argToProp.Add(arg.LongName, prop);
            }

            var args = ap.Parse(parameters);

            if (args.MissingArguments.Any())
            {
                throw new Exception($"Command line argument '{args.MissingArguments.FirstOrDefault().LongName}' is missing an argument.");
            }

            if (args.Contains("help"))
            {
                printOptions(action.GetType().GetAttribute <DisplayAttribute>().Name, ap.AllOptions, unnamedArgToProp);
                return(0);
            }

            foreach (var opts in args)
            {
                if (argToProp.ContainsKey(opts.Key) == false)
                {
                    continue;
                }
                var prop = argToProp[opts.Key];

                if (prop.TypeDescriptor is TypeData propTd)
                {
                    Type propType = propTd.Load();
                    if (propType == typeof(bool))
                    {
                        prop.SetValue(action, true);
                    }
                    else if (propType.IsEnum)
                    {
                        prop.SetValue(action, ParseEnum(opts.Key, opts.Value.Value, propType));
                    }
                    else if (propType == typeof(string))
                    {
                        prop.SetValue(action, opts.Value.Value);
                    }
                    else if (propType == typeof(string[]))
                    {
                        prop.SetValue(action, opts.Value.Values.ToArray());
                    }
                    else if (propType == typeof(int))
                    {
                        prop.SetValue(action, int.Parse(opts.Value.Value));
                    }
                    else
                    {
                        throw new Exception(string.Format("Command line option '{0}' is of an unsupported type '{1}'.", opts.Key, propType.Name));
                    }
                }
                else
                {
                    throw new Exception(string.Format("Command line option '{0}' is of an unsupported type '{1}'.", opts.Key, prop.TypeDescriptor.Name));
                }
            }

            unnamedArgToProp = unnamedArgToProp.OrderBy(p => p.GetAttribute <UnnamedCommandLineArgument>().Order).ToList();
            var requiredArgs = unnamedArgToProp.Where(x => x.GetAttribute <UnnamedCommandLineArgument>().Required).ToHashSet();
            int idx          = 0;

            for (int i = 0; i < unnamedArgToProp.Count; i++)
            {
                var p = unnamedArgToProp[i];

                if (p.TypeDescriptor.IsA(typeof(string)))
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        p.SetValue(action, args.UnnamedArguments[idx++]);
                        requiredArgs.Remove(p);
                    }
                }
                else if (p.TypeDescriptor.IsA(typeof(string[])))
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        p.SetValue(action, args.UnnamedArguments.Skip(idx).ToArray());
                        requiredArgs.Remove(p);
                    }

                    idx = args.UnnamedArguments.Length;
                }
                else if (p.TypeDescriptor is TypeData td2 && td2.Type.IsEnum)
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        var name = p.GetAttribute <UnnamedCommandLineArgument>()?.Name ?? p.Name;
                        p.SetValue(action, ParseEnum($"<{name}>", args.UnnamedArguments[idx++], td2.Type));
                        requiredArgs.Remove(p);
                    }
                }
            }

            if (args.UnknownsOptions.Any() || requiredArgs.Any())
            {
                if (args.UnknownsOptions.Any())
                {
                    Console.WriteLine("Unknown options: " + string.Join(" ", args.UnknownsOptions));
                }

                if (requiredArgs.Any())
                {
                    Console.WriteLine("Missing argument: " + string.Join(" ", requiredArgs.Select(p => p.GetAttribute <UnnamedCommandLineArgument>().Name)));
                }

                printOptions(action.GetType().GetAttribute <DisplayAttribute>().Name, ap.AllOptions, unnamedArgToProp);
                return(1);
            }

            var actionFullName = td.GetDisplayAttribute().GetFullName();

            log.Debug($"Executing CLI action: {actionFullName}");
            var sw       = Stopwatch.StartNew();
            int exitCode = action.Execute(TapThread.Current.AbortToken);

            log.Debug(sw, "CLI action returned exit code: {0}", exitCode);
            return(exitCode);
        }
Пример #26
0
        /// <summary> Creates a Key and a Value node in the XML.</summary>
        public override bool Serialize(XElement node, object obj, ITypeData _expectedType)
        {
            if (obj == null || false == obj.GetType().DescendsTo(typeof(KeyValuePair <,>)))
            {
                return(false);
            }

            if (_expectedType is TypeData expectedType2 && expectedType2.Type is Type expectedType)
            {
                var  key     = new XElement("Key");
                var  value   = new XElement("Value");
                bool keyok   = Serializer.Serialize(key, _expectedType.GetMember("Key").GetValue(obj), TypeData.FromType(expectedType.GetGenericArguments()[0]));
                bool valueok = Serializer.Serialize(value, _expectedType.GetMember("Value").GetValue(obj), TypeData.FromType(expectedType.GetGenericArguments()[1]));
                if (!keyok || !valueok)
                {
                    return(false);
                }
                node.Add(key);
                node.Add(value);
                return(true);
            }
            return(false);
        }
Пример #27
0
        public void RunSweepWithInterruptions(bool loopRange)
        {
            IEnumerable <int> check;
            var      tp = new TestPlan();
            TestStep sweep;

            if (loopRange)
            {
                var sweepRange = new SweepLoopRange();
                sweepRange.SweepStart      = 10;
                sweepRange.SweepEnd        = 30;
                sweepRange.SweepStep       = 1;
                sweepRange.SweepProperties = new List <IMemberData>()
                {
                    TypeData.FromType(typeof(SweepTestStep)).GetMember("SweepProp")
                };
                sweep = sweepRange;
                check = Enumerable.Range(10, (int)(sweepRange.SweepEnd - sweepRange.SweepStart + 1));
            }
            else
            {
                check = Enumerable.Range(10, 20);
                var sweepRange = new SweepLoop();
                var lst        = new List <SweepParam>();
                lst.Add(new SweepParam(new[] { TypeData.FromType(typeof(SweepTestStep)).GetMember("SweepProp") }, check.Cast <object>().ToArray()));
                sweepRange.SweepParameters = lst;
                sweep = sweepRange;
            }
            var step = new SweepTestStep();

            tp.ChildTestSteps.Add(sweep);
            sweep.ChildTestSteps.Add(step);

            var rlistener = new PlanRunCollectorListener()
            {
                CollectResults = true
            };
            bool done = false;

            void interruptOperations()
            {
                // this is to reproduce an error previously happening when the
                // SweepLoopRange.Error value was getted.
                // this would have changed the value of SweepProp intermiddently.
                while (!done)
                {
                    // so bother as much as possible...
                    var error2 = sweep.Error;
                }
            }

            var trd = new Thread(interruptOperations);

            trd.Start();
            var result = tp.Execute(new[] { rlistener });

            done = true;
            trd.Join();
            var results = rlistener.Results.Select(x => (int)x.Result.Columns[0].Data.GetValue(0)).ToArray();

            Assert.IsTrue(results.SequenceEqual(check));
        }
Пример #28
0
        public void TestResourceReference()
        {
            // Loop seems to provoke a race condition in test plan execution
            for (int i = 0; i < 10; i++)
            {
                EngineSettings.Current.ToString();
                var step = new OpenTap.Plugins.BasicSteps.SweepLoop();

                var theDuts  = Enumerable.Range(0, 10).Select(number => new IsOpenedDut()).ToArray();
                var otherdut = new IsOpenedDut();

                step.ChildTestSteps.Add(new IsOpenUsedTestStep()
                {
                    Resource = new IsOpenedDut(), Resource2 = otherdut, Resource3 = new [] { new IsOpenedDut() }
                });
                step.SweepParameters.Add(new OpenTap.Plugins.BasicSteps.SweepParam(new IMemberData[] { TypeData.FromType(typeof(IsOpenUsedTestStep)).GetMember("Resource") }, theDuts));
                var plan = new TestPlan();
                plan.PrintTestPlanRunSummary = true;
                plan.ChildTestSteps.Add(step);
                var rlistener = new PlanRunCollectorListener();
                var planRun   = plan.Execute(new IResultListener[] { rlistener });
                Assert.AreEqual(theDuts.Length + 1, rlistener.StepRuns.Count);
                Assert.IsTrue(planRun.Verdict == Verdict.NotSet);
                Assert.IsTrue(theDuts.All(dut => dut.IsClosed && dut.IsOpened && dut.IsUsed));
            }
        }
Пример #29
0
        public void SweepRaceBug()
        {
            // test that validation rules can be checked while the test plan is running
            // without causing an error. The validation rules does not need to do actual validation
            // but since SweepLoop and SweepLoopRange modifies its child steps this could cause an error
            // as shown by SweepRaceBugCheckStep and SweepRaceBugStep.
            var plan   = new TestPlan();
            var repeat = new RepeatStep {
                Count = 10, Action = RepeatStep.RepeatStepAction.Fixed_Count
            };
            var loop = new SweepLoop();

            repeat.ChildTestSteps.Add(loop);
            loop.ChildTestSteps.Add(new SweepRaceBugStep()
            {
            });
            loop.ChildTestSteps.Add(new SweepRaceBugCheckStep()
            {
            });
            var steptype = TypeData.FromType(typeof(SweepRaceBugStep));
            var member   = steptype.GetMember(nameof(SweepRaceBugStep.Frequency));
            var member2  = TypeData.FromType(typeof(SweepRaceBugCheckStep)).GetMember(nameof(SweepRaceBugCheckStep.Frequency2));

            var lst = new List <SweepParam>();

            double[] values = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            lst.Add(new SweepParam(new[] { member }, values.Cast <object>().ToArray()));
            lst.Add(new SweepParam(new[] { member2 }, values.Cast <object>().ToArray()));
            loop.SweepParameters = lst;

            var loopRange = new SweepLoopRange();

            loopRange.SweepStart  = 1;
            loopRange.SweepEnd    = 10;
            loopRange.SweepPoints = 10;
            loopRange.ChildTestSteps.Add(new SweepRaceBugStep()
            {
            });
            loopRange.ChildTestSteps.Add(new SweepRaceBugCheckStep()
            {
            });
            loopRange.SweepProperties = new List <IMemberData> {
                member, member2
            };
            var repeat2 = new RepeatStep {
                Count = 10, Action = RepeatStep.RepeatStepAction.Fixed_Count
            };

            repeat2.ChildTestSteps.Add(loopRange);
            var parallel = new ParallelStep();

            plan.ChildTestSteps.Add(parallel);
            parallel.ChildTestSteps.Add(repeat);
            parallel.ChildTestSteps.Add(repeat2);

            TestPlanRun run = null;

            TapThread.Start(() => run = plan.Execute());
            TapThread.Start(() =>
            {
                while (run == null)
                {
                    loopRange.Error.ToList();
                }
            });
            while (run == null)
            {
                loop.Error.ToList();
            }

            Assert.AreEqual(Verdict.NotSet, run.Verdict);
        }
Пример #30
0
        public void RepeatWithReferenceOutsideStep()
        {
            var      stream = File.OpenRead("TestTestPlans/whiletest.TapPlan");
            TestPlan plan   = (TestPlan) new TapSerializer().Deserialize(stream, type: TypeData.FromType(typeof(TestPlan)));
            var      run    = plan.Execute();

            Assert.AreEqual(Verdict.Pass, run.Verdict);
        }