HttpClientUploadSafeTests.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import XCTest
  21. import ThreemaFramework
  22. @testable import Threema
  23. class HttpClientUploadSafeTests: XCTestCase {
  24. var receivedData: Data?
  25. override func setUp() {
  26. super.setUp()
  27. // Put setup code here. This method is called before the invocation of each test method in the class.
  28. }
  29. override func tearDown() {
  30. // Put teardown code here. This method is called after the invocation of each test method in the class.
  31. super.tearDown()
  32. }
  33. func testSafeHttpClientUploadWithCompletionHandler() {
  34. let store = SafeStore(safeConfigManager: SafeConfigManager(), serverApiConnector: ServerAPIConnector())
  35. if let key = store.createKey(identity: "ECHOECHO", password: "shootdeathstar"), let backupId = store.getBackupId(key: key) {
  36. if let data = store.backupData() {
  37. let encryptedData = try! store.encryptBackupData(key: key, data: data)
  38. let backupUrl = URL(string: "https://safe.threema.ch/backups/\(hexString(data: backupId))")
  39. let client = HttpClient()
  40. client.uploadData(url: backupUrl!, data: Data(encryptedData)) { (data, response, error) in
  41. if let error = error {
  42. print ("http client upload error: \(error)")
  43. XCTAssert(false)
  44. return
  45. }
  46. guard let response = response as? HTTPURLResponse,
  47. (200...299).contains(response.statusCode) else {
  48. print ("http client download wrong state")
  49. if let data = data {
  50. print("http client upload failed: \(String(data: data, encoding: .utf8)!)")
  51. }
  52. XCTAssert(false)
  53. return
  54. }
  55. }
  56. } else {
  57. print ("missing private key")
  58. XCTAssert(false)
  59. return
  60. }
  61. }
  62. }
  63. func testHttpSafeClientUploadWithDelegate() {
  64. self.receivedData = Data()
  65. let store = SafeStore(safeConfigManager: SafeConfigManager(), serverApiConnector: ServerAPIConnector())
  66. if let key = store.createKey(identity: "ECHOECHO", password: "shootdeathstar"), let backupId = store.getBackupId(key: key) {
  67. if let data = store.backupData() {
  68. let encryptedData = try! store.encryptBackupData(key: key, data: data)
  69. //save into local documents storage
  70. let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
  71. let backupFile = documents + "/backup-safe"
  72. let backupFileUrl = URL(fileURLWithPath: documents + "/backup-safe")
  73. let fileManager = FileManager.default
  74. print(backupFileUrl.absoluteString)
  75. if fileManager.fileExists(atPath: backupFile) {
  76. do {
  77. let attr = try FileManager.default.attributesOfItem(atPath: backupFile)
  78. let fileSize = attr[FileAttributeKey.size] as! UInt64
  79. print("safe backup size \(fileSize)")
  80. try fileManager.removeItem(atPath: backupFile)
  81. }
  82. catch let error as NSError {
  83. print("deletion of safe backup file failed: \(error)")
  84. }
  85. }
  86. fileManager.createFile(atPath: backupFile, contents: Data(encryptedData), attributes: nil)
  87. let backupUrl = URL(string: "https://safe.threema.ch/backups/\(hexString(data: backupId))")
  88. let client = HttpClient()
  89. client.uploadData(url: backupUrl!, file: backupFileUrl, delegate: self)
  90. } else {
  91. print ("backup failed: missing private key")
  92. }
  93. }
  94. }
  95. /*
  96. func testPerformanceExample() {
  97. // This is an example of a performance test case.
  98. self.measure {
  99. // Put the code you want to measure the time of here.
  100. }
  101. }
  102. */
  103. private func hexString(data: [UInt8]) -> String {
  104. return data.map { String(format: "%02hhx", $0) }.joined(separator: "")
  105. }
  106. }
  107. extension HttpClientUploadSafeTests : URLSessionDataDelegate {
  108. // delegate methods
  109. func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  110. print("bytes: expected \(totalBytesExpectedToSend) / sent \(bytesSent) / total \(totalBytesSent)")
  111. }
  112. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  113. self.receivedData?.append(data)
  114. }
  115. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  116. DispatchQueue.main.async {
  117. if let error = error {
  118. print("http client upload error \(error)")
  119. XCTAssert(false)
  120. } else if let receivedData = self.receivedData,
  121. let receivedDataString = String(bytes: receivedData, encoding: .utf8) {
  122. print("http client upload failed \(receivedDataString)")
  123. XCTAssert(false)
  124. }
  125. }
  126. }
  127. }
  128. extension HttpClientUploadSafeTests: URLSessionDelegate {
  129. // call standard background session handler
  130. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  131. print("session for download finished")
  132. }
  133. }