用 quantum test 写第一个测试
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 检查一个页面列出了数据库中的内容、它的动作保存了一行并告知结果, 并且拒绝错误的输入——不用写 Python。
一个小应用:一张数据表、一个列出它的页面,以及一个向它添加数据的动作。
yaml
# Recipe: a first test with `quantum test`.
paths:
components: ./components
migrations: ./migrations
datasources:
db:
driver: sqlite
database: ./data/notes.dbsql
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL
);
INSERT INTO notes (title) VALUES ('Read the guide');xml
<q:component name="Notes">
<q:action name="add" method="POST">
<q:param name="title" required="true" minlength="3" />
<q:query name="added" datasource="db">
INSERT INTO notes (title) VALUES (:title)
<q:param name="title" value="{title}" type="string" />
</q:query>
<q:redirect url="/" flash="Added: {title}" />
</q:action>
<q:query name="notes" datasource="db">SELECT title FROM notes ORDER BY id</q:query>
<h1>Notes ({notes_result.recordCount})</h1>
<q:if condition="flash"><p class="flash">{flash}</p></q:if>
<form method="POST" action="/?action=add">
<input name="title" />
<button>Add</button>
</form>
<ul>
<q:loop query="notes"><li>{notes.title}</li></q:loop>
</ul>
</q:component>测试就在它旁边的 tests/ 中。每个 q:test 都从一个根据 migrations/ 新建的数据库开始,所以它们互不依赖:
xml
<q:test name="the page lists the notes" page="/">
<test:visit />
<test:expect status="200" text="Notes (1)" />
<test:expect text="Read the guide" />
</q:test>
<q:test name="adding a note stores it and says so" page="/">
<test:submit action="add" title="Buy bread" />
<test:expect redirect="/" flash="Added: Buy bread" />
<test:expect table="notes" count="1" where="title = 'Buy bread'" />
<test:expect text="Notes (2)" />
</q:test>
<q:test name="a title that is too short is refused on its field" page="/">
<test:submit action="add" title="x" />
<test:expect error="title" />
<test:expect table="notes" count="1" />
</q:test>在应用的文件夹中运行它们:
bash
quantum testtext
tests/notes.test.q
PASS the page lists the notes
PASS adding a note stores it and says so
PASS a title that is too short is refused on its field
3 passed, 0 failedtest:visit 打开页面;test:submit 提交一个动作,其他属性作为它的字段; test:expect 检查发生了什么——状态码、重定向和提示消息(flash)、页面上的一段文本、 数据表中的行,或者输入被拒绝的字段。完整的词汇见 Testing an App 指南(英文)。
已测试: 本页导入了 examples/cookbook/testing/first-test/ 中的文件, 上面的结果就是运行它们得到的报告。