AutoTest.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. let operateQueue = OperationQueue()
  11. class AutoTest : NSObject, AutoTestProtocal {
  12. var reportString : NSMutableAttributedString? = nil
  13. public var _status : AutoTestStatus = .Normal
  14. var _fileType : String = "RTF"
  15. var _type : String = "Others"
  16. var _extention : String = "rtf"
  17. var _name : String = "对照测试"
  18. var _params : NSDictionary = [:]
  19. var testFiles : NSArray = NSArray()
  20. var convertFiles : NSMutableArray = NSMutableArray()
  21. var convertProgress : Double = 0.0
  22. var compareFinishedFiles : NSMutableArray = NSMutableArray()
  23. var compareProgress : Double = 0.0
  24. var testlog : (_ msg:String, _ progress:Double) -> () = {(msg, progress) in
  25. }
  26. class func autoTestFor(_ fileType:NSString ,type:NSString) -> AutoTest? {
  27. let key = String(fileType) + "." + String(type)
  28. if cacheObjects.value(forKey: key) != nil {
  29. let object = cacheObjects.value(forKey: key)
  30. return object as? AutoTest
  31. }
  32. // if let cacheObject as AutoTest {
  33. // return cacheObject
  34. // }
  35. let fileTypes = testTypeInfo[fileType] as! NSArray
  36. let clsname = "KdanAuto"//Bundle.main.infoDictionary! ["CFBundleExecutable"]
  37. for item in fileTypes {
  38. let cItem = item as! NSDictionary
  39. let cType = cItem["Type"] as! NSString
  40. let cExtention = cItem["Extention"] as! NSString
  41. let cName = cItem["Name"] as! NSString
  42. let cParams = cItem["Params"] as? NSDictionary
  43. if (cType.isEqual(to: type)) {
  44. let className = String((clsname )+"."+(cItem["Class"] as! String))
  45. let cl = NSClassFromString(className) as! AutoTest.Type
  46. let object = cl.shared()
  47. object?._fileType = fileType as String
  48. object?._type = String(cType)
  49. object?._extention = String(cExtention)
  50. object?._name = String(cName)
  51. if nil != cParams {
  52. object?._params = cParams ?? [:];
  53. }
  54. cacheObjects.setValue(object, forKey: key)
  55. return object
  56. }
  57. }
  58. let object = AutoTest.shared()
  59. object?._fileType = fileType as String
  60. object?._type = String(cType)
  61. object?._extention = ""
  62. object?._name = "对照测试"
  63. cacheObjects.setValue(object, forKey: key)
  64. return object
  65. }
  66. class func shared() -> AutoTest? {
  67. return AutoTest()
  68. }
  69. func fileType() -> String {
  70. return _fileType
  71. }
  72. func type() -> String {
  73. return _type
  74. }
  75. func name() -> String {
  76. return _name
  77. }
  78. func extention() -> String {
  79. return _extention
  80. }
  81. func params() -> NSDictionary {
  82. return _params
  83. }
  84. func keys() -> NSArray {
  85. return ["快照"]
  86. }
  87. func selectedKeys() -> NSArray {
  88. let userDefaults = UserDefaults.standard
  89. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  90. if userDefaults.value(forKey: key) != nil {
  91. return userDefaults.value(forKey: key) as! NSArray
  92. }
  93. self.setSelectedKeys(self.keys())
  94. return self.keys()
  95. }
  96. func setSelectedKeys(_ keys: NSArray) {
  97. let userDefaults = UserDefaults.standard
  98. let key = self.fileType() + "." + self.type() + ".selectedKeys"
  99. userDefaults.setValue(keys, forKey: key)
  100. userDefaults.synchronize()
  101. }
  102. func needCompareTest() -> Bool {
  103. return self.selectedKeys().contains("快照")
  104. }
  105. func status() -> AutoTestStatus {
  106. return _status
  107. }
  108. func setStatus(_ status:AutoTestStatus) {
  109. _status = status
  110. }
  111. // Auto Test
  112. func autoTest(_ complention:@escaping (_ object:AutoTest, _ report:NSAttributedString?) -> ()) {
  113. self.compareFinishedFiles.removeAllObjects();
  114. self.convertFiles.removeAllObjects()
  115. NSLog(String("转换\(self.type())"))
  116. let needCompare = self.selectedKeys().contains("快照")
  117. if !needCompare {
  118. // 未勾选 ”快照“ 选项
  119. self._status = .Finished
  120. complention(self, self.reportString)
  121. return
  122. }
  123. clearCacheFiles()
  124. if hasOriginFile() {
  125. //目录中有需要执行对照的文件
  126. DispatchQueue.global().async {
  127. self._status = .Process
  128. self.reportString = NSMutableAttributedString.init(string: "\n【\(String(self.fileType())) - \(self.name())】快照比对开始!\n",
  129. attributes:[.foregroundColor : NSColor.blue])
  130. let files = DataModel.shared.originFilesFor(self.fileType(), type: self.type()) as [String]
  131. self.testFiles = NSArray(array: files);
  132. let checkDirectory = self.checkFileDirectory()
  133. let originDirectory = self.originFileDirectory()
  134. let resultDirectory = self.resultFileDirectory()
  135. if (files.count > 0) {
  136. try? FileManager.default.createDirectory(atPath: checkDirectory, withIntermediateDirectories: true);
  137. try? FileManager.default.createDirectory(atPath: resultDirectory, withIntermediateDirectories: true);
  138. }
  139. var tDegree = Double(0);
  140. var tCount = Int(0)
  141. var fileIndex = 0
  142. var compareIndex = 0;
  143. var convertFinished = false;
  144. // 用 Block 递归调用形式,确保转档单任务执行
  145. var convertFileBlock = { (files:[String]) in }
  146. convertFileBlock = { (files:[String]) in
  147. if (fileIndex >= files.count) {
  148. convertFinished = true;
  149. return
  150. }
  151. //
  152. let fileName = files[fileIndex];
  153. autoreleasepool {
  154. let checkDirectory = self.checkFileDirectory()
  155. let originDirectory = self.originFileDirectory()
  156. let resultDirectory = self.resultFileDirectory()
  157. let fName = NSString(string: fileName).deletingPathExtension
  158. let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  159. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+self.extention())
  160. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  161. // self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】开始转换文件 \"\(fName)\"\n",
  162. // attributes:[.foregroundColor : NSColor.blue]))
  163. // ...
  164. // 执行异步转换过程
  165. let index = self.testFiles.index(of: fileName);
  166. if (index != NSNotFound) {
  167. self.convertProgress = Double(index) / Double(self.testFiles.count)
  168. }
  169. self.convertFiles.add(fileName);
  170. self.testlog("开始转换:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  171. self.process(originPath, resultPath: resultPath) { status in
  172. DispatchQueue.global().async {
  173. Thread.sleep(forTimeInterval: 0.3)
  174. fileIndex += 1;
  175. convertFileBlock(files)
  176. self.compareResult(fileName, resultPath: resultPath, status: status, needCompare: needCompare) { degree in
  177. autoreleasepool {
  178. if (degree >= 0.0) {
  179. tDegree += degree;
  180. tCount += 1;
  181. }
  182. compareIndex += 1;
  183. if (convertFinished && compareIndex >= files.count) {
  184. //所有任务已经执行完成
  185. TestDegreeManager.shared().set(((tCount != 0) ? tDegree/Double(tCount) : 0.0),
  186. fileType: self.fileType(),
  187. type: self.type())
  188. self._status = .Finished
  189. DispatchQueue.main.async {
  190. complention(self, self.reportString);
  191. }
  192. }
  193. }
  194. };
  195. }
  196. }
  197. }
  198. }
  199. // 启动第0号任务
  200. convertFileBlock(files);
  201. }
  202. }else {
  203. _status = .Normal
  204. DispatchQueue.main.async {
  205. complention(self, nil)
  206. }
  207. }
  208. }
  209. func process(_ originPath:String, resultPath:String, complention:@escaping (_ status:Int) -> ()) {
  210. return process(originPath, resultPath: resultPath, params: self.params(), complention: complention)
  211. }
  212. func process(_ originPath:String, resultPath:String, params:NSDictionary, complention:@escaping (_ status:Int) -> ()) {
  213. FileConverter.shared().converter(originPath, inDesPath: resultPath, params: params) { status in
  214. // 修复转 PNG 实际图片为 JPG 问题, 导致无法匹配问题
  215. if (NSArray(array: ["png", "PNG"]).contains(NSString(string: resultPath).pathExtension)) {
  216. let items = (FileManager.default.subpaths(atPath: resultPath) ?? []) as [String]
  217. for item in items {
  218. if NSArray(array: ["jpg", "JPG"]).contains(NSString(string:item).pathExtension) {
  219. let path = NSString(string: resultPath).appendingPathComponent(item);
  220. try? FileManager.default.moveItem(atPath: path,
  221. toPath: NSString(string: path).deletingPathExtension+".png");
  222. }
  223. }
  224. }
  225. complention(status)
  226. }
  227. }
  228. func compareResult(_ fileName:String, resultPath:String, status:Int, needCompare:Bool, complention:@escaping (_ degree:Double) -> ()) {
  229. NSLog("开始识别:\(fileName)")
  230. self.testlog("开始对比:"+fileName, (self.convertProgress + self.compareProgress)/2.0)
  231. let checkDirectory = self.checkFileDirectory()
  232. // let originDirectory = self.originFileDirectory()
  233. let resultDirectory = self.resultFileDirectory()
  234. let fName = NSString(string: fileName).deletingPathExtension
  235. var isDirectory = ObjCBool(false)
  236. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) && status == 1 {
  237. // compare screenshoot between result file with check file
  238. if needCompare {
  239. let items = NSMutableArray()
  240. if (isDirectory.boolValue) {
  241. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  242. for item in NSArray(array: searchItems) {
  243. let ext = NSString(string: item as! String).pathExtension.lowercased()
  244. if (NSArray(array: [self.extention()]).contains(ext)) {
  245. let fileName = NSString(string: fName+"."+self.extention()+"/\(item as! String)").deletingPathExtension
  246. items.add(fileName)
  247. }
  248. }
  249. }else {
  250. items.add(fName)
  251. }
  252. var subDegree = Double(0);
  253. var subCount = Int(0)
  254. var itemIndex = 0;
  255. // let maxProcessCount = min(3, max(items.count, 1))
  256. var processItemBlock = {(items:NSMutableArray) in
  257. }
  258. processItemBlock = {(items:NSMutableArray) in
  259. if (itemIndex >= items.count) {
  260. // if (itemIndex >= (items.count + (maxProcessCount - 1))) {
  261. if subCount != 0 {
  262. subDegree = subDegree/Double(subCount)
  263. }else {
  264. subDegree = 0.0
  265. }
  266. TestDegreeManager.shared().set(subDegree,
  267. fileType: self.fileType(),
  268. type: self.type(),
  269. fileName: fileName)
  270. DispatchQueue.global().async {
  271. autoreleasepool {
  272. // 执行下一个文件转档
  273. complention(subDegree)
  274. NSLog("结束识别:\(fileName)");
  275. let index = self.testFiles.index(of: fileName);
  276. if (index != NSNotFound) {
  277. self.compareProgress = Double(index) / Double(self.testFiles.count)
  278. }
  279. self.compareFinishedFiles.add(fileName);
  280. self.testlog("对比完成:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  281. }
  282. }
  283. // }
  284. return
  285. }
  286. DispatchQueue.global().async {
  287. autoreleasepool {
  288. let item = items[itemIndex]
  289. NSLog("\(itemIndex):\(item)")
  290. let subFileName = item as! String
  291. let subResultPath = NSString(string: resultDirectory).appendingPathComponent(subFileName+"."+self.extention())
  292. objc_sync_enter(self)
  293. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subFileName+".\(self.extention())")\"快照生成中\n",
  294. attributes:[.foregroundColor : NSColor.black]))
  295. objc_sync_exit(self)
  296. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  297. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  298. ProcessThumbnal.process(subResultPath, desPath: rComparePath, outputSize: CGSize.init(width: 2048, height: 2048)) { processSuccess in
  299. autoreleasepool {
  300. if ( processSuccess &&
  301. FileManager.default.fileExists(atPath: rComparePath)) {
  302. var isDirectory = ObjCBool(false)
  303. if FileManager.default.fileExists(atPath: rComparePath, isDirectory: &isDirectory) && isDirectory.boolValue {
  304. // 单个文件生成批量快照目录情形
  305. let subImages = try! FileManager.default.contentsOfDirectory(atPath: rComparePath)
  306. var compareCount = 0;
  307. for sImageName in subImages {
  308. let subImageName = sImageName
  309. autoreleasepool {
  310. let pathCompotent = "/"+subImageName
  311. ImageProcess.compareJPEG(String(rComparePath+pathCompotent), checkPath: String(cComparePath+pathCompotent), processCover: true, complention: { degree in
  312. NSLog(String("文件夹,\(subFileName+".jpg"+pathCompotent)"))
  313. TestDegreeManager.shared().set(degree, fileType: self.fileType(), type: self.type(),
  314. fileName: fileName, refFilePath: subFileName+".jpg"+pathCompotent)
  315. if degree == -1 {
  316. objc_sync_enter(self)
  317. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath+pathCompotent)\"快照对比失败,生成快照失败或无比对文件\n",
  318. attributes:[.foregroundColor : NSColor.red]))
  319. objc_sync_exit(self)
  320. }else {
  321. var color = NSColor.black
  322. if fabs(degree-100.0) >= 0.01 {
  323. color = NSColor.red
  324. }
  325. subDegree += degree
  326. subCount += 1
  327. objc_sync_enter(self)
  328. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath+pathCompotent)\"快照对比完成,图像相似度 \(degree)%\n",
  329. attributes:[.foregroundColor : color]))
  330. objc_sync_exit(self)
  331. }
  332. compareCount += 1
  333. if (compareCount >= subImages.count) {
  334. DispatchQueue.global().async {
  335. itemIndex += 1
  336. processItemBlock(items)
  337. }
  338. }
  339. })
  340. }
  341. }
  342. if (subImages.count == 0) {
  343. // complention
  344. DispatchQueue.global().async {
  345. itemIndex += 1
  346. processItemBlock(items)
  347. }
  348. return
  349. }
  350. }else {
  351. // 单个文件生成单个快照文件情形
  352. ImageProcess.compareJPEG(rComparePath, checkPath: cComparePath, processCover: true, complention: { degree in
  353. NSLog(String("非文件夹,\(subFileName+".jpg")"))
  354. TestDegreeManager.shared().set(degree, fileType: self.fileType(), type: self.type(),
  355. fileName: fileName, refFilePath: subFileName+".jpg")
  356. if degree == -1 {
  357. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比失败,生成快照失败或无比对文件\n",
  358. attributes:[.foregroundColor : NSColor.red]))
  359. }else {
  360. var color = NSColor.black
  361. if fabs(degree-100.0) >= 0.01 {
  362. color = NSColor.red
  363. }
  364. subDegree += degree
  365. subCount += 1
  366. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照对比完成,图像相似度 \(degree)%\n",
  367. attributes:[.foregroundColor : color]))
  368. }
  369. // complention
  370. DispatchQueue.global().async {
  371. itemIndex += 1
  372. processItemBlock(items)
  373. }
  374. })
  375. }
  376. }else {
  377. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(subResultPath)\"快照生成失败\n",
  378. attributes:[.foregroundColor : NSColor.red]))
  379. // complention
  380. DispatchQueue.global().async {
  381. itemIndex += 1
  382. processItemBlock(items)
  383. }
  384. }
  385. }
  386. }
  387. }
  388. }
  389. }
  390. processItemBlock(items)
  391. // while (itemIndex < (maxProcessCount - 1)) {
  392. // itemIndex += 1;
  393. // processItemBlock(items)
  394. // }
  395. return
  396. }
  397. }else {
  398. if (status == 0) {
  399. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档失败!\n",
  400. attributes:[.foregroundColor : NSColor.red]))
  401. }else if (status == -1 || status == -2) {
  402. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"文档无法打开!\n",
  403. attributes:[.foregroundColor : NSColor.red]))
  404. }else if (status == -3) {
  405. self.reportString?.append(NSMutableAttributedString.init(string: "【\(String(self.fileType())) - \(self.name())】文件 \"\(fName)\"转档中 Crash!\n",
  406. attributes:[.foregroundColor : NSColor.red]))
  407. }
  408. }
  409. DispatchQueue.global().async {
  410. autoreleasepool {
  411. // 执行下一个文件转档
  412. NSLog("结束识别:\(fileName)");
  413. let index = self.testFiles.index(of: fileName);
  414. if (index != NSNotFound) {
  415. self.compareProgress = Double(index) / Double(self.testFiles.count)
  416. }
  417. self.compareFinishedFiles.add(fileName);
  418. self.testlog("对比完成:"+fileName, (self.compareProgress + self.convertProgress)/2.0)
  419. complention(0)
  420. }
  421. }
  422. }
  423. ///
  424. func testReport() -> NSAttributedString? {
  425. return reportString
  426. }
  427. func degree() -> Double {
  428. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type())
  429. }
  430. // func testReportOfFile(_ fileName:String) -> NSAttributedString? {
  431. //
  432. // }
  433. func degreeOfFile(_ fileName:String) -> Double {
  434. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName)
  435. }
  436. func degreeOfFile(_ fileName:String, refFilePath:String?) -> Double {
  437. if refFilePath != nil {
  438. return TestDegreeManager.shared().degreeFor(self.fileType(), type: self.type(), fileName: fileName, refFilePath: refFilePath)
  439. }else {
  440. return degreeOfFile(fileName)
  441. }
  442. }
  443. // Update Refrence image
  444. func canUpdateRefImage() -> Bool {
  445. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  446. let checkDirectory = self.checkFileDirectory()
  447. // let originDirectory = self.originFileDirectory()
  448. let resultDirectory = self.resultFileDirectory()
  449. for fileName in files {
  450. let fName = NSString(string: fileName).deletingPathExtension
  451. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  452. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  453. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  454. var isDirectory = ObjCBool(false)
  455. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  456. // compare screenshoot between result file with check file
  457. let items = NSMutableArray()
  458. if (isDirectory.boolValue) {
  459. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  460. for item in NSArray(array: searchItems) {
  461. let ext = NSString(string: item as! String).pathExtension.lowercased()
  462. if NSArray(array: [_extention]).contains(ext) {
  463. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  464. items.add(fileName)
  465. }
  466. }
  467. }else {
  468. items.add(fName)
  469. }
  470. for item in items {
  471. let subFileName = item as! String
  472. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  473. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  474. if FileManager.default.fileExists(atPath: rComparePath) {
  475. if !FileManager.default.fileExists(atPath: cComparePath) {
  476. return true
  477. }
  478. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  479. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  480. if rfs.int64Value != cfs.int64Value {
  481. return true
  482. }
  483. }
  484. }
  485. }
  486. }
  487. return false
  488. }
  489. func updateRefImage() {
  490. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  491. for fileName in files {
  492. updateRefImage(fileName)
  493. }
  494. }
  495. func canUpdateRefImage(_ fileName:String) -> Bool {
  496. let checkDirectory = self.checkFileDirectory()
  497. // let originDirectory = self.originFileDirectory()
  498. let resultDirectory = self.resultFileDirectory()
  499. let fName = NSString(string: fileName).deletingPathExtension
  500. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  501. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  502. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  503. var isDirectory = ObjCBool(false)
  504. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  505. // compare screenshoot between result file with check file
  506. let items = NSMutableArray()
  507. if (isDirectory.boolValue) {
  508. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  509. for item in NSArray(array: searchItems) {
  510. let ext = NSString(string: item as! String).pathExtension.lowercased()
  511. if NSArray(array: [_extention]).contains(ext) {
  512. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  513. items.add(fileName)
  514. }
  515. }
  516. }else {
  517. items.add(fName)
  518. }
  519. for item in items {
  520. let subFileName = item as! String
  521. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  522. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  523. if FileManager.default.fileExists(atPath: rComparePath) {
  524. if !FileManager.default.fileExists(atPath: cComparePath) {
  525. return true
  526. }
  527. let rfs = try! FileManager.default.attributesOfItem(atPath: rComparePath)[FileAttributeKey.size] as! NSNumber
  528. let cfs = try! FileManager.default.attributesOfItem(atPath: cComparePath)[FileAttributeKey.size] as! NSNumber
  529. if rfs.int64Value != cfs.int64Value {
  530. return true
  531. }
  532. }
  533. }
  534. }
  535. return false
  536. }
  537. func updateRefImage(_ fileName:String) {
  538. let checkDirectory = self.checkFileDirectory()
  539. // let originDirectory = self.originFileDirectory()
  540. let resultDirectory = self.resultFileDirectory()
  541. let fName = NSString(string: fileName).deletingPathExtension
  542. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  543. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  544. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  545. var isDirectory = ObjCBool(false)
  546. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  547. // compare screenshoot between result file with check file
  548. let items = NSMutableArray()
  549. if (isDirectory.boolValue) {
  550. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  551. for item in NSArray(array: searchItems) {
  552. let ext = NSString(string: item as! String).pathExtension.lowercased()
  553. if NSArray(array: [_extention]).contains(ext) {
  554. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  555. items.add(fileName)
  556. }
  557. }
  558. }else {
  559. items.add(fName)
  560. }
  561. for item in items {
  562. let subFileName = item as! String
  563. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  564. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  565. if FileManager.default.fileExists(atPath: rComparePath) {
  566. if FileManager.default.fileExists(atPath: cComparePath) {
  567. try! FileManager.default.removeItem(atPath: cComparePath)
  568. }
  569. try! FileManager.default.createDirectory(atPath: NSString(string: cComparePath).deletingLastPathComponent,
  570. withIntermediateDirectories: true)
  571. try! FileManager.default.copyItem(atPath: rComparePath, toPath: cComparePath)
  572. }
  573. }
  574. }
  575. }
  576. func compareFiles() -> NSArray? {
  577. let items = NSMutableArray()
  578. let files = DataModel.shared.originFilesFor(_fileType, type: _type) as [String]
  579. for fileName in files {
  580. let sItems = compareFiles(fileName)
  581. if sItems != nil && sItems!.count != 0 {
  582. items.addObjects(from: sItems as! [Any])
  583. }
  584. }
  585. return items
  586. }
  587. func compareFiles(_ fileName: String) -> NSArray? {
  588. let files = NSMutableArray()
  589. let checkDirectory = self.checkFileDirectory()
  590. // let originDirectory = self.originFileDirectory()
  591. let resultDirectory = self.resultFileDirectory()
  592. let fName = NSString(string: fileName).deletingPathExtension
  593. // let originPath = NSString(string: originDirectory).appendingPathComponent(fName+".pdf")
  594. let resultPath = NSString(string: resultDirectory).appendingPathComponent(fName+"."+_extention)
  595. // let checkPath = NSString(string: checkDirectory).appendingPathComponent(fName+"."+_extention)
  596. var isDirectory = ObjCBool(false)
  597. if FileManager.default.fileExists(atPath: resultPath, isDirectory:&isDirectory) {
  598. // compare screenshoot between result file with check file
  599. let items = NSMutableArray()
  600. if (isDirectory.boolValue) {
  601. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultPath)
  602. for item in NSArray(array: searchItems) {
  603. let ext = NSString(string: item as! String).pathExtension.lowercased()
  604. if (NSArray(array: [_extention]).contains(ext) &&
  605. !NSString(string: item as! String).contains("_cover.png")) {
  606. let fileName = NSString(string: fName+"."+_extention+"/\(item as! String)").deletingPathExtension
  607. items.add(fileName)
  608. }
  609. }
  610. }else {
  611. items.add(fName)
  612. }
  613. let nitems = items.sortedArray { str1, str2 in
  614. let s1 = NSString(string: str1 as! String).deletingPathExtension
  615. let s2 = NSString(string: str2 as! String).deletingPathExtension
  616. if (NSString(string: s1).length != NSString(string: s2).length) {
  617. if (NSString(string: s1).length > NSString(string: s2).length) {
  618. return .orderedDescending
  619. }else {
  620. return .orderedAscending
  621. }
  622. }
  623. return NSString(string: s1).compare(s2)
  624. }
  625. for item in nitems {
  626. let subFileName = item as! String
  627. let rComparePath = NSString(string: resultDirectory).appendingPathComponent(subFileName+".jpg")
  628. let cComparePath = NSString(string: checkDirectory).appendingPathComponent(subFileName+".jpg")
  629. let fileInfo = NSMutableDictionary.fileInfoWith(fileName,
  630. refFilePath: subFileName+".jpg",
  631. resultPath: rComparePath,
  632. comparePath: cComparePath,
  633. objc: self)
  634. files.add(fileInfo)
  635. }
  636. }
  637. return files
  638. }
  639. /// Path
  640. func originFileDirectory() -> String {
  641. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kOriginPathComponent)")
  642. }
  643. func resultFileDirectory() -> String {
  644. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kResultPathComponent)")
  645. }
  646. func checkFileDirectory() -> String {
  647. return DataModel.shared.directoryPath().appendingFormat("/\(self.fileType())/\(self.type())/\(kCheckPathComponent)")
  648. }
  649. // check File Exist
  650. func hasOriginFile() -> Bool {
  651. if FileManager.default.fileExists(atPath: self.originFileDirectory()) {
  652. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.originFileDirectory())
  653. return (files ?? []).count > 0
  654. }
  655. return false
  656. }
  657. func hasResultFile() -> Bool {
  658. if FileManager.default.fileExists(atPath: self.resultFileDirectory()) {
  659. let files = try? FileManager.default.subpathsOfDirectory(atPath: self.resultFileDirectory())
  660. return (files ?? []).count > 0
  661. }
  662. return false
  663. }
  664. ///
  665. func clearCacheFiles() {
  666. reportString = NSMutableAttributedString.init();
  667. let resultDirectory = self.resultFileDirectory()
  668. var isDirectory = ObjCBool(false)
  669. if FileManager.default.fileExists(atPath: resultDirectory, isDirectory: &isDirectory) && isDirectory.boolValue {
  670. let searchItems = try! FileManager.default.contentsOfDirectory(atPath: resultDirectory)
  671. for item in NSArray(array: searchItems) {
  672. let path = NSString(string: resultDirectory).appendingPathComponent(item as! String)
  673. if FileManager.default.fileExists(atPath: path) {
  674. try! FileManager.default.removeItem(atPath: path)
  675. }
  676. }
  677. }
  678. }
  679. }
  680. extension AutoTest {
  681. func stringToImage(_ string:String) ->NSImage? {
  682. let length = Int(string.lengthOfBytes(using: .utf8)/2)
  683. let bytes = malloc(length)!
  684. for i in 0..<length {
  685. let index = i
  686. let subString = String(NSString(string: string).substring(with: NSMakeRange(Int(index * 2), 2)))
  687. bytes.storeBytes(of: UInt8(hexForString(subString)), as: UInt8.self)
  688. }
  689. let data = Data.init(bytes: bytes, count: length)
  690. let image = NSImage.init(data: data)
  691. return image
  692. }
  693. func hexForString(_ string:String) -> UInt8 {
  694. let chars = string.utf8CString
  695. if (string.lengthOfBytes(using: .utf8) >= 2) {
  696. return UInt8(intvalueForChar(chars[0]) * 16 + intvalueForChar(chars[1]))
  697. }
  698. return UInt8(0)
  699. }
  700. func intvalueForChar(_ char:CChar) -> UInt8 {
  701. let iValue = char
  702. // 0 ~ 9s
  703. if iValue >= 48 && iValue <= 57 {
  704. return UInt8(iValue - 48)
  705. }else if iValue >= 65 && iValue <= 70 {
  706. return UInt8(iValue - 65 + 10)
  707. }else if iValue >= 97 && iValue <= 102 {
  708. return UInt8(iValue - 97 + 10)
  709. }
  710. return UInt8(0)
  711. }
  712. }
  713. extension AutoTest {
  714. func isEqual(to object: AutoTest) -> Bool {
  715. return (NSString(string: self.className).isEqual(to: object.className) &&
  716. NSString(string: self.fileType()).isEqual(to: object.fileType()) &&
  717. NSString(string: self.type()).isEqual(to: object.type()) &&
  718. NSString(string: self.extention()).isEqual(to: object.extention()))
  719. }
  720. }