private void DoExpand(SpecScreen screen, string pathToApp, MyLog myLog, List <ClassExpression> allClassesExp)
 {
     for (int fi = 0; fi < screen.Scenarios.Count; fi++)
     {
         IScenario tempScenario = screen.Scenarios[fi];
         if (tempScenario is SpecScenario)
         {
             SpecScenario  scenario      = tempScenario as SpecScenario;
             List <string> listActionExp = scenario.UserActionsInString;
             List <Color>  colors        = scenario.Colors;
             for (int se = 0; se < listActionExp.Count; se++)
             {
                 string actionExp = listActionExp[se];
                 if (actionExp == null)
                 {
                     myLog.Error("NULL at (" + (fi + 1) + "," + (se + 2) + ")");
                     continue;
                 }
                 SpecNode specNode = screen.ListSpecNodes[se];
                 ScriptGenerationParams _params        = null;
                 AbstractSpecUserAction specUserAction = null;
                 int lastInd = IsValidationUserCode(se, screen.ListValidationUserCode);
                 if (lastInd > se)
                 {
                     specUserAction = new ValidationUserCodeSpecUserAction();
                     _params        = new ValidationUCScriptGenerationParams();
                     List <string> listExp = new List <string>();
                     for (int th = se; th <= lastInd; th++)
                     {
                         String tempActionExp        = listActionExp[th];
                         AbstractSpecUserAction temp = handleUserActionExpression(
                             tempActionExp.Trim(), specNode, colors[th], myLog);
                         if (!(temp is ValidationSpecUserAction))
                         {
                             myLog.Warn("Expression: " + tempActionExp + " must be validation", logger);
                             screen = null;
                             return;
                         }
                         else
                         {
                             if (tempActionExp != null && !tempActionExp.Trim().Equals(""))
                             {
                                 listExp.Add(tempActionExp.Trim());
                             }
                         }
                     }
                     (specUserAction as ValidationUserCodeSpecUserAction).ListExps = listExp;
                     ((ValidationUCScriptGenerationParams)_params).ListExps        = listExp;
                     if (screen is TestSpecificationScreen)
                     {
                         ((ValidationUCScriptGenerationParams)_params).ClassExpressions = allClassesExp;
                     }
                     ((ValidationUCScriptGenerationParams)_params).ClassName =
                         AbstractSpecUserAction.GetFolderNameFromScreen(screen) + "_Validation";
                     ((ValidationUCScriptGenerationParams)_params).FunctionName = "Validate_" +
                                                                                  Regex.Replace(specNode.Expression, "[^A-Za-z0-9]", "_");
                     SetAttributes(scenario, specUserAction, specNode,
                                   screen, pathToApp, colors, _params, se, myLog);
                     se = lastInd;
                 }
                 else
                 {
                     string[] listActionsEpx = splitAction(actionExp, AbstractSpecUserAction.AND);
                     foreach (string action in listActionsEpx)
                     {
                         specUserAction = handleUserActionExpression(action.Trim(), specNode, colors[se], myLog);
                         if (specUserAction != null)
                         {
                             if (specUserAction is UserCodeSpecUserAction userCodeExpression)
                             {
                                 _params = new UserCodeScriptGenerationParams();
                                 ((UserCodeScriptGenerationParams)_params).MapAliasWithNode = screen.MappingAliasWithNode;
                                 if (screen is TestSpecificationScreen testSpecScreen)
                                 {
                                     ((UserCodeScriptGenerationParams)_params).ClassExpressions = allClassesExp;
                                 }
                             }
                             else if (specUserAction is WaitValidateSpecUserAction waitUserAction)
                             {
                                 _params = new WaitValidateScriptGenerationParams();
                             }
                             else
                             {
                                 _params = new ScriptGenerationParams();
                             }
                             SetAttributes(scenario, specUserAction, specNode,
                                           screen, pathToApp, colors, _params, se, myLog);
                         }
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// return {function content, List[UserCodeScriptsExpression]}
        /// </summary>
        /// <param name="specScenario"></param>
        /// <param name="instanceName"></param>
        /// <param name="countLineBreak">determine new_line with blank line or only break new line</param>
        /// <param name="ignoreScenarioIfError">indicate whether ignore current scenario if an error occur</param>
        /// <returns></returns>
        protected Tuple <string, List <UserCodeScriptsExpression> > GenerateAScenario(SpecScenario specScenario,
                                                                                      MyLog myLog,
                                                                                      string instanceName        = INSTANCE_NAME,
                                                                                      int countLineBreak         = 1,
                                                                                      bool ignoreScenarioIfError = true)
        {
            string newLine     = string.Concat(Enumerable.Repeat(NEW_LINE, countLineBreak + 1));
            string funcContent = "";
            List <UserCodeScriptsExpression> listUcScriptExp = new List <UserCodeScriptsExpression>();
            List <IScenario> preConditions = specScenario.PreConditions;

            if (preConditions != null)
            {
                foreach (IScenario preCondition in preConditions)
                {
                    if (preCondition is SpecScenario preConditionSpec)
                    {
                        if (!funcContent.Equals(""))
                        {
                            funcContent += newLine;
                        }
                        Tuple <string, List <UserCodeScriptsExpression> > pair = GenerateAScenario(
                            preConditionSpec, myLog, instanceName, countLineBreak, ignoreScenarioIfError);
                        funcContent += pair.Item1;
                        var temp = pair.Item2;
                        if (temp != null && temp.Count > 0)
                        {
                            Utils.MergeUcScriptsEpx(listUcScriptExp, temp);
                            listUcScriptExp.AddRange(temp);
                        }
                    }
                    else
                    {
                        logger.Error("Not handled yet!");
                    }
                }
            }
            foreach (IUserAction userAction in specScenario.UserActions)
            {
                if (userAction is AbstractSpecUserAction specUserAction)
                {
                    if (specUserAction.IgnoreGenerateScripts)
                    {
                        continue;
                    }
                    if (!funcContent.Equals(""))
                    {
                        funcContent += newLine;
                    }
                    try
                    {
                        ScriptsExpression scriptsExpression = GenScriptType(specUserAction, instanceName);
                        // if error
                        if (scriptsExpression == null)
                        {
                            LogError(specUserAction.Expression, specUserAction.Params.ScreenName,
                                     specUserAction.Params.Id, myLog, specUserAction.NodeAffect.ToString());
                            if (ignoreScenarioIfError)
                            {
                                return(null); // ignore current scenario, process with the next one
                            }
                            // in contrast, continue with the remains UserAction-s
                            continue;
                        }
                        funcContent += scriptsExpression.Expression;
                        if (scriptsExpression is UserCodeScriptsExpression ucScriptsExp)
                        {
                            // remove duplicate function
                            Utils.MergeUcScriptsEpx(listUcScriptExp, ucScriptsExp);
                            listUcScriptExp.Add(ucScriptsExp);
                        }
                    }
                    catch (NotImplementedException)
                    {
                        logger.Error("Not implement with " + userAction.GetType().Name);
                    }
                }
                else
                {
                    logger.Error("Not handled yet!");
                }
            }
            return(new Tuple <string, List <UserCodeScriptsExpression> >(funcContent, listUcScriptExp));
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="normalSheet"></param>
        /// <param name="elementsAndIndicator">indication to determine root elements or list of all elements</param>
        /// <param name="myLog"></param>
        /// <returns></returns>
        private SpecScreen parseNormalSheet(NormalSheet normalSheet, ListUIElements elementsAndIndicator, MyLog myLog)
        {
            NormalSheetParser normalSheetParser = new NormalSheetParser();

            return(normalSheetParser.Parse(normalSheet, elementsAndIndicator, myLog));
        }
        public bool Expand(List <SpecScreen> listScreens, string pathToApp, MyLog myLog)
        {
            List <IScreen> temp = new List <IScreen>(listScreens);

            return(Expand(temp, pathToApp, myLog));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="classExpression"></param>
        /// <param name="projectPath"></param>
        /// <param name="name_space"></param>
        /// <param name="listUIElements"></param>
        /// <param name="mapAliasWithNode"></param>
        /// <param name="myLog"></param>
        /// <param name="instanceName"></param>
        /// <returns>relative file path</returns>
        private string GenerateClassExpScripts(ClassExpression classExpression, string projectPath, string name_space,
                                               ListUIElements listUIElements, Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            if (classExpression.getName() == null || classExpression.getListFunction() == null ||
                classExpression.getListFunction().Count <= 0)
            {
                return(null);
            }
            string functionsScripts = "";

            foreach (FunctionExpression func in classExpression.getListFunction())
            {
                if (functionsScripts != "")
                {
                    functionsScripts += NEW_LINE;
                }
                functionsScripts += GenerateFunctionExpScripts(func, listUIElements, mapAliasWithNode, myLog, instanceName);
            }
            // create new file
            string classContent = GetTemplateUCClassContent()
                                  //.Replace(GLOBAL_REPLACE, "") disabled by @duongtd 05/29
                                  .Replace(CLASS_REPLACE, classExpression.getName())
                                  .Replace(CONTENT_REPLACE, functionsScripts);
            string filePath            = Path.Combine(classExpression.GetCorrectWorkspace(), classExpression.getName() + ".cs");
            string fileContentTemplate = GetTemplateRunCsFileContent()
                                         .Replace(NAMESPACE_REPLACE, name_space);

            CreateNewFile(fileContentTemplate, classContent, Path.Combine(projectPath, filePath));
            return(filePath);
        }
        /// <summary>
        /// </summary>
        /// <param name="params"></param>
        /// <param name="listUIElements"></param>
        /// <param name="mapAliasWithNode"></param>
        /// <param name="myLog"></param>
        /// <param name="instanceName"></param>
        /// <returns>{params scripts, list of param's name}</returns>
        private Tuple <string, List <string> > GetParamsScripts(List <ParameterExpression> @params, ListUIElements listUIElements,
                                                                Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            if (@params == null || @params.Count == 0)
            {
                return(new Tuple <string, List <string> >("", null));
            }
            string        re         = "";
            List <string> nameParams = new List <string>();

            for (int fi = 1; fi <= @params.Count; fi++)
            {
                ParameterExpression param = @params[fi - 1];
                if (re != "")
                {
                    re += ", ";
                }
                string varName = "param_" + fi;
                nameParams.Add(varName);
                re += "object " + varName;
            }
            return(new Tuple <string, List <string> >(re, nameParams));
        }
        /// <summary>
        /// 'GetAttributeValue<object>("Text")' for Ranorex
        /// </summary>
        /// <param name="nodeExp"></param>
        /// <param name="listUIElements"></param>
        /// <param name="mappingAlias"></param>
        /// <param name="myLog"></param>
        /// <param name="instanceName"></param>
        /// <returns></returns>
        public static string Node2ParamExp(string nodeExp, ListUIElements listUIElements, Dictionary <string, string> mappingAlias, MyLog myLog, string instanceName, ScriptType scriptType)
        {
            Tuple <IElement, string> elementAndAttibute = NormalSheetParser.parseNodeAndAttribute(nodeExp, listUIElements, mappingAlias, myLog);

            if (elementAndAttibute == null || elementAndAttibute.Item1 == null)
            {
                myLog.Warn("cannot find node: " + nodeExp);
                return("null");
            }
            if (scriptType == ScriptType.Normal)
            {
                return(GetScriptAccessElement(elementAndAttibute.Item1, instanceName));
            }
            //Ranorex scripts
            string re = getScriptAccessRanorexElement(
                new SpecNode(elementAndAttibute.Item1, elementAndAttibute.Item2, null), instanceName);

            if (elementAndAttibute.Item2 != null && !elementAndAttibute.Item2.Equals(""))
            {
                re += ".GetAttributeValue<object>(\"" + elementAndAttibute.Item2 + "\")";
            }
            return(re);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="screenList"></param>
        /// <param name="folderPath">="D:\MyTestProject"</param>
        /// <param name="repoFilePath">="D:\ElementsRepo.xml"</param>
        /// <param name="imageCapFilePath">="D:\ImageCapture.xml"</param>
        /// <param name="appFilePath">="D:\app.exe"</param>
        /// <param name="classRepoName">="MyTestProjectDefinition"</param>
        /// <param name="name_space">="MyTestProject"</param>
        /// <param name="mainClassInstance">="Instance"</param>
        /// <param name="myLog"></param>
        /// <returns>map (folder_path, list_files_in_folder)</returns>
        public Tuple <Dictionary <string, string>, List <string> > Generate(List <IScreen> screenList, string folderPath,
                                                                            string repoFilePath, string imageCapFilePath, string appFilePath, string classRepoName,
                                                                            string name_space, string mainClassInstance, MyLog myLog, string instanceName = INSTANCE_NAME)
        {
            //List<string> runningFilePath = new List<string>();
            Dictionary <string, string>      mapFilePathAndId = new Dictionary <string, string>();
            List <UserCodeScriptsExpression> additionScripts  = new List <UserCodeScriptsExpression>();
            List <ClassExpression>           additionClasses  = new List <ClassExpression>();
            SpecScreen aScreen = null;

            foreach (IScreen screen in screenList)
            {
                if (screen is SpecScreen specScreen)
                {
                    if (aScreen == null)
                    {
                        aScreen = specScreen;
                    }
                    ProcessScreen(specScreen, mapFilePathAndId, additionScripts, additionClasses,
                                  folderPath, repoFilePath, imageCapFilePath, appFilePath, classRepoName, name_space,
                                  mainClassInstance, myLog, instanceName);
                }
                else
                {
                    logger.Error("Not handled yet!");
                }
            }
            List <string> otherFilePath = GenerateAdditionClassses(additionScripts, additionClasses, aScreen, myLog, folderPath, repoFilePath,
                                                                   imageCapFilePath, appFilePath, classRepoName, name_space, mainClassInstance, instanceName, mapFilePathAndId);

            return(new Tuple <Dictionary <string, string>, List <string> >(mapFilePathAndId, otherFilePath));
        }
Ejemplo n.º 9
0
        public bool GenerateRanorexProject(List <IElement> listRootElements, List <SpecScreen> screensExpanded,
                                           string repoFilePath, string folderOutPath, string appPath, MyLog myLog)
        {
            string tempFolderPath = Utils.CreateTempFolder(PROJECT_NAME + "_" +
                                                           DateTime.Now.ToString("yyMMdd_HHmmss"));

            ZipFile.ExtractToDirectory(PROJECT_TEMPLATE_PATH, tempFolderPath);

            string projectTempFolder = Path.Combine(tempFolderPath, PROJECT_NAME);

            // generate scripts
            Tuple <Dictionary <string, string>, List <string> > pair = null;

            if (screensExpanded != null && screensExpanded.Count > 0)
            {
                RanorexScriptsGeneration scriptsGeneration = new RanorexScriptsGeneration();
                pair = scriptsGeneration.Generate(
                    screensExpanded,
                    projectTempFolder,
                    null,
                    null,
                    appPath,
                    PROJECT_NAME + REPOSITORY,
                    PROJECT_NAME,
                    INSTANCE,
                    myLog,
                    "repo");
                if (pair == null)
                {
                    myLog.Error("An error occured when generating C# scripts");
                    return(false);
                }
            }

            RanorexSolutionGeneration gen = new RanorexSolutionGeneration();
            bool rGenCheck = gen.Generate(repoFilePath, folderOutPath, tempFolderPath, projectTempFolder,
                                          pair?.Item1,
                                          pair?.Item2,
                                          appPath,
                                          myLog);

            if (!rGenCheck)
            {
                myLog.Error("An error occured when generating Ranorex project");
                return(false);
            }
            return(true);
        }
Ejemplo n.º 10
0
        public bool Generate(List <IElement> listRootElements, List <SpecScreen> screensExpanded,
                             string folderOutPath, string projectName, string appPath, MyLog myLog)
        {
            string tempFolderPath = Utils.CreateTempFolder(projectName + "_" +
                                                           DateTime.Now.ToString("yyMMdd_HHmmss"));
            // generate CSharp code
            ElementCSharpCodeGeneration elementCSharpCodeGeneration = new ElementCSharpCodeGeneration();
            string   repoClassName = projectName + DEFINITION;
            FileInfo csFile        = elementCSharpCodeGeneration.Generate(
                listRootElements, tempFolderPath, repoClassName, projectName);

            if (csFile == null)
            {
                myLog.Error("An error occured when generating C# codes");
                return(false);
            }
            // generate .xml file(s)
            ElementXmlGeneration elementXmlGeneration = new ElementXmlGeneration();
            string          repoFileName   = projectName + REPO;
            string          imgCapFileName = projectName + IMAGE_CAPTURE;
            List <FileInfo> listXmlFile    = elementXmlGeneration.Store(listRootElements,
                                                                        Path.Combine(tempFolderPath, repoFileName),
                                                                        Path.Combine(tempFolderPath, imgCapFileName));

            if (listXmlFile == null)
            {
                myLog.Error("An error occured when generating .xml files");
                return(false);
            }

            // generate scripts
            Tuple <Dictionary <string, string>, List <string> > pair = null;

            if (screensExpanded != null && screensExpanded.Count > 0)
            {
                CSharpScriptsGeneration scriptsGeneration = new CSharpScriptsGeneration();
                pair = scriptsGeneration.Generate(
                    screensExpanded,
                    tempFolderPath,
                    repoFileName,
                    imgCapFileName,
                    appPath,
                    repoClassName,
                    projectName,
                    INSTANCE,
                    myLog);
                if (pair == null)
                {
                    myLog.Error("An error occured when generating C# scripts");
                    return(false);
                }
            }

            // generate visual studio solution
            List <FileInfo> listFiles = new List <FileInfo>();

            listFiles.Add(csFile);
            listFiles.AddRange(listXmlFile);

            //generate text file contain all running class
            if (pair != null)
            {
                File.WriteAllText(Path.Combine(tempFolderPath, RUNNING_TEST_FILE_NAME),
                                  string.Join(CSharpScriptsGeneration.NEW_LINE, pair.Item1));
                pair.Item2.Add(RUNNING_TEST_FILE_NAME);
            }

            VsSolutionGeneration gen = new VsSolutionGeneration();
            bool vsGenCheck          = gen.Generate(listFiles, projectName, folderOutPath,
                                                    // read from user's settings
                                                    Properties.Settings.Default.path_GUI_Testing_Automation_ref,
                                                    Properties.Settings.Default.path_to_vstemplate_output_proj,
                                                    tempFolderPath,
                                                    pair?.Item1,
                                                    pair?.Item2,
                                                    appPath);

            if (!vsGenCheck)
            {
                myLog.Error("An error occured when generating Visual Studio project");
                return(false);
            }
            return(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="elementsAndIndicator">indication to determine root elements or list of all elements</param>
        /// <param name="myLog"></param>
        /// <returns></returns>
        private List <SpecScreen> DoParse(string filePath, ListUIElements elementsAndIndicator, MyLog myLog)
        {
            string newFilePath = Utils.CreateTempFile(filePath);

            //Create COM Objects. Create a COM object for everything that is referenced
            Excel.Application xlApp      = new Excel.Application();
            Excel.Workbook    xlWorkbook = xlApp.Workbooks.Open(newFilePath);
            //Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

            List <AbstractSheet> listAbstractSheets = new List <AbstractSheet>();

            for (int fi = 1; fi <= xlWorkbook.Sheets.Count; fi++)
            {
                Excel._Worksheet sheet         = xlWorkbook.Sheets[fi];
                string           name          = sheet.Name;
                AbstractSheet    abstractSheet = null;
                foreach (Tuple <string, string> pairSheetNameRule in SHEET_NAME_TEMPLATE_LIST)
                {
                    Regex           regex   = new Regex(pairSheetNameRule.Item1);
                    MatchCollection matches = regex.Matches(name);
                    if (matches.Count > 0)
                    {
                        string featureName = matches[0].Groups[1].Value;
                        abstractSheet = new TestSpecificationSheet(featureName, sheet);
                    }
                    else
                    {
                        Regex           regex2   = new Regex(pairSheetNameRule.Item2);
                        MatchCollection matches2 = regex2.Matches(name);
                        if (matches2.Count > 0)
                        {
                            string featureName = matches2[0].Groups[1].Value;
                            abstractSheet = new FunctionDescriptionSheet(featureName, sheet);
                        }
                    }
                }
                if (abstractSheet == null)
                {
                    abstractSheet = new NormalSheet(name, sheet);
                }
                listAbstractSheets.Add(abstractSheet);
            }
            List <NormalSheet> normalSheets = new List <NormalSheet>();
            List <Tuple <TestSpecificationSheet, FunctionDescriptionSheet> > pairSheets =
                new List <Tuple <TestSpecificationSheet, FunctionDescriptionSheet> >();

            foreach (AbstractSheet abstractSheet in listAbstractSheets)
            {
                if (abstractSheet is NormalSheet)
                {
                    normalSheets.Add((NormalSheet)abstractSheet);
                }
                else if (abstractSheet is TestSpecificationSheet)
                {
                    FunctionDescriptionSheet funcDescSheet =
                        findFuncDesc(abstractSheet.getFeatureName(), listAbstractSheets);
                    pairSheets.Add(new Tuple <TestSpecificationSheet, FunctionDescriptionSheet>(
                                       (TestSpecificationSheet)abstractSheet, funcDescSheet));
                }
            }
            List <SpecScreen> screenList = new List <SpecScreen>();

            foreach (Tuple <TestSpecificationSheet, FunctionDescriptionSheet> pairSheet in pairSheets)
            {
                SpecScreen screen = parsePairSheet(pairSheet, elementsAndIndicator, myLog);
                if (screen != null)
                {
                    screenList.Add(screen);
                }
            }
            foreach (NormalSheet normalSheet in normalSheets)
            {
                SpecScreen screen = parseNormalSheet(normalSheet, elementsAndIndicator, myLog);
                if (screen != null)
                {
                    screenList.Add(screen);
                }
            }
            //return screenList;
            //cleanup
            //GC.Collect();
            //GC.WaitForPendingFinalizers();

            //rule of thumb for releasing com objects:
            //  never use two dots, all COM objects must be referenced and released individually
            //  ex: [somthing].[something].[something] is bad

            //close and release
            xlWorkbook.Close(false);
            Marshal.ReleaseComObject(xlWorkbook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
            return(screenList);
        }
Ejemplo n.º 12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="allElements">a list of all ui elements</param>
 /// <param name="myLog"></param>
 public List <SpecScreen> ParseWithListAllElements(string filePath, List <IElement> allElements, MyLog myLog)
 {
     //handleSheetsType(
     return(DoParse(filePath, //myLog,
                    new ListUIElements(ListElementsIndicator.AllElements, allElements), myLog));
 }
Ejemplo n.º 13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="rootElements">all root elements (not contain children)</param>
 /// <param name="myLog"></param>
 public List <SpecScreen> ParseWithRootElements(string filePath, List <IElement> rootElements, MyLog myLog)
 {
     //handleSheetsType(
     return(DoParse(filePath, //myLog),
                    new ListUIElements(ListElementsIndicator.OnlyRootElements, rootElements), myLog));
 }
        /// <summary>
        /// only retrieve MapClassAndFuncsAddition
        /// </summary>
        /// <param name="listUcScriptsExp"></param>
        private List <string> GenerateAdditionScripts(List <UserCodeScriptsExpression> listUcScriptsExp, string projectPath, string name_space,
                                                      ListUIElements listUIElements, Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            Dictionary <string, List <FunctionExpression> > mapClassFunc = new Dictionary <string, List <FunctionExpression> >();

            foreach (var ucScriptsExp in listUcScriptsExp)
            {
                var newMapClassFunc = ucScriptsExp.MapClassAndFuncsAddition;
                foreach (var pair in newMapClassFunc)
                {
                    if (mapClassFunc.ContainsKey(pair.Key))
                    {
                        mapClassFunc[pair.Key].AddRange(pair.Value);
                    }
                    else
                    {
                        mapClassFunc.Add(pair.Key, pair.Value);
                    }
                }
            }
            return(GenerateAdditionScripts(mapClassFunc, projectPath, name_space, listUIElements, mapAliasWithNode, myLog, instanceName));
        }
        public static string ParamExp2String(string param, ListUIElements listUIElements,
                                             Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName, ScriptType scriptType)
        {
            string tempParamExp = "";

            // Variable_ControlCPUStatus
            if (Regex.IsMatch(param, USER_CODE_WITH_VARIABLE_DECLARE))
            {
                tempParamExp += param;
            }
            // Text Box One.Text
            else
            {
                tempParamExp += Node2ParamExp(param, listUIElements, mapAliasWithNode, myLog, instanceName, scriptType);
            }
            return(tempParamExp);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="mapClassFunc">(classname, list of functions)</param>
        private List <string> GenerateAdditionScripts(Dictionary <string, List <FunctionExpression> > mapClassFunc, string projectPath,
                                                      string name_space, ListUIElements listUIElements, Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            List <string> listRelativeFilePath = new List <string>();
            string        fileContentTemplate  = GetTemplateRunCsFileContent()
                                                 .Replace(NAMESPACE_REPLACE, name_space);

            foreach (var pair in mapClassFunc)
            {
                string className = pair.Key;
                List <FunctionExpression> listFunctions = pair.Value;
                string functionsScripts = "";
                foreach (FunctionExpression func in listFunctions)
                {
                    if (functionsScripts != "")
                    {
                        functionsScripts += NEW_LINE;
                    }
                    functionsScripts += GenerateFunctionExpScripts(func, listUIElements, mapAliasWithNode, myLog, instanceName);
                }
                // create new file
                string classContent = GetTemplateUCClassContent()
                                      //.Replace(GLOBAL_REPLACE, "") modified by @duong 05/29
                                      .Replace(CLASS_REPLACE, className)
                                      .Replace(CONTENT_REPLACE, functionsScripts);
                string filePath = Path.Combine("UserCode", className + ".cs");
                listRelativeFilePath.Add(filePath);
                CreateNewFile(fileContentTemplate, classContent, Path.Combine(projectPath, filePath));
            }
            return(listRelativeFilePath);
        }
 private void SetAttributes(SpecScenario scenario, AbstractSpecUserAction specUserAction, SpecNode specNode,
                            IScreen screen, string pathToApp, List <Color> colors, ScriptGenerationParams _params, int se, MyLog myLog)
 {
     // importance: must create on the same thread with UI thread
     try
     {
         Application.Current.Dispatcher.Invoke((Action) delegate
         {
             specUserAction.BgColor = new System.Windows.Media.SolidColorBrush(
                 System.Windows.Media.Color.FromArgb(
                     255, colors[se].R, colors[se].G, colors[se].B));
         });
     }
     catch (Exception)
     {
         specUserAction.BgColor = new System.Windows.Media.SolidColorBrush(
             System.Windows.Media.Color.FromArgb(
                 255, colors[se].R, colors[se].G, colors[se].B));
     }
     _params.Color             = colors[se];
     _params.Id                = scenario.Id;
     _params.ListUIElements    = screen.AllUIElements;
     _params.MyLog             = myLog;
     _params.ScreenName        = screen.Name;
     _params.SpecNode          = specNode;
     _params.PathToApp         = pathToApp;
     specUserAction.Params     = _params;
     specUserAction.NodeAffect = specNode;
     if (scenario.UserActions == null)
     {
         scenario.UserActions = new List <IUserAction>();
     }
     scenario.UserActions.Add(specUserAction);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="classesExpression"></param>
        /// <param name="projectPath"></param>
        /// <param name="name_space"></param>
        /// <param name="listUIElements"></param>
        /// <param name="mapAliasWithNode"></param>
        /// <param name="myLog"></param>
        /// <param name="instanceName"></param>
        /// <returns>a list of relative file path</returns>
        private List <string> GenerateClassExpScripts(List <ClassExpression> classesExpression, string projectPath, string name_space,
                                                      ListUIElements listUIElements, Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            List <string> re = new List <string>();

            foreach (ClassExpression classExp in classesExpression)
            {
                re.Add(GenerateClassExpScripts(classExp, projectPath, name_space, listUIElements, mapAliasWithNode, myLog, instanceName));
            }
            return(re);
        }
 /// <summary>
 /// add pre-conditions to each screnario
 /// </summary>
 /// <param name="screen"></param>
 /// <param name="mapNameAndScreens"></param>
 /// <param name="myLog"></param>
 private void AddPreCondition(SpecScreen screen, Dictionary <string, SpecScreen> mapNameAndScreens, MyLog myLog)
 {
     foreach (IScenario scenario in screen.Scenarios)
     {
         if (scenario is SpecScenario specScenario)
         {
             if (specScenario.PreConditionsExpression != null &&
                 specScenario.PreConditionsExpression.Count > 0)
             {
                 foreach (string preConditionExp in specScenario.PreConditionsExpression)
                 {
                     if (preConditionExp == null || preConditionExp.Equals(""))
                     {
                         continue;
                     }
                     int idx = preConditionExp.LastIndexOf("_");
                     if (idx < 0)
                     {
                         myLog.Warn("Can not find the pre-condiction: " + preConditionExp);
                     }
                     else
                     {
                         string preScreen = preConditionExp.Substring(0, idx);
                         try
                         {
                             int          preScenarioIdx      = Int32.Parse(preConditionExp.Substring(idx + 1));
                             SpecScreen   preConditionScreen  = mapNameAndScreens[preScreen];
                             SpecScenario preConditonScenario = getScenarioByIndex(
                                 preScenarioIdx, preConditionScreen.Scenarios);
                             if (preConditionScreen == null ||
                                 preScenarioIdx > preConditionScreen.Scenarios.Count ||
                                 preConditonScenario == null)
                             {
                                 myLog.Warn("Can not find the pre-condiction: " + preConditionExp);
                             }
                             else
                             {
                                 specScenario.PreConditions.Add(preConditonScenario);
                             }
                         }
                         catch (FormatException e)
                         {
                             myLog.Warn("Invalid pre-condiction: " + preConditionExp);
                         }
                     }
                 }
             }
         }
         else
         {
             myLog.Warn("Not implement this type");
         }
     }
 }
        /// <summary>
        /// scripts content for a function
        /// </summary>
        /// <param name="functionExpression"></param>
        /// <param name="listUIElements"></param>
        /// <param name="mapAliasWithNode"></param>
        /// <param name="myLog"></param>
        /// <param name="instanceName"></param>
        /// <returns></returns>
        private string GenerateFunctionExpScripts(FunctionExpression functionExpression, ListUIElements listUIElements,
                                                  Dictionary <string, string> mapAliasWithNode, MyLog myLog, string instanceName)
        {
            string accessibility = functionExpression.GetCorrectAccessibility();
            string summary       = functionExpression.getSummary();
            List <ParameterExpression> @params = functionExpression.getParams();
            string name      = functionExpression.getName();
            string returnDes = functionExpression.getReturnDescription();
            string content   = functionExpression.getContent();

            string re = "";

            if (summary != null)
            {
                re += "/// <summary>" + NEW_LINE;
                string[] listLines = summary.Split('\n');
                foreach (string line in listLines)
                {
                    re += "/// " + line + NEW_LINE;
                }
                re += "/// </summary>";
            }
            var pair = GetParamsScripts(@params, listUIElements, mapAliasWithNode, myLog, instanceName);

            if (pair.Item2 != null && pair.Item2.Count > 0)
            {
                for (int fi = 0; fi < pair.Item2.Count; fi++)
                {
                    string paramName = pair.Item2[fi];
                    string paramDesc = @params[fi].getDescription();
                    if (paramDesc == null)
                    {
                        paramDesc = "";
                    }
                    if (re != "")
                    {
                        re += NEW_LINE;
                    }
                    re += "/// <param name=\"" + paramName + "\">" + paramDesc + "</param>";
                }
            }
            string returnType = functionExpression.GetCorrectReturnType();

            if (returnType != FunctionExpression.VOID)
            {
                if (re != "")
                {
                    re += NEW_LINE;
                }
                re += "/// <returns>" + (returnDes ?? "") + "</returns>";
            }
            if (re != "")
            {
                re += NEW_LINE;
            }
            // Ranorex need to insert annotation
            re += InsertAnnotation();
            re += accessibility + " static " + returnType + " " + name + "(";
            re += pair.Item1;
            re += ")" + NEW_LINE;
            re += "{" + NEW_LINE;
            if (content != null)
            {
                string[] listLines = content.Split('\n');
                foreach (string line in listLines)
                {
                    string line1 = line.Trim().StartsWith("//") ? line.Trim() : "// " + line.Trim();
                    re += line1 + NEW_LINE;
                }
            }
            if (returnType != FunctionExpression.VOID)
            {
                re += "return null;" + NEW_LINE;
            }
            re += "}" + NEW_LINE;
            return(re);
        }
        /// <summary>
        /// type expression
        /// </summary>
        /// <param name="actionEpx"></param>
        /// <param name="specNode"></param>
        /// <param name="color"></param>
        /// <param name="myLog"></param>
        /// <returns></returns>
        private AbstractSpecUserAction handleUserActionExpression(String actionEpx,
                                                                  SpecNode specNode,
                                                                  Color color,
                                                                  MyLog myLog)
        {
            if (actionEpx == null || actionEpx.Equals("") ||
                actionEpx.Equals(AbstractSpecUserAction.NA) ||
                actionEpx.Equals(AbstractSpecUserAction.DO_NOTHING) ||
                actionEpx.Equals(AbstractSpecUserAction.EMPTY) ||
                color.Equals(AbstractSpecUserAction.NOT_TEST_COLOR1) ||
                color.Equals(AbstractSpecUserAction.NOT_TEST_COLOR2))    // ||
//                color.Equals(AbstractSpecUserAction.NOT_TEST_COLOR3))
            {
                return(null);
            }

            /**
             * determine if delay, wait, keyboard press
             */
            if (specNode.UIElement == null)
            {
                // delay
                if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.DELAY_TITLE_EXPRESSION))
                {
                    DelaySpecUserAction delaySpecUserAction = new DelaySpecUserAction();
                    delaySpecUserAction.Expression = actionEpx;
                    return(delaySpecUserAction);
                }
                // wait
                else if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.PRE_WAIT + "(_\\d*)*"))
                {
                    PreWaitValidateSpecUserAction waitValidateSpecUserAction = new PreWaitValidateSpecUserAction();
                    waitValidateSpecUserAction.Expression = actionEpx;
                    return(waitValidateSpecUserAction);
                }
                else if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.POST_WAIT + "(_\\d*)*"))
                {
                    PostWaitValidateSpecUserAction waitValidateSpecUserAction = new PostWaitValidateSpecUserAction();
                    waitValidateSpecUserAction.Expression = actionEpx;
                    return(waitValidateSpecUserAction);
                }
                //keyboard press
                else if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.KEYBOARD_PRESS_REGEX))
                {
                    KeyboardSpecUserAction keyboardPressSpecUserAction = new KeyboardSpecUserAction();
                    keyboardPressSpecUserAction.Expression = actionEpx;
                    return(keyboardPressSpecUserAction);
                }
                //test - not test
                else if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.RESULT))
                {
                    return(null);
                }
                // usercode
                else if (Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.USER_CODE) ||
                         Regex.IsMatch(specNode.Expression, AbstractSpecUserAction.USER_CODE_WITH_VARIABLE_DECLARE))
                {
                    UserCodeSpecUserAction userCodeExpression = new UserCodeSpecUserAction();
                    userCodeExpression.Expression = actionEpx;
                    return(userCodeExpression);
                }
            }
            AbstractSpecUserAction specUserAction = null;
            string attribute = specNode.Attribute;

            if (actionEpx.Equals(AbstractSpecUserAction.OPEN))
            {
                specUserAction = new OpenAppSpecUserAction();
            }
            else if (actionEpx.Equals(AbstractSpecUserAction.CLOSE))
            {
                specUserAction = new CloseAppSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.CLICK))
            {
                specUserAction = new ClickSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.DOUBLE_CLICK))
            {
                specUserAction = new DoubleClickSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.RIGHT_CLICK))
            {
                specUserAction = new RightClickSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.WAIT_EXIST) ||
                     actionEpx.StartsWith(AbstractSpecUserAction.WAIT_NOT_EXIST))
            {
                specUserAction = new WaitExistSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.EXIST) ||
                     actionEpx.StartsWith(AbstractSpecUserAction.NOT_EXIST))
            {
                specUserAction = new CheckExistSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.DELAY))
            {
                specUserAction = new DelaySpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.GET))
            {
                specUserAction = new GetSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.CAPTURE))
            {
                specUserAction = new CaptureSpecUserAction();
            }
            else if (actionEpx.StartsWith(AbstractSpecUserAction.DROP))
            {
                specUserAction = new DropSpecUserAction();
            }
            //else if (actionEpx.StartsWith(AbstractSpecUserAction.COMPARE_IMAGE))
            //{
            //    specUserAction = new ImageComparativeSpecUserAction();
            //    specUserAction.Expression = actionEpx;
            //}
            else if (actionEpx.StartsWith(AbstractSpecUserAction.ATTRIBUTE_CONTAIN) ||
                     actionEpx.StartsWith(AbstractSpecUserAction.ATTRIBUTE_NOT_CONTAIN))
            {
                specUserAction = new ContainSpecUserAction();
            }

            else if (color.Equals(AbstractSpecUserAction.VALIDATION_COLOR) ||
                     color.Equals(AbstractSpecUserAction.ENVIRONMENT_COLOR))
            {
                specUserAction = new ValidationSpecUserAction();
            }
            else if (color.Equals(AbstractSpecUserAction.PROCEDURES_COLOR) ||
                     color.Equals(AbstractSpecUserAction.PRE_CONDITION_COLOR))
            {
                if (attribute != null && !attribute.Equals("") &&
                    (Regex.IsMatch(attribute, "^\\w+$") ||
                     Regex.IsMatch(attribute, ".*\\..*")))
                {
                    specUserAction = new SetSpecUserAction();
                }
                else if (attribute == null || attribute.Equals("") ||
                         Regex.IsMatch(attribute, "Cell\\s*\\((\\d+?),\\s*(\\d+?)\\)") ||
                         Regex.IsMatch(attribute, "Row\\s*\\((\\d+?)\\)"))
                {
                    specUserAction = new PressSpecUserAction();
                }
            }

            // add new case to handle here
            else
            {
                myLog.Warn("Incorrect expression: " + actionEpx);
            }
            if (specUserAction != null)
            {
                specUserAction.Expression = actionEpx;
            }
            return(specUserAction);
        }
Ejemplo n.º 22
0
 protected override void GenerateOthers(MyLog myLog, string folderPath, string repoFilePath, string imageCapFilePath,
                                        string appFilePath, string classRepoName, string name_space, string mainClassInstance, string instanceName,
                                        Dictionary <string, string> mapFilePathAndId, List <string> otherFilePath)
 {
     // do nothing
 }
Ejemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pairSheet"></param>
        /// <param name="elementsAndIndicator">indication to determine root elements or list of all elements</param>
        /// <param name="myLog"></param>
        /// <returns></returns>
        private TestSpecificationScreen parsePairSheet(Tuple <TestSpecificationSheet, FunctionDescriptionSheet> pairSheet,
                                                       ListUIElements elementsAndIndicator, MyLog myLog)
        {
            FunctionSheetParser    functionSheetParser = new FunctionSheetParser();
            List <ClassExpression> classExpressions    = functionSheetParser.parse(pairSheet.Item2, myLog);

            TestSpecSheetParser testSpecSheetParser = new TestSpecSheetParser();

            return(testSpecSheetParser.parse(pairSheet.Item1, elementsAndIndicator, myLog, classExpressions));
        }