Exemple #1
0
        public object CastConstantValue(Type targetType, string objStr)
        {
            if (targetType.IsInterface || targetType.IsAbstract)
            {
                throw new TestflowDataException(ModuleErrorCode.UnsupportedTypeCast,
                                                _context.I18N.GetFStr("CastInterface", targetType.Name));
            }
            object       castedObject = null;
            BindingFlags flags        = BindingFlags.Public | BindingFlags.Instance;

            try
            {
                if (targetType.IsArray)
                {
                    string[] datas          = JsonConvert.DeserializeObject <string[]>(objStr, _settings);
                    Type     elementType    = targetType.GetElementType();
                    Array    targetInstance = Array.CreateInstance(elementType, datas.Length);
                    for (int i = 0; i < datas.Length; i++)
                    {
                        object elementValue = _context.Convertor.CastConstantValue(elementType, datas[i]);
                        targetInstance.SetValue(elementValue, i);
                    }
                    castedObject = targetInstance;
                }
                // struct
                else if (targetType.IsValueType)
                {
                    object targetInstance = targetType.Assembly.CreateInstance(ModuleUtils.GetTypeFullName(targetType));
                    SetValueToStructOrClass(targetType, objStr, flags, ref targetInstance);
                    castedObject = targetInstance;
                }
                // 暂不考虑List的情况
                else
                {
                    ConstructorInfo constructor = targetType.GetConstructor(new Type[] {});
                    if (null == constructor)
                    {
                        _context.LogSession.Print(LogLevel.Error, _context.SessionId,
                                                  $"Cannot cast string <{objStr}> as target type <{targetType.Name}> has no default constructor.");
                        throw new TestflowDataException(ModuleErrorCode.UnsupportedTypeCast,
                                                        _context.I18N.GetFStr("NoDefaultConstructor", targetType.Name));
                    }
                    object targetInstance = constructor.Invoke(new object[] { });
                    SetValueToStructOrClass(targetType, objStr, flags, ref targetInstance);
                    castedObject = targetInstance;
                }
            }
            catch (JsonReaderException ex)
            {
                _context.LogSession.Print(LogLevel.Error, _context.SessionId, $"Cast value <{objStr}> failed: {ex.Message}");
                throw new TestflowDataException(ModuleErrorCode.UnsupportedTypeCast,
                                                _context.I18N.GetFStr("CastValueFailed", targetType.Name), ex);
            }
            return(castedObject);
        }
Exemple #2
0
        ISequenceFlowContainer ICloneableClass <ISequenceFlowContainer> .Clone()
        {
            AssemblyInfoCollection assemblies = new AssemblyInfoCollection();

            foreach (IAssemblyInfo assemblyInfo in this.Assemblies)
            {
                assemblies.Add(assemblyInfo);
            }

            TypeDataCollection typeDatas = new TypeDataCollection();

            foreach (ITypeData typeData in TypeDatas)
            {
                typeDatas.Add(typeData);
            }

            ArgumentCollection arguments = new ArgumentCollection();

            ModuleUtils.CloneCollection(this.Arguments, arguments);

            VariableCollection variables = new VariableCollection();

            ModuleUtils.CloneFlowCollection(this.Variables, variables);

            // SequenceGroupParameter只在序列化时使用
            // Parameters只有在序列化时才会生成,在加载完成后会被删除
            ISequenceGroupParameter parameters = (null == Parameters) ?
                                                 null : this.Parameters.Clone() as ISequenceGroupParameter;

            SequenceCollection sequenceCollection = new SequenceCollection();

            ModuleUtils.CloneFlowCollection(this.Sequences, sequenceCollection);

            SequenceGroup sequenceGroup = new SequenceGroup()
            {
                Name           = this.Name + Constants.CopyPostfix,
                Description    = this.Description,
                Parent         = this.Parent,
                Info           = this.Info.Clone(),
                Assemblies     = assemblies,
                TypeDatas      = typeDatas,
                Arguments      = arguments,
                Variables      = variables,
                Parameters     = parameters,
                ExecutionModel = this.ExecutionModel,
                SetUp          = this.SetUp.Clone() as ISequence,
                Sequences      = sequenceCollection,
                TearDown       = this.TearDown.Clone() as ISequence
            };

            sequenceGroup.SetUp.Index    = CommonConst.SetupIndex;
            sequenceGroup.TearDown.Index = CommonConst.TeardownIndex;
            sequenceGroup.RefreshSignature();
            return(sequenceGroup);
        }
Exemple #3
0
        protected override void FlowTaskAction()
        {
            SendStartMessage();

            // 打印状态日志
            Context.LogSession.Print(LogLevel.Info, Context.SessionId, $"Start run sequence {_sequenceIndex}.");

            Context.State = RuntimeState.Running;

            SessionTaskEntity sessionTaskEntity = Context.SessionTaskEntity;

            try
            {
                sessionTaskEntity.InvokeSetUp();
                RuntimeState setUpState = sessionTaskEntity.GetSequenceTaskState(CommonConst.SetupIndex);
                // 如果SetUp执行失败,则执行TearDown,且配置所有序列为失败状态,并发送所有序列都失败的信息
                if (CoreUtils.IsFailed(setUpState))
                {
                    // 打印状态日志
                    Context.LogSession.Print(LogLevel.Error, Context.SessionId, "Run setup failed.");
                    for (int i = 0; i < sessionTaskEntity.SequenceCount; i++)
                    {
                        SequenceTaskEntity sequenceTaskEntity = sessionTaskEntity.GetSequenceTaskEntity(i);
                        sequenceTaskEntity.State = RuntimeState.Failed;

                        FailedInfo         failedInfo    = new FailedInfo(Context.I18N.GetStr("SetUpFailed"), FailedType.SetUpFailed);
                        CallStack          sequenceStack = ModuleUtils.GetSequenceStack(i, sequenceTaskEntity.RootCoroutineId);
                        SequenceStatusInfo statusInfo    = new SequenceStatusInfo(i, sequenceStack,
                                                                                  StatusReportType.Failed, setUpState, StepResult.NotAvailable, failedInfo)
                        {
                            ExecutionTime  = DateTime.Now,
                            ExecutionTicks = -1,
                            CoroutineId    = sequenceTaskEntity.RootCoroutineId
                        };
                        Context.StatusQueue.Enqueue(statusInfo);
                    }
                }
                else
                {
                    sessionTaskEntity.InvokeSequence(_sequenceIndex);
                }
            }
            finally
            {
                sessionTaskEntity.InvokeTearDown();

                Context.State = RuntimeState.Over;
                this.Next     = null;

                SendOverMessage();

                // 打印状态日志
                Context.LogSession.Print(LogLevel.Info, Context.SessionId, "Run single sequence over.");
            }
        }
        private void FillFinalExceptionReportInfo(Exception ex, out StatusReportType finalReportType,
                                                  out StepResult lastStepResult, out FailedInfo failedInfo)
        {
            if (ex is TaskFailedException)
            {
                TaskFailedException failedException = (TaskFailedException)ex;
                FailedType          failedType      = failedException.FailedType;
                this.State      = ModuleUtils.GetRuntimeState(failedType);
                finalReportType = ModuleUtils.GetReportType(failedType);
                lastStepResult  = ModuleUtils.GetStepResult(failedType);
                failedInfo      = new FailedInfo(ex, failedType);
                _context.LogSession.Print(LogLevel.Info, Index, "Step force failed.");
            }
            else if (ex is TestflowAssertException)
            {
                this.State      = RuntimeState.Failed;
                finalReportType = StatusReportType.Failed;
                lastStepResult  = StepResult.Failed;
                failedInfo      = new FailedInfo(ex, FailedType.AssertionFailed);
                _context.LogSession.Print(LogLevel.Error, Index, "Assert exception catched.");
            }
            else if (ex is ThreadAbortException)
            {
                this.State      = RuntimeState.Abort;
                finalReportType = StatusReportType.Error;
                lastStepResult  = StepResult.Abort;
                failedInfo      = new FailedInfo(ex, FailedType.Abort);
                _context.LogSession.Print(LogLevel.Warn, Index, $"Sequence {Index} execution aborted");
            }
            else if (ex is TestflowException)
            {
                this.State      = RuntimeState.Error;
                finalReportType = StatusReportType.Error;
                lastStepResult  = StepResult.Error;
                failedInfo      = new FailedInfo(ex, FailedType.RuntimeError);
                _context.LogSession.Print(LogLevel.Error, Index, ex, "Inner exception catched.");
            }
            else
            {
                this.State      = RuntimeState.Error;
                finalReportType = StatusReportType.Error;
                lastStepResult  = StepResult.Error;
                failedInfo      = new FailedInfo(ex, FailedType.RuntimeError);
                _context.LogSession.Print(LogLevel.Error, Index, ex, "Runtime exception catched.");
            }
//            else if (ex is TargetInvocationException)
//            {
//                this.State = RuntimeState.Failed;
//                finalReportType = StatusReportType.Failed;
//                lastStepResult = StepResult.Failed;
//                failedInfo = new FailedInfo(ex.InnerException, FailedType.TargetError);
//                _context.LogSession.Print(LogLevel.Error, Index, ex, "Invocation exception catched.");
//            }
        }
Exemple #5
0
        public IEnumerable <ICommand> Compile(IEnumerable <Type> typesEnumerable)
        {
            var modules   = typesEnumerable as Type[] ?? typesEnumerable.ToArray();
            var stopwatch = Stopwatch.StartNew();
            var commands  = modules
                            .SelectMany(t => ModuleUtils.GetMethods(t).Select(m => new ReflectionCommand(m.id, m.aliases, t, m.method, _valueProviders)))
                            .ToArray();

            _logger.LogTrace("Compiled {CommandCount} commands from {ModuleCount} modules in {Duration:0.00} ms.", commands.Length, modules.Length, stopwatch.Elapsed.TotalMilliseconds);

            return(commands);
        }
Exemple #6
0
        private string GetSequenceGroupSignature()
        {
            const string  datetimeFormat = "yyyy-mm-dd-hh-MM-ss-fff";
            const string  delim          = "_";
            string        hostInfo       = ModuleUtils.GetHostInfo();
            StringBuilder featureInfo    = new StringBuilder(4000);

            featureInfo.Append(Name).Append(delim).Append(Info.CreationTime.ToString("datetimeFormat")).Append(delim).
            Append(Info.ModifiedTime.ToString(datetimeFormat)).Append(delim).Append(hostInfo).Append(delim)
            .Append(GetSequenceGroupFlowInfo());
            return(ModuleUtils.GetHashValue(featureInfo.ToString(), Encoding.UTF8));
        }
Exemple #7
0
        public RuntimeContainer Generate(ISequenceGroup sequenceGroup, RuntimePlatform platform, params object[] param)
        {
            // 如果是SequenceGroup并且还有入参,则必须和包含上级TestProject一起运行
            if (null != sequenceGroup && null == sequenceGroup.Parent && 0 != sequenceGroup.Arguments.Count)
            {
                ModuleUtils.LogAndRaiseDataException(LogLevel.Error, "SequenceGroup with input arguments cannot run with out test project.", ModuleErrorCode.SequenceDataError, null, "UnexistArgumentSource");
            }
            RuntimeContainer runtimeContainer = RuntimeContainer.CreateContainer(0, platform, _globalInfo, param);

            _runtimeContainers.Add(runtimeContainer.Session, runtimeContainer);
            return(runtimeContainer);
        }
        protected override void Stop()
        {
            _cancellation.Cancel();
            ModuleUtils.StopThreadWork(_receiveThread);
            //如果两个队列在被锁的状态则释放锁
            _engineMessageQueue.FreeLock();
            _statusMessageQueue.FreeLock();

            ModuleUtils.StopThreadWork(_engineMessageListener);
            ModuleUtils.StopThreadWork(_statusMessageListener);
            ZombieCleaner.Stop();
        }
Exemple #9
0
        private void application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context           = ((HttpApplication)sender).Context;
            HttpRequest request           = context.Request;
            string      filePath          = request.FilePath;
            string      executionFilePath = request.AppRelativeCurrentExecutionFilePath;

            GlobalCulture.SetContextCulture();
            LogicContext current = LogicContext.Current;

            current.SetDatabase(AppConfig.DefaultDbId);
            current.Source = filePath;
            HttpCookie cookie = request.Cookies[CookieMemory.FormsCookieName];
            bool       flag   = cookie != null;

            if (flag)
            {
                CookieMemory cookie2      = new CookieMemory(cookie);
                LogicSession logicSession = AuthUtils.GetLogicSession(cookie2);
                bool         flag2        = logicSession != null && logicSession.UserId == cookie2.UserId;
                if (!flag2)
                {
                    AppEventLog.Debug("无法恢复");
                    return;
                }
                current.CookieUpdateTime     = cookie2.UpdateTime;
                logicSession.LastRequestTime = AppRuntime.ServerDateTime;
                current.SetLogicSession(logicSession);
                current.UserAuthCookies = cookie;
            }
            bool flag3 = filePath == null;

            if (!flag3)
            {
                string s     = StringHelper.RightSubstring(filePath, 5);
                bool   flag4 = (!StringHelper.EqualsIgnoreCase(s, ".aspx") && !StringHelper.EqualsIgnoreCase(s, ".asmx") && !StringHelper.EqualsIgnoreCase(s, ".ashx")) || context.Request.Url.ToString().IndexOf("ActiveModule.aspx") < 0;
                if (!flag4)
                {
                    string routeUrl = ModuleUtils.GetRouteUrl(request.QueryString["AMID"].ToString().Trim().ToInt());
                    current.AmId = request.QueryString["AMID"].ToString().Trim().ToInt();
                    bool flag5 = routeUrl.IndexOf("?") < 0;
                    if (flag5)
                    {
                        context.Response.Redirect(routeUrl + "?" + context.Request.QueryString, false);
                    }
                    else
                    {
                        context.Response.Redirect(routeUrl + "&" + context.Request.QueryString, false);
                    }
                }
            }
        }
Exemple #10
0
        private ScriptAssembly[] GetAllScriptAssemblies(BuildFlags buildFlags, EditorScriptCompilationOptions options, PrecompiledAssembly[] unityAssembliesArg, PrecompiledAssembly[] precompiledAssembliesArg)
        {
            EditorBuildRules.CompilationAssemblies assemblies = new EditorBuildRules.CompilationAssemblies
            {
                UnityAssemblies          = unityAssembliesArg,
                PrecompiledAssemblies    = precompiledAssembliesArg,
                CustomTargetAssemblies   = this.customTargetAssemblies,
                EditorAssemblyReferences = ModuleUtils.GetAdditionalReferencesForUserScripts()
            };
            ScriptAssemblySettings settings = this.CreateEditorScriptAssemblySettings(options);

            return(EditorBuildRules.GetAllScriptAssemblies(this.allScripts, this.projectDirectory, buildFlags, settings, assemblies));
        }
        public void Stop()
        {
            if (_stopFlag == 1)
            {
                return;
            }
            _globalInfo.TestGenBlocker.Set();
            _cancellation.Cancel();
            _globalInfo.EventQueue.FreeBlocks();
//            Thread.Sleep(_globalInfo.ConfigData.GetProperty<int>("StopTimeout"));
            ModuleUtils.StopThreadWork(_internalMessageThd);
            Thread.VolatileWrite(ref _stopFlag, 1);
        }
    private static MonoIsland CreateMonoIsland(SupportedLanguage language)
    {
        const string kInputFilePath     = "Packages/com.unity.inputsystem/InputSystem";
        var          outputAssemblyPath = Path.GetTempFileName();

        var options          = EditorScriptCompilationOptions.BuildingForEditor;
        var buildTarget      = UnityEditor.EditorUserBuildSettings.activeBuildTarget;
        var buildTargetGroup = UnityEditor.EditorUserBuildSettings.activeBuildTargetGroup;
        var defines          = ieu.GetCompilationDefines(options, buildTargetGroup, buildTarget);

        var references = new List <string>();

        references.Add(ieu.GetEngineAssemblyPath());
        references.Add(ieu.GetEngineCoreModuleAssemblyPath());
        references.Add(ieu.GetEditorAssemblyPath());
        references.AddRange(ModuleUtils.GetAdditionalReferencesForUserScripts());
#if UNITY_EDITOR_OSX
        references.Add(Path.Combine(EditorApplication.applicationContentsPath, "UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll"));
#elif UNITY_EDITOR_WIN
        references.Add(Path.Combine(Path.GetDirectoryName(EditorApplication.applicationPath), "Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll"));
#endif
        var unityAssemblies = InternalEditorUtility.GetUnityAssemblies(true, buildTargetGroup, buildTarget);
        foreach (var asm in unityAssemblies)
        {
            references.Add(asm.Path);
        }

        var apiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup);

        // Hopefully the churn on these mono library helpers is over, this is going to be a bit a pain to
        // always chase.
#if UNITY_2018_3_OR_NEWER && !(UNITY_2019_1_OR_NEWER)
        var scriptAssembly = new ScriptAssembly
        {
            Filename = AssetPath.GetFileName(outputAssemblyPath),
            Flags    = AssemblyFlags.None
        };
        references.AddRange(MonoLibraryHelpers.GetSystemLibraryReferences(apiCompatibilityLevel, buildTarget, language, true, scriptAssembly));
#elif UNITY_2019_1_OR_NEWER
        references.AddRange(MonoLibraryHelpers.GetSystemLibraryReferences(apiCompatibilityLevel, buildTarget, language));
#endif

        var sources = new List <string>();
        sources.AddRange(Directory.GetFiles(kInputFilePath, "*.cs", SearchOption.AllDirectories));

        var island = new MonoIsland(buildTarget, apiCompatibilityLevel, true, sources.ToArray(),
                                    references.ToArray(), defines, outputAssemblyPath);

        return(island);
    }
Exemple #13
0
        public static void LoadParameter(SequenceGroup sequenceGroup, string filePath, bool forceLoad)
        {
            filePath = ModuleUtils.GetAbsolutePath(filePath, Directory.GetCurrentDirectory());
            SequenceGroupParameter parameter = XmlReaderHelper.ReadSequenceGroupParameter(filePath);

            if (!forceLoad && !sequenceGroup.Info.Hash.Equals(parameter.Info.Hash))
            {
                I18N i18N = I18N.GetInstance(Constants.I18nName);
                throw new TestflowDataException(ModuleErrorCode.UnmatchedFileHash, i18N.GetStr("UnmatchedHash"));
            }
            sequenceGroup.Parameters = parameter;
            SetParameterToSequenceData(sequenceGroup, parameter);
            ValidateTypeDatas(sequenceGroup);
        }
        protected void SendStartMessage()
        {
            StatusMessage statusMessage = new StatusMessage(MessageNames.StartStatusName, RuntimeState.Running,
                                                            Context.SessionId)
            {
                Index = Context.MsgIndex
            };

            if (Context.GetProperty <bool>("EnablePerformanceMonitor"))
            {
                ModuleUtils.FillPerformance(statusMessage);
            }
            Context.UplinkMsgProcessor.SendMessage(statusMessage, false);
        }
Exemple #15
0
 // 使能retry调用step,且失败后强制继续执行
 private void InvokeStepWithRetryAndForceContinue(bool forceInvoke)
 {
     try
     {
         InvokeStepWithRetry(forceInvoke);
     }
     catch (TaskFailedException ex)
     {
         // 如果该失败类型不能被处理,则直接抛出
         if (!ModuleUtils.IsErrorCanBeHandled(ex.FailedType))
         {
             throw;
         }
         // 停止计时
         Actuator.EndTiming();
         this.Result = ModuleUtils.GetStepResult(ex.FailedType);
         // 如果InvokeErrorAction不是Continue,则抛出异常
         RecordInvocationError(ex, ex.FailedType);
         HandleException(StepData.InvokeErrorAction, ex);
     }
     catch (TestflowAssertException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Failed;
         RecordInvocationError(ex, FailedType.AssertionFailed);
         HandleException(StepData.AssertFailedAction, ex);
     }
     catch (TargetInvocationException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Error;
         RecordTargetInvocationError(ex);
         // 如果失败行为是终止,则抛出异常
         FailedAction failedAction = ex.InnerException is TestflowAssertException
             ? StepData.AssertFailedAction
             : StepData.InvokeErrorAction;
         HandleException(failedAction, ex.InnerException);
     }
     catch (TargetException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Error;
         RecordInvocationError(ex, FailedType.TargetError);
         HandleException(StepData.InvokeErrorAction, ex);
     }
 }
Exemple #16
0
        public IExpressionData Clone()
        {
            List <IExpressionElement> copyedArguments = new List <IExpressionElement>(this.Arguments.Count);

            ModuleUtils.CloneDataCollection(this.Arguments, copyedArguments);
            ExpressionData data = new ExpressionData(this.Arguments.Count)
            {
                Name      = string.Empty,
                Operation = this.Operation,
                Source    = (IExpressionElement)Source.Clone(),
                Arguments = copyedArguments
            };

            return(data);
        }
 public static bool IsInternalAssembly(string file)
 {
     // ISSUE: object of a compiler-generated type is created
     // ISSUE: variable of a compiler-generated type
     AssemblyHelper.\u003CIsInternalAssembly\u003Ec__AnonStorey30 assemblyCAnonStorey30 = new AssemblyHelper.\u003CIsInternalAssembly\u003Ec__AnonStorey30();
     // ISSUE: reference to a compiler-generated field
     assemblyCAnonStorey30.file = file;
     // ISSUE: reference to a compiler-generated field
     if (!ModuleManager.IsRegisteredModule(assemblyCAnonStorey30.file))
     {
         // ISSUE: reference to a compiler-generated method
         return(((IEnumerable <string>)ModuleUtils.GetAdditionalReferencesForUserScripts()).Any <string>(new Func <string, bool>(assemblyCAnonStorey30.\u003C\u003Em__43)));
     }
     return(true);
 }
Exemple #18
0
        public override MessageBase GetHeartBeatMessage()
        {
            StatusMessage statusMessage = new StatusMessage(MessageNames.HeartBeatStatusName, Context.State, Context.SessionId)
            {
                Index = Context.MsgIndex
            };
            SessionTaskEntity sessionTaskEntity = Context.SessionTaskEntity;

            sessionTaskEntity.FillSequenceInfo(statusMessage);
            if (Context.GetProperty <bool>("EnablePerformanceMonitor"))
            {
                ModuleUtils.FillPerformance(statusMessage);
            }
            return(statusMessage);
        }
        protected void SendOverMessage()
        {
            StatusMessage statusMessage = new StatusMessage(MessageNames.ResultStatusName, RuntimeState.Over,
                                                            Context.SessionId)
            {
                Index = Context.MsgIndex
            };

            if (Context.GetProperty <bool>("EnablePerformanceMonitor"))
            {
                ModuleUtils.FillPerformance(statusMessage);
            }
            statusMessage.WatchData = Context.VariableMapper.GetReturnDataValues(Context.Sequence);
            Context.UplinkMsgProcessor.SendMessage(statusMessage, true);
        }
Exemple #20
0
        public static void Serialize(string seqFilePath, SequenceGroup sequenceGroup)
        {
            VerifySequenceData(sequenceGroup);

            string paramFilePath = ModuleUtils.GetParameterFilePath(seqFilePath);

            SequenceGroupParameter parameter = new SequenceGroupParameter();

            parameter.Initialize(sequenceGroup);
            // 将SequeneGroup配置的参数写入ParameterData中,用以序列化
            FillParameterDataToSequenceData(sequenceGroup, parameter);
            sequenceGroup.RefreshSignature();
            parameter.RefreshSignature(sequenceGroup);
            List <string> serializedFileList = new List <string>(20);

            try
            {
                // 暂时修改序列组文件路径为相对路径
                sequenceGroup.Info.SequenceGroupFile = ModuleUtils.GetFileName(seqFilePath);
                sequenceGroup.Info.SequenceParamFile = ModuleUtils.GetRelativePath(paramFilePath, seqFilePath);

                BackupExistFile(seqFilePath, paramFilePath);

                serializedFileList.Add(seqFilePath);
                XmlWriterHelper.Write(sequenceGroup, seqFilePath);

                serializedFileList.Add(paramFilePath);
                XmlWriterHelper.Write(parameter, paramFilePath);

                DeleteBackupFile(seqFilePath, paramFilePath);
            }
            catch (IOException ex)
            {
                RollBackFilesIfFailed(serializedFileList);
                throw new TestflowRuntimeException(ModuleErrorCode.SerializeFailed, ex.Message, ex);
            }
            catch (ApplicationException)
            {
                RollBackFilesIfFailed(serializedFileList);
                throw;
            }
            finally
            {
                // 恢复序列文件的绝对路径
                sequenceGroup.Info.SequenceGroupFile = seqFilePath;
                sequenceGroup.Info.SequenceParamFile = paramFilePath;
            }
        }
Exemple #21
0
        protected override void TaskErrorAction(Exception ex)
        {
            StatusMessage errorMessage = new StatusMessage(MessageNames.ErrorStatusName, Context.State, Context.SessionId)
            {
                ExceptionInfo = new FailedInfo(ex, FailedType.RuntimeError),
                Index         = Context.MsgIndex
            };

            Context.SessionTaskEntity.FillSequenceInfo(errorMessage, Context.I18N.GetStr("RuntimeError"));
            if (Context.GetProperty <bool>("EnablePerformanceMonitor"))
            {
                ModuleUtils.FillPerformance(errorMessage);
            }
            errorMessage.WatchData = Context.VariableMapper.GetReturnDataValues();
            Context.UplinkMsgProcessor.SendMessage(errorMessage, true);
        }
Exemple #22
0
        public static ucModule CreateModuleInstance(string moduleID)
        {
            ModuleInfo moduleInfo;

            if (moduleID.Contains("."))
            {
                var strs = moduleID.Split(new[] { "." }, StringSplitOptions.None);
                moduleInfo = ModuleUtils.GetModuleInfo(strs[0], strs[1]);
            }
            else
            {
                moduleInfo = ModuleUtils.GetModuleInfo(moduleID);
            }

            return(CreateModuleInstance(moduleInfo));
        }
 private void btnMail_Click(object sender, EventArgs e)
 {
     try
     {
         var sendMailInfo = ModuleUtils.GetModuleInfo(ModuleInfo.ModuleID, CODES.DEFMOD.SUBMOD.SEND_MAIL);
         var ucSendMail   = (ucSendMail)MainProcess.CreateModuleInstance(sendMailInfo.ModuleID, sendMailInfo.SubModule);
         //ucExport.LastSearchResultKey = BufferResult.LastSearchResultKey;
         //ucExport.LastSearchTime = BufferResult.LastSearchTime;
         //ucExport.PrintGrid = gcMain;
         ucSendMail.ShowDialogModule(this);
     }
     catch (Exception ex)
     {
         ShowError(ex);
     }
 }
Exemple #24
0
 protected StepTaskEntityBase(ISequenceStep step, SlaveContext context, int sequenceIndex)
 {
     this.Context       = context;
     this.StepData      = step;
     this.Result        = StepResult.NotAvailable;
     this.SequenceIndex = sequenceIndex;
     this.Actuator      = ActuatorBase.GetActuator(step, context, sequenceIndex);
     this.Coroutine     = null;
     // 只有在断言失败和调用异常都配置为终止执行时,该步骤才会被判断为失败后终止
     if (null != StepData && StepData.HasSubSteps)
     {
         this.SubStepRoot = ModuleUtils.CreateSubStepModelChain(StepData.SubSteps, Context, sequenceIndex);
     }
     BreakIfFailed = (null == StepData) || (StepData.AssertFailedAction == FailedAction.Terminate &&
                                            StepData.InvokeErrorAction == FailedAction.Terminate);
 }
Exemple #25
0
        public static TestProject LoadTestProject(string filePath, bool forceLoad, IModuleConfigData envInfo)
        {
            filePath = ModuleUtils.GetAbsolutePath(filePath, Directory.GetCurrentDirectory());

            if (!filePath.EndsWith($".{CommonConst.TestGroupFileExtension}"))
            {
                I18N i18N = I18N.GetInstance(Constants.I18nName);
                throw new TestflowRuntimeException(ModuleErrorCode.InvalidFileType, i18N.GetStr("InvalidFileType"));
            }
            TestProject testProject = null;

            testProject = XmlReaderHelper.ReadTestProject(filePath);

            // 需要单独配置Setup和TearDown的索引号
            testProject.SetUp.Index    = CommonConst.SetupIndex;
            testProject.TearDown.Index = CommonConst.TeardownIndex;

            CheckModelVersion(testProject.ModelVersion, envInfo);
            foreach (ISequenceGroup sequenceGroup in testProject.SequenceGroups)
            {
                CheckModelVersion(sequenceGroup.Info.Version, envInfo);
            }
            foreach (SequenceGroupLocationInfo sequenceGroupLocation in testProject.SequenceGroupLocations)
            {
                SequenceGroup sequenceGroup = null;

                string sequenceGroupFile = ModuleUtils.GetAbsolutePath(sequenceGroupLocation.SequenceFilePath, filePath);
                if (File.Exists(sequenceGroupFile))
                {
                    sequenceGroup        = LoadSequenceGroup(sequenceGroupFile, forceLoad, envInfo);
                    sequenceGroup.Parent = testProject;
                }
                else
                {
                    ILogService logService = TestflowRunner.GetInstance().LogService;
                    logService.Print(LogLevel.Warn, CommonConst.PlatformLogSession, 0, "Sequence group file not exist.");
                    sequenceGroup = new SequenceGroup();
                    sequenceGroup.Initialize(testProject);
                    sequenceGroup.Info.SequenceGroupFile = sequenceGroupFile;
                    sequenceGroup.Available = false;
                }
                testProject.SequenceGroups.Add(sequenceGroup);
            }
            ValidateTypeDatas(testProject);

            return(testProject);
        }
Exemple #26
0
        private bool FindTypeByModulePath(WildcardPattern classNameMatcher)
        {
            bool matchFound = false;

            var moduleList = ModuleUtils.GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, _context);

            foreach (var modulePath in moduleList)
            {
                string expandedModulePath = IO.Path.GetFullPath(modulePath);
                var    cachedClasses      = AnalysisCache.GetExportedClasses(expandedModulePath, _context);

                if (cachedClasses != null)
                {
                    //Exact match
                    if (!_useWildCards)
                    {
                        if (cachedClasses.ContainsKey(_className))
                        {
                            var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath);
                            if (classInfo != null)
                            {
                                _matchingClassList.Add(classInfo);
                                matchFound = true;
                            }
                        }
                    }
                    else
                    {
                        foreach (var className in cachedClasses.Keys)
                        {
                            if (classNameMatcher.IsMatch(className))
                            {
                                var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath);
                                if (classInfo != null)
                                {
                                    _matchingClassList.Add(classInfo);
                                    matchFound = true;
                                }
                            }
                        }
                    }
                }
            }

            return(matchFound);
        }
Exemple #27
0
        protected override void InitializeParamsValues()
        {
            string instanceVarName = null;

            if (!string.IsNullOrWhiteSpace(Function.Instance))
            {
                instanceVarName = ModuleUtils.GetVariableNameFromParamValue(Function.Instance);
                _instanceVar    = ModuleUtils.GetVariableFullName(instanceVarName, StepData, Context.SessionId);
            }
            IParameterDataCollection parameters = Function.Parameters;

            for (int i = 0; i < _properties.Count; i++)
            {
                string    paramValue = parameters[i].Value;
                IArgument argument   = Function.ParameterType[i];
                if (null == _properties[i] || string.IsNullOrEmpty(paramValue))
                {
                    _params.Add(null);
                    continue;
                }
                switch (parameters[i].ParameterType)
                {
                case ParameterType.NotAvailable:
                    _params.Add(null);
                    break;

                case ParameterType.Value:
                    _params.Add(Context.TypeInvoker.CastConstantValue(argument.Type,
                                                                      paramValue));
                    break;

                case ParameterType.Variable:
                    string variableRawName = ModuleUtils.GetVariableNameFromParamValue(paramValue);
                    string varFullName     = ModuleUtils.GetVariableFullName(variableRawName, StepData,
                                                                             Context.SessionId);
                    // 将parameter的Value中,变量名称替换为运行时变量名
                    parameters[i].Value = ModuleUtils.GetFullParameterVariableName(varFullName, paramValue);
                    _params.Add(null);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            CommonStepDataCheck(instanceVarName);
        }
Exemple #28
0
 public virtual void Start()
 {
     if (Lib.IsFlight() || Lib.IsEditor())
     {
         if (engineModule == null)
         {
             engineModule = FindEngineModule(part, engineModuleID);
         }
         if (Features.Radiation && emitter == null)
         {
             emitter = FindEmitterModule(part);
         }
         if (FirstLoad)
         {
             if (emitter != null)
             {
                 EmitterMaxRadiation = emitter.radiation;
                 if (EmitterMaxRadiation < 0)
                 {
                     EmitterMaxRadiation = 0d;
                 }
             }
             if (engineModule != null)
             {
                 MaxECGeneration      = engineModule.ElectricalGeneration.Evaluate(100f);
                 MinThrottle          = engineModule.MinimumThrottle / 100f;
                 GeneratesElectricity = engineModule.GeneratesElectricity;
                 LastReactorState     = engineModule.Enabled;
             }
             if (inputs == null || inputs.Count == 0)
             {
                 ConfigNode node = ModuleUtils.GetModuleConfigNode(part, moduleName);
                 if (node != null)
                 {
                     OnLoad(node);
                 }
             }
             FirstLoad = false;
         }
         else
         {
             EmitterRunning = true;
         }
     }
 }
Exemple #29
0
 // 执行step,即使失败也继续执行。如果失败写入RuntimeStatus
 private void InvokeStepAndForcePass(bool forceInvoke)
 {
     try
     {
         InvokeStepSingleTime(forceInvoke);
     }
     catch (TaskFailedException ex)
     {
         // 如果该失败类型不能被处理,则直接抛出
         if (!ModuleUtils.IsErrorCanBeHandled(ex.FailedType))
         {
             throw;
         }
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Pass;
         Context.LogSession.Print(LogLevel.Warn, Context.SessionId, $"Sequence step <{this.GetStack()}> failed but force pass.");
         RecordInvocationError(ex, ex.FailedType);
     }
     catch (TestflowAssertException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Pass;
         Context.LogSession.Print(LogLevel.Warn, Context.SessionId, $"Sequence step <{this.GetStack()}> failed but force pass.");
         RecordInvocationError(ex, FailedType.AssertionFailed);
     }
     catch (TargetInvocationException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Pass;
         Context.LogSession.Print(LogLevel.Warn, Context.SessionId, $"Sequence step <{this.GetStack()}> failed but force pass.");
         RecordInvocationError(ex.InnerException, FailedType.TargetError);
     }
     catch (TargetException ex)
     {
         // 停止计时
         Actuator.EndTiming();
         this.Result = StepResult.Error;
         Context.LogSession.Print(LogLevel.Error, Context.SessionId, $"Sequence step <{this.GetStack()}> failed but force pass.");
         RecordInvocationError(ex, FailedType.TargetError);
         HandleException(StepData.InvokeErrorAction, ex);
     }
 }
Exemple #30
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var exportInfo = ModuleUtils.GetModuleInfo(MID, CODES.DEFMOD.SUBMOD.SEARCH_EXPORT);
                var ucExport   = (ucSearchExport)FIS.AppClient.Utils.MainProcess.CreateModuleInstance(exportInfo.ModuleID, exportInfo.SubModule);
                ucExport.LastSearchResultKey = LastSearchResultKey;
                ucExport.LastSearchTime      = LastSearchTime;
                ucExport.PrintGrid           = gcMain;
                ucExport.listLayout          = listLayout;
                ucExport.Bands = Bands;

                if (rdgExportColumn.Checked)
                {
                    var       gridView     = gcMain.DefaultView as GridView;
                    DataTable columnRemove = new DataTable();
                    columnRemove.Columns.Add("Value", typeof(string));
                    for (var i = 0; i < chkLstColumnExport.Items.Count; i++)
                    {
                        CheckState chkSate;
                        chkSate = chkLstColumnExport.GetItemCheckState(i);
                        if (chkSate == CheckState.Unchecked)
                        {
                            var columnValue = chkLstColumnExport.GetItemValue(i).ToString();
                            foreach (GridColumn column in gridView.Columns)
                            {
                                if (column.FieldName == columnValue)
                                {
                                    columnRemove.Rows.Add(columnValue);
                                    break;
                                }
                            }
                        }
                    }
                    ucExport.columnRemove = columnRemove;
                    ucExport.modExport    = 1;
                }
                this.CloseModule();
                ucExport.ShowDialogModule(this.Parent);
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }