DEV Community

David Goyes
David Goyes

Posted on

Swift Testing #11: Desactivación condicional de pruebas con .enabled() y .disabled()

Deshabilitar una prueba sin condición

El trait disabled(_:sourceLocation:) sin modificaciones permite deshabilitar una prueba sin condiciones.

@Test(.disabled()) // ↩️ Omitida
func test1() {
  #expect(1 + 1 == 3)
}
Enter fullscreen mode Exit fullscreen mode

Deshabilitar si una condición no se cumple

enabled(if:_:sourceLocation:) construye un trait que deshabilita una prueba si la condición es falsa.

static func enabled(
  if condition: @autoclosure @escaping () throws -> Bool,
  _ comment: Comment? = nil,
  sourceLocation: SourceLocation = #_sourceLocation
) -> Self
Enter fullscreen mode Exit fullscreen mode

Como la condición es un autoclosure, se puede pasar un valor booleano o invocar una función que arroje una excepción.

@Test(.enabled(if: currentAPIversion == .v1)) // 🚦 Se ejecuta si API == v1
func test2() {
    #expect(1 + 1 == 2)
}
Enter fullscreen mode Exit fullscreen mode

Deshabilitar después de ejecutar algún código asíncrono

Puede darse el caso, por ejemplo, que se quiera deshabilitar una prueba o Suite si el servidor no responde. En este caso, se puede pasar una función async como condición de enabled(_:sourceLocation:_:).

static func enabled(
  _ comment: Comment? = nil,
  sourceLocation: SourceLocation = #_sourceLocation,
  _ condition: @escaping () async throws -> Bool
) -> Self
Enter fullscreen mode Exit fullscreen mode

Por ejemplo

@Test(.enabled {
    // Código async/throws para validar si debe ejecutar la prueba
    try await Task.sleep(for: .seconds(10))
    return true 
}) // ⌛️ Se activa/desactiva después de ejecutar el código asíncrono
func test4() {
    #expect(1 + 1 == 2)
}
Enter fullscreen mode Exit fullscreen mode

Bibliografía

  • Documentación sobre Swift Testing, aquí.

Top comments (0)