def test_map_operations_does_not_insert_too_many_moments():
    q = cirq.LineQubit.range(5)
    c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4]))

    def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE:
        if (op.gate == cirq.CX):
            (yield cirq.Z.on_each(*op.qubits))
            (yield cirq.CX(*op.qubits))
            (yield cirq.Z.on_each(*op.qubits))
        return op
    cirq.testing.assert_has_diagram(c_orig, '\n0: ───@───────\n      │\n1: ───X───────\n\n2: ───X───────\n      │\n3: ───@───@───\n          │\n4: ───────X───\n')
    c_mapped = cirq.map_operations(c_orig, map_func)
    circuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.Z.on_each(q[0], q[1]), cirq.CNOT(q[0], q[1]), cirq.Z.on_each(q[0], q[1])))
    c_expected = cirq.Circuit(circuit_op.with_qubits(q[0], q[1]).mapped_op().with_tags('<mapped_circuit_op>'), circuit_op.with_qubits(q[3], q[2]).mapped_op().with_tags('<mapped_circuit_op>'), circuit_op.with_qubits(q[3], q[4]).mapped_op().with_tags('<mapped_circuit_op>'))
    cirq.testing.assert_same_circuits(c_mapped, c_expected)
    cirq.testing.assert_has_diagram(cirq.map_operations_and_unroll(c_orig, map_func), '\n0: ───Z───@───Z───────────────\n          │\n1: ───Z───X───Z───────────────\n\n2: ───Z───X───Z───────────────\n          │\n3: ───Z───@───Z───Z───@───Z───\n                      │\n4: ───────────────Z───X───Z───\n')
def test_map_operations_does_not_insert_too_many_moments():
    q = cirq.LineQubit.range(5)
    c_orig = cirq.Circuit(cirq.CX(q[0], q[1]), cirq.CX(q[3], q[2]), cirq.CX(q[3], q[4]))

    def map_func(op: cirq.Operation, _: int) -> cirq.OP_TREE:
        if (op.gate == cirq.CX):
            (yield cirq.Z.on_each(*op.qubits))
            (yield cirq.CX(*op.qubits))
            (yield cirq.Z.on_each(*op.qubits))
        return op
    cirq.testing.assert_has_diagram(c_orig, '\n0: ───@───────\n      │\n1: ───X───────\n\n2: ───X───────\n      │\n3: ───@───@───\n          │\n4: ───────X───\n')
    c_mapped = cirq.map_operations(c_orig, map_func)
    circuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.Z.on_each(q[0], q[1]), cirq.CNOT(q[0], q[1]), cirq.Z.on_each(q[0], q[1])))
    c_expected = cirq.Circuit(circuit_op.with_qubits(q[0], q[1]).mapped_op().with_tags('<mapped_circuit_op>'), circuit_op.with_qubits(q[3], q[2]).mapped_op().with_tags('<mapped_circuit_op>'), circuit_op.with_qubits(q[3], q[4]).mapped_op().with_tags('<mapped_circuit_op>'))
    cirq.testing.assert_same_circuits(c_mapped, c_expected)
    cirq.testing.assert_has_diagram(cirq.map_operations_and_unroll(c_orig, map_func), '\n0: ───Z───@───Z───────────────\n          │\n1: ───Z───X───Z───────────────\n\n2: ───Z───X───Z───────────────\n          │\n3: ───Z───@───Z───Z───@───Z───\n                      │\n4: ───────────────Z───X───Z───\n')