<commit_before>/*
 * Copyright 2018, gRPC Authors All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Dispatch
import Foundation
@testable import SwiftGRPC
import XCTest

fileprivate class CancellingProvider: Echo_EchoProvider {
  func get(request: Echo_EchoRequest, session: Echo_EchoGetSession) throws -> Echo_EchoResponse {
    session.cancel()
    return Echo_EchoResponse()
  }
  
  func expand(request: Echo_EchoRequest, session: Echo_EchoExpandSession) throws {
    session.cancel()
    XCTAssertThrowsError(try session.send(Echo_EchoResponse()))
  }
  
  func collect(session: Echo_EchoCollectSession) throws {
    session.cancel()
    try! session.sendAndClose(response: Echo_EchoResponse(), status: .ok, completion: nil)
  }
  
  func update(session: Echo_EchoUpdateSession) throws {
    session.cancel()
    XCTAssertThrowsError(try session.send(Echo_EchoResponse()))
  }
}

class ServerCancellingTests: BasicEchoTestCase {
  static var allTests: [(String, (ServerCancellingTests) -> () throws -> Void)] {
    return [
      ("testServerThrowsUnary", testServerThrowsUnary),
      ("testServerThrowsClientStreaming", testServerThrowsClientStreaming),
      ("testServerThrowsServerStreaming", testServerThrowsServerStreaming),
      ("testServerThrowsBidirectionalStreaming", testServerThrowsBidirectionalStreaming)
    ]
  }
  
  override func makeProvider() -> Echo_EchoProvider { return CancellingProvider() }
}

extension ServerCancellingTests {
  func testServerThrowsUnary() {
    do {
      let result = try client.get(Echo_EchoRequest(text: "foo")).text
      XCTFail("should have thrown, received \(result) instead")
    } catch {
      guard case let .callError(callResult) = error as! RPCError
        else { XCTFail("unexpected error \(error)"); return }
      XCTAssertEqual(.cancelled, callResult.statusCode)
      XCTAssertEqual("Cancelled", callResult.statusMessage)
    }
  }
  
  func testServerThrowsClientStreaming() {
    let completionHandlerExpectation = expectation(description: "final completion handler called")
    let call = try! client.collect { callResult in
      XCTAssertEqual(.cancelled, callResult.statusCode)
      XCTAssertEqual("Cancelled", callResult.statusMessage)
      completionHandlerExpectation.fulfill()
    }
    
    let sendExpectation = expectation(description: "send completion handler 1 called")
    try! call.send(Echo_EchoRequest(text: "foo")) { [sendExpectation] in
      // The server only times out later in its lifecycle, so we shouldn't get an error when trying to send a message.
      XCTAssertNil($0)
      sendExpectation.fulfill()
    }
    call.waitForSendOperationsToFinish()<commit_msg>Try increasing the default timeout for server-cancelling tests to 5 seconds?<commit_after>/*
 * Copyright 2018, gRPC Authors All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Dispatch
import Foundation
@testable import SwiftGRPC
import XCTest

fileprivate class CancellingProvider: Echo_EchoProvider {
  func get(request: Echo_EchoRequest, session: Echo_EchoGetSession) throws -> Echo_EchoResponse {
    session.cancel()
    return Echo_EchoResponse()
  }
  
  func expand(request: Echo_EchoRequest, session: Echo_EchoExpandSession) throws {
    session.cancel()
    XCTAssertThrowsError(try session.send(Echo_EchoResponse()))
  }
  
  func collect(session: Echo_EchoCollectSession) throws {
    session.cancel()
    try! session.sendAndClose(response: Echo_EchoResponse(), status: .ok, completion: nil)
  }
  
  func update(session: Echo_EchoUpdateSession) throws {
    session.cancel()
    XCTAssertThrowsError(try session.send(Echo_EchoResponse()))
  }
}

class ServerCancellingTests: BasicEchoTestCase {
  static var allTests: [(String, (ServerCancellingTests) -> () throws -> Void)] {
    return [
      ("testServerThrowsUnary", testServerThrowsUnary),
      ("testServerThrowsClientStreaming", testServerThrowsClientStreaming),
      ("testServerThrowsServerStreaming", testServerThrowsServerStreaming),
      ("testServerThrowsBidirectionalStreaming", testServerThrowsBidirectionalStreaming)
    ]
  }
  
  override func makeProvider() -> Echo_EchoProvider { return CancellingProvider() }
  
  override var defaultTimeout: TimeInterval { return 5.0 }
}

extension ServerCancellingTests {
  func testServerThrowsUnary() {
    do {
      let result = try client.get(Echo_EchoRequest(text: "foo")).text
      XCTFail("should have thrown, received \(result) instead")
    } catch {
      guard case let .callError(callResult) = error as! RPCError
        else { XCTFail("unexpected error \(error)"); return }
      XCTAssertEqual(.cancelled, callResult.statusCode)
      XCTAssertEqual("Cancelled", callResult.statusMessage)
    }
  }
  
  func testServerThrowsClientStreaming() {
    let completionHandlerExpectation = expectation(description: "final completion handler called")
    let call = try! client.collect { callResult in
      XCTAssertEqual(.cancelled, callResult.statusCode)
      XCTAssertEqual("Cancelled", callResult.statusMessage)
      completionHandlerExpectation.fulfill()
    }
    
    let sendExpectation = expectation(description: "send completion handler 1 called")
    try! call.send(Echo_EchoRequest(text: "foo")) { [sendExpectation] in
      // The server only times out later in its lifecycle, so we shouldn't get an error when trying to send a message.
      XCTAssertNil($0)
      sendExpectation.fulfill()
    }
    call.waitForSendOperationsToFinish()
{'fraction_non_alphanumeric': 0.08730280287946086, 'fraction_numerical': 0.0035227446775922804, 'mean_word_length': 4.317589576547231, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '5388255', 'n_tokens_mistral': 1875, 'n_tokens_neox': 1822, 'n_words': 519}