Datos de prueba con test:given
Traducción automática
Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.
Tarea: probar una página que depende de los datos y de quién la mira — sin un archivo de fixtures y sin una contraseña.
La página lista las tareas abiertas del usuario que inició sesión:
# Recipe: test data with test:given, and a signed-in user with test:as.
paths:
components: ./components
migrations: ./migrations
datasources:
db:
driver: sqlite
database: ./data/tasks.dbCREATE TABLE tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner TEXT NOT NULL,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0 CHECK (done IN (0, 1))
);<q:component name="MyTasks" require_auth="true">
<q:query name="mine" datasource="db">
SELECT title FROM tasks WHERE owner = :me AND done = 0 ORDER BY id
<q:param name="me" value="{session.userName}" type="string" />
</q:query>
<h1>{session.userName}'s open tasks</h1>
<q:if condition="mine_result.recordCount == 0">
<p>Nothing to do.</p>
</q:if>
<ul>
<q:loop query="mine"><li>{mine.title}</li></q:loop>
</ul>
</q:component>Cada prueba empieza con una base de datos vacía construida por migrations/. test:given inserta las filas que la prueba necesita — a través de las reglas del esquema, así que una fila que la aplicación nunca podría haber escrito (un done fuera del CHECK (… IN …), una columna obligatoria que no puede completar) hace fallar el paso en lugar de colarse. test:as inicia la sesión de un usuario como lo hace un login:
<q:test name="a user sees only their own open tasks" page="/">
<test:given table="tasks" owner="Ana" title="Write the report" />
<test:given table="tasks" owner="Ana" title="Old task" done="1" />
<test:given table="tasks" owner="Bruno" title="Fix the printer" />
<test:as user="Ana" />
<test:visit />
<test:expect status="200" text="Ana's open tasks" />
<test:expect text="Write the report" />
<test:expect no-text="Old task" />
<test:expect no-text="Fix the printer" />
</q:test>
<q:test name="a user with nothing open is told so" page="/">
<test:given table="tasks" owner="Bruno" title="Fix the printer" />
<test:as user="Ana" />
<test:visit />
<test:expect text="Nothing to do." />
</q:test>
<q:test name="the page needs a signed-in user" page="/">
<test:visit />
<test:expect status="302" />
</q:test>tests/tasks.test.q
PASS a user sees only their own open tasks
PASS a user with nothing open is told so
PASS the page needs a signed-in user
3 passed, 0 failedno-text verifica lo que no debe estar en la página — aquí, la tarea de otro usuario y una terminada. Todo el vocabulario está en la guía Testing an App (en inglés).
Probado: esta página importa los archivos de examples/cookbook/testing/test-data/, y el resultado de arriba es el informe de ejecutarlos.