HttpClientDownloadSafeTests.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 HttpClientDownloadSafeTests: 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 testSafeHttpClientDownloadWithCompletionHandler() {
  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. let safeServer = store.getSafeDefaultServer(key: key)!
  37. let backupUrl = URL(string: "\(safeServer)/backups/\(hexString(data: backupId))")
  38. let client = HttpClient()
  39. client.downloadData(url: backupUrl!, contentType: .octetStream) { (data, response, error) in
  40. if let error = error {
  41. print ("http client download error: \(error)")
  42. XCTAssert(false)
  43. return
  44. }
  45. guard let response = response as? HTTPURLResponse,
  46. (200...299).contains(response.statusCode) else {
  47. print ("http client download wrong state")
  48. if let data = data {
  49. print("http client download failed: \(String(data: data, encoding: .utf8)!)")
  50. }
  51. XCTAssert(false)
  52. return
  53. }
  54. if let encryptedData = data {
  55. let decryptedData = try! store.decryptBackupData(key: key, data: Array(encryptedData))
  56. let parser = SafeJsonParser()
  57. let safeBackupData = try! parser.getSafeBackupData(from: Data(decryptedData))
  58. XCTAssertEqual(1, safeBackupData.info.version)
  59. }
  60. else {
  61. XCTAssert(false)
  62. }
  63. }
  64. }
  65. }
  66. func testSafeHttpClientDownloadWithDelegate() {
  67. self.receivedData = Data()
  68. let store = SafeStore(safeConfigManager: SafeConfigManager(), serverApiConnector: ServerAPIConnector())
  69. if let key = store.createKey(identity: "ECHOECHO", password: "shootdeathstar"), let backupId = store.getBackupId(key: key) {
  70. let backupUrl = URL(string: "https://safe.threema.ch/backups/\(hexString(data: backupId))")
  71. let client = HttpClient()
  72. client.downloadData(url: backupUrl!, delegate: self)
  73. }
  74. }
  75. /*
  76. func testPerformanceExample() {
  77. // This is an example of a performance test case.
  78. self.measure {
  79. // Put the code you want to measure the time of here.
  80. }
  81. }
  82. */
  83. private func hexString(data: [UInt8]) -> String {
  84. return data.map { String(format: "%02hhx", $0) }.joined(separator: "")
  85. }
  86. }
  87. extension HttpClientDownloadSafeTests : URLSessionDataDelegate {
  88. // delegate methods
  89. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  90. guard let response = response as? HTTPURLResponse,
  91. (200...299).contains(response.statusCode),
  92. let mimeType = response.mimeType,
  93. mimeType == "application/octet-stream" else {
  94. completionHandler(.cancel)
  95. return
  96. }
  97. completionHandler(.allow)
  98. }
  99. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  100. self.receivedData?.append(data)
  101. }
  102. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  103. DispatchQueue.main.async {
  104. if let error = error {
  105. print("http client download error \(error)")
  106. XCTAssert(false)
  107. } else if let receivedData = self.receivedData {
  108. let store = SafeStore(safeConfigManager: SafeConfigManager(), serverApiConnector: ServerAPIConnector())
  109. if let key = store.createKey(identity: "ECHOECHO", password: "shootdeathstar") {
  110. let decryptedData = try! store.decryptBackupData(key: key, data: Array(receivedData))
  111. let parser = SafeJsonParser()
  112. let safeBackupData = try! parser.getSafeBackupData(from: Data(decryptedData))
  113. XCTAssertEqual(1, safeBackupData.info.version)
  114. }
  115. }
  116. }
  117. }
  118. }
  119. extension HttpClientDownloadSafeTests: URLSessionDelegate {
  120. // call standard background session handler
  121. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  122. print("session for download finished")
  123. }
  124. }