AutoTest.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. // Image compare
  180. func compareJPEG(_ resultPath:String, checkPath:String) -> Double {
  181. if !FileManager.default.fileExists(atPath: resultPath) || !FileManager.default.fileExists(atPath: checkPath) {
  182. return -1
  183. }
  184. let rImage = NSImage.init(contentsOfFile: resultPath) ?? nil
  185. let cImage = NSImage.init(contentsOfFile: checkPath) ?? nil
  186. if nil == rImage || nil == cImage {
  187. return -1
  188. }
  189. let resultImage = rImage as! NSImage
  190. let checkImage = cImage as! NSImage
  191. let resultImageRep = NSBitmapImageRep.init(cgImage: resultImage.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  192. let checkImageRep = NSBitmapImageRep.init(cgImage: checkImage.cgImage(forProposedRect: nil, context: nil, hints: nil)!)
  193. let rWidth = resultImageRep.pixelsWide
  194. let rHeight = resultImageRep.pixelsHigh
  195. let rBitPerPixel = resultImageRep.bitsPerPixel / 8
  196. let rBytePerRow = resultImageRep.bytesPerRow
  197. let cWidth = checkImageRep.pixelsWide
  198. let cHeight = checkImageRep.pixelsHigh
  199. let cBitPerPixel = checkImageRep.bitsPerPixel / 8
  200. let cBytePerRow = checkImageRep.bytesPerRow
  201. let maxWidth = min(rWidth, cWidth) - 1
  202. let maxHeight = min(rHeight, cHeight) - 1
  203. // check background color
  204. // 挑选图片 对角斜线 上的相素进行识别
  205. var markInfo = NSMutableDictionary.init()
  206. for w in 0...maxWidth {
  207. let x = Int(w)
  208. for mark in 0...1 {
  209. let color = checkImageRep.colorAt(x: min(x, cWidth-1), y: min(mark == 0 ? x : (maxWidth - x), (cHeight-1))) as! NSColor
  210. let r = Int(color.redComponent*255)
  211. let g = Int(color.greenComponent*255)
  212. let b = Int(color.blueComponent*255)
  213. if (markInfo[color] != nil) {
  214. let count = (markInfo[color] as? NSNumber)!.intValue ?? 0
  215. markInfo[color] = NSNumber.init(value: count + 1)
  216. }else {
  217. markInfo[color] = NSNumber.init(value: 1)
  218. }
  219. }
  220. }
  221. var maxCount = Int(0);
  222. var bgColor : NSColor? = nil
  223. for color in markInfo.allKeys {
  224. let count = (markInfo[color] as? NSNumber)!.intValue ?? 0
  225. if count > maxCount {
  226. maxCount = count
  227. bgColor = color as! NSColor
  228. }
  229. }
  230. if nil != bgColor {
  231. NSLog(String("识别到背景色\(bgColor)"))
  232. }
  233. // Compare
  234. var equalCount = 0 as Double
  235. var bgCount = 0 as Double
  236. for w in 0...maxWidth {
  237. let x = Int(w)
  238. for h in 0...maxHeight {
  239. let y = Int(h)
  240. let cColor = checkImageRep.colorAt(x: x, y: y) as! NSColor
  241. let rColor = resultImageRep.colorAt(x: x, y: y) as! NSColor
  242. if (cColor.isEqual(to: rColor)) {
  243. equalCount = equalCount + 1
  244. if bgColor != nil &&
  245. cColor.isEqual(to: bgColor) {
  246. bgCount += 1
  247. }
  248. }
  249. }
  250. }
  251. NSLog(String("过滤点数目\(bgCount)"))
  252. return Double(max(equalCount-bgCount, 1)/(max(Double(cWidth) * Double(cHeight)-bgCount, 1)) * 100.0)
  253. }
  254. // Update Refrence image
  255. func canUpdateRefImage() -> Bool {
  256. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  257. let checkDirectory = self.checkFileDirectory()
  258. let originDirectory = self.originFileDirectory()
  259. let resultDirectory = self.resultFileDirectory()
  260. for fileName in files {
  261. let fName = NSString(string: fileName).deletingPathExtension
  262. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  263. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  264. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  265. var isDirectory = ObjCBool(false)
  266. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  267. // compare screenshoot between result file with check file
  268. let items = NSMutableArray()
  269. if (isDirectory.boolValue) {
  270. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  271. for item in NSArray(array: searchItems) {
  272. let ext = NSString(string: item as! String).pathExtension.lowercased()
  273. if NSArray(array: [_extention]).contains(ext) {
  274. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  275. items.add(fileName)
  276. }
  277. }
  278. }else {
  279. items.add(fName)
  280. }
  281. for item in items {
  282. let subFileName = item as! String
  283. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"_\(DataModel.shared.latestReportID()!).jpg")
  284. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  285. if FileManager.default.fileExists(atPath: rComparePath) {
  286. if !FileManager.default.fileExists(atPath: cComparePath) {
  287. return true
  288. }
  289. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  290. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  291. if rfs.int64Value != cfs.int64Value {
  292. return true
  293. }
  294. }
  295. }
  296. }
  297. }
  298. return false
  299. }
  300. func updateRefImage() {
  301. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  302. for fileName in files {
  303. updateRefImage(fileName)
  304. }
  305. }
  306. func canUpdateRefImage(_ fileName:String) -> Bool {
  307. let checkDirectory = self.checkFileDirectory()
  308. let originDirectory = self.originFileDirectory()
  309. let resultDirectory = self.resultFileDirectory()
  310. let fName = NSString(string: fileName).deletingPathExtension
  311. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  312. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  313. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  314. var isDirectory = ObjCBool(false)
  315. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  316. // compare screenshoot between result file with check file
  317. let items = NSMutableArray()
  318. if (isDirectory.boolValue) {
  319. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  320. for item in NSArray(array: searchItems) {
  321. let ext = NSString(string: item as! String).pathExtension.lowercased()
  322. if NSArray(array: [_extention]).contains(ext) {
  323. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  324. items.add(fileName)
  325. }
  326. }
  327. }else {
  328. items.add(fName)
  329. }
  330. for item in items {
  331. let subFileName = item as! String
  332. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"_\(DataModel.shared.latestReportID()!).jpg")
  333. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  334. if FileManager.default.fileExists(atPath: rComparePath) {
  335. if !FileManager.default.fileExists(atPath: cComparePath) {
  336. return true
  337. }
  338. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  339. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  340. if rfs.int64Value != cfs.int64Value {
  341. return true
  342. }
  343. }
  344. }
  345. }
  346. return false
  347. }
  348. func updateRefImage(_ fileName:String) {
  349. let checkDirectory = self.checkFileDirectory()
  350. let originDirectory = self.originFileDirectory()
  351. let resultDirectory = self.resultFileDirectory()
  352. let fName = NSString(string: fileName).deletingPathExtension
  353. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  354. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  355. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  356. var isDirectory = ObjCBool(false)
  357. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  358. // compare screenshoot between result file with check file
  359. let items = NSMutableArray()
  360. if (isDirectory.boolValue) {
  361. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  362. for item in NSArray(array: searchItems) {
  363. let ext = NSString(string: item as! String).pathExtension.lowercased()
  364. if NSArray(array: [_extention]).contains(ext) {
  365. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  366. items.add(fileName)
  367. }
  368. }
  369. }else {
  370. items.add(fName)
  371. }
  372. for item in items {
  373. let subFileName = item as! String
  374. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"_\(DataModel.shared.latestReportID()!).jpg")
  375. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  376. if FileManager.default.fileExists(atPath: rComparePath) {
  377. if FileManager.default.fileExists(atPath: cComparePath) {
  378. try! FileManager.default.removeItem(atPath: cComparePath)
  379. }
  380. try! FileManager.default.createDirectory(atPath: NSString(string: cComparePath).deletingLastPathComponent,
  381. withIntermediateDirectories: true)
  382. try! FileManager.default.copyItem(atPath: rComparePath, toPath: cComparePath)
  383. }
  384. }
  385. }
  386. }
  387. /// Path
  388. func originFileDirectory() -> String {
  389. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kOriginPathComponent)")
  390. }
  391. func resultFileDirectory() -> String {
  392. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kResultPathComponent)")
  393. }
  394. func checkFileDirectory() -> String {
  395. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kCheckPathComponent)")
  396. }
  397. // check File Exist
  398. func hasOriginFile() -> Bool {
  399. if nil != self.originFileDirectory() && FileManager.default.fileExists(atPath: self.originFileDirectory()) {
  400. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.originFileDirectory())
  401. return (files ?? []).count > 0
  402. }
  403. return false
  404. }
  405. func hasResultFile() -> Bool {
  406. if nil != self.resultFileDirectory() && FileManager.default.fileExists(atPath: self.resultFileDirectory()) {
  407. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.resultFileDirectory())
  408. return (files ?? []).count > 0
  409. }
  410. return false
  411. }
  412. ///
  413. func clearCacheFiles() {
  414. reportString = NSMutableAttributedString.init();
  415. let resultDirectory = self.resultFileDirectory()
  416. var isDirectory = ObjCBool(false)
  417. if FileManager.default.fileExists(atPath: resultDirectory, isDirectory: &isDirectory) && isDirectory.boolValue {
  418. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultDirectory)
  419. for item in NSArray(array: searchItems) {
  420. let path = NSString(string: resultDirectory).appendingPathComponent(item as! String)
  421. if FileManager.default.fileExists(atPath: path) {
  422. try! FileManager.default.removeItem(atPath: path)
  423. }
  424. }
  425. }
  426. }
  427. }
  428. extension AutoTest {
  429. func stringToImage(_ string:String) ->NSImage? {
  430. let length = Int(string.lengthOfBytes(using: .utf8)/2)
  431. var bytes = malloc(length)!
  432. for i in 0..<length {
  433. let index = i
  434. let subString = String(NSString(string: string).substring(with: NSMakeRange(Int(index * 2), 2)))
  435. bytes.storeBytes(of: UInt8(hexForString(subString)), as: UInt8.self)
  436. }
  437. var data = Data.init(bytes: bytes, count: length)
  438. let image = NSImage.init(data: data)
  439. return image
  440. }
  441. func hexForString(_ string:String) -> UInt8 {
  442. let chars = string.utf8CString
  443. if (string.lengthOfBytes(using: .utf8) >= 2) {
  444. return UInt8(intvalueForChar(chars[0]) * 16 + intvalueForChar(chars[1]))
  445. }
  446. return UInt8(0)
  447. }
  448. func intvalueForChar(_ char:CChar) -> UInt8 {
  449. let iValue = char
  450. // 0 ~ 9s
  451. if iValue >= 48 && iValue <= 57 {
  452. return UInt8(iValue - 48)
  453. }else if iValue >= 65 && iValue <= 70 {
  454. return UInt8(iValue - 65 + 10)
  455. }else if iValue >= 97 && iValue <= 102 {
  456. return UInt8(iValue - 97 + 10)
  457. }
  458. return UInt8(0)
  459. }
  460. }