跳到正文

用 test:given 准备测试数据 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 测试一个依赖数据和访问者身份的页面——不需要夹具(fixtures)文件,也不需要密码。

这个页面列出已登录用户未完成的任务:

yaml
# 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.db
sql
CREATE 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))
);
xml
<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>

每个测试都从一个由 migrations/ 构建的空数据库开始。test:given 放入测试需要的行—— 经过数据表结构的规则,所以应用本来不可能写入的行(done 不在 CHECK (… IN …) 之内、 缺少无法填写的必填列)会让这一步失败,而不是悄悄混进去。test:as 像登录那样让一个用户登录:

xml
<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>
text
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 failed

no-text 检查页面上不能出现的内容——这里是另一个用户的任务和一个已完成的任务。 完整的词汇见 Testing an App 指南(英文)。

已测试: 本页导入了 examples/cookbook/testing/test-data/ 中的文件, 上面的结果就是运行它们得到的报告。

MIT 许可证 · 使用 VitePress 构建