AutoTest.swift 25 KB

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