FlatBuffersMonsterWriterTests

/*
typealias Test = MyGame_Example_Test
typealias Monster = MyGame_Example_Monster
typealias Vec3 = MyGame_Example_Vec3
typealias Stat = MyGame_Example_Stat
class FlatBuffersMonsterWriterTests: XCTestCase {
  func testData() {
    // swiftformat:disable all
    let data: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]
    // swiftformat:enable all
    let _data = ByteBuffer(bytes: data)
    readVerifiedMonster(fb: _data)
  }
  func testCreateMonster() {
    let bytes = createMonster(withPrefix: false)
    // swiftformat:disable all
    XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
    // swiftformat:enable all
    var buffer = bytes.buffer
    let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer)
    readMonster(monster: monster)
    mutateMonster(fb: bytes.buffer)
    readMonster(monster: monster)
  }
  func testCreateMonsterResizedBuffer() {
    let bytes = createMonster(withPrefix: false)
    // swiftformat:disable all
    XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
    // swiftformat:enable all
    readVerifiedMonster(fb: bytes.sizedBuffer)
  }
  func testCreateMonsterPrefixed() {
    let bytes = createMonster(withPrefix: true)
    // swiftformat:disable all
    XCTAssertEqual(bytes.sizedByteArray, [44, 1, 0, 0, 44, 0, 0, 0, 77, 79, 78, 83, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
    // swiftformat:enable all
    var buffer = bytes.buffer
    readMonster(monster: getPrefixedSizeRoot(byteBuffer: &buffer))
  }
  func testCreateMonsterUsingCreateMonsterMethodWithNilPos() {
    var fbb = FlatBufferBuilder(initialSize: 1)
    let name = fbb.create(string: "Frodo")
    let mStart = Monster.startMonster(&fbb)
    Monster.add(name: name, &fbb)
    let root = Monster.endMonster(&fbb, start: mStart)
    fbb.finish(offset: root)
    var buffer = fbb.sizedBuffer
    let newMonster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer)
    XCTAssertNil(newMonster.pos)
    XCTAssertEqual(newMonster.name, "Frodo")
  }
  func testCreateMonsterUsingCreateMonsterMethodWithPosX() {
    var fbb = FlatBufferBuilder(initialSize: 1)
    let name = fbb.create(string: "Barney")
    let mStart = Monster.startMonster(&fbb)
    Monster.add(
      pos: MyGame_Example_Vec3(
        x: 10,
        y: 0,
        z: 0,
        test1: 0,
        test2: .blue,
        test3: .init()),
      &fbb)
    Monster.add(name: name, &fbb)
    let root = Monster.endMonster(&fbb, start: mStart)
    fbb.finish(offset: root)
    var buffer = fbb.sizedBuffer
    let newMonster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer)
    XCTAssertEqual(newMonster.pos!.x, 10)
    XCTAssertEqual(newMonster.name, "Barney")
  }
  func testArrayOfBools() {
    let boolArray = [false, true, false, true, false, true, false]
    var fbb = FlatBufferBuilder(initialSize: 1)
    let name = fbb.create(string: "Frodo")
    let bools = fbb.createVector(boolArray)
    let root = Monster.createMonster(
      &fbb,
      nameOffset: name,
      testarrayofboolsVectorOffset: bools)
    fbb.finish(offset: root)
    var buffer = fbb.sizedBuffer
    let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer)
    let values = monster.testarrayofbools
    XCTAssertEqual(boolArray, values)
    for i in 0..<monster.testarrayofboolsCount {
      XCTAssertEqual(boolArray[Int(i)], monster.testarrayofbools(at: i))
    }
  }
  func readVerifiedMonster(fb: ByteBuffer) {
    var byteBuffer = fb
    XCTAssertNoThrow(
      try readMonster(
        monster: getCheckedRoot(
          byteBuffer: &byteBuffer) as MyGame_Example_Monster))
  }
  func readMonster(monster: Monster) {
    var monster = monster
    readFlatbufferMonster(monster: &monster)
    let unpacked: MyGame_Example_MonsterT? = monster.unpack()
    readObjectApi(monster: unpacked!)
    guard var buffer = unpacked?.serialize()
    else { fatalError("Couldnt generate bytebuffer") }
    var newMonster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer)
    readFlatbufferMonster(monster: &newMonster)
  }
  func createMonster(withPrefix prefix: Bool) -> FlatBufferBuilder {
    var fbb = FlatBufferBuilder(initialSize: 1)
    let names = [
      fbb.create(string: "Frodo"),
      fbb.create(string: "Barney"),
      fbb.create(string: "Wilma"),
    ]
    var offsets: [Offset] = []
    let start1 = Monster.startMonster(&fbb)
    Monster.add(name: names[0], &fbb)
    offsets.append(Monster.endMonster(&fbb, start: start1))
    let start2 = Monster.startMonster(&fbb)
    Monster.add(name: names[1], &fbb)
    offsets.append(Monster.endMonster(&fbb, start: start2))
    let start3 = Monster.startMonster(&fbb)
    Monster.add(name: names[2], &fbb)
    offsets.append(Monster.endMonster(&fbb, start: start3))
    let sortedArray = Monster.sortVectorOfMonster(offsets: offsets, &fbb)
    let str = fbb.create(string: "MyMonster")
    let test1 = fbb.create(string: "test1")
    let test2 = fbb.create(string: "test2")
    let _inv: [Byte] = [0, 1, 2, 3, 4]
    let inv = fbb.createVector(_inv)
    let fred = fbb.create(string: "Fred")
    let mon1Start = Monster.startMonster(&fbb)
    Monster.add(name: fred, &fbb)
    let mon2 = Monster.endMonster(&fbb, start: mon1Start)
    let test4 = fbb.createVector(ofStructs: [
      MyGame_Example_Test(a: 30, b: 40),
      MyGame_Example_Test(a: 10, b: 20),
    ])
    let stringTestVector = fbb.createVector(ofOffsets: [test1, test2])
    let mStart = Monster.startMonster(&fbb)
    Monster.add(
      pos: MyGame_Example_Vec3(
        x: 1,
        y: 2,
        z: 3,
        test1: 3,
        test2: .green,
        test3: .init(a: 5, b: 6)),
      &fbb)
    Monster.add(hp: 80, &fbb)
    Monster.add(name: str, &fbb)
    Monster.addVectorOf(inventory: inv, &fbb)
    Monster.add(testType: .monster, &fbb)
    Monster.add(test: mon2, &fbb)
    Monster.addVectorOf(test4: test4, &fbb)
    Monster.addVectorOf(testarrayofstring: stringTestVector, &fbb)
    Monster.add(testbool: true, &fbb)
    Monster.addVectorOf(testarrayoftables: sortedArray, &fbb)
    let end = Monster.endMonster(&fbb, start: mStart)
    Monster.finish(&fbb, end: end, prefix: prefix)
    return fbb
  }
  func mutateMonster(fb: ByteBuffer) {
    var fb = fb
    let monster: Monster = getRoot(byteBuffer: &fb)
    XCTAssertFalse(monster.mutate(mana: 10))
    XCTAssertEqual(monster.testarrayoftables(at: 0)?.name, "Barney")
    XCTAssertEqual(monster.testarrayoftables(at: 1)?.name, "Frodo")
    XCTAssertEqual(monster.testarrayoftables(at: 2)?.name, "Wilma")
    // Example of searching for a table by the key
    XCTAssertNotNil(monster.testarrayoftablesBy(key: "Frodo"))
    XCTAssertNotNil(monster.testarrayoftablesBy(key: "Barney"))
    XCTAssertNotNil(monster.testarrayoftablesBy(key: "Wilma"))
    XCTAssertEqual(monster.testType, .monster)
    XCTAssertTrue(monster.mutate(testbool: false))
    XCTAssertEqual(monster.testbool, false)
    XCTAssertTrue(monster.mutate(testbool: true))
    XCTAssertEqual(monster.mutate(inventory: 1, at: 0), true)
    XCTAssertEqual(monster.mutate(inventory: 2, at: 1), true)
    XCTAssertEqual(monster.mutate(inventory: 3, at: 2), true)
    XCTAssertEqual(monster.mutate(inventory: 4, at: 3), true)
    XCTAssertEqual(monster.mutate(inventory: 5, at: 4), true)
    for i in 0..<monster.inventoryCount {
      XCTAssertEqual(monster.inventory(at: i), Byte(i + 1))
    }
    XCTAssertEqual(monster.mutate(inventory: 0, at: 0), true)
    XCTAssertEqual(monster.mutate(inventory: 1, at: 1), true)
    XCTAssertEqual(monster.mutate(inventory: 2, at: 2), true)
    XCTAssertEqual(monster.mutate(inventory: 3, at: 3), true)
    XCTAssertEqual(monster.mutate(inventory: 4, at: 4), true)
    let vec = monster.mutablePos
    XCTAssertEqual(vec?.x, 1)
    XCTAssertTrue(vec?.mutate(x: 55.0) ?? false)
    XCTAssertTrue(vec?.mutate(test1: 55) ?? false)
    XCTAssertEqual(vec?.x, 55.0)
    XCTAssertEqual(vec?.test1, 55.0)
    XCTAssertTrue(vec?.mutate(x: 1) ?? false)
    XCTAssertEqual(vec?.x, 1)
    XCTAssertTrue(vec?.mutate(test1: 3) ?? false)
  }
  func readFlatbufferMonster(monster: inout MyGame_Example_Monster) {
    XCTAssertEqual(monster.hp, 80)
    XCTAssertEqual(monster.mana, 150)
    XCTAssertEqual(monster.name, "MyMonster")
    let pos = monster.pos
    XCTAssertEqual(pos?.x, 1)
    XCTAssertEqual(pos?.y, 2)
    XCTAssertEqual(pos?.z, 3)
    XCTAssertEqual(pos?.test1, 3)
    XCTAssertEqual(pos?.test2, .green)
    let test = pos?.test3
    XCTAssertEqual(test?.a, 5)
    XCTAssertEqual(test?.b, 6)
    XCTAssertEqual(monster.testType, .monster)
    let monster2 = monster.test(type: Monster.self)
    XCTAssertEqual(monster2?.name, "Fred")
    XCTAssertEqual(monster.mutate(mana: 10), false)
    XCTAssertEqual(monster.mana, 150)
    XCTAssertEqual(monster.inventoryCount, 5)
    var sum: Byte = 0
    for i in 0...monster.inventoryCount {
      sum += monster.inventory(at: i)
    }
    XCTAssertEqual(sum, 10)
    XCTAssertEqual(monster.test4Count, 2)
    let test0 = monster.test4(at: 0)
    let test1 = monster.test4(at: 1)
    var sum0 = 0
    var sum1 = 0
    if let a = test0?.a, let b = test0?.b {
      sum0 = Int(a) + Int(b)
    }
    if let a = test1?.a, let b = test1?.b {
      sum1 = Int(a) + Int(b)
    }
    XCTAssertEqual(sum0 + sum1, 100)
    let mutableTest0 = monster.mutableTest4(at: 0)
    let mutableTest1 = monster.mutableTest4(at: 1)
    var sum2 = 0
    var sum3 = 0
    if let a = mutableTest0?.a, let b = mutableTest0?.b {
      sum2 = Int(a) + Int(b)
    }
    if let a = mutableTest1?.a, let b = mutableTest1?.b {
      sum3 = Int(a) + Int(b)
    }
    XCTAssertEqual(sum2 + sum3, 100)
    XCTAssertEqual(monster.testarrayofstringCount, 2)
    XCTAssertEqual(monster.testarrayofstring(at: 0), "test1")
    XCTAssertEqual(monster.testarrayofstring(at: 1), "test2")
    XCTAssertEqual(monster.testbool, true)
    let array = monster.nameSegmentArray
    XCTAssertEqual(String(bytes: array ?? [], encoding: .utf8), "MyMonster")
    if 0 == monster.testarrayofboolsCount  {
      XCTAssertEqual(monster.testarrayofbools.isEmpty, true)
    } else {
      XCTAssertEqual(monster.testarrayofbools.isEmpty, false)
    }
  }
  func readObjectApi(monster: MyGame_Example_MonsterT) {
    XCTAssertEqual(monster.hp, 80)
    XCTAssertEqual(monster.mana, 150)
    XCTAssertEqual(monster.name, "MyMonster")
    let pos = monster.pos
    XCTAssertEqual(pos?.x, 1)
    XCTAssertEqual(pos?.y, 2)
    XCTAssertEqual(pos?.z, 3)
    XCTAssertEqual(pos?.test1, 3)
    XCTAssertEqual(pos?.test2, .green)
    let test = pos?.test3
    XCTAssertEqual(test?.a, 5)
    XCTAssertEqual(test?.b, 6)
    let monster2 = monster.test?.value as? MyGame_Example_MonsterT
    XCTAssertEqual(monster2?.name, "Fred")
    XCTAssertEqual(monster.mana, 150)
    monster.mana = 10
    XCTAssertEqual(monster.mana, 10)
    monster.mana = 150
    XCTAssertEqual(monster.mana, 150)
    XCTAssertEqual(monster.inventory.count, 5)
    var sum: Byte = 0
    for i in monster.inventory {
      sum += i
    }
    XCTAssertEqual(sum, 10)
    XCTAssertEqual(monster.test4.count, 2)
    let test0 = monster.test4[0]
    let test1 = monster.test4[1]
    var sum0 = 0
    var sum1 = 0
    if let a = test0?.a, let b = test0?.b {
      sum0 = Int(a) + Int(b)
    }
    if let a = test1?.a, let b = test1?.b {
      sum1 = Int(a) + Int(b)
    }
    XCTAssertEqual(sum0 + sum1, 100)
    XCTAssertEqual(monster.testbool, true)
  }
  var jsonData: String {
    """
    {\"hp\":80,\"inventory\":[0,1,2,3,4],\"test\":{\"name\":\"Fred\"},\"testarrayofstring\":[\"test1\",\"test2\"],\"testarrayoftables\":[{\"name\":\"Barney\"},{\"name\":\"Frodo\"},{\"name\":\"Wilma\"}],\"test4\":[{\"a\":30,\"b\":40},{\"a\":10,\"b\":20}],\"testbool\":true,\"test_type\":\"Monster\",\"pos\":{\"y\":2,\"test3\":{\"a\":5,\"b\":6},\"z\":3,\"x\":1,\"test1\":3,\"test2\":\"Green\"},\"name\":\"MyMonster\"}
    """
  }
}


GTXToolkitSwiftTests

//
//
import XCTest
import GTXiLib
class GTXToolkitSwiftTests: XCTestCase {
  func testToolkitCreationMethods() {
    XCTAssertNotNil(GTXToolKit.defaultToolkit)
    XCTAssertNotNil(GTXToolKit.toolkitWithNoChecks)
    XCTAssertNotNil(GTXToolKit.toolkitWithAllDefaultChecks)
  }
}


ExampleTests

//
class ExampleTests: XCTestCase {
}


AppDelegate

//
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    return true
  }
}


ExampleTests

//
class ExampleTests: XCTestCase {
}


EarlGrey

//
  GREYAssert(expression(), reason, details: "Expected the boolean expression to be true")
}
  GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term")
}
                                                     reason: String) {
  GREYAssert(left() != right(), reason, details: "Expected object of the left term to not " +
    "equal the object of the right term")
}
public func GREYFail(_ reason: String) {
  EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                    reason: reason),
                  details: "")
}
public func GREYFailWithDetails(_ reason: String, details: String) {
  EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                    reason: reason),
                  details: details)
}
                        _ reason: String, details: String) {
  GREYSetCurrentAsFailable()
  GREYWaitUntilIdle()
  if !expression() {
    EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                      reason: reason),
                    details: details)
  }
}
private func GREYSetCurrentAsFailable() {
  let greyFailureHandlerSelector =
    #selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
  let greyFailureHandler =
    Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler
  if greyFailureHandler.responds(to: greyFailureHandlerSelector) {
    greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line)
  }
}
private func GREYWaitUntilIdle() {
  GREYUIThreadExecutor.sharedInstance().drainUntilIdle()
}
open class EarlGrey: NSObject {
  open class func select(elementWithMatcher matcher:GREYMatcher,
                         file: StaticString = #file,
                         line: UInt = #line) -> GREYElementInteraction {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .selectElement(with: matcher)
  }
  open class func setFailureHandler(handler: GREYFailureHandler,
                                    file: StaticString = #file,
                                    line: UInt = #line) {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .setFailureHandler(handler)
  }
  open class func handle(exception: GREYFrameworkException,
                         details: String,
                         file: StaticString = #file,
                         line: UInt = #line) {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .handle(exception, details: details)
  }
    return self.assert(with:matcher())
  }
                                       onElementWithMatcher matcher: GREYMatcher) -> Self {
    return self.usingSearch(searchAction, onElementWith: matcher)
  }
}
extension GREYCondition {
  open func waitWithTimeout(seconds: CFTimeInterval) -> Bool {
    return self.wait(withTimeout: seconds)
  }
  open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval)
    -> Bool {
      return self.wait(withTimeout: seconds, pollInterval: pollInterval)
  }
}


//
  GREYAssert(expression(), reason, details: "Expected the boolean expression to be true")
}
  GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term")
}
                                                     reason: String) {
  GREYAssert(left() != right(), reason, details: "Expected object of the left term to not " +
    "equal the object of the right term")
}
public func GREYFail(_ reason: String) {
  EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                    reason: reason),
                  details: "")
}
public func GREYFailWithDetails(_ reason: String, details: String) {
  EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                    reason: reason),
                  details: details)
}
                        _ reason: String, details: String) {
  GREYSetCurrentAsFailable()
  GREYWaitUntilIdle()
  if !expression() {
    EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException,
                                                      reason: reason),
                    details: details)
  }
}
private func GREYSetCurrentAsFailable() {
  let greyFailureHandlerSelector =
    #selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
  let greyFailureHandler =
    Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler
  if greyFailureHandler.responds(to: greyFailureHandlerSelector) {
    greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line)
  }
}
private func GREYWaitUntilIdle() {
  GREYUIThreadExecutor.sharedInstance().drainUntilIdle()
}
open class EarlGrey: NSObject {
  public static func selectElement(with matcher: GREYMatcher,
                                   file: StaticString = #file,
                                   line: UInt = #line) -> GREYInteraction {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .selectElement(with: matcher)
  }
  open class func select(elementWithMatcher matcher:GREYMatcher,
                         file: StaticString = #file,
                         line: UInt = #line) -> GREYElementInteraction {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .selectElement(with: matcher)
  }
  open class func setFailureHandler(handler: GREYFailureHandler,
                                    file: StaticString = #file,
                                    line: UInt = #line) {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .setFailureHandler(handler)
  }
  open class func handle(exception: GREYFrameworkException,
                         details: String,
                         file: StaticString = #file,
                         line: UInt = #line) {
    return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line)
      .handle(exception, details: details)
  }
    return self.__assert(with: matcher())
  }
    return self.__perform(action)
  }
                                       onElementWithMatcher matcher: GREYMatcher) -> Self {
    return self.usingSearch(searchAction, onElementWith: matcher)
  }
}
extension GREYCondition {
  open func waitWithTimeout(seconds: CFTimeInterval) -> Bool {
    return self.wait(withTimeout: seconds)
  }
  open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval)
    -> Bool {
      return self.wait(withTimeout: seconds, pollInterval: pollInterval)
  }
}


EarlGreyContribsSwiftTests

//
//
import EarlGrey
import XCTest
class EarlGreyContribsSwiftTests: XCTestCase {
  override func tearDown() {
    EarlGrey.selectElement(with: grey_anyOf([grey_text("EarlGreyContribTestApp"),
                                                    grey_text("Back")]))
      .perform(grey_tap())
    super.tearDown()
  }
  func testBasicViewController() {
    EarlGrey.selectElement(with: grey_text("Basic Views"))
      .usingSearch(grey_scrollInDirection(.down, 50),
        onElementWith: grey_kindOfClass(UITableView.self))
      .perform(grey_tap())
    EarlGrey.selectElement(with: grey_accessibilityLabel("textField"))
      .perform(grey_typeText("Foo"))
    EarlGrey.selectElement(with: grey_accessibilityLabel("showButton"))
      .perform(grey_tap())
    EarlGrey.selectElement(with: grey_accessibilityLabel("textLabel"))
      .assert(grey_text("Foo"))
  }
  func testCountOfTableViewCells() {
    var error: NSError? = nil
    let matcher: GREYMatcher! = grey_kindOfClass(UITableViewCell.self)
    let countOfTableViewCells: UInt = count(matcher: matcher)
    GREYAssert(countOfTableViewCells > 1, reason: "There are more than one cell present.")
    EarlGrey.selectElement(with: matcher)
      .atIndex(countOfTableViewCells + 1)
      .assert(grey_notNil(), error: &error)
    let errorCode: GREYInteractionErrorCode =
      GREYInteractionErrorCode.matchedElementIndexOutOfBoundsErrorCode
    let errorReason: String = "The Interaction element's index being used was over the count " +
    "of matched elements available."
    GREYAssert(error?.code == errorCode.rawValue, reason:errorReason)
  }
}
func count(matcher: GREYMatcher!) -> UInt {
  var error: NSError? = nil
  var index: UInt = 0
  let countMatcher: GREYElementMatcherBlock =
    GREYElementMatcherBlock.matcher(matchesBlock: { (element: Any) -> Bool in
      if (matcher.matches(element)) {
        index = index + 1;
      }
      return false;
    }) { (description: AnyObject?) in
      let greyDescription:GREYDescription = description as! GREYDescription
      greyDescription.appendText("Count of Matcher")
    }
  EarlGrey.selectElement(with: countMatcher)
    .assert(grey_notNil(), error: &error);
  return index
}


AppDelegate

//
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  func application(_ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    return true
  }
}


ViewController

//
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  var tableItems = (1...50).map { $0 }
  override func viewDidLoad() {
    super.viewDidLoad()
    // Create the send message view to contain one of the two send buttons
    let sendMessageView = SendMessageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    sendMessageView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(sendMessageView)
    // Create buttons
    let clickMe = createButton("ClickMe")
    view.addSubview(clickMe)
    let send = createButton("Send")
    // Change label to identify this button more easily for the layout test
    send.accessibilityLabel = "SendForLayoutTest"
    view.addSubview(send)
    let send2 = createButton("Send")
    sendMessageView.addSubview(send2)
    // Create a UITableView to send some elements out of the screen
    let table = createTable()
    view.addSubview(table)
    // Create constraints
    let views = ["clickMe": clickMe, "send": send, "send2": send2, "table": table,
                 "sendMessageView": sendMessageView]
    let metrics = ["smallMargin": 10, "mediumMargin": 20, "largeMargin": 40, "buttonSize": 100,
                   "tableSize": 320]
    var allConstraints = [NSLayoutConstraint]()
    let verticalConstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "V:|-largeMargin-[clickMe]-largeMargin-[send2]-largeMargin-[table]|",
      options: [],
      metrics: metrics,
      views: views)
    allConstraints += verticalConstraints
    let buttonsHorizontalConstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "|-smallMargin-[clickMe(buttonSize)]-mediumMargin-[send(buttonSize)]",
      options:.alignAllTop,
      metrics: metrics,
      views: views)
    allConstraints += buttonsHorizontalConstraints
    let sendMessageViewConstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "|-smallMargin-[send2(buttonSize)]",
      options:.alignAllTop,
      metrics: metrics,
      views: views)
    allConstraints += sendMessageViewConstraints
    let tableConstraints = NSLayoutConstraint.constraints(
      withVisualFormat: "|-smallMargin-[table(tableSize)]",
      options:.alignAllTop,
      metrics: metrics,
      views: views)
    allConstraints += tableConstraints
    NSLayoutConstraint.activate(allConstraints)
  }
  func createButton(_ title: String) -> UIButton {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    button.backgroundColor = UIColor.green
    button.setTitle(title, for: UIControlState())
    button.addTarget(self, action: #selector(ViewController.buttonAction(_:)),
        for: .touchUpInside)
    button.accessibilityIdentifier = title
    button.accessibilityLabel = title
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
  }
    if let id = sender.accessibilityIdentifier {
      print("Button \(id) clicked")
    }
  }
  func createTable() -> UITableView {
    let tableView = UITableView()
    tableView.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.estimatedRowHeight = 85.0
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.accessibilityIdentifier = "table"
    return tableView
  }
  func numberOfSections(in tableView:UITableView) -> Int {
    return 1
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableItems.count
  }
  func tableView(_ tableView: UITableView,
      cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell =
        tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
    // For cell 1 to 7, add a date
    var cellID : String
    if ((indexPath as NSIndexPath).row >= 1 && (indexPath as NSIndexPath).row <= 7) {
      cellID = getDateForIndex((indexPath as NSIndexPath).row)
    } else {
      cellID = "Cell\(tableItems[(indexPath as NSIndexPath).row])"
    }
    cell.textLabel?.text = cellID
    cell.accessibilityIdentifier = cellID
    return cell
  }
  func getDateForIndex(_ index: Int) -> String {
    var date = Date()
    var dateDeltaComponents = DateComponents()
    dateDeltaComponents.day = index
    date = (Calendar.current as NSCalendar).date(
        byAdding: dateDeltaComponents, to: date, options: NSCalendar.Options(rawValue: 0))!
    let formatter = DateFormatter()
    formatter.dateStyle = .long
    return formatter.string(from: date)
  }
}
  // empty sub class of UIView to exercise inRoot
}


EarlGreyExampleSwiftTests

//
class EarlGreyExampleSwiftTests: XCTestCase {
  func testBasicSelection() {
    // Select the button with Accessibility ID "clickMe".
    // This should throw a warning for "Result of Call Unused."
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
  }
  func testBasicSelectionAndAction() {
    // Select and tap the button with Accessibility ID "clickMe".
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
      .perform(grey_tap())
  }
  func testBasicSelectionAndAssert() {
    // Select the button with Accessibility ID "clickMe" and assert it's visible.
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
      .assert(grey_sufficientlyVisible())
  }
  func testBasicSelectionActionAssert() {
    // Select and tap the button with Accessibility ID "clickMe", then assert it's visible.
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
      .perform(grey_tap())
      .assert(grey_sufficientlyVisible())
  }
  func testSelectionOnMultipleElements() {
    // This test will fail because both buttons are visible and match the selection.
    // We add a custom error here to prevent the Test Suite failing.
    var error: NSError?
    EarlGrey.selectElement(with: grey_text("Non-Existent Element Text"))
      .perform(grey_tap(), error: &error)
    if let _ = error {
      print("Test Failed with Error : \(error.self!)")
    }
  }
  func testCollectionMatchers() {
    // First way to disambiguate: use collection matchers.
    let visibleSendButtonMatcher: GREYMatcher! =
        grey_allOf([grey_accessibilityID("ClickMe"), grey_sufficientlyVisible()])
    EarlGrey.selectElement(with: visibleSendButtonMatcher)
      .perform(grey_doubleTap())
  }
  func testWithInRoot() {
    // Second way to disambiguate: use inRoot to focus on a specific window or container.
    // There are two buttons with accessibility id "Send", but only one is inside SendMessageView.
    EarlGrey.selectElement(with: grey_accessibilityID("Send"))
      .inRoot(grey_kindOfClass(SendMessageView.self))
      .perform(grey_doubleTap())
  }
  func testWithCustomMatcher() {
    // Define the match condition: matches table cells that contains a date for a Thursday.
    let matches: MatchesBlock = { (element: Any?) -> Bool in
      if let cell = element as? UITableViewCell {
        let formatter = DateFormatter()
        formatter.dateStyle = DateFormatter.Style.long
        if let date = formatter.date(from: cell.textLabel!.text!) {
          let calendar = Calendar.current
          let weekday = (calendar as NSCalendar).component(NSCalendar.Unit.weekday, from: date)
          return weekday == 5
        } else {
          return false
        }
      } else {
        return false
      }
    }
    // Create a description for the matcher.
    let describe: DescribeToBlock = { (description: Any) -> Void in
      let greyDescription:GREYDescription = description as! GREYDescription
      greyDescription.appendText("Date for a Thursday")
    }
    // Create an EarlGrey custom matcher.
    let matcherForThursday: GREYElementMatcherBlock! =
      GREYElementMatcherBlock.init(matchesBlock: matches, descriptionBlock: describe)
    // Profit
    EarlGrey.selectElement(with: matcherForThursday)
      .perform(grey_doubleTap())
  }
  func testTableCellOutOfScreen() {
    // Go find one cell out of the screen.
    EarlGrey.selectElement(with: grey_accessibilityID("Cell30"))
      .usingSearch(grey_scrollInDirection(GREYDirection.down, 100),
          onElementWith: grey_accessibilityID("table"))
      .perform(grey_tap())
    // Move back to top of the table.
    EarlGrey.selectElement(with: grey_accessibilityID("Cell1"))
      .usingSearch(grey_scrollInDirection(GREYDirection.up, 500),
          onElementWith: grey_accessibilityID("table"))
      .perform(grey_doubleTap())
  }
  func testCatchErrorOnFailure() {
    // TapMe doesn't exist, but the test doesn't fail because we are getting a pointer to the
    // error.
    var error: NSError?
    EarlGrey.selectElement(with: grey_accessibilityID("TapMe"))
      .perform(grey_tap(), error: &error)
    if let myError = error {
      print(myError)
    }
  }
  func testCustomAction() {
    // Fade in and out an element.
    let fadeInAndOut = { (element: UIView) -> Void in
      UIView.animate(withDuration: 1.0, delay: 0.0,
                     options: UIViewAnimationOptions.curveEaseOut,
                     animations: { element.alpha = 0.0 }, completion: {
            (finished: Bool) -> Void in
              UIView.animate(withDuration: 1.0,
                             delay: 0.0,
                             options: UIViewAnimationOptions.curveEaseIn,
                             animations: { element.alpha = 1.0 },
                             completion: nil)
      })
    }
    // Define a custom action that applies fadeInAndOut to the selected element.
    let tapClickMe: GREYActionBlock =
      GREYActionBlock.action(withName: "Fade In And Out", perform: {
        (element: Any?, errorOrNil: UnsafeMutablePointer<NSError?>?) -> Bool in
        // First make sure element is attached to a window.
        let elementAsView :UIView = element as! UIView
        guard let window = elementAsView.window! as UIView! else {
          let errorInfo = [NSLocalizedDescriptionKey:
            NSLocalizedString("Element is not attached to a window",
                              comment: "")]
          errorOrNil?.pointee = NSError(domain: kGREYInteractionErrorDomain,
                                        code: 1,
                                        userInfo: errorInfo)
          return false
        }
        fadeInAndOut(window)
        return true
      });
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
      .perform(tapClickMe)
  }
  func testWithCustomAssertion() {
    // Write a custom assertion that checks if the alpha of an element is equal to the expected
    // value.
    let alphaEqual = { (expectedAlpha: CGFloat) -> GREYAssertionBlock in
      return GREYAssertionBlock.assertion(withName: "Assert Alpha Equal",
                                          assertionBlockWithError: {
        (element: Any?, errorOrNil: UnsafeMutablePointer<NSError?>?) -> Bool in
        guard let view = element! as! UIView as UIView! else {
          let errorInfo = [NSLocalizedDescriptionKey:
            NSLocalizedString("Element is not a UIView",
                              comment: "")]
          errorOrNil?.pointee =
            NSError(domain: kGREYInteractionErrorDomain,
                    code: 2,
                    userInfo: errorInfo)
          return false
        }
        return view.alpha == expectedAlpha
      })
    }
    EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
      .assert(alphaEqual(1.0))
  }
  func testWithCustomFailureHandler() {
    // This test will fail and use our custom handler to handle the failure.
    // The custom handler is defined at the end of this file.
    let myHandler = SampleFailureHandler()
    EarlGrey.setFailureHandler(handler: myHandler)
    EarlGrey.selectElement(with: grey_accessibilityID("TapMe"))
      .perform(grey_tap())
  }
  func testLayout() {
    // Define a layout constraint.
    let onTheRight: GREYLayoutConstraint =
      GREYLayoutConstraint(attribute: GREYLayoutAttribute.left,
                           relatedBy: GREYLayoutRelation.greaterThanOrEqual,
                           toReferenceAttribute: GREYLayoutAttribute.right,
                           multiplier: 1.0,
                           constant: 0.0)
    EarlGrey.selectElement(with: grey_accessibilityLabel("SendForLayoutTest"))
      .assert(grey_layout([onTheRight], grey_accessibilityID("ClickMe")))
  }
  func testWithCondition() {
    let myCondition = GREYCondition.init(name: "Example condition", block: { () -> Bool in
      for j in 0...100000 {
        _ = j
      }
      return true
    })
    // Wait for my condition to be satisfied or timeout after 5 seconds.
    let success = myCondition.wait(withTimeout: 5)
    if !success {
      // Just printing for the example.
      print("Condition not met")
    } else {
      EarlGrey.selectElement(with: grey_accessibilityID("ClickMe"))
        .perform(grey_tap())
    }
  }
  func testWithGreyAssertions() {
    GREYAssert(1 == 1, reason: "Assert with GREYAssert")
    GREYAssertTrue(1 == 1, reason: "Assert with GREYAssertTrue")
    GREYAssertFalse(1 != 1, reason: "Assert with GREYAssertFalse")
    GREYAssertNotNil(1, reason: "Assert with GREYAssertNotNil")
    GREYAssertNil(nil, reason: "Assert with GREYAssertNil")
    GREYAssertEqualObjects(1, 1, reason: "Assert with GREYAssertEqualObjects")
    // Uncomment one of the following lines to fail the test.
    //GREYFail("Failing with GREYFail")
  }
}
class SampleFailureHandler : NSObject, GREYFailureHandler {
  /**
   *  Called by the framework to raise an exception.
   *
   */
  public func handle(_ exception: GREYFrameworkException!, details: String!) {
    print("Test Failed With Reason : \(exception.reason!) and details \(details)")
  }
}


FTRSwiftTests

//
//
import EarlGrey
import XCTest
class TextFieldEventsRecorder {
  var textDidBeginEditing = false
  var textDidChange = false
  var textDidEndEditing = false
  var editingDidBegin = false
  var editingChanged = false
  var editingDidEndOnExit = false
  var editingDidEnd = false
  func registerActionBlock() -> GREYActionBlock {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(textDidBeginEditingHandler),
                                           name: NSNotification.Name.UITextFieldTextDidBeginEditing,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(textDidChangeHandler),
                                           name: NSNotification.Name.UITextFieldTextDidChange,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(textDidEndEditingHandler),
                                           name: NSNotification.Name.UITextFieldTextDidEndEditing,
                                           object: nil)
    return GREYActionBlock.action(withName: "Register to editing events") {
      (element: Any?, errorOrNil: UnsafeMutablePointer<NSError?>?) -> Bool in
      let element:UIControl = element as! UIControl
      element.addTarget(self,
                        action: #selector(self.editingDidBeginHandler), for: .editingDidBegin)
      element.addTarget(self,
                        action: #selector(self.editingChangedHandler), for: .editingChanged)
      element.addTarget(self,
                        action: #selector(self.editingDidEndOnExitHandler),
                        for: .editingDidEndOnExit)
      element.addTarget(self,
                        action: #selector(self.editingDidEndHandler), for: .editingDidEnd)
      return true
    }
  }
  func verify() -> Bool {
    return textDidBeginEditing && textDidChange && textDidEndEditing &&
      editingDidBegin && editingChanged && editingDidEndOnExit && editingDidEnd
  }
}
class FTRSwiftTests: XCTestCase {
  override func tearDown() {
    super.tearDown()
    let delegateWindow:UIWindow! = UIApplication.shared.delegate!.window!
    var navController:UINavigationController?
    if ((delegateWindow.rootViewController?.isKind(of: UINavigationController.self)) != nil) {
      navController = delegateWindow.rootViewController as? UINavigationController
    } else {
      navController = delegateWindow.rootViewController!.navigationController
    }
    _ = navController?.popToRootViewController(animated: true)
  }
  func testOpeningView() {
    self.openTestView("Typing Views")
  }
  func testRotation() {
    EarlGrey.rotateDeviceTo(orientation: UIDeviceOrientation.landscapeLeft, errorOrNil: nil)
    EarlGrey.rotateDeviceTo(orientation: UIDeviceOrientation.portrait, errorOrNil: nil)
  }
  func testTyping() {
    self.openTestView("Typing Views")
    let matcher = grey_accessibilityID("TypingTextField")
    let action = grey_typeText("Sample Swift Test")
    let assertionMatcher = grey_text("Sample Swift Test")
    EarlGrey.selectElement(with: matcher)
      .perform(action)
      .assert(assertionMatcher)
  }
  func testTypingWithError() {
    self.openTestView("Typing Views")
    EarlGrey.selectElement(with: grey_accessibilityID("TypingTextField"))
      .perform(grey_typeText("Sample Swift Test"))
      .assert(grey_text("Sample Swift Test"))
    var error: NSError?
    EarlGrey.selectElement(with: grey_accessibilityID("TypingTextField"))
      .perform(grey_typeText(""), error: &error)
      .assert(grey_text("Sample Swift Test"), error: nil)
    GREYAssert(error != nil, reason: "Performance should have errored")
    error = nil
    EarlGrey.selectElement(with: grey_accessibilityID("TypingTextField"))
      .perform(grey_clearText())
      .perform(grey_typeText("Sample Swift Test"), error: nil)
      .assert(grey_text("Garbage Value"), error: &error)
    GREYAssert(error != nil, reason: "Performance should have errored")
  }
  func testFastTyping() {
    self.openTestView("Typing Views")
    let textFieldEventsRecorder = TextFieldEventsRecorder()
    EarlGrey.selectElement(with: grey_accessibilityID("TypingTextField"))
      .perform(textFieldEventsRecorder.registerActionBlock())
      .perform(grey_replaceText("Sample Swift Test"))
      .assert(grey_text("Sample Swift Test"))
    GREYAssert(textFieldEventsRecorder.verify(), reason: "Text field events were not all received")
  }
  func testTypingWithDeletion() {
    self.openTestView("Typing Views")
    EarlGrey.selectElement(with: grey_accessibilityID("TypingTextField"))
      .perform(grey_typeText("Fooo\u{8}B\u{8}Bar"))
      .assert(grey_text("FooBar"))
  }
  func testButtonPressWithGREYAllOf() {
    self.openTestView("Basic Views")
    EarlGrey.selectElement(with: grey_text("Tab 2")).perform(grey_tap())
    let matcher = grey_allOf([grey_text("Long Press"), grey_sufficientlyVisible()])
    EarlGrey.selectElement(with: matcher).perform(grey_longPressWithDuration(1.1))
      .assert(grey_notVisible())
  }
  func testPossibleOpeningViews() {
    self.openTestView("Alert Views")
    let matcher = grey_anyOf([grey_text("FooText"),
                              grey_text("Simple Alert"),
                              grey_buttonTitle("BarTitle")])
    EarlGrey.selectElement(with: matcher).perform(grey_tap())
    EarlGrey.selectElement(with: grey_text("Flee"))
      .assert(grey_sufficientlyVisible())
      .perform(grey_tap())
  }
  func testSwiftCustomMatcher() {
    // Verify description in custom matcher isn't nil.
    // unexpectedly found nil while unwrapping an Optional value
    EarlGrey.selectElement(with: grey_allOf([grey_firstElement(),
                                                    grey_text("FooText")]))
      .assert(grey_nil())
  }
  func testInteractionWithALabelWithParentHidden() {
    let checkHiddenBlock:GREYActionBlock =
      GREYActionBlock.action(withName: "checkHiddenBlock", perform: { element, errorOrNil in
        // Check if the found element is hidden or not.
        let superView:UIView! = element as! UIView
        return !superView.isHidden
      })
    self.openTestView("Basic Views")
    EarlGrey.selectElement(with: grey_text("Tab 2")).perform(grey_tap())
    EarlGrey.selectElement(with: grey_accessibilityLabel("tab2Container"))
      .perform(checkHiddenBlock).assert(grey_sufficientlyVisible())
    var error: NSError?
    EarlGrey.selectElement(with: grey_text("Non Existent Element"))
      .perform(grey_tap(), error:&error)
    if let errorVal = error {
      GREYAssertEqual(errorVal.domain as AnyObject?, kGREYInteractionErrorDomain as AnyObject?,
                      reason: "Element Not Found Error")
    }
  }
  func testChangingDatePickerToAFutureDate() {
    self.openTestView("Picker Views")
    // Have an arbitrary date created
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let date = Date(timeIntervalSinceReferenceDate: 118800)
    dateFormatter.locale = Locale(identifier: "en_US")
    EarlGrey.selectElement(with: grey_text("Date")).perform(grey_tap())
    EarlGrey.selectElement(with: grey_accessibilityID("DatePickerId"))
      .perform(grey_setDate(date))
    EarlGrey.selectElement(with: grey_accessibilityID("DatePickerId"))
      .assert(grey_datePickerValue(date))
  }
  func testStepperActionWithCondition() {
    self.openTestView("Basic Views")
    var stepperValue = 51.0
    // Without the parameter using the value of the wait action, a warning should be seen.
    _ = GREYCondition.init(name: "conditionWithAction", block: {
      stepperValue += 1
      EarlGrey.selectElement(with: grey_kindOfClass(UIStepper.self))
        .perform(grey_setStepperValue(stepperValue))
      return stepperValue == 55
    }).waitWithTimeout(seconds: 10.0)
    EarlGrey.selectElement(with: grey_kindOfClass(UIStepper.self))
      .assert(grey_stepperValue(55))
  }
  func openTestView(_ name: String) {
    var errorOrNil : NSError?
    EarlGrey.selectElement(with: grey_accessibilityLabel(name))
      .perform(grey_tap(), error: &errorOrNil)
    if ((errorOrNil == nil)) {
      return
    }
    EarlGrey.selectElement(with: grey_kindOfClass(UITableView.self))
      .perform(grey_scrollToContentEdge(GREYContentEdge.top))
    EarlGrey.selectElement(with: grey_allOf([grey_accessibilityLabel(name),
                                                    grey_interactable()]))
      .using(searchAction: grey_scrollInDirection(GREYDirection.down, 200),
             onElementWithMatcher: grey_kindOfClass(UITableView.self))
      .perform(grey_tap())
  }
  func grey_firstElement() -> GREYMatcher {
    var firstMatch = true
    let matches: MatchesBlock = { (element: Any) -> Bool in
      if firstMatch {
        firstMatch = false
        return true
      }
      return false
    }
    let describe: DescribeToBlock = { (description: GREYDescription?) -> Void in
      description!.appendText("first match")
    }
    return GREYElementMatcherBlock.init(matchesBlock: matches, descriptionBlock: describe)
  }
}


GPBSwiftTests

// Protocol Buffers - Google's data interchange format
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
import Foundation
import XCTest
// Test some usage of the ObjC library from Swift.
class GPBBridgeTests: XCTestCase {
  func testProto2Basics() {
    let msg = Message2()
    let msg2 = Message2()
    let msg3 = Message2_OptionalGroup()
    msg.optionalInt32 = 100
    msg.optionalString = "abc"
    msg.optionalEnum = .bar
    msg2.optionalString = "other"
    msg.optional = msg2
    msg3.a = 200
    msg.optionalGroup = msg3
    msg.repeatedInt32Array.addValue(300)
    msg.repeatedInt32Array.addValue(301)
    msg.repeatedStringArray.add("mno")
    msg.repeatedStringArray.add("pqr")
    msg.repeatedEnumArray.addValue(Message2_Enum.bar.rawValue)
    msg.repeatedEnumArray.addValue(Message2_Enum.baz.rawValue)
    msg.mapInt32Int32.setInt32(400, forKey:500)
    msg.mapInt32Int32.setInt32(401, forKey:501)
    msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
    msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
    msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600)
    msg.mapInt32Enum.setEnum(Message2_Enum.baz.rawValue, forKey:601)
    // Check has*.
    XCTAssertTrue(msg.hasOptionalInt32)
    XCTAssertTrue(msg.hasOptionalString)
    XCTAssertTrue(msg.hasOptionalEnum)
    XCTAssertTrue(msg2.hasOptionalString)
    XCTAssertTrue(msg.hasOptionalMessage)
    XCTAssertTrue(msg3.hasA)
    XCTAssertTrue(msg.hasOptionalGroup)
    XCTAssertFalse(msg.hasOptionalInt64)
    XCTAssertFalse(msg.hasOptionalFloat)
    // Check values.
    XCTAssertEqual(msg.optionalInt32, Int32(100))
    XCTAssertEqual(msg.optionalString, "abc")
    XCTAssertEqual(msg2.optionalString, "other")
    XCTAssertTrue(msg.optional === msg2)
    XCTAssertEqual(msg.optionalEnum, Message2_Enum.bar)
    XCTAssertEqual(msg3.a, Int32(200))
    XCTAssertTrue(msg.optionalGroup === msg3)
    XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2))
    XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300))
    XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301))
    XCTAssertEqual(msg.repeatedStringArray.count, Int(2))
    XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno")
    XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr")
    XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2))
    XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message2_Enum.bar.rawValue)
    XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message2_Enum.baz.rawValue)
    XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0))
    XCTAssertEqual(msg.mapInt32Int32.count, UInt(2))
    var intValue: Int32 = 0
    XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey: 500))
    XCTAssertEqual(intValue, Int32(400))
    XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey: 501))
    XCTAssertEqual(intValue, Int32(401))
    XCTAssertEqual(msg.mapStringString.count, Int(2))
    XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo")
    XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc")
    XCTAssertEqual(msg.mapInt32Enum.count, UInt(2))
    XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600))
    XCTAssertEqual(intValue, Message2_Enum.bar.rawValue)
    XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601))
    XCTAssertEqual(intValue, Message2_Enum.baz.rawValue)
    // Clearing a string with nil.
    msg2.optionalString = nil
    XCTAssertFalse(msg2.hasOptionalString)
    XCTAssertEqual(msg2.optionalString, "")
    // Clearing a message with nil.
    msg.optionalGroup = nil
    XCTAssertFalse(msg.hasOptionalGroup)
    XCTAssertTrue(msg.optionalGroup !== msg3)  // New instance
    // Clear.
    msg.clear()
    XCTAssertFalse(msg.hasOptionalInt32)
    XCTAssertFalse(msg.hasOptionalString)
    XCTAssertFalse(msg.hasOptionalEnum)
    XCTAssertFalse(msg.hasOptionalMessage)
    XCTAssertFalse(msg.hasOptionalInt64)
    XCTAssertFalse(msg.hasOptionalFloat)
    XCTAssertEqual(msg.optionalInt32, Int32(0))
    XCTAssertEqual(msg.optionalString, "")
    XCTAssertTrue(msg.optional !== msg2)  // New instance
    XCTAssertEqual(msg.optionalEnum, Message2_Enum.foo)  // Default
    XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0))
    XCTAssertEqual(msg.repeatedStringArray.count, Int(0))
    XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0))
    XCTAssertEqual(msg.mapInt32Int32.count, UInt(0))
    XCTAssertEqual(msg.mapStringString.count, Int(0))
    XCTAssertEqual(msg.mapInt32Enum.count, UInt(0))
  }
  func testProto3Basics() {
    let msg = Message3()
    let msg2 = Message3()
    msg.optionalInt32 = 100
    msg.optionalString = "abc"
    msg.optionalEnum = .bar
    msg2.optionalString = "other"
    msg.optional = msg2
    msg.repeatedInt32Array.addValue(300)
    msg.repeatedInt32Array.addValue(301)
    msg.repeatedStringArray.add("mno")
    msg.repeatedStringArray.add("pqr")
    // "proto3" syntax lets enum get unknown values.
    msg.repeatedEnumArray.addValue(Message3_Enum.bar.rawValue)
    msg.repeatedEnumArray.addRawValue(666)
    SetMessage3_OptionalEnum_RawValue(msg2, 666)
    msg.mapInt32Int32.setInt32(400, forKey:500)
    msg.mapInt32Int32.setInt32(401, forKey:501)
    msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
    msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
    msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600)
    // "proto3" syntax lets enum get unknown values.
    msg.mapInt32Enum.setRawValue(666, forKey:601)
    // Has only exists on for message fields.
    XCTAssertTrue(msg.hasOptionalMessage)
    XCTAssertFalse(msg2.hasOptionalMessage)
    // Check values.
    XCTAssertEqual(msg.optionalInt32, Int32(100))
    XCTAssertEqual(msg.optionalString, "abc")
    XCTAssertEqual(msg2.optionalString, "other")
    XCTAssertTrue(msg.optional === msg2)
    XCTAssertEqual(msg.optionalEnum, Message3_Enum.bar)
    XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2))
    XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300))
    XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301))
    XCTAssertEqual(msg.repeatedStringArray.count, Int(2))
    XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno")
    XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr")
    XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0))
    XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2))
    XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message3_Enum.bar.rawValue)
    XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue)
    XCTAssertEqual(msg.repeatedEnumArray.rawValue(at: 1), 666)
    XCTAssertEqual(msg2.optionalEnum, Message3_Enum.gpbUnrecognizedEnumeratorValue)
    XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Int32(666))
    XCTAssertEqual(msg.mapInt32Int32.count, UInt(2))
    var intValue: Int32 = 0
    XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey:500))
    XCTAssertEqual(intValue, Int32(400))
    XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey:501))
    XCTAssertEqual(intValue, Int32(401))
    XCTAssertEqual(msg.mapStringString.count, Int(2))
    XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo")
    XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc")
    XCTAssertEqual(msg.mapInt32Enum.count, UInt(2))
    XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600))
    XCTAssertEqual(intValue, Message2_Enum.bar.rawValue)
    XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601))
    XCTAssertEqual(intValue, Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue)
    XCTAssertTrue(msg.mapInt32Enum.getRawValue(&intValue, forKey:601))
    XCTAssertEqual(intValue, 666)
    // Clearing a string with nil.
    msg2.optionalString = nil
    XCTAssertEqual(msg2.optionalString, "")
    // Clearing a message with nil.
    msg.optional = nil
    XCTAssertFalse(msg.hasOptionalMessage)
    XCTAssertTrue(msg.optional !== msg2)  // New instance
    // Clear.
    msg.clear()
    XCTAssertFalse(msg.hasOptionalMessage)
    XCTAssertEqual(msg.optionalInt32, Int32(0))
    XCTAssertEqual(msg.optionalString, "")
    XCTAssertTrue(msg.optional !== msg2)  // New instance
    XCTAssertEqual(msg.optionalEnum, Message3_Enum.foo)  // Default
    XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0))
    XCTAssertEqual(msg.repeatedStringArray.count, Int(0))
    XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0))
    msg2.clear()
    XCTAssertEqual(msg2.optionalEnum, Message3_Enum.foo)  // Default
    XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Message3_Enum.foo.rawValue)
    XCTAssertEqual(msg.mapInt32Int32.count, UInt(0))
    XCTAssertEqual(msg.mapStringString.count, Int(0))
    XCTAssertEqual(msg.mapInt32Enum.count, UInt(0))
  }
  func testAutoCreation() {
    let msg = Message2()
    XCTAssertFalse(msg.hasOptionalGroup)
    XCTAssertFalse(msg.hasOptionalMessage)
    // Access shouldn't result in has* but should return objects.
    let msg2 = msg.optionalGroup
    let msg3 = msg.optional.optional
    let msg4 = msg.optional
    XCTAssertNotNil(msg2)
    XCTAssertNotNil(msg3)
    XCTAssertFalse(msg.hasOptionalGroup)
    XCTAssertFalse(msg.optional.hasOptionalMessage)
    XCTAssertFalse(msg.hasOptionalMessage)
    // Setting things should trigger has* getting set.
    msg.optionalGroup.a = 10
    msg.optional.optional.optionalInt32 = 100
    XCTAssertTrue(msg.hasOptionalGroup)
    XCTAssertTrue(msg.optional.hasOptionalMessage)
    XCTAssertTrue(msg.hasOptionalMessage)
    // And they should be the same pointer as before.
    XCTAssertTrue(msg2 === msg.optionalGroup)
    XCTAssertTrue(msg3 === msg.optional.optional)
    XCTAssertTrue(msg4 === msg.optional)
    // Clear gets us new objects next time around.
    msg.clear()
    XCTAssertFalse(msg.hasOptionalGroup)
    XCTAssertFalse(msg.optional.hasOptionalMessage)
    XCTAssertFalse(msg.hasOptionalMessage)
    msg.optionalGroup.a = 20
    msg.optional.optional.optionalInt32 = 200
    XCTAssertTrue(msg.hasOptionalGroup)
    XCTAssertTrue(msg.optional.hasOptionalMessage)
    XCTAssertTrue(msg.hasOptionalMessage)
    XCTAssertTrue(msg2 !== msg.optionalGroup)
    XCTAssertTrue(msg3 !== msg.optional.optional)
    XCTAssertTrue(msg4 !== msg.optional)
    // Explicit set of a message, means autocreated object doesn't bind.
    msg.clear()
    let autoCreated = msg.optional
    XCTAssertFalse(msg.hasOptionalMessage)
    let msg5 = Message2()
    msg5.optionalInt32 = 123
    msg.optional = msg5
    XCTAssertTrue(msg.hasOptionalMessage)
    // Modifying the autocreated doesn't replaced the explicit set one.
    autoCreated?.optionalInt32 = 456
    XCTAssertTrue(msg.hasOptionalMessage)
    XCTAssertTrue(msg.optional === msg5)
    XCTAssertEqual(msg.optional.optionalInt32, Int32(123))
  }
  func testProto2OneOfSupport() {
    let msg = Message2()
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(110.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz)  // Default
    let autoCreated = msg.oneof  // Default create one.
    XCTAssertNotNil(autoCreated)
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
    msg.oneofInt32 = 10
    XCTAssertEqual(msg.oneofInt32, Int32(10))
    XCTAssertEqual(msg.oneofFloat, Float(110.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32)
    msg.oneofFloat = 20.0
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(20.0))
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofFloat)
    msg.oneofEnum = .bar
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(110.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.bar)
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofEnum)
    // Sets via the autocreated instance.
    msg.oneof.optionalInt32 = 200
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(110.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(200))
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage)
    // Clear the oneof.
    Message2_ClearOOneOfCase(msg)
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(110.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz)  // Default
    let autoCreated2 = msg.oneof  // Default create one
    XCTAssertNotNil(autoCreated2)
    XCTAssertTrue(autoCreated2 !== autoCreated)  // New instance
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
    msg.oneofInt32 = 10
    XCTAssertEqual(msg.oneofInt32, Int32(10))
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32)
    // Confirm Message.clear() handles the oneof correctly.
    msg.clear()
    XCTAssertEqual(msg.oneofInt32, Int32(100))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
    // Sets via the autocreated instance.
    msg.oneof.optionalInt32 = 300
    XCTAssertTrue(msg.oneof !== autoCreated)  // New instance
    XCTAssertTrue(msg.oneof !== autoCreated2)  // New instance
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(300))
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage)
    // Set message to nil clears the oneof.
    msg.oneof = nil
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
  }
  func testProto3OneOfSupport() {
    let msg = Message3()
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(0.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo)  // Default
    let autoCreated = msg.oneof  // Default create one.
    XCTAssertNotNil(autoCreated)
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
    msg.oneofInt32 = 10
    XCTAssertEqual(msg.oneofInt32, Int32(10))
    XCTAssertEqual(msg.oneofFloat, Float(0.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32)
    msg.oneofFloat = 20.0
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(20.0))
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofFloat)
    msg.oneofEnum = .bar
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(0.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.bar)
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofEnum)
    // Sets via the autocreated instance.
    msg.oneof.optionalInt32 = 200
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(0.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo)  // Default
    XCTAssertTrue(msg.oneof === autoCreated)  // Still the same
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(200))
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage)
    // Clear the oneof.
    Message3_ClearOOneOfCase(msg)
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oneofFloat, Float(0.0))  // Default
    XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo)  // Default
    let autoCreated2 = msg.oneof  // Default create one
    XCTAssertNotNil(autoCreated2)
    XCTAssertTrue(autoCreated2 !== autoCreated)  // New instance
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
    msg.oneofInt32 = 10
    XCTAssertEqual(msg.oneofInt32, Int32(10))
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32)
    // Confirm Message.clear() handles the oneof correctly.
    msg.clear()
    XCTAssertEqual(msg.oneofInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
    // Sets via the autocreated instance.
    msg.oneof.optionalInt32 = 300
    XCTAssertTrue(msg.oneof !== autoCreated)  // New instance
    XCTAssertTrue(msg.oneof !== autoCreated2)  // New instance
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(300))
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage)
    // Set message to nil clears the oneof.
    msg.oneof = nil
    XCTAssertEqual(msg.oneof.optionalInt32, Int32(0))  // Default
    XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
  }
  func testSerialization() {
    let msg = Message2()
    msg.optionalInt32 = 100
    msg.optionalInt64 = 101
    msg.optionalGroup.a = 102
    msg.repeatedStringArray.add("abc")
    msg.repeatedStringArray.add("def")
    msg.mapInt32Int32.setInt32(200, forKey:300)
    msg.mapInt32Int32.setInt32(201, forKey:201)
    msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
    msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
    let data = msg.data()
    let msg2 = try! Message2(data: data!)
    XCTAssertTrue(msg2 !== msg)  // New instance
    XCTAssertEqual(msg.optionalInt32, Int32(100))
    XCTAssertEqual(msg.optionalInt64, Int64(101))
    XCTAssertEqual(msg.optionalGroup.a, Int32(102))
    XCTAssertEqual(msg.repeatedStringArray.count, Int(2))
    XCTAssertEqual(msg.mapInt32Int32.count, UInt(2))
    XCTAssertEqual(msg.mapStringString.count, Int(2))
    XCTAssertEqual(msg2, msg)
  }
}


TFLBertTokenizerTest

class TFLBertTokenizerTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertTokenizerTest.self)
  static let mobileBertVocabPath = bundle.path(forResource: "mobilebert_vocab", ofType: "txt")!
  func testInitBertTokenizerFromPath() {
    let bertTokenizer = TFLBertTokenizer(vocabPath: TFLBertTokenizerTest.mobileBertVocabPath)
    XCTAssertNotNil(bertTokenizer)
    let tokens = bertTokenizer.tokens(fromInput: "i'm questionansweraskask")
    XCTAssertEqual(tokens, ["i", "'", "m", "question", "##ans", "##wer", "##ask", "##ask"])
    let ids = bertTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [1045, 1005, 1049, 3160, 6962, 13777, 19895, 19895])
  }
  func testInitBertTokenizerFromVocab() {
    let bertTokenizer = TFLBertTokenizer(vocab: ["hell", "##o", "wor", "##ld", "there"])
    XCTAssertNotNil(bertTokenizer)
    let tokens = bertTokenizer.tokens(fromInput: "hello there hello world")
    XCTAssertEqual(tokens, ["hell", "##o", "there", "hell", "##o", "wor", "##ld"])
    let ids = bertTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [0, 1, 4, 0, 1, 2, 3])
  }
}


TFLSentencepieceTokenizerTest

class TFLSentencepieceTokenizerTest: XCTestCase {
  static let bundle = Bundle(for: TFLSentencepieceTokenizerTest.self)
  static let spModelPath = bundle.path(forResource: "30k-clean", ofType: "model")!
  func testInitSentenpieceTokenizerFromPath() {
    let spTokenizer = TFLSentencepieceTokenizer(
      modelPath: TFLSentencepieceTokenizerTest.spModelPath)
    XCTAssertNotNil(spTokenizer)
    let tokens = spTokenizer.tokens(fromInput: "good morning, i'm your teacher.\n")
    XCTAssertEqual(tokens, ["▁good", "▁morning", ",", "▁i", "'", "m", "▁your", "▁teacher", "."])
    let ids = spTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [254, 959, 15, 31, 22, 79, 154, 2197, 9])
  }
}


TFLAudioClassifierTests

class AudioClassifierTests: XCTestCase {
  static let bundle = Bundle(for: AudioClassifierTests.self)
  static let modelPath = bundle.path(
    forResource: "yamnet_audio_classifier_with_metadata",
    ofType: "tflite")
  func verifyError(
    _ error: Error,
    expectedLocalizedDescription: String
  ) {
    XCTAssertEqual(
      error.localizedDescription,
      expectedLocalizedDescription)
  }
  func verifyCategory(
    _ category: ClassificationCategory,
    expectedIndex: NSInteger,
    expectedScore: Float,
    expectedLabel: String,
    expectedDisplayName: String?
  ) {
    XCTAssertEqual(
      category.index,
      expectedIndex)
    XCTAssertEqual(
      category.score,
      expectedScore,
      accuracy: 1e-6)
    XCTAssertEqual(
      category.label,
      expectedLabel)
    XCTAssertEqual(
      category.displayName,
      expectedDisplayName)
  }
  func verifyClassifications(
    _ classifications: Classifications,
    expectedHeadIndex: NSInteger,
    expectedCategoryCount: NSInteger
  ) {
    XCTAssertEqual(
      classifications.headIndex,
      expectedHeadIndex)
    XCTAssertEqual(
      classifications.categories.count,
      expectedCategoryCount)
  }
  func verifyClassificationResult(
    _ classificationResult: ClassificationResult,
    expectedClassificationsCount: NSInteger
  ) {
    XCTAssertEqual(
      classificationResult.classifications.count,
      expectedClassificationsCount)
  }
  func bufferFromFile(
    withName name: String,
    fileExtension: String,
    audioFormat: AudioFormat
  ) -> AVAudioPCMBuffer? {
    guard
      let filePath = AudioClassifierTests.bundle.path(
        forResource: name,
        ofType: fileExtension)
    else {
      return nil
    }
    return AVAudioPCMBuffer.loadPCMBufferFromFile(
      withPath: filePath,
      audioFormat: audioFormat)
  }
  func createAudioClassifierOptions(
    modelPath: String?
  ) throws -> AudioClassifierOptions? {
    let modelPath = try XCTUnwrap(modelPath)
    let options = AudioClassifierOptions(modelPath: modelPath)
    return options
  }
  func createAudioClassifier(
    withModelPath modelPath: String?
  ) throws -> AudioClassifier? {
    let options = try XCTUnwrap(
      self.createAudioClassifierOptions(
        modelPath: AudioClassifierTests.modelPath))
    let audioClassifier = try XCTUnwrap(
      AudioClassifier.classifier(
        options: options))
    return audioClassifier
  }
  func createAudioTensor(
    withAudioClassifier audioClassifier: AudioClassifier
  ) -> AudioTensor {
    let audioTensor = audioClassifier.createInputAudioTensor()
    return audioTensor
  }
  func loadAudioTensor(
    _ audioTensor: AudioTensor,
    fromWavFileWithName fileName: String
  ) throws {
    // Load pcm buffer from file.
    let buffer = try XCTUnwrap(
      self.bufferFromFile(
        withName: fileName,
        fileExtension: "wav",
        audioFormat: audioTensor.audioFormat))
    // Get float buffer from pcm buffer.
    let floatBuffer = try XCTUnwrap(buffer.floatBuffer)
    // Load float buffer into the audio tensor.
    try audioTensor.load(
      buffer: floatBuffer,
      offset: 0,
      size: floatBuffer.size)
  }
  func classify(
    audioTensor: AudioTensor,
    usingAudioClassifier audioClassifier: AudioClassifier
  ) throws -> ClassificationResult? {
    let classificationResult = try XCTUnwrap(
      audioClassifier.classify(
        audioTensor: audioTensor))
    let expectedClassificationsCount = 1
    self.verifyClassificationResult(
      classificationResult,
      expectedClassificationsCount: expectedClassificationsCount)
    let expectedCategoryCount = 521
    let expectedHeadIndex = 0
    self.verifyClassifications(
      classificationResult.classifications[0],
      expectedHeadIndex: expectedHeadIndex,
      expectedCategoryCount: expectedCategoryCount)
    return classificationResult
  }
  func validateForInferenceWithFloatBuffer(
    categories: [ClassificationCategory]
  ) {
    self.verifyCategory(
      categories[0],
      expectedIndex: 0,
      expectedScore: 0.957031,
      expectedLabel: "Speech",
      expectedDisplayName: nil)
    self.verifyCategory(
      categories[1],
      expectedIndex: 500,
      0.019531,               // expectedScore
      expectedLabel: "Inside, small room",
      expectedDisplayName: nil)
  }
  func testInferenceWithFloatBufferSucceeds() throws {
    let audioClassifier = try XCTUnwrap(
      self.createAudioClassifier(
        withModelPath: AudioClassifierTests.modelPath))
    let audioTensor = self.createAudioTensor(
      withAudioClassifier: audioClassifier)
    try self.loadAudioTensor(
      audioTensor, fromWavFileWithName: "speech")
    let classificationResult = try XCTUnwrap(
      self.classify(
        audioTensor: audioTensor,
        usingAudioClassifier: audioClassifier))
    self.validateForInferenceWithFloatBuffer(
      categories: classificationResult.classifications[0].categories)
  }
  func testInferenceWithNoModelPathFails() throws {
    let options = AudioClassifierOptions()
    do {
      let audioClassifier = try AudioClassifier.classifier(
        options: options)
      XCTAssertNil(audioClassifier)
    } catch {
      self.verifyError(
        error,
        expectedLocalizedDescription:
          "INVALID_ARGUMENT: Missing mandatory `model_file` field in `base_options`")
    }
  }
}


TFLImageSegmenterTests

class ImageSegmenterTests: XCTestCase {
  static let bundle = Bundle(for: ImageSegmenterTests.self)
  static let modelPath = bundle.path(
    forResource: "deeplabv3",
    ofType: "tflite")
  // The maximum fraction of pixels in the candidate mask that can have a
  // different class than the golden mask for the test to pass.
  let kGoldenMaskTolerance: Float = 1e-2
  // Magnification factor used when creating the golden category masks to make
  // them more human-friendly. Each pixel in the golden masks has its value
  // multiplied by this factor, i.e. a value of 10 means class index 1, a value of
  // 20 means class index 2, etc.
  let kGoldenMaskMagnificationFactor: UInt8 = 10
  let deepLabV3SegmentationWidth = 257
  let deepLabV3SegmentationHeight = 257
  func verifyDeeplabV3PartialSegmentationResult(_ coloredLabels: [ColoredLabel]) {
    self.verifyColoredLabel(
      coloredLabels[0],
      expectedR: 0,
      expectedG: 0,
      expectedB: 0,
      expectedLabel: "background")
    self.verifyColoredLabel(
      coloredLabels[1],
      expectedR: 128,
      expectedG: 0,
      expectedB: 0,
      expectedLabel: "aeroplane")
    self.verifyColoredLabel(
      coloredLabels[2],
      expectedR: 0,
      expectedG: 128,
      expectedB: 0,
      expectedLabel: "bicycle")
    self.verifyColoredLabel(
      coloredLabels[3],
      expectedR: 128,
      expectedG: 128,
      expectedB: 0,
      expectedLabel: "bird")
    self.verifyColoredLabel(
      coloredLabels[4],
      expectedR: 0,
      expectedG: 0,
      expectedB: 128,
      expectedLabel: "boat")
    self.verifyColoredLabel(
      coloredLabels[5],
      expectedR: 128,
      expectedG: 0,
      expectedB: 128,
      expectedLabel: "bottle")
    self.verifyColoredLabel(
      coloredLabels[6],
      expectedR: 0,
      expectedG: 128,
      expectedB: 128,
      expectedLabel: "bus")
    self.verifyColoredLabel(
      coloredLabels[7],
      expectedR: 128,
      expectedG: 128,
      expectedB: 128,
      expectedLabel: "car")
    self.verifyColoredLabel(
      coloredLabels[8],
      expectedR: 64,
      expectedG: 0,
      expectedB: 0,
      expectedLabel: "cat")
    self.verifyColoredLabel(
      coloredLabels[9],
      expectedR: 192,
      expectedG: 0,
      expectedB: 0,
      expectedLabel: "chair")
    self.verifyColoredLabel(
      coloredLabels[10],
      expectedR: 64,
      expectedG: 128,
      expectedB: 0,
      expectedLabel: "cow")
    self.verifyColoredLabel(
      coloredLabels[11],
      expectedR: 192,
      expectedG: 128,
      expectedB: 0,
      expectedLabel: "dining table")
    self.verifyColoredLabel(
      coloredLabels[12],
      expectedR: 64,
      expectedG: 0,
      expectedB: 128,
      expectedLabel: "dog")
    self.verifyColoredLabel(
      coloredLabels[13],
      expectedR: 192,
      expectedG: 0,
      expectedB: 128,
      expectedLabel: "horse")
    self.verifyColoredLabel(
      coloredLabels[14],
      expectedR: 64,
      expectedG: 128,
      expectedB: 128,
      expectedLabel: "motorbike")
    self.verifyColoredLabel(
      coloredLabels[15],
      expectedR: 192,
      expectedG: 128,
      expectedB: 128,
      expectedLabel: "person")
    self.verifyColoredLabel(
      coloredLabels[16],
      expectedR: 0,
      expectedG: 64,
      expectedB: 0,
      expectedLabel: "potted plant")
    self.verifyColoredLabel(
      coloredLabels[17],
      expectedR: 128,
      expectedG: 64,
      expectedB: 0,
      expectedLabel: "sheep")
    self.verifyColoredLabel(
      coloredLabels[18],
      expectedR: 0,
      expectedG: 192,
      expectedB: 0,
      expectedLabel: "sofa")
    self.verifyColoredLabel(
      coloredLabels[19],
      expectedR: 128,
      expectedG: 192,
      expectedB: 0,
      expectedLabel: "train")
    self.verifyColoredLabel(
      coloredLabels[20],
      expectedR: 0,
      expectedG: 64,
      expectedB: 128,
      expectedLabel: "tv")
  }
  func verifyColoredLabel(
    _ coloredLabel: ColoredLabel,
    expectedR: UInt,
    expectedG: UInt,
    expectedB: UInt,
    expectedLabel: String
  ) {
    XCTAssertEqual(
      coloredLabel.r,
      expectedR)
    XCTAssertEqual(
      coloredLabel.g,
      expectedG)
    XCTAssertEqual(
      coloredLabel.b,
      expectedB)
    XCTAssertEqual(
      coloredLabel.label,
      expectedLabel)
  }
  func testSuccessfullInferenceOnMLImageWithUIImage() throws {
    let modelPath = try XCTUnwrap(ImageSegmenterTests.modelPath)
    let imageSegmenterOptions = ImageSegmenterOptions(modelPath: modelPath)
    let imageSegmenter =
      try ImageSegmenter.segmenter(options: imageSegmenterOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "segmentation_input_rotation0",
        type: "jpg"))
    let segmentationResult: SegmentationResult =
      try XCTUnwrap(imageSegmenter.segment(mlImage: gmlImage))
    XCTAssertEqual(segmentationResult.segmentations.count, 1)
    let coloredLabels = try XCTUnwrap(segmentationResult.segmentations[0].coloredLabels)
    verifyDeeplabV3PartialSegmentationResult(coloredLabels)
    let categoryMask = try XCTUnwrap(segmentationResult.segmentations[0].categoryMask)
    XCTAssertEqual(deepLabV3SegmentationWidth, categoryMask.width)
    XCTAssertEqual(deepLabV3SegmentationHeight, categoryMask.height)
    let goldenMaskImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "segmentation_golden_rotation0",
        type: "png"))
    let pixelBuffer = goldenMaskImage.grayScalePixelBuffer().takeRetainedValue()
    CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
    let pixelBufferBaseAddress = (try XCTUnwrap(CVPixelBufferGetBaseAddress(pixelBuffer)))
      .assumingMemoryBound(to: UInt8.self)
    let numPixels = deepLabV3SegmentationWidth * deepLabV3SegmentationHeight
    let mask = try XCTUnwrap(categoryMask.mask)
    var inconsistentPixels: Float = 0.0
    for i in 0..<numPixels {
      if mask[i] * kGoldenMaskMagnificationFactor != pixelBufferBaseAddress[i] {
        inconsistentPixels += 1
      }
    }
    CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
    XCTAssertLessThan(inconsistentPixels / Float(numPixels), kGoldenMaskTolerance)
  }
}


TFLObjectDetectorTests

class ObjectDetectorTests: XCTestCase {
  static let bundle = Bundle(for: ObjectDetectorTests.self)
  static let modelPath = bundle.path(
    forResource: "coco_ssd_mobilenet_v1_1.0_quant_2018_06_29",
    ofType: "tflite")
  func verifyDetectionResult(_ detectionResult: DetectionResult) {
    XCTAssertGreaterThan(detectionResult.detections.count, 0)
    self.verifyDetection(
      detectionResult.detections[0],
      expectedBoundingBox: CGRect(x: 54, y: 396, width: 393, height: 199),
      expectedFirstScore: 0.632812,
      expectedFirstLabel: "cat")
    self.verifyDetection(
      detectionResult.detections[1],
      expectedBoundingBox: CGRect(x: 602, y: 157, width: 394, height: 447),
      expectedFirstScore: 0.609375,
      expectedFirstLabel: "cat")
    self.verifyDetection(
      detectionResult.detections[2],
      expectedBoundingBox: CGRect(x: 260, y: 394, width: 179, height: 209),
      expectedFirstScore: 0.5625,
      expectedFirstLabel: "cat")
    self.verifyDetection(
      detectionResult.detections[3],
      expectedBoundingBox: CGRect(x: 387, y: 197, width: 281, height: 409),
      expectedFirstScore: 0.488281,
      expectedFirstLabel: "dog")
  }
  func verifyDetection(
    _ detection: Detection, expectedBoundingBox: CGRect,
    expectedFirstScore: Float,
    expectedFirstLabel: String
  ) {
    XCTAssertGreaterThan(detection.categories.count, 0)
    XCTAssertEqual(
      detection.boundingBox.origin.x,
      expectedBoundingBox.origin.x)
    XCTAssertEqual(
      detection.boundingBox.origin.y,
      expectedBoundingBox.origin.y)
    XCTAssertEqual(
      detection.boundingBox.size.width,
      expectedBoundingBox.size.width)
    XCTAssertEqual(
      detection.boundingBox.size.height,
      expectedBoundingBox.size.height)
    XCTAssertEqual(
      detection.categories[0].label,
      expectedFirstLabel)
    XCTAssertEqual(
      detection.categories[0].score,
      expectedFirstScore, accuracy: 0.001)
  }
  func testSuccessfullInferenceOnMLImageWithUIImage() throws {
    let modelPath = try XCTUnwrap(ObjectDetectorTests.modelPath)
    let objectDetectorOptions = ObjectDetectorOptions(modelPath: modelPath)
    let objectDetector =
      try ObjectDetector.detector(options: objectDetectorOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "cats_and_dogs",
        type: "jpg"))
    let detectionResults: DetectionResult =
      try objectDetector.detect(mlImage: gmlImage)
    self.verifyDetectionResult(detectionResults)
  }
  func testModelOptionsWithMaxResults() throws {
    let modelPath = try XCTUnwrap(ObjectDetectorTests.modelPath)
    let objectDetectorOptions = ObjectDetectorOptions(modelPath: modelPath)
    let maxResults = 3
    objectDetectorOptions.classificationOptions.maxResults = maxResults
    let objectDetector =
      try ObjectDetector.detector(options: objectDetectorOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "cats_and_dogs",
        type: "jpg"))
    let detectionResult: DetectionResult = try objectDetector.detect(
      mlImage: gmlImage)
    XCTAssertLessThanOrEqual(detectionResult.detections.count, maxResults)
    self.verifyDetection(
      detectionResult.detections[0],
      expectedBoundingBox: CGRect(x: 54, y: 396, width: 393, height: 199),
      expectedFirstScore: 0.632812,
      expectedFirstLabel: "cat")
    self.verifyDetection(
      detectionResult.detections[1],
      expectedBoundingBox: CGRect(x: 602, y: 157, width: 394, height: 447),
      expectedFirstScore: 0.609375,
      expectedFirstLabel: "cat")
    self.verifyDetection(
      detectionResult.detections[2],
      expectedBoundingBox: CGRect(x: 260, y: 394, width: 179, height: 209),
      expectedFirstScore: 0.5625,
      expectedFirstLabel: "cat")
  }
}


TFLImageClassifierTests

class ImageClassifierTests: XCTestCase {
  static let bundle = Bundle(for: ImageClassifierTests.self)
  static let modelPath = bundle.path(
    forResource: "mobilenet_v2_1.0_224",
    ofType: "tflite")
  func testSuccessfullInferenceOnMLImageWithUIImage() throws {
    let modelPath = try XCTUnwrap(ImageClassifierTests.modelPath)
    let imageClassifierOptions = ImageClassifierOptions(modelPath: modelPath)
    let imageClassifier =
      try ImageClassifier.classifier(options: imageClassifierOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "burger",
        type: "jpg"))
    let classificationResults: ClassificationResult =
      try imageClassifier.classify(mlImage: gmlImage)
    XCTAssertNotNil(classificationResults)
    XCTAssertEqual(classificationResults.classifications.count, 1)
    XCTAssertGreaterThan(classificationResults.classifications[0].categories.count, 0)
    // TODO: match the score as image_classifier_test.cc
    let category = classificationResults.classifications[0].categories[0]
    XCTAssertEqual(category.label, "cheeseburger")
    XCTAssertEqual(category.score, 0.748976, accuracy: 0.001)
  }
  func testModelOptionsWithMaxResults() throws {
    let modelPath = try XCTUnwrap(ImageClassifierTests.modelPath)
    let imageClassifierOptions = ImageClassifierOptions(modelPath: modelPath)
    let maxResults = 3
    imageClassifierOptions.classificationOptions.maxResults = maxResults
    let imageClassifier =
      try ImageClassifier.classifier(options: imageClassifierOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "burger",
        type: "jpg"))
    let classificationResults: ClassificationResult = try imageClassifier.classify(
      mlImage: gmlImage)
    XCTAssertNotNil(classificationResults)
    XCTAssertEqual(classificationResults.classifications.count, 1)
    XCTAssertLessThanOrEqual(classificationResults.classifications[0].categories.count, maxResults)
    // TODO: match the score as image_classifier_test.cc
    let category = classificationResults.classifications[0].categories[0]
    XCTAssertEqual(category.label, "cheeseburger")
    XCTAssertEqual(category.score, 0.748976, accuracy: 0.001)
  }
  func testInferenceWithBoundingBox() throws {
    let modelPath = try XCTUnwrap(ImageClassifierTests.modelPath)
    let imageClassifierOptions = ImageClassifierOptions(modelPath: modelPath)
    let imageClassifier =
      try ImageClassifier.classifier(options: imageClassifierOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "multi_objects",
        type: "jpg"))
    let roi = CGRect(x: 406, y: 110, width: 148, height: 153)
    let classificationResults =
      try imageClassifier.classify(mlImage: gmlImage, regionOfInterest: roi)
    XCTAssertNotNil(classificationResults)
    XCTAssertEqual(classificationResults.classifications.count, 1)
    XCTAssertGreaterThan(classificationResults.classifications[0].categories.count, 0)
    // TODO: match the label and score as image_classifier_test.cc
    // let category = classificationResults.classifications[0].categories[0]
    // XCTAssertEqual(category.label, "soccer ball")
    // XCTAssertEqual(category.score, 0.256512, accuracy:0.001);
  }
  func testInferenceWithRGBAImage() throws {
    let modelPath = try XCTUnwrap(ImageClassifierTests.modelPath)
    let imageClassifierOptions = ImageClassifierOptions(modelPath: modelPath)
    let imageClassifier =
      try ImageClassifier.classifier(options: imageClassifierOptions)
    let gmlImage = try XCTUnwrap(
      MLImage.imageFromBundle(
        class: type(of: self),
        filename: "sparrow",
        type: "png"))
    let classificationResults =
      try imageClassifier.classify(mlImage: gmlImage)
    XCTAssertNotNil(classificationResults)
    XCTAssertEqual(classificationResults.classifications.count, 1)
    XCTAssertGreaterThan(classificationResults.classifications[0].categories.count, 0)
    let category = classificationResults.classifications[0].categories[0]
    XCTAssertEqual(category.label, "junco")
    XCTAssertEqual(category.score, 0.253016, accuracy: 0.001)
  }
}


TFLNLClassifierTest

class TFLNLClassifierTest: XCTestCase {
  static let bundle = Bundle(for: TFLNLClassifierTest.self)
  static let modelPath = bundle.path(
    forResource: "test_model_nl_classifier_with_regex_tokenizer",
    ofType: "tflite")!
  var modelOptions:TFLNLClassifierOptions!;
  override func setUp() {
    modelOptions = TFLNLClassifierOptions()
    modelOptions.inputTensorName = "input_text"
    modelOptions.outputScoreTensorName = "probability"
  }
  func testClassifyPositiveResult() {
    let nlClassifier = TFLNLClassifier.nlClassifier(
      modelPath: TFLNLClassifierTest.modelPath,
      options: modelOptions)
    XCTAssertNotNil(nlClassifier)
    let categories = nlClassifier.classify(
      text: "This is the best movie I’ve seen in recent years. Strongly recommend it!")
    XCTAssertGreaterThan(categories["Positive"]!.doubleValue, categories["Negative"]!.doubleValue)
  }
   func testClassifyNegativeResult() {
     let nlClassifier = TFLNLClassifier.nlClassifier(
       modelPath: TFLNLClassifierTest.modelPath,
       options: modelOptions)
     XCTAssertNotNil(nlClassifier)
     let categories = nlClassifier.classify(text: "What a waste of my time.")
     XCTAssertGreaterThan(categories["Negative"]!.doubleValue, categories["Positive"]!.doubleValue)
   }
}


TFLBertNLClassifierTest

class TFLBertNLClassifierTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertNLClassifierTest.self)
  static let bertModelPath = bundle.path(forResource: "bert_nl_classifier", ofType: "tflite")!
  func testClassifyPositiveResult() {
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "it's a charming and often affecting journey")
    XCTAssertGreaterThan(categories["positive"]!.doubleValue, categories["negative"]!.doubleValue)
  }
  func testClassifyNegativeResult() {
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "unflinchingly bleak and desperate")
    XCTAssertGreaterThan(categories["negative"]!.doubleValue, categories["positive"]!.doubleValue)
  }
  func testCreateFromOptionsClassifyPositiveResult() {
    let modelOptions = TFLBertNLClassifierOptions()
    modelOptions.maxSeqLen = 128
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath,
      options: modelOptions)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "it's a charming and often affecting journey")
    XCTAssertGreaterThan(categories["positive"]!.doubleValue, categories["negative"]!.doubleValue)
  }
  func testCreateFromOptionsClassifyNegativeResult() {
    let modelOptions = TFLBertNLClassifierOptions()
    modelOptions.maxSeqLen = 128
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath,
      options: modelOptions)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "unflinchingly bleak and desperate")
    XCTAssertGreaterThan(categories["negative"]!.doubleValue, categories["positive"]!.doubleValue)
  }
}


TFLBertQuestionAnswererTest

class TFLBertQuestionAnswererTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertQuestionAnswererTest.self)
  static let mobileBertModelPath = bundle.path(forResource: "mobilebert_with_metadata", ofType: "tflite")!
  static let albertModelPath = bundle.path(forResource: "albert_with_metadata", ofType: "tflite")!
  static let context = """
    The role of teacher is often formal and ongoing, carried out at a school or other place of
    formal education. In many countries, a person who wishes to become a teacher must first obtain
     specified professional qualifications or credentials from a university or college. These
    professional qualifications may include the study of pedagogy, the science of teaching.
    Teachers, like other professionals, may have to continue their education after they qualify,
    a process known as continuing professional development. Teachers may use a lesson plan to
    facilitate student learning, providing a course of study which is called the curriculum.
    """
  static let question = "What is a course of study called?"
  static let answer = "the curriculum."
  func testInitMobileBert() {
    let mobileBertAnswerer = TFLBertQuestionAnswerer.questionAnswerer(
      modelPath: TFLBertQuestionAnswererTest.mobileBertModelPath)
    XCTAssertNotNil(mobileBertAnswerer)
    let answers = mobileBertAnswerer.answer(
      context: TFLBertQuestionAnswererTest.context, question: TFLBertQuestionAnswererTest.question)
    XCTAssertNotNil(answers)
    XCTAssertEqual(answers[0].text, TFLBertQuestionAnswererTest.answer)
  }
  func testInitAlbert() {
    let albertAnswerer = TFLBertQuestionAnswerer.questionAnswerer(
      modelPath: TFLBertQuestionAnswererTest.albertModelPath)
    XCTAssertNotNil(albertAnswerer)
    let answers = albertAnswerer.answer(
      context: TFLBertQuestionAnswererTest.context, question: TFLBertQuestionAnswererTest.question)
    XCTAssertNotNil(answers)
    XCTAssertEqual(answers[0].text, TFLBertQuestionAnswererTest.answer)
  }
}


import UIKit
/// Globally maps reference views to layout guides.
///
/// Usage:
/// 1.  Reference a view from a part of the UI under a specific name.
/// 2.  In a different part of the UI, request a layout guide under that name. Add the synced layout
///     guide to the UI. It will track the reference view automatically.
///
/// Details:
/// -   Referenced views and created layout guides are only weakly stored by the layout guide
///     center.
/// -   Referenced views don't have to be laid out by AutoLayout.
/// -   Referenced views and layout guides don't have to be in the same window.
  public func reference(view referenceView: UIView?, under name: String) {
    let oldReferenceView = referencedView(under: name)
    // Early return if `referenceView` is already set.
    if referenceView == oldReferenceView {
      return
    }
    oldReferenceView?.cr_onWindowCoordinatesChanged = nil
    if let referenceView = referenceView {
      referenceViews.setObject(referenceView, forKey: name as NSString)
    } else {
      referenceViews.removeObject(forKey: name as NSString)
    }
    updateGuides(named: name)
    // Schedule updates to the matching layout guides when the reference view
    // moves in its window.
    referenceView?.cr_onWindowCoordinatesChanged = { [weak self] _ in
      self?.updateGuides(named: name)
    }
  }
  /// Returns the referenced view under `name`.
  public func makeLayoutGuide(named name: String) -> UILayoutGuide {
    let layoutGuide = FrameLayoutGuide()
    layoutGuide.onDidMoveToWindow = { [weak self] _ in
      self?.updateGuides(named: name)
    }
    // Keep a weak reference to the layout guide.
    if layoutGuides[name] == nil {
      layoutGuides[name] = NSHashTable<FrameLayoutGuide>.weakObjects()
    }
    layoutGuides[name]?.add(layoutGuide)
    return layoutGuide
  }
  /// MARK: Private
  /// Weakly stores the reference views.
  private var referenceViews = NSMapTable<NSString, UIView>.strongToWeakObjects()
  /// Weakly stores the layout guides.
  private var layoutGuides = [String: NSHashTable<FrameLayoutGuide>]()
  /// Updates all available guides for the given `name`.
  private func updateGuides(named name: String) {
    // Early return if there is no reference window.
    guard let referenceView = referencedView(under: name) else { return }
    guard let referenceWindow = referenceView.window else { return }
    // Early return if there are no layout guides.
    guard let layoutGuidesForName = layoutGuides[name] else { return }
    for layoutGuide in layoutGuidesForName.allObjects {
      // Skip if there is no owning window.
      guard let owningView = layoutGuide.owningView else { continue }
      guard let owningWindow = owningView.window else { continue }
      let frameInReferenceWindow = referenceView.convert(referenceView.bounds, to: nil)
      let frameInOwningWindow = referenceWindow.convert(frameInReferenceWindow, to: owningWindow)
      let frameInOwningView = owningView.convert(frameInOwningWindow, from: nil)
      layoutGuide.constrainedFrame = frameInOwningView
    }
  }
}