<commit_before>//
//  MockServer.swift
//  Punos
//
//  Created by <NAME> on 9.2.16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import GCDWebServers


typealias MockResponseMatcher = (request: GCDWebServerRequest) -> Bool


private struct MockResponse {
    let statusCode: Int?
    let data: NSData?
    let contentType: String?
    let headers: [String:String]?
    let matcher: MockResponseMatcher?
    let onlyOnce: Bool
}


/// A web server that runs on `localhost` and can be told how to respond
/// to incoming requests. Meant for automated tests.
///
public class MockServer {
    
    private let server = GCDWebServer()
    
    init() {
        attachHandlers()
    }
    
    // ------------------------------------
    // MARK: Starting and stopping
    
    /// Start the server on the given `port` (`8080` by default.)
    ///
    func start(port: UInt? = nil) {
        if !server.startWithPort(port ?? 8080, bonjourName: nil) {
            fatalError("The mock server failed to start on port \(port)")
        }
    }
    
    /// Stop the server.
    ///
    func stop() {
        server.stop()
    }
    
    /// Whether the server is currently running.
    ///
    var isRunning: Bool { return server.running }
    
    /// The port the server is running on, or 0 if the server
    /// is not running.
    ///
    var port: UInt {
        return isRunning ? server.port : 0
    }
    
    /// The “base URL” (protocol, hostname, port) for the
    /// running server, or `nil` if the server is not running.
    ///
    var baseURLString: String? {
        if !server.running {
            return nil
        }
        return "http://localhost:\(server.port)"
    }
    
    
    // ------------------------------------
    // MARK: Responding
    
    private let allHTTPVerbs = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"]
    
    private func attachHandlers() {
        for method in allHTTPVerbs {
            server.addDefaultHandlerForMethod(method, requestClass: GCDWebServerDataRequest.self, processBlock: respondToRequest)
        }
    }
    
    private func mockResponseDataForRequest(request: GCDWebServerRequest!) -> MockResponse? {
        
        for i in mockResponsesWithMatchers.indices {
            let responseWithMatcher = mockResponsesWithMatchers[i]
            guard let matcher = responseWithMatcher.matcher else { continue }
            
            if matcher(request: request) {
                if responseWithMatcher.onlyOnce {
                    mockResponsesWithMatchers.removeAtIndex(i)
                }<commit_msg>Use public HTTPRequest type in the matcher funcs<commit_after>//
//  MockServer.swift
//  Punos
//
//  Created by <NAME> on 9.2.16.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import GCDWebServers


typealias MockResponseMatcher = (request: HTTPRequest) -> Bool


private struct MockResponse {
    let statusCode: Int?
    let data: NSData?
    let contentType: String?
    let headers: [String:String]?
    let matcher: MockResponseMatcher?
    let onlyOnce: Bool
}


/// A web server that runs on `localhost` and can be told how to respond
/// to incoming requests. Meant for automated tests.
///
public class MockServer {
    
    private let server = GCDWebServer()
    
    init() {
        attachHandlers()
    }
    
    // ------------------------------------
    // MARK: Starting and stopping
    
    /// Start the server on the given `port` (`8080` by default.)
    ///
    func start(port: UInt? = nil) {
        if !server.startWithPort(port ?? 8080, bonjourName: nil) {
            fatalError("The mock server failed to start on port \(port)")
        }
    }
    
    /// Stop the server.
    ///
    func stop() {
        server.stop()
    }
    
    /// Whether the server is currently running.
    ///
    var isRunning: Bool { return server.running }
    
    /// The port the server is running on, or 0 if the server
    /// is not running.
    ///
    var port: UInt {
        return isRunning ? server.port : 0
    }
    
    /// The “base URL” (protocol, hostname, port) for the
    /// running server, or `nil` if the server is not running.
    ///
    var baseURLString: String? {
        if !server.running {
            return nil
        }
        return "http://localhost:\(server.port)"
    }
    
    
    // ------------------------------------
    // MARK: Responding
    
    private let allHTTPVerbs = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"]
    
    private func attachHandlers() {
        for method in allHTTPVerbs {
            server.addDefaultHandlerForMethod(method, requestClass: GCDWebServerDataRequest.self, processBlock: respondToRequest)
        }
    }
    
    private func mockResponseDataForRequest(request: GCDWebServerRequest!) -> MockResponse? {
        
        let publicRequest = HTTPRequest(request)
        for i in mockResponsesWithMatchers.indices {
            let responseWithMatcher = mockResponsesWithMatchers[i]
            guard let matcher = responseWithMatcher.matcher else { continue }
            
            if matcher(request: publicRequest) {
                if responseWithMatcher.onlyOnce {
                    mockResponsesWithMatchers.removeAtIndex(i)
                }
{'fraction_non_alphanumeric': 0.1272488755622189, 'fraction_numerical': 0.006746626686656672, 'mean_word_length': 1.8662728249194414, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2187853', 'n_tokens_mistral': 1518, 'n_tokens_neox': 1470, 'n_words': 454}