Saltar al contenido

Guía 15 de 53

Deriving y pruebas con nombre

Productores de derive compartidos y títulos conservados por el runner.

En esta página

Productores de derive compartidos y títulos conservados por el runner.

Deriving uniforme

Añade un sufijo deriving a structs y enums para solicitar los productores existentes. Usa la misma validación e implementación generada que los decoradores de derive. Los traits no admitidos y campos incompatibles generan diagnóstico, sin crear implementaciones sin verificar.

Practica en By Example · Programa fuente

// Uniform requests use the existing producer registry and real builtins.
@derive_for(Marker)
fn marker(info) -> Syntax<.Items> {
    return quote items { impl ${info.ref} { fn marker(self) -> int { 37 } } }
}

@derive(Clone)
struct User { id: int, name: str } deriving Eq, Hash
let user = User { id: 1, name: "Ada" }
print(user.eq(User { id: 1, name: "Ada" }))
print(user.eq(User { id: 1, name: "Bea" }))
print(user.clone().name)
print(user.hash())
print(user.eq(User { id: 1, name: "Ada" }) && user.hash() == User { id: 1, name: "Ada" }.hash())
print(user.hash() != User { id: 2, name: "Ada" }.hash())

struct Counter(value: int) { fn read(self) -> int { self.value } } deriving Clone
print(Counter.new(7).clone().read())

enum State(Ready, Busy) deriving Eq, Marker
let state: State = .Ready
print(state.marker())
print(state.eq(State::Ready))
print(state.eq(State::Busy))

enum Shape { Empty, Point(int), Pair(int, str), Rect { width: int, height: int } } deriving Eq
print(Shape::Pair(7, "Ada").eq(Shape::Pair(7, "Ada")))
print(Shape::Pair(7, "Ada").eq(Shape::Pair(7, "Bea")))
print(Shape::Rect { width: 2, height: 3 }.eq(Shape::Rect { width: 2, height: 4 }))

struct Envelope<T: core::cmp::Eq + core::hash::Hash> { value: T } deriving Eq, Hash
let nested = Envelope { value: user }
print(nested.hash())
print(nested.eq(Envelope { value: User { id: 1, name: "Ada" } }))

struct Empty {} deriving Eq, Hash
print(Empty {}.hash())
struct Text { value: str } deriving Eq, Hash
print(Text { value: "ação" }.hash())
print(Text { value: "" }.hash())

newtype Id(int) deriving Eq, Hash
print(Id.new(8).hash())
print(Id.new(8).eq(Id.new(9)))

struct Defaults { count: int } deriving Default
print(Defaults.default().count)

Pruebas con nombres legibles

Una declaración test usa un título entre comillas y el runner existente. Descubrimiento, filtros, informes y navegación conservan ese título. Los atributos y suites existentes siguen disponibles. Ejecutar el archivo normalmente no ejecuta sus pruebas: usa zolo test.

Practica en By Example · Programa fuente

fn total(values: [int]) -> int {
    var sum = 0
    for value in values { sum += value }
    return sum
}
@test(tag: "cart")
test "empty cart has zero total" { assert_eq(total([]), 0) }
@suite("cart suite")
mod cart {
    test "empty cart" { assert_eq(0, 0) }
    @test(skip: "example of existing attributes")
    test "pending cart rule" { assert_eq(1, 1) }
}
fn main() { print("run preserves ordinary test behavior") }

Ejecuta este ejemplo con zolo test localmente o usa el botón de pruebas del playground del navegador. La ejecución normal no ejecuta las declaraciones test.

Ejecuta las pruebas en el playground del navegador

Sigue aprendiendo

Documentación · Practica en By Example

DOCS / OPINIÓN

¿Esta página dejó alguna pregunta?

Cuéntanos dónde te perdió la explicación. La documentación también forma parte de la experiencia del lenguaje.

Índice global

Encuentra tu camino por Zolo

Prueba una idea

Empieza aquí

9 resultados

9 resultados

enespt-br