AutoTest.swift 25 KB

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