AutoTest.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. var tDegree = Double(0);
  102. var tCount = Int(0)
  103. for fileName in files {
  104. let fName = NSString(string: fileName).deletingPathExtension
  105. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  106. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  107. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  108. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】开始转换文件 \"\(fName)\"\n",
  109. attributes:[.foregroundColor : NSColor.blue]))
  110. // ...
  111. // 执行转换过程
  112. let convertSemaphore = DispatchSemaphore(value: 0)
  113. var success = false
  114. let convertQueue = DispatchQueue.global()
  115. convertQueue.async {
  116. success = FileConverter.shared().converter(originPath, inDesPath: resultPath)
  117. convertSemaphore.signal()
  118. }
  119. convertSemaphore.wait()
  120. var isDirectory = ObjCBool(false)
  121. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) && success {
  122. // compare screenshoot between result file with check file
  123. if needCompare {
  124. let items = NSMutableArray()
  125. if (isDirectory.boolValue) {
  126. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  127. for item in NSArray(array: searchItems) {
  128. let ext = NSString(string: item as! String).pathExtension.lowercased()
  129. if NSArray(array: [_extention]).contains(ext) {
  130. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  131. items.add(fileName)
  132. }
  133. }
  134. }else {
  135. items.add(fName)
  136. }
  137. var subDegree = Double(0);
  138. var subCount = Int(0)
  139. for item in items {
  140. let subFileName = item as! String
  141. let subResultPath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"."+_extention)
  142. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subFileName+".\(_extention)")\"快照生成中\n",
  143. attributes:[.foregroundColor : NSColor.black]))
  144. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  145. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  146. let processThumbSemaphore = DispatchSemaphore(value: 0)
  147. var processSuccess = false
  148. let thumbnailQueue = DispatchQueue.global()
  149. thumbnailQueue.async {
  150. processSuccess = ProcessThumbnal.process(subResultPath, desPath: rComparePath, outputSize: CGSize.init(width: 2048, height: 2048))
  151. if ( processSuccess &&
  152. FileManager.default.fileExists(atPath: rComparePath)) {
  153. let degree = ImageProcess.compareJPEG(rComparePath, checkPath: cComparePath)
  154. if isDirectory.boolValue {
  155. TestDegreeManager.shared().set(degree,
  156. fileType: self.fileType(),
  157. type: self.type(),
  158. fileName: fileName,
  159. refFilePath: subFileName)
  160. }
  161. if degree == -1 {
  162. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比失败,生成快照失败或无比对文件\n",
  163. attributes:[.foregroundColor : NSColor.red]))
  164. }else {
  165. var color = NSColor.black
  166. if fabs(degree-100.0) >= 0.01 {
  167. color = NSColor.red
  168. }
  169. subDegree += degree
  170. subCount += 1
  171. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比完成,图像相似度 \(degree)%\n",
  172. attributes:[.foregroundColor : color]))
  173. }
  174. }else {
  175. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照生成失败\n",
  176. attributes:[.foregroundColor : NSColor.red]))
  177. }
  178. processThumbSemaphore.signal()
  179. }
  180. processThumbSemaphore.wait()
  181. }
  182. if subCount != 0 {
  183. subDegree = subDegree/Double(subCount)
  184. }else {
  185. subDegree = 0.0
  186. }
  187. TestDegreeManager.shared().set(subDegree,
  188. fileType: self.fileType(),
  189. type: self.type(),
  190. fileName: fileName)
  191. tDegree += subDegree;
  192. tCount += 1
  193. }
  194. }else {
  195. reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档失败!\n",
  196. attributes:[.foregroundColor : NSColor.red]))
  197. }
  198. }
  199. TestDegreeManager.shared().set(((tCount != 0) ? tDegree/Double(tCount) : 0.0),
  200. fileType: _fileType,
  201. type: _type)
  202. _status = .Finished
  203. }else {
  204. _status = .Normal
  205. }
  206. }
  207. func testReport() -> NSAttributedString? {
  208. return reportString
  209. }
  210. func degree() -> Double {
  211. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type())
  212. }
  213. // func testReportOfFile(_ fileName:String) -> NSAttributedString? {
  214. //
  215. // }
  216. func degreeOfFile(_ fileName:String) -> Double {
  217. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName)
  218. }
  219. func degreeOfFile(_ fileName:String, refFilePath:String?) -> Double {
  220. if refFilePath != nil {
  221. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName, refFilePath: refFilePath)
  222. }else {
  223. return degreeOfFile(fileName)
  224. }
  225. }
  226. // Update Refrence image
  227. func canUpdateRefImage() -> Bool {
  228. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  229. let checkDirectory = self.checkFileDirectory()
  230. let originDirectory = self.originFileDirectory()
  231. let resultDirectory = self.resultFileDirectory()
  232. for fileName in files {
  233. let fName = NSString(string: fileName).deletingPathExtension
  234. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  235. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  236. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  237. var isDirectory = ObjCBool(false)
  238. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  239. // compare screenshoot between result file with check file
  240. let items = NSMutableArray()
  241. if (isDirectory.boolValue) {
  242. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  243. for item in NSArray(array: searchItems) {
  244. let ext = NSString(string: item as! String).pathExtension.lowercased()
  245. if NSArray(array: [_extention]).contains(ext) {
  246. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  247. items.add(fileName)
  248. }
  249. }
  250. }else {
  251. items.add(fName)
  252. }
  253. for item in items {
  254. let subFileName = item as! String
  255. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  256. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  257. if FileManager.default.fileExists(atPath: rComparePath) {
  258. if !FileManager.default.fileExists(atPath: cComparePath) {
  259. return true
  260. }
  261. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  262. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  263. if rfs.int64Value != cfs.int64Value {
  264. return true
  265. }
  266. }
  267. }
  268. }
  269. }
  270. return false
  271. }
  272. func updateRefImage() {
  273. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  274. for fileName in files {
  275. updateRefImage(fileName)
  276. }
  277. }
  278. func canUpdateRefImage(_ fileName:String) -> Bool {
  279. let checkDirectory = self.checkFileDirectory()
  280. let originDirectory = self.originFileDirectory()
  281. let resultDirectory = self.resultFileDirectory()
  282. let fName = NSString(string: fileName).deletingPathExtension
  283. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  284. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  285. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  286. var isDirectory = ObjCBool(false)
  287. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  288. // compare screenshoot between result file with check file
  289. let items = NSMutableArray()
  290. if (isDirectory.boolValue) {
  291. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  292. for item in NSArray(array: searchItems) {
  293. let ext = NSString(string: item as! String).pathExtension.lowercased()
  294. if NSArray(array: [_extention]).contains(ext) {
  295. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  296. items.add(fileName)
  297. }
  298. }
  299. }else {
  300. items.add(fName)
  301. }
  302. for item in items {
  303. let subFileName = item as! String
  304. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  305. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  306. if FileManager.default.fileExists(atPath: rComparePath) {
  307. if !FileManager.default.fileExists(atPath: cComparePath) {
  308. return true
  309. }
  310. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  311. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  312. if rfs.int64Value != cfs.int64Value {
  313. return true
  314. }
  315. }
  316. }
  317. }
  318. return false
  319. }
  320. func updateRefImage(_ fileName:String) {
  321. let checkDirectory = self.checkFileDirectory()
  322. let originDirectory = self.originFileDirectory()
  323. let resultDirectory = self.resultFileDirectory()
  324. let fName = NSString(string: fileName).deletingPathExtension
  325. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  326. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  327. let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  328. var isDirectory = ObjCBool(false)
  329. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  330. // compare screenshoot between result file with check file
  331. let items = NSMutableArray()
  332. if (isDirectory.boolValue) {
  333. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  334. for item in NSArray(array: searchItems) {
  335. let ext = NSString(string: item as! String).pathExtension.lowercased()
  336. if NSArray(array: [_extention]).contains(ext) {
  337. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  338. items.add(fileName)
  339. }
  340. }
  341. }else {
  342. items.add(fName)
  343. }
  344. for item in items {
  345. let subFileName = item as! String
  346. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  347. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  348. if FileManager.default.fileExists(atPath: rComparePath) {
  349. if FileManager.default.fileExists(atPath: cComparePath) {
  350. try! FileManager.default.removeItem(atPath: cComparePath)
  351. }
  352. try! FileManager.default.createDirectory(atPath: NSString(string: cComparePath).deletingLastPathComponent,
  353. withIntermediateDirectories: true)
  354. try! FileManager.default.copyItem(atPath: rComparePath, toPath: cComparePath)
  355. }
  356. }
  357. }
  358. }
  359. func compareFiles() -> NSArray? {
  360. let items = NSMutableArray()
  361. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  362. for fileName in files {
  363. let sItems = compareFiles(fileName)
  364. if sItems != nil && sItems!.count != 0 {
  365. items.addObjects(from: sItems as! [Any])
  366. }
  367. }
  368. return items
  369. }
  370. func compareFiles(_ fileName: String) -> NSArray? {
  371. let files = NSMutableArray()
  372. let checkDirectory = self.checkFileDirectory()
  373. let originDirectory = self.originFileDirectory()
  374. let resultDirectory = self.resultFileDirectory()
  375. let fName = NSString(string: fileName).deletingPathExtension
  376. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  377. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  378. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  379. var isDirectory = ObjCBool(false)
  380. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  381. // compare screenshoot between result file with check file
  382. let items = NSMutableArray()
  383. if (isDirectory.boolValue) {
  384. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  385. for item in NSArray(array: searchItems) {
  386. let ext = NSString(string: item as! String).pathExtension.lowercased()
  387. if NSArray(array: [_extention]).contains(ext) {
  388. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  389. items.add(fileName)
  390. }
  391. }
  392. }else {
  393. items.add(fName)
  394. }
  395. let nitems = items.sortedArray { str1, str2 in
  396. let s1 = str1 as! String
  397. let s2 = str2 as! String
  398. return NSString(string: s1).compare(s2)
  399. }
  400. for item in nitems {
  401. let subFileName = item as! String
  402. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  403. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  404. let fileInfo = NSMutableDictionary.fileInfoWith(fileName,
  405. refFilePath: (isDirectory.boolValue ? subFileName : nil),
  406. resultPath: rComparePath,
  407. comparePath: cComparePath,
  408. objc: self)
  409. files.add(fileInfo)
  410. }
  411. }
  412. return files
  413. }
  414. /// Path
  415. func originFileDirectory() -> String {
  416. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kOriginPathComponent)")
  417. }
  418. func resultFileDirectory() -> String {
  419. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kResultPathComponent)")
  420. }
  421. func checkFileDirectory() -> String {
  422. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kCheckPathComponent)")
  423. }
  424. // check File Exist
  425. func hasOriginFile() -> Bool {
  426. if nil != self.originFileDirectory() && FileManager.default.fileExists(atPath: self.originFileDirectory()) {
  427. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.originFileDirectory())
  428. return (files ?? []).count > 0
  429. }
  430. return false
  431. }
  432. func hasResultFile() -> Bool {
  433. if nil != self.resultFileDirectory() && FileManager.default.fileExists(atPath: self.resultFileDirectory()) {
  434. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.resultFileDirectory())
  435. return (files ?? []).count > 0
  436. }
  437. return false
  438. }
  439. ///
  440. func clearCacheFiles() {
  441. reportString = NSMutableAttributedString.init();
  442. let resultDirectory = self.resultFileDirectory()
  443. var isDirectory = ObjCBool(false)
  444. if FileManager.default.fileExists(atPath: resultDirectory, isDirectory: &isDirectory) && isDirectory.boolValue {
  445. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultDirectory)
  446. for item in NSArray(array: searchItems) {
  447. let path = NSString(string: resultDirectory).appendingPathComponent(item as! String)
  448. if FileManager.default.fileExists(atPath: path) {
  449. try! FileManager.default.removeItem(atPath: path)
  450. }
  451. }
  452. }
  453. }
  454. }
  455. extension AutoTest {
  456. func stringToImage(_ string:String) ->NSImage? {
  457. let length = Int(string.lengthOfBytes(using: .utf8)/2)
  458. var bytes = malloc(length)!
  459. for i in 0..<length {
  460. let index = i
  461. let subString = String(NSString(string: string).substring(with: NSMakeRange(Int(index * 2), 2)))
  462. bytes.storeBytes(of: UInt8(hexForString(subString)), as: UInt8.self)
  463. }
  464. var data = Data.init(bytes: bytes, count: length)
  465. let image = NSImage.init(data: data)
  466. return image
  467. }
  468. func hexForString(_ string:String) -> UInt8 {
  469. let chars = string.utf8CString
  470. if (string.lengthOfBytes(using: .utf8) >= 2) {
  471. return UInt8(intvalueForChar(chars[0]) * 16 + intvalueForChar(chars[1]))
  472. }
  473. return UInt8(0)
  474. }
  475. func intvalueForChar(_ char:CChar) -> UInt8 {
  476. let iValue = char
  477. // 0 ~ 9s
  478. if iValue >= 48 && iValue <= 57 {
  479. return UInt8(iValue - 48)
  480. }else if iValue >= 65 && iValue <= 70 {
  481. return UInt8(iValue - 65 + 10)
  482. }else if iValue >= 97 && iValue <= 102 {
  483. return UInt8(iValue - 97 + 10)
  484. }
  485. return UInt8(0)
  486. }
  487. }