<commit_before>//
//  TraderDesktopApiTests.swift
//  StompClient
//
//  Created by <NAME> on 4/6/16.
//  Copyright © 2016 shenghuawu. All rights reserved.
//

import XCTest
import Starscream
@testable import StompClient

class TraderDesktopApiTests: XCTestCase {
    
    private var client: StompClient!
    private var socket: WebSocket!
    private let host = "http://10.1.20.28:8080"
    
    override func setUp() {
        super.setUp()
        
        let url = NSURL(string: host + "/traderdesktop")!.appendServerIdAndSessionId()
        socket = WebSocket(url: url)
        client = StompClient(socket: socket)
    }
    
    override func tearDown() {
        super.tearDown()
    }
    
    // MARK: - Enabled Tests
    func testSubscribeAccountPNL() {
        let delegate = AccountPNLDelegate()
        delegate.expectation = expectationWithDescription("Subscribe account pnl")
        client.delegate = delegate

        let session = NSURLSession.sharedSession()
        let loginURLString = host + "/trader/desktop/auth/login"
        let request = NSMutableURLRequest(URL: NSURL(string: loginURLString)!)
        let param = ["id" : "<EMAIL>", "pass" : "<PASSWORD>"]
//        var parts = [String]()
//        for (key, value) in param {
//            let field = key + "=" + value
//            parts.append(field)
//        }
//        let string = parts.joinWithSeparator("&")
//        let stringData = string.dataUsingEncoding(NSUTF8StringEncoding)!
        let data = try! NSJSONSerialization.dataWithJSONObject(param, options: NSJSONWritingOptions(rawValue: 0))
        request.HTTPMethod = "POST"
//        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = data
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            let res = response as! NSHTTPURLResponse
            if res.statusCode == 200 {
                self.parseCookies(res)
                
                self.client.connect()
            } else {
                debugPrint(res)
                XCTAssert(false, "Status code isn't 200")
                delegate.expectation.fulfill()
            }
        }
        task.resume()
     
        waitForExpectationsWithTimeout(500.0, handler: nil)
    }
    
    // MARK: - Private Methods
    private func parseCookies(res: NSHTTPURLResponse) {
        let fields = res.allHeaderFields as! [String : String]
        let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: res.URL!)
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: res.URL!, mainDocumentURL: nil)
        for cookie in cookies {
            var cookieProperties = [String: AnyObject]()
            cookieProperties[NSHTTPCookieName] = cookie.name
            cookieProperties[NSHTTPCookieValue] = cookie.value
            cookieProperties[NSHTTPCookieDomain] = cookie.domain
            cookieProperties[NSHTTPCookiePath] = cookie.path
            cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
            cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
            
            let newCookie = NSHTTPCookie(properties: cookieProperties)
            NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
            
            print("name: \(cookie.name) value: \(cookie.value)")
        }
    }
    
}

// MARK: - Stub Delegate
class AccountPNLDelegate: NSObject, StompClientDelegate {
    
    // MARK: - Public Properties
    var expectation: XCTestExpectation!
    
    // MARK: - Private Properties
    private let destination = "/account/accountpnl/<EMAIL>"
    
    // MARK: - Stomp Client Delegate
    func stompClientDidConnected(client: StompClient) {
        client.subscribe(destination, parameters: nil)
    }
    
    func stompClient(client: StompClient, didErrorOccurred error: NSError) {
        XCTAssertTrue(false, "Error: \(error.localizedDescription)")
        expectation.fulfill()
    }
    
    func stompClient(client: StompClient, didReceivedData data: NSData) {
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        debugPrint(json)
//        XCTAssert(json is [AnyObject], "Reveived data isn't an array.")
        
        client.unsubscribe(destination)
        
        XCTAssertNotNil(expectation, "Expectation doesn't setup.")
        expectation.fulfill()
    }
    
}
<commit_msg>Finish testing trader desktop websocket connection.<commit_after>//
//  TraderDesktopApiTests.swift
//  StompClient
//
//  Created by <NAME> on 4/6/16.
//  Copyright © 2016 shenghuawu. All rights reserved.
//

import XCTest
import Starscream
@testable import StompClient

class TraderDesktopApiTests: XCTestCase {
    
    private var client: StompClient!
    private var socket: WebSocket!
    private let host = "http://10.1.10.113:8080"
    
    override func setUp() {
        super.setUp()
        
        let url = NSURL(string: host + "/traderdesktop")!.appendServerIdAndSessionId()
        socket = WebSocket(url: url)
        client = StompClient(socket: socket)
    }
    
    override func tearDown() {
        super.tearDown()
    }
    
    // MARK: - Enabled Tests
    func testSubscribeAccountPNL() {
        let delegate = AccountPNLDelegate()
        delegate.expectation = expectationWithDescription("Subscribe account pnl")
        client.delegate = delegate

        let session = NSURLSession.sharedSession()
        let loginURLString = host + "/trader/desktop/auth/login"
        let request = NSMutableURLRequest(URL: NSURL(string: loginURLString)!)
        request.HTTPMethod = "POST"
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let param = ["id" : "<EMAIL>", "pass" : "<PASSWORD>"]
        let string = convertToQueryString(param)
        let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
//        let data = try! NSJSONSerialization.dataWithJSONObject(param, options: NSJSONWritingOptions(rawValue: 0))
        request.HTTPBody = data
        
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            let res = response as! NSHTTPURLResponse
            if res.statusCode == 200 {
                let fields = res.allHeaderFields as! [String : String]
                let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: res.URL!)
                let cookie = cookies.filter({
                    $0.name == "JSESSIONID"
                }).first!
                self.socket.headers["Cookie"] = cookie.name + "=" + cookie.value
                self.client.connect()
            } else {
                debugPrint(res)
                XCTAssert(false, "Status code isn't 200. Login failed.")
                delegate.expectation.fulfill()
            }
        }
        task.resume()
     
        waitForExpectationsWithTimeout(500.0, handler: nil)
    }
    
    // MARK: - Private Methods
    func convertToQueryString(parameters: [String : String]) -> String {
        var parts = [String]()
        for (key, value) in parameters {
            let field = key + "=" + value
            parts.append(field)
        }
        return parts.joinWithSeparator("&")
    }
    
}

// MARK: - Stub Delegate
class AccountPNLDelegate: NSObject, StompClientDelegate {
    
    // MARK: - Public Properties
    var expectation: XCTestExpectation!
    
    // MARK: - Private Properties
    private let destination = "/account/accountpnl/<EMAIL>"
    
    // MARK: - Stomp Client Delegate
    func stompClientDidConnected(client: StompClient) {
        client.subscribe(destination, parameters: nil)
    }
    
    func stompClient(client: StompClient, didErrorOccurred error: NSError) {
        XCTAssertTrue(false, "Error: \(error.localizedDescription)")
        expectation.fulfill()
    }
    
    func stompClient(client: StompClient, didReceivedData data: NSData) {
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        XCTAssertNotNil(json["accountId"], "Account Id is empty.")
        XCTAssertEqual(json["accountId"]!, "<EMAIL>", "Account Id is wrong.")
        
        client.unsubscribe(destination)
        
        XCTAssertNotNil(expectation, "Expectation doesn't setup.")
        expectation.fulfill()
    }
    
}

{'fraction_non_alphanumeric': 0.10418842093050237, 'fraction_numerical': 0.008353637312913331, 'mean_word_length': 2.4328952608522503, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 2, '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': '3620994', 'n_tokens_mistral': 2514, 'n_tokens_neox': 2405, 'n_words': 531}