Created
September 4, 2017 13:50
-
-
Save michalciurus/f2313d8e5f4fdaedb8917ad5f78b0384 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Swifter | |
enum HTTPMethod { | |
case POST | |
case GET | |
} | |
class HTTPDynamicStubs { | |
var server = HttpServer() | |
func setUp() { | |
setupInitialStubs() | |
try! server.start() | |
} | |
func tearDown() { | |
server.stop() | |
} | |
func setupInitialStubs() { | |
// Setting up all the initial mocks from the array | |
for stub in initialStubs { | |
setupStub(url: stub.url, filename: stub.jsonFilename, method: stub.method) | |
} | |
} | |
public func setupStub(url: String, filename: String, method: HTTPMethod = .GET) { | |
let testBundle = Bundle(for: type(of: self)) | |
let filePath = testBundle.path(forResource: filename, ofType: "json") | |
let fileUrl = URL(fileURLWithPath: filePath!) | |
let data = try! Data(contentsOf: fileUrl, options: .uncached) | |
// Looking for a file and converting it to JSON | |
let json = dataToJSON(data: data) | |
// Swifter makes it very easy to create stubbed responses | |
let response: ((HttpRequest) -> HttpResponse) = { _ in | |
return HttpResponse.ok(.json(json as AnyObject)) | |
} | |
switch method { | |
case .GET : server.GET[url] = response | |
case .POST: server.POST[url] = response | |
} | |
} | |
func dataToJSON(data: Data) -> Any? { | |
do { | |
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) | |
} catch let myJSONError { | |
print(myJSONError) | |
} | |
return nil | |
} | |
} | |
struct HTTPStubInfo { | |
let url: String | |
let jsonFilename: String | |
let method: HTTPMethod | |
} | |
let initialStubs = [ | |
HTTPStubInfo(url: "/api/feed", jsonFilename: "feed", method: .GET), | |
HTTPStubInfo(url: "/api/createPost", jsonFilename: "createPost", method: .POST) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment