AutoTest.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //
  2. // AutoTest.swift
  3. // KdanAuto
  4. //
  5. // Created by 朱东勇 on 2022/11/25.
  6. //
  7. import Foundation
  8. import AppKit
  9. var cacheObjects = NSMutableDictionary()
  10. class AutoTest : NSObject, AutoTestProtocal {
  11. var reportString : NSMutableAttributedString? = nil
  12. public var _status : AutoTestStatus = .Normal
  13. var _fileType : String = "RTF"
  14. var _type : String = "Others"
  15. var _extention : String = "rtf"
  16. class func autoTestFor(_ fileType:NSString ,type:NSString) -> AutoTest? {
  17. let key = String(fileType) + "." + String(type)
  18. if cacheObjects.value(forKey: key) != nil {
  19. let object = cacheObjects.value(forKey: key)
  20. return object as? AutoTest
  21. }
  22. // if let cacheObject as AutoTest {
  23. // return cacheObject
  24. // }
  25. let fileTypes = testTypeInfo[fileType] as! NSArray
  26. let clsname = "KdanAuto"//Bundle.main.infoDictionary! ["CFBundleExecutable"]
  27. for item in fileTypes {
  28. let cItem = item as! NSDictionary
  29. let cType = cItem["Type"] as! NSString
  30. let cExtention = cItem["Extention"] as! NSString
  31. if (cType.isEqual(to: type)) {
  32. let className = String((clsname )+"."+(cItem["Class"] as! String)) as! String
  33. let cl = NSClassFromString(className) as! AutoTest.Type
  34. let object = cl.shared()
  35. object?._fileType = fileType as! String
  36. object?._type = String(cType)
  37. object?._extention = String(cExtention)
  38. cacheObjects.setValue(object, forKey: key)
  39. return object
  40. }
  41. }
  42. let object = AutoTest.shared()
  43. object?._fileType = fileType as String
  44. object?._type = String(cType)
  45. object?._extention = ""
  46. cacheObjects.setValue(object, forKey: key)
  47. return object
  48. }
  49. class func shared() -> AutoTest? {
  50. return AutoTest()
  51. }
  52. func fileType() -> String {
  53. return _fileType
  54. }
  55. func type() -> String {
  56. return _type
  57. }
  58. func name() -> String {
  59. return "未指定类型对照测试"
  60. }
  61. func keys() -> NSArray {
  62. return ["快照对比"]
  63. }
  64. func selectedKeys() -> NSArray {
  65. let userDefaults = UserDefaults.standard
  66. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  67. if userDefaults.value(forKey: key) != nil {
  68. return userDefaults.value(forKey: key) as! NSArray
  69. }
  70. self.setSelectedKeys(self.keys())
  71. return self.keys()
  72. }
  73. func setSelectedKeys(_ keys: NSArray) {
  74. let userDefaults = UserDefaults.standard
  75. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  76. userDefaults.setValue(keys, forKey: key)
  77. userDefaults.synchronize()
  78. }
  79. func status() -> AutoTestStatus {
  80. return _status
  81. }
  82. func setStatus(_ status:AutoTestStatus) {
  83. _status = status
  84. }
  85. // Auto Test
  86. func autoTest() {
  87. clearCacheFiles()
  88. if hasOriginFile() {
  89. let needCompare = self.selectedKeys().contains("快照对比")
  90. if !needCompare {
  91. _status = .Finished
  92. return
  93. }
  94. _status = .Process
  95. reportString = NSMutableAttributedString.init(string: "\n【\(String(self.fileType())) - \(self.name())】快照比对开始!\n",
  96. attributes:[.foregroundColor : NSColor.blue])
  97. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  98. let checkDirectory = self.checkFileDirectory()
  99. let originDirectory = self.originFileDirectory()
  100. let resultDirectory = self.resultFileDirectory()
  101. for fileName in files {
  102. let fName = NSString(string: fileName).deletingPathExtension
  103. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  104. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  105. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  106. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】开始转换文件 \"\(fName)\"\n",
  107. attributes:[.foregroundColor : NSColor.blue]))
  108. // ...
  109. // 执行转换过程
  110. let convertSemaphore = DispatchSemaphore(value: 0)
  111. var success = false
  112. let convertQueue = DispatchQueue.global()
  113. convertQueue.async {
  114. success = FileConverter.shared().converter(originPath, inDesPath: resultPath)
  115. convertSemaphore.signal()
  116. }
  117. convertSemaphore.wait()
  118. var isDirectory = ObjCBool(false)
  119. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) && success {
  120. // compare screenshoot between result file with check file
  121. if needCompare {
  122. let items = NSMutableArray()
  123. if (isDirectory.boolValue) {
  124. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  125. for item in NSArray(array: searchItems) {
  126. let ext = NSString(string: item as! String).pathExtension.lowercased()
  127. if NSArray(array: [_extention]).contains(ext) {
  128. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  129. items.add(fileName)
  130. }
  131. }
  132. }else {
  133. items.add(fName)
  134. }
  135. for item in items {
  136. let subFileName = item as! String
  137. let subResultPath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"."+_extention)
  138. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subFileName+".\(_extention)")\"快照生成中\n",
  139. attributes:[.foregroundColor : NSColor.black]))
  140. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"_\(DataModel.shared.latestReportID()!).jpg")
  141. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  142. let processThumbSemaphore = DispatchSemaphore(value: 0)
  143. var processSuccess = false
  144. let thumbnailQueue = DispatchQueue.global()
  145. thumbnailQueue.async {
  146. processSuccess = ProcessThumbnal.process(subResultPath, desPath: rComparePath, outputSize: CGSize.init(width: 2048, height: 2048))
  147. if ( processSuccess &&
  148. FileManager.default.fileExists(atPath: rComparePath)) {
  149. let degree = self.compareJPEG(rComparePath, checkPath: cComparePath)
  150. if degree == -1 {
  151. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比失败,生成快照失败或无比对文件\n",
  152. attributes:[.foregroundColor : NSColor.red]))
  153. }else {
  154. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比完成,图像相似度 \(degree)%\n",
  155. attributes:[.foregroundColor : NSColor.red]))
  156. }
  157. }else {
  158. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照生成失败\n",
  159. attributes:[.foregroundColor : NSColor.red]))
  160. }
  161. processThumbSemaphore.signal()
  162. }
  163. processThumbSemaphore.wait()
  164. }
  165. }
  166. }else {
  167. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档失败!\n",
  168. attributes:[.foregroundColor : NSColor.red]))
  169. }
  170. }
  171. _status = .Finished
  172. }else {
  173. _status = .Normal
  174. }
  175. }
  176. func testReport() -> NSAttributedString? {
  177. return reportString
  178. }
  179. func compareJPEG(_ resultPath:String, checkPath:String) -> Double {
  180. if !FileManager.default.fileExists(atPath: resultPath) || !FileManager.default.fileExists(atPath: checkPath) {
  181. return -1
  182. }
  183. let rImage = NSImage.init(contentsOfFile: resultPath) ?? nil
  184. let cImage = NSImage.init(contentsOfFile: checkPath) ?? nil
  185. if nil == rImage || nil == cImage {
  186. return -1
  187. }
  188. let resultImage = rImage as! NSImage
  189. let checkImage = cImage as! NSImage
  190. let resultImageRep = NSBitmapImageRep.init(cgImage: resultImage.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  191. let checkImageRep = NSBitmapImageRep.init(cgImage: checkImage.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  192. let rWidth = resultImageRep.pixelsWide
  193. let rHeight = resultImageRep.pixelsHigh
  194. let rBitPerPixel = resultImageRep.bitsPerPixel / 8
  195. let rBytePerRow = resultImageRep.bytesPerRow
  196. let cWidth = checkImageRep.pixelsWide
  197. let cHeight = checkImageRep.pixelsHigh
  198. let cBitPerPixel = checkImageRep.bitsPerPixel / 8
  199. let cBytePerRow = checkImageRep.bytesPerRow
  200. let maxWidth = min(rWidth, cWidth) - 1
  201. let maxHeight = min(rHeight, cHeight) - 1
  202. var equalCount = 0 as Double
  203. for w in 0...maxWidth {
  204. let x = Int(w)
  205. for h in 0...maxHeight {
  206. let y = Int(h)
  207. let cColor = checkImageRep.colorAt(x: x, y: y) as! NSColor
  208. let rColor = resultImageRep.colorAt(x: x, y: y) as! NSColor
  209. if (cColor.isEqual(to: rColor)) {
  210. equalCount = equalCount + 1
  211. }
  212. }
  213. }
  214. return Double(equalCount/(Double(cWidth) * Double(cHeight)) * 100.0)
  215. }
  216. /// Path
  217. func originFileDirectory() -> String {
  218. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kOriginPathComponent)")
  219. }
  220. func resultFileDirectory() -> String {
  221. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kResultPathComponent)")
  222. }
  223. func checkFileDirectory() -> String {
  224. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kCheckPathComponent)")
  225. }
  226. // check File Exist
  227. func hasOriginFile() -> Bool {
  228. if nil != self.originFileDirectory() && FileManager.default.fileExists(atPath: self.originFileDirectory()) {
  229. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.originFileDirectory())
  230. return (files ?? []).count > 0
  231. }
  232. return false
  233. }
  234. func hasResultFile() -> Bool {
  235. if nil != self.resultFileDirectory() && FileManager.default.fileExists(atPath: self.resultFileDirectory()) {
  236. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.resultFileDirectory())
  237. return (files ?? []).count > 0
  238. }
  239. return false
  240. }
  241. ///
  242. func clearCacheFiles() {
  243. let resultDirectory = self.resultFileDirectory()
  244. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultDirectory)
  245. for item in NSArray(array: searchItems) {
  246. let path = NSString(string: resultDirectory).appendingPathComponent(item as! String)
  247. try! FileManager.default.removeItem(atPath: path)
  248. }
  249. }
  250. }
  251. extension AutoTest {
  252. func stringToImage(_ string:String) ->NSImage? {
  253. let length = Int(string.lengthOfBytes(using: .utf8)/2)
  254. var bytes = malloc(length)!
  255. for i in 0..<length {
  256. let index = i
  257. let subString = String(NSString(string: string).substring(with: NSMakeRange(Int(index * 2), 2)))
  258. bytes.storeBytes(of: UInt8(hexForString(subString)), as: UInt8.self)
  259. }
  260. var data = Data.init(bytes: bytes, count: length)
  261. let image = NSImage.init(data: data)
  262. return image
  263. }
  264. func hexForString(_ string:String) -> UInt8 {
  265. let chars = string.utf8CString
  266. if (string.lengthOfBytes(using: .utf8) >= 2) {
  267. return UInt8(intvalueForChar(chars[0]) * 16 + intvalueForChar(chars[1]))
  268. }
  269. return UInt8(0)
  270. }
  271. func intvalueForChar(_ char:CChar) -> UInt8 {
  272. let iValue = char
  273. // 0 ~ 9s
  274. if iValue >= 48 && iValue <= 57 {
  275. return UInt8(iValue - 48)
  276. }else if iValue >= 65 && iValue <= 70 {
  277. return UInt8(iValue - 65 + 10)
  278. }else if iValue >= 97 && iValue <= 102 {
  279. return UInt8(iValue - 97 + 10)
  280. }
  281. return UInt8(0)
  282. }
  283. }