瀏覽代碼

添加自动化测试

denny 1 年之前
父節點
當前提交
97e51bc239

+ 23 - 0
Tools/Flyinsono.Client.AutoTestApplication/AutoTestApplication.csproj

@@ -0,0 +1,23 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <TargetFramework>netcoreapp3.1</TargetFramework>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <None Update="Config\AppSetting.json">
+      <CopyToOutputDirectory>Never</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
+
+  <ItemGroup>
+    <Resource Update="Config\AppSetting.json">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </Resource>
+  </ItemGroup>
+</Project>

+ 25 - 0
Tools/Flyinsono.Client.AutoTestApplication/AutoTestApplication.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30128.74
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoTestApplication", "AutoTestApplication.csproj", "{2D5ED014-A523-4B85-957F-D98CA8CF827F}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{2D5ED014-A523-4B85-957F-D98CA8CF827F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{2D5ED014-A523-4B85-957F-D98CA8CF827F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{2D5ED014-A523-4B85-957F-D98CA8CF827F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{2D5ED014-A523-4B85-957F-D98CA8CF827F}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {A658A6FF-EC34-4FFC-B40B-156766EAC9BC}
+	EndGlobalSection
+EndGlobal

+ 193 - 0
Tools/Flyinsono.Client.AutoTestApplication/AutoTestService.cs

@@ -0,0 +1,193 @@
+using AutoTestApplication.Common;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace AutoTestApplication
+{
+    public class AutoTestService
+    {
+        /// <summary>
+        /// 运行机器人报告
+        /// </summary>
+        public void RunRobotFrameworkReport()
+        {
+            try
+            {
+                var maxCount = CommonConfigManager.MaxExcuteCount;
+                var curDateRecord = CommonConfigManager.Records.Find(d => d.ExcuteDate.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"));
+                if (curDateRecord?.ExcuteRecords?.Count >= maxCount)
+                {
+                    //大于5次不执行
+                    Console.WriteLine($"今日执行次数大于每日执行最大次数{maxCount}, 自动化测试报告不执行");
+                    return;
+                }
+                //开始比较版本,并copy文件
+                CheckAndCopyFile();
+                var scheduledBeginTime = DateTime.Now;
+                var outputResult = ProcessStarter.StartCmdProcess(CommonConfigManager.ExcuteCmdConfig);
+                var scheduledEndTime = DateTime.Now;
+                //记录今日执行次数
+                if (curDateRecord == null)
+                {
+                    curDateRecord = new RecordEntity()
+                    {
+                        ExcuteDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")),
+                        ExcuteRecords = new List<ExcuteRecordsEntity>()
+                    };
+                    CommonConfigManager.Records.Add(curDateRecord);
+                }
+                var recordsEntity = new ExcuteRecordsEntity()
+                {
+                    ExcuteStartTime = scheduledBeginTime,
+                    ExcuteEndTime = scheduledEndTime
+                };
+                curDateRecord.ExcuteRecords.Add(recordsEntity);
+                WriteJsonFile();
+                if (outputResult.IndexOf("465") > 0)
+                {
+                    Console.WriteLine(scheduledEndTime.ToString("yyyy-MM-dd HH:mm:ss") + ":执行自动化测试报告Success");
+                }
+                else
+                {
+                    Console.WriteLine(scheduledEndTime.ToString("yyyy-MM-dd HH:mm:ss") + ":执行自动化测试报告Fail");
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine("RunRobotFrameworkReport异常:" + ex.Message);
+            }
+        }
+
+        /// <summary>
+        /// 监测并copy文件
+        /// </summary>
+        /// <returns></returns>
+        private bool CheckAndCopyFile()
+        {
+            var result = false;
+            try
+            {
+                var version = GetVersion();
+                if (!string.IsNullOrEmpty(version))
+                {
+                    if (version != CommonConfigManager.CurrentVersion)
+                    {
+                        //需要更新
+                        //copy art文件
+                        string sourceFile = CommonConfigManager.SourceFilePath + "\\" + CommonConfigManager.RideFileName;
+                        string destinationFile = CommonConfigManager.RideArtPath + "\\" + CommonConfigManager.RideFileName;
+                        bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
+                        System.IO.File.Copy(sourceFile, destinationFile, isrewrite);
+
+                        //copy custom 文件夹及子项
+                        var strFromPath = CommonConfigManager.SourceFilePath + "\\" + CommonConfigManager.CustomFileName;
+                        var strToPath = CommonConfigManager.CustomPyPath;
+                        DirectoryInfo target = new DirectoryInfo(strFromPath);
+                        CopyToDirect(target, strToPath, true);
+
+                        //copy robot 文件夹及子项
+                        if (CommonConfigManager.RobotFileNames?.Count > 0)
+                        {
+                            foreach (var item in CommonConfigManager.RobotFileNames)
+                            {
+                                strFromPath = CommonConfigManager.SourceFilePath + "\\" + item;
+                                strToPath = CommonConfigManager.RobotRunPath + "\\" + item;
+                                target = new DirectoryInfo(strFromPath);
+                                CopyToDirect(target, strToPath, true);
+                            }
+                        }
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine("CheckAndCopyFile异常:" + ex.Message);
+            }
+            return result;
+        }
+
+        /// <summary>
+        /// 递归copy文件夹
+        /// </summary>
+        /// <param name="strFromPath"></param>
+        /// <param name="strToPath"></param>
+        private void CopyToDirect(DirectoryInfo source, string destDirectory, bool recursive)
+        {
+            if (source == null)
+                throw new ArgumentNullException("source");
+            if (destDirectory == null)
+                throw new ArgumentNullException("destDirectory");
+            // If the source doesn't exist, we have to throw an exception.
+            if (!source.Exists)
+                throw new DirectoryNotFoundException(
+                       "Source directory not found:" + source.FullName);
+            // Compile the target.
+            DirectoryInfo target = new DirectoryInfo(destDirectory);
+            // If the target doesn't exist, we create it.
+            if (!target.Exists)
+                target.Create();
+            // Get all files and copy them over.
+            foreach (FileInfo file in source.GetFiles())
+            {
+                file.CopyTo(Path.Combine(target.FullName, file.Name), true);
+            }
+            // Return if no recursive call is required.
+            if (!recursive)
+                return;
+            // Do the same for all sub directories.
+            foreach (DirectoryInfo directory in source.GetDirectories())
+            {
+                CopyToDirect(directory,
+                    Path.Combine(target.FullName, directory.Name), recursive);
+            }
+        }
+
+        /// <summary>
+        /// 获取到制定文件目录的version
+        /// </summary>
+        /// <returns></returns>
+        private string GetVersion()
+        {
+            string version = string.Empty;
+            var filePath = CommonConfigManager.SourceFilePath + "\\version.txt";
+            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
+            {
+                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
+                {
+                    version = sr.ReadToEnd().ToString();
+                }
+            }
+            return version;
+        }
+        
+
+        /// <summary>
+        /// 写入文件
+        /// </summary>
+        /// <returns></returns>
+        private void WriteJsonFile()
+        {
+            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Config", "AppSetting.json");
+            var model = new AppSettingEntity()
+            {
+                MaxExcuteCount = CommonConfigManager.MaxExcuteCount,
+                ExcuteCmdConfig = CommonConfigManager.ExcuteCmdConfig,
+                Records = CommonConfigManager.Records,
+                CurrentVersion = CommonConfigManager.CurrentVersion,
+                SourceFilePath = CommonConfigManager.SourceFilePath,
+                RobotRunPath = CommonConfigManager.RobotRunPath,
+                CustomPyPath = CommonConfigManager.CustomPyPath,
+                RideArtPath = CommonConfigManager.RideArtPath,
+                CustomFileName = CommonConfigManager.CustomFileName,
+                RideFileName = CommonConfigManager.RideFileName,
+                RobotFileNames = CommonConfigManager.RobotFileNames,
+            };
+            var jsonConents = JsonConvert.SerializeObject(model);
+            File.WriteAllText(path, jsonConents, System.Text.Encoding.UTF8);          
+        }
+    }
+}

+ 34 - 0
Tools/Flyinsono.Client.AutoTestApplication/Common/AppSettingEntity.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace AutoTestApplication.Common
+{
+    public class AppSettingEntity
+    {
+        public int MaxExcuteCount { get; set; }
+        public string ExcuteCmdConfig { get; set; }
+        public List<RecordEntity> Records { get; set; }
+        public string CurrentVersion { get; set; }
+        public string SourceFilePath { get; set; }
+        public string RobotRunPath { get; set; }
+        public string CustomPyPath { get; set; }
+        public string RideArtPath { get; set; }
+        public List<string> RobotFileNames { get; set; }
+        public string CustomFileName { get; set; }
+        public string RideFileName { get; set; }
+    }
+
+    public class RecordEntity
+    { 
+        public DateTime ExcuteDate { get; set; }
+
+        public List<ExcuteRecordsEntity> ExcuteRecords { get; set; }
+    }
+
+    public class ExcuteRecordsEntity
+    { 
+        public DateTime ExcuteStartTime { get; set; }
+        public DateTime ExcuteEndTime { get; set; }
+    }
+}

+ 91 - 0
Tools/Flyinsono.Client.AutoTestApplication/Common/CommonConfigManager.cs

@@ -0,0 +1,91 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+namespace AutoTestApplication.Common
+{
+    public class CommonConfigManager
+    {
+        /// <summary>
+        /// 初始化读取数据
+        /// </summary>
+        static CommonConfigManager()
+        {
+            var jsonContent = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Config", "AppSetting.json"));
+            var config = JsonConvert.DeserializeObject<AppSettingEntity>(jsonContent);
+            if (config != null)
+            {
+                if (config.Records?.Count > 0)
+                {
+                    Records = config.Records;
+                }
+                if (config.MaxExcuteCount > 0)
+                {
+                    MaxExcuteCount = config.MaxExcuteCount;
+                }
+                if (!string.IsNullOrEmpty(config.ExcuteCmdConfig))
+                {
+                    ExcuteCmdConfig = config.ExcuteCmdConfig;
+                }
+                if (!string.IsNullOrEmpty(config.CurrentVersion))
+                {
+                    CurrentVersion = config.CurrentVersion;
+                }
+                if (!string.IsNullOrEmpty(config.SourceFilePath))
+                {
+                    SourceFilePath = config.SourceFilePath;
+                }
+                if (!string.IsNullOrEmpty(config.RobotRunPath))
+                {
+                    RobotRunPath = config.RobotRunPath;
+                }
+                if (!string.IsNullOrEmpty(config.CustomPyPath))
+                {
+                    CustomPyPath = config.CustomPyPath;
+                }
+                if (!string.IsNullOrEmpty(config.RideArtPath))
+                {
+                    RideArtPath = config.RideArtPath;
+                }
+                if (config.RobotFileNames?.Count > 0)
+                {
+                    RobotFileNames = config.RobotFileNames;
+                }
+                if (!string.IsNullOrEmpty(config.CustomFileName))
+                {
+                    CustomFileName = config.CustomFileName;
+                }
+                if (!string.IsNullOrEmpty(config.RideFileName))
+                {
+                    RideFileName = config.RideFileName;
+                }
+            }
+        }
+
+        /// <summary>
+        /// 记录
+        /// </summary>
+        public static List<RecordEntity> Records { get; set; }
+
+        /// <summary>
+        /// 每日最大执行次数
+        /// </summary>
+        public static int MaxExcuteCount { get; set; }
+
+        /// <summary>
+        /// 执行命令
+        /// </summary>
+        public static string ExcuteCmdConfig { get; set; }
+
+        public static string CurrentVersion { get; set; }
+        public static string SourceFilePath { get; set; }
+        public static string RobotRunPath { get; set; }
+        public static string CustomPyPath { get; set; }
+        public static string RideArtPath { get; set; }
+        public static List<string> RobotFileNames { get; set; }
+        public static string CustomFileName { get; set; }
+        public static string RideFileName { get; set; }
+    }
+}

+ 38 - 0
Tools/Flyinsono.Client.AutoTestApplication/Common/ProcessStarter.cs

@@ -0,0 +1,38 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace AutoTestApplication.Common
+{
+    public class ProcessStarter
+    {
+         /// <summary>
+        /// 开始执行CMD命令程序
+        /// </summary>
+        /// <param name="processName">工具程序名称</param>
+        public static string StartCmdProcess(string cmdStr)
+        {
+            try
+            {
+                Process process = new Process();
+                process.StartInfo.FileName = "cmd.exe";
+                process.StartInfo.CreateNoWindow  = true;
+                process.StartInfo.UseShellExecute  = false;
+                process.StartInfo.RedirectStandardInput = true; //重定向输入,
+                process.StartInfo.RedirectStandardOutput = true; //重定向输出,
+                process.StartInfo.RedirectStandardError = true;
+                process.StartInfo.Arguments = "/c " + cmdStr;//"=====cmd命令======";//“/C”表示执行完命令后马上退出  
+                process.Start();//执行 
+                var result = process.StandardOutput.ReadToEnd();//获取返回值   
+                process.WaitForExit();//等待程序执行完退出进程   
+                process.Close();//结束
+                return result;
+            }
+            catch(Exception ex)
+            {
+                Console.WriteLine("执行CMD命令异常:/c " + cmdStr + ",ex: "+ ex.Message);
+                return "";
+            }
+        }
+    }
+}

+ 23 - 0
Tools/Flyinsono.Client.AutoTestApplication/Config/AppSetting.json

@@ -0,0 +1,23 @@
+{
+  "MaxExcuteCount": 5,
+  "ExcuteCmdConfig": "robot --listener \"C:\\Python\\Python37\\Lib\\site-packages\\CustomLibrary\\PythonListener.py\" --argumentfile C:\\Users\\vinno\\AppData\\Local\\Temp\\RIDE8gxnc7ut.d\\argfile.txt C:\\Python\\Python37\\Lib\\site-packages\\FlyinsonoRobotFrameworkApi",
+  "CurrentVersion": "1.0.0.1",
+  "SourceFilePath": "D:\\Project\\git\\robot Tests\\FlyinsonoRobotFrameworkApi",
+  "RobotFileNames": [ "AllApi", "AllSuite", "CommonConfig", "Utils" ],
+  "CustomFileName": "CustomLibrary",
+  "RideFileName": "argfile.txt",
+  "RobotRunPath": "C:\\Python\\Python37\\Lib\\site-packages\\FlyinsonoRobotFrameworkApi",
+  "CustomPyPath": "C:\\Python\\Python37\\Lib\\site-packages\\CustomLibrary",
+  "RideArtPath": "C:\\Users\\vinno\\AppData\\Local\\Temp\\RIDE8gxnc7ut.d",
+  "Records": [
+    {
+      "ExcuteDate": "2023-06-09",
+      "ExcuteRecords": [
+        {
+          "ExcuteStartTime": "2023-06-09 10:00:00",
+          "ExcuteEndTime": "2023-06-09 10:05:00"
+        }
+      ]
+    }
+  ]
+}

+ 14 - 0
Tools/Flyinsono.Client.AutoTestApplication/Program.cs

@@ -0,0 +1,14 @@
+using System;
+
+namespace AutoTestApplication
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            var service = new AutoTestService();
+            service.RunRobotFrameworkReport();
+            Console.ReadLine();
+        }
+    }
+}