/// <summary>
        /// Run cypress test project
        /// </summary>
        /// <param name="strategy"><see cref="EstrategiaDTO"/></param>
        public void RunCypressTest(EstrategiaDTO strategy)
        {
            foreach (TipoPruebaDTO tipoPrueba in strategy.TipoPruebas)
            {
                TipoPruebaController tipoPruebaController = new TipoPruebaController();
                int idExecution = tipoPruebaController.InsertEjecucionTipoPrueba(strategy.Estrategia_ID, strategy.TipoPruebas[0].ID, 0, "", EstadoEnum.EnEjecucion);

                string testProject       = Path.Combine(GetScriptProjectPath(), @"wwwroot\uploads");
                string destinationFolder = @"C:\Temp";
                string scriptPath        = string.Concat(testProject, strategy.TipoPruebas.First().Script.Script);
                string destinationPath   = string.Concat(destinationFolder, @"\",
                                                         Path.GetFileNameWithoutExtension(scriptPath));

                if (!File.Exists(scriptPath))
                {
                    String msg = String.Format("{0} do not exist. Please verify the information provided.", scriptPath);
                    Console.WriteLine(msg);
                    return;
                }

                // Extract the zip file
                GeneralWorkerNetFramework.ActionsFile actionsFile = new GeneralWorkerNetFramework.ActionsFile();
                actionsFile.UnzipFile(scriptPath, destinationFolder);

                // Install the node modules for each of the test projects
                var psiNpmRunDist = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    RedirectStandardInput = true,
                };
                var pNpmRunDist = Process.Start(psiNpmRunDist);

                Directory.GetDirectories(destinationPath).ToList().ForEach(p =>
                {
                    string[] packageJsonFile = Directory.GetFiles(p, "package.json");
                    if (packageJsonFile.Length == 1)
                    {
                        pNpmRunDist.StandardInput.WriteLine(Path.GetPathRoot(p).Replace(@"\", ""));
                        pNpmRunDist.StandardInput.WriteLine(string.Format("cd {0}", p));
                        pNpmRunDist.StandardInput.WriteLine("npm i");
                    }
                });

                pNpmRunDist.StandardInput.WriteLine("npx cypress run test " + tipoPrueba.Parametros);

                pNpmRunDist.WaitForExit();

                tipoPruebaController.InsertEjecucionTipoPrueba(strategy.Estrategia_ID, strategy.TipoPruebas[0].ID, idExecution, "", EstadoEnum.Finalizado);
            }
        }
        static void TestCypress(EstrategiaDTO estrategia)
        {
            foreach (TipoPruebaDTO tipoPrueba in estrategia.TipoPruebas)
            {
                TipoPruebaController tipoPruebaController = new TipoPruebaController();
                int idExecution = tipoPruebaController.InsertEjecucionTipoPrueba(estrategia.Estrategia_ID, estrategia.TipoPruebas[0].ID, 0, "");

                GeneralWorkerNetFramework.ActionsFile actionsFile = new GeneralWorkerNetFramework.ActionsFile();
                var psiNpmRunDist = new ProcessStartInfo
                {
                    FileName = "cmd",
                    RedirectStandardInput = true,
                    //WorkingDirectory = guiProjectDirectory
                };
                var pNpmRunDist = Process.Start(psiNpmRunDist);
                pNpmRunDist.StandardInput.WriteLine("cd C:\\Windows\\System32\\cmd.exe");

                //Traer y copiar el archivo script al sitio donde están los scripts
                string rutaAbsoluta = "C:\\Users\\Sistemas\\source\\repos\\VulkanoPruebasAutomatizadas-Front\\VulkanoPruebasAutomatizadas-Front\\wwwroot";
                //string rutaAbsoluta = "D:\\Takezo316\\GitHub\\VulkanoPruebasAutomatizadas-Front\\VulkanoPruebasAutomatizadas-Front\\wwwroot\\uploads";
                Directory.SetCurrentDirectory(@"C:\vulkanotest");
                string cypath      = Path.GetFullPath(@"C:");
                string rutaScript  = string.Concat(rutaAbsoluta, estrategia.TipoPruebas.First().Script.Script);
                string rutaDestino = string.Concat(cypath, "\\", estrategia.TipoPruebas.First().Script.ID);

                if (!Directory.Exists(rutaDestino))
                {
                    Directory.CreateDirectory(rutaDestino);
                }

                //rutaDestino= string.Concat("C:\\Users\\Sistemas\\Pruebas automatizadas\\E2E\\E2E\\cypress\\integration", estrategia.TipoPruebas.First().Script.Script);
                rutaDestino = string.Concat(cypath, estrategia.TipoPruebas.First().Script.Script);

                string filename = Path.GetFileNameWithoutExtension(rutaDestino);

                File.Copy(rutaScript, rutaDestino, true);

                actionsFile.UnzipFile(rutaScript, string.Concat(cypath, "\\", estrategia.TipoPruebas.First().Script.ID, "\\"));

                pNpmRunDist.StandardInput.WriteLine(string.Concat("cd ", cypath, "\\", estrategia.TipoPruebas.First().Script.ID, "\\", filename));
                pNpmRunDist.StandardInput.WriteLine("npm i");
                pNpmRunDist.StandardInput.WriteLine("npx cypress run .");
                pNpmRunDist.WaitForExit();

                tipoPruebaController.InsertEjecucionTipoPrueba(estrategia.Estrategia_ID, estrategia.TipoPruebas[0].ID, idExecution, "");
            }
        }
Esempio n. 3
0
        static void StartProcess(EstrategiaDTO estrategia)
        {
            TipoPruebaController tipoPruebaController = new TipoPruebaController();
            int idExecution = tipoPruebaController.InsertEjecucionTipoPrueba(estrategia.Estrategia_ID, estrategia.TipoPruebas[0].ID, 0, "", EstadoEnum.EnEjecucion);


            int    times = estrategia.TipoPruebas.First().CantidadEjecuciones;
            string delay = "0.2";
            string seed1;
            string seed2;
            string seed3;
            string seed4;
            string completeSeed = estrategia.TipoPruebas.First().Semilla;

            if (string.IsNullOrEmpty(completeSeed))
            {
                seed1        = new Random().Next(0, 999999999).ToString();
                seed2        = new Random().Next(0, 999999999).ToString();
                seed3        = new Random().Next(0, 999999999).ToString();
                seed4        = new Random().Next(0, 999999999).ToString();
                completeSeed = seed1 + seed2 + seed3 + seed4;
            }

            string ruta     = estrategia.TipoPruebas.First().Script.Script;
            string fileName = ConfigurationManager.AppSettings["RutaScript"] + ruta + "\\features\\monkey.feature";

            string zipFile      = "features.zip";
            string featuresPath = ConfigurationManager.AppSettings["RutaScript"] + ruta;
            string zipPath      = ConfigurationManager.AppSettings["RutaScript"] + ruta + "\\" + zipFile;

            try
            {
                // Check if file already exists. If yes, delete it.
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                // Create a new file
                using (FileStream fs = File.Create(fileName))
                {
                    // Add some text to file
                    Byte[] title = new UTF8Encoding(true).GetBytes("Feature: Monkey Testing");
                    fs.Write(title, 0, title.Length);

                    Byte[] newLine = new UTF8Encoding(true).GetBytes("\n");
                    fs.Write(newLine, 0, newLine.Length);

                    Byte[] scenarioTitle = new UTF8Encoding(true).GetBytes("Scenario: Random touch");
                    fs.Write(newLine, 0, newLine.Length);

                    Byte[] author = new UTF8Encoding(true).GetBytes("    Given I make " + times + " events with a waiting time of " + delay + " with seed " + completeSeed);
                    fs.Write(author, 0, author.Length);
                }

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }

                if (File.Exists(zipPath))
                {
                    File.Delete(zipPath);
                }

                ZipFile.CreateFromDirectory(featuresPath, zipPath);
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }

            //Create upload for apk
            String cmd = @"/C C:\PROGRA~1\Amazon\AWSCLI\bin\aws devicefarm create-upload --project-arn arn:aws:devicefarm:us-west-2:813226252700:project:45bfef00-da01-48d6-bc69-2b2c7f6fb425 --name " + estrategia.TipoPruebas.First().Parametros + "--type ANDROID_APP";

            var psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = cmd
            };
            var pNpmRunDist = Process.Start(psiNpmRunDist);

            string output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            dynamic response        = JsonConvert.DeserializeObject(output);
            string  urlForApkUpload = response.upload.url.ToString();

            Console.WriteLine("url: " + urlForApkUpload);

            //Upload apk
            string rutaAbsoluta = estrategia.Aplicacion.Ruta_Aplicacion;

            String paramsForApkUpload = @"/C curl -T " + rutaAbsoluta + " \"" + urlForApkUpload + "\"";

            psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = paramsForApkUpload
            };
            pNpmRunDist = Process.Start(psiNpmRunDist);

            output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            pNpmRunDist.WaitForExit();

            Console.WriteLine("finished");

            //Create Upload for script
            cmd = @"/C C:\PROGRA~1\Amazon\AWSCLI\bin\aws devicefarm create-upload --project-arn arn:aws:devicefarm:us-west-2:813226252700:project:45bfef00-da01-48d6-bc69-2b2c7f6fb425 --name " + estrategia.TipoPruebas.First().Script.Nombre + estrategia.TipoPruebas.First().Script.Extension + " --type CALABASH_TEST_PACKAGE";

            psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = cmd
            };
            pNpmRunDist = Process.Start(psiNpmRunDist);

            output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            response = JsonConvert.DeserializeObject(output);
            var urlForScriptUpload = response.upload.url.ToString();

            Console.WriteLine("url: " + urlForScriptUpload);

            //Upload script
            rutaAbsoluta = zipPath;

            string paramsForScriptUpload = @"/C curl -T " + rutaAbsoluta + " \"" + urlForScriptUpload + "\"";

            psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = paramsForScriptUpload
            };
            pNpmRunDist = Process.Start(psiNpmRunDist);

            output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            pNpmRunDist.WaitForExit();

            Console.WriteLine("finished");

            //response = JsonConvert.DeserializeObject(output);

            //string output = pNpmRunDist.StandardOutput.ReadToEnd();

            //Thread.Sleep(10000);

            //Execute test
            cmd = @"/C C:\PROGRA~1\Amazon\AWSCLI\bin\aws devicefarm schedule-run --project-arn arn:aws:devicefarm:us-west-2:813226252700:project:45bfef00-da01-48d6-bc69-2b2c7f6fb425  --app-arn arn:aws:devicefarm:us-west-2:813226252700:upload:45bfef00-da01-48d6-bc69-2b2c7f6fb425/cf5e1be8-e01c-4ceb-87d6-0a2970e32957 --device-pool-arn arn:aws:devicefarm:us-west-2::devicepool:1c59cfd0-ee56-4443-b290-7a808d9fd885 --name MyTestRun --test type=CALABASH,testPackageArn=arn:aws:devicefarm:us-west-2:813226252700:upload:45bfef00-da01-48d6-bc69-2b2c7f6fb425/a642b018-2ca7-4b16-9469-92cf7c363849";

            psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = cmd
            };
            pNpmRunDist = Process.Start(psiNpmRunDist);

            output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            response = JsonConvert.DeserializeObject(output);
            var arnForRun = response.run.arn.ToString();

            Console.WriteLine("arnForRun: " + arnForRun);

            string status = "";

            while (status != "COMPLETED" || status != "STOPPING")
            {
                //Check if finished

                cmd = @"/C C:\PROGRA~1\Amazon\AWSCLI\bin\aws devicefarm get-run --arn" + " \"" + arnForRun + "\"";

                psiNpmRunDist = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    Arguments = cmd
                };
                pNpmRunDist = Process.Start(psiNpmRunDist);

                output = pNpmRunDist.StandardOutput.ReadToEnd();
                Console.WriteLine(output);
                response = JsonConvert.DeserializeObject(output);
                status   = response.run.status.ToString();

                Thread.Sleep(60000);
            }

            //For the results is used arnForRun
            //for example:
            //arn:aws:devicefarm:us-west-2:813226252700:run:45bfef00-da01-48d6-bc69-2b2c7f6fb425/ff7d0b49-162b-4bc2-9ee9-9cdc96a1c239

            //Screenshots results
            cmd = @"/C C:\PROGRA~1\Amazon\AWSCLI\bin\aws devicefarm list-artifacts --arn" + " \"" + arnForRun + "\" --type SCREENSHOT";

            psiNpmRunDist = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                Arguments = cmd
            };
            pNpmRunDist = Process.Start(psiNpmRunDist);

            output = pNpmRunDist.StandardOutput.ReadToEnd();

            Console.WriteLine(output);

            response = JsonConvert.DeserializeObject(output);

            //marca como finalizado
            tipoPruebaController.InsertEjecucionTipoPrueba(estrategia.Estrategia_ID, estrategia.TipoPruebas[0].ID, idExecution, "", EstadoEnum.Finalizado);
        }
        /// <summary>
        /// Start with the process of environment preparation and test execution
        /// </summary>
        /// <param name="strategy"><see cref="EstrategiaDTO"/></param>
        static void StartProcess(EstrategiaDTO strategy)
        {
            DebugLog.EscribirLog("Procesando la estrategia " + strategy.Estrategia_ID);
            TipoPruebaController tipoPruebaController = new TipoPruebaController();
            int idExecution = 0;

            try
            {
                WorkerStatus worker = new WorkerStatus();
                worker.WorkerID   = Convert.ToInt32(ConfigurationManager.AppSettings["WorkerID"]);
                worker.Estado.ID  = 6;
                worker.TipoPrueba = "QUEUE_BDT";
                WorkerController workerController = new WorkerController();
                workerController.UpdateWorkerStatus(worker);

                foreach (TipoPruebaDTO tipoPrueba in strategy.TipoPruebas)
                {
                    DebugLog.EscribirLog("Procesando la prueba " + tipoPrueba.ID);

                    ScriptFile scriptFile = new ScriptFile();
                    //guarda en el historico de ejecucion de pruebas
                    idExecution = tipoPruebaController.InsertEjecucionTipoPrueba(strategy.Estrategia_ID, strategy.TipoPruebas[0].ID, 0, "", EstadoEnum.EnEjecucion);

                    //ruta donde se encuentra el archivo del script
                    string testProject = Path.Combine(ConfigurationManager.AppSettings["RutaScript"]);
                    //ruta destino temporal
                    string destinationFolder = @"C:\Temp";
                    DebugLog.EscribirLog("id ejecucion " + idExecution);
                    string destinationPath = string.Concat(destinationFolder, @"\", tipoPrueba.Script.Script);
                    DebugLog.EscribirLog(destinationPath);
                    //ruta de origen del script
                    string scriptPath = string.Concat(testProject, tipoPrueba.Script.Script, tipoPrueba.Script.Nombre, tipoPrueba.Script.Extension);

                    //si la ruta destino no existe se crea
                    if (!File.Exists(destinationPath))
                    {
                        Directory.CreateDirectory(destinationPath);
                    }
                    DebugLog.EscribirLog("creo ruta de temp");
                    // Extract the zip file
                    GeneralWorkerNetFramework.ActionsFile actionsFile = new GeneralWorkerNetFramework.ActionsFile();
                    actionsFile.UnzipFile(scriptPath, destinationPath);
                    // Create json structure file
                    //string projectPath = //@"F:\Universidad de los Andes\MISO\Pruebas Automaticas\T Grupal\-201920_MISO4208\PrestashopTest";
                    string dataDestinationFolder = Path.Combine(destinationPath, @"Prestashop.Core\fixtures\data.json");
                    DebugLog.EscribirLog("ruta del fixtures");
                    //parametros de mockaroo
                    #region Mockaroo
                    ParametersRequest parameters = new ParametersRequest
                    {
                        ApiController = tipoPrueba.ApiController,
                        Key           = tipoPrueba.ApiKey
                    };

                    JsonFile jsonFile            = new JsonFile();
                    int      numberDataGenerated = jsonFile.GenerateData(parameters, dataDestinationFolder);
                    #endregion
                    // Reemplaza tokens del script
                    DebugLog.EscribirLog(destinationPath);
                    #region Reemplazar tokens
                    IEnumerable <string> featureFiles = scriptFile.GetFeatureFiles(destinationPath);
                    // Replace tokens with random position object of json file
                    DebugLog.EscribirLog("inicio del reemplazo tokens");
                    foreach (string featureFile in featureFiles)
                    {
                        scriptFile.ReplaceTokens(featureFile, numberDataGenerated);
                    }
                    DebugLog.EscribirLog("reemplazo tokens");
                    #endregion
                    // Executes Cypress script
                    if (strategy != null)
                    {
                        DebugLog.EscribirLog("ruta del package");

                        string package = destinationPath + "\\" + "BDT.TestProject";
                        DebugLog.EscribirLog("fin ruta del fixtures");
                        // Install the node modules for each of the test project

                        var psiNpmRunDist = new ProcessStartInfo
                        {
                            FileName = "cmd.exe",
                            RedirectStandardInput = true,
                            UseShellExecute       = false,
                            WorkingDirectory      = package
                        };
                        DebugLog.EscribirLog("Abiendo CMD " + package);
                        using (var pNpmRunDist = Process.Start(psiNpmRunDist))
                        {
                            StringBuilder output = new StringBuilder();
                            pNpmRunDist.StandardInput.WriteLine("npm i");
                            Thread.Sleep(1000);

                            pNpmRunDist.StandardInput.WriteLine("npx cypress run " + tipoPrueba.Parametros);
                            pNpmRunDist.WaitForExit(360000);
                            pNpmRunDist.Close();
                        }
                        DebugLog.EscribirLog("marca como finalizado");
                        //marca como finalizado
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLog.EscribirLog("error " + ex.Message);
                Console.WriteLine("error " + ex);
                //en caso de error envia nuevamente a la cola
                Dispatcher rabbit = new Dispatcher();
                rabbit.EnviaMensajes(strategy);
            }
            finally
            {
                DebugLog.EscribirLog("Liberando el worker");
                WorkerStatus worker = new WorkerStatus();
                worker.WorkerID   = Convert.ToInt32(ConfigurationManager.AppSettings["WorkerID"]);
                worker.Estado.ID  = 5;
                worker.TipoPrueba = "QUEUE_BDT";
                WorkerController workerController = new WorkerController();
                workerController.UpdateWorkerStatus(worker);
                DebugLog.EscribirLog("Fin del proceso de la estrategia " + strategy.Estrategia_ID);
                tipoPruebaController.InsertEjecucionTipoPrueba(strategy.Estrategia_ID, strategy.TipoPruebas[0].ID, idExecution, "", EstadoEnum.WorkerLibre);
            }
        }