Dados de teste com test:given
Tradução automática
Esta página foi traduzida automaticamente do inglês e ainda não foi revisada por um falante nativo; correções são bem-vindas no GitHub. Se algo não bater, vale o original em inglês. O código e os resultados são os mesmos do original, importados dos arquivos testados.
Tarefa: testar uma página que depende de dados e de quem está olhando — sem arquivo de fixtures e sem senha.
A página lista as tarefas abertas do usuário que entrou:
# 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 teste começa de um banco vazio construído por migrations/. test:given coloca as linhas de que o teste precisa — passando pelas regras do esquema, então uma linha que a aplicação nunca poderia ter gravado (um done fora do CHECK (… IN …), uma coluna obrigatória que ele não consegue preencher) faz o passo falhar em vez de entrar escondida. test:as faz um usuário entrar do jeito que um login faz:
<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 confere o que não pode estar na página — aqui, a tarefa de outro usuário e uma concluída. O vocabulário completo está no guia Testing an App (em inglês).
Testado: esta página importa os arquivos de examples/cookbook/testing/test-data/, e o resultado acima é o relatório de rodá-los.