让我们想象一下编写MVC应用程序。在编写测试时,你将会遇到一种情况,有一些模型必须添加到数据库中,可能也需要检查这些模型的新状态。
这意味着当你用Lettuce编写测试时,在步骤中处理数据将非常有用。
步骤表展示如下
Feature: bill students alphabetically
In order to bill students properly
As a financial specialist
I want to bill those which name starts with some letter
Scenario: Bill students which name starts with "G"
Given I have the following students in my database:
| name | monthly_due | billed |
| Anton | $ 500 | no |
| Jack | $ 400 | no |
| Gabriel | $ 300 | no |
| Gloria | $ 442.65 | no |
| Ken | $ 907.86 | no |
| Leonard | $ 742.84 | no |
When I bill names starting with "G"
Then I see those billed students:
| name | monthly_due | billed |
| Gabriel | $ 300 | no |
| Gloria | $ 442.65 | no |
And those that weren't:
| name | monthly_due | billed |
| Anton | $ 500 | no |
| Jack | $ 400 | no |
| Ken | $ 907.86 | no |
| Leonard | $ 742.84 | no |
在上面的例子中有4个步骤,其中3个包含表。
现在让我们想象,我们将用Django写一些步骤定义来使用这些表。
from lettuce import step
from school.models import Student
@step('I have the following students in my database:')
def students_in_database(step):
for student_dict in step.hashes:
person = Student(**student_dict)
person.save()
获取表的第一行或最后一行的便利函数呢?!
from lettuce import step
from school.models import Student
@step('I have the following students in my database:')
def students_in_database(step):
person1 = Student(**step.hashes.first)
person2 = Student(**step.hashes.last)
person1.save()
person2.save()
很简单,是吧?!
每一步都有一个属性调用一个列表词典的哈希值。每个字典中,表头为键,每一行的值。
换句话说,Lettuce将这个表等同于字典传递在第一步
@step('I have the following students in my database:')
def students_in_database(step):
assert step.hashes == [
{
'name': 'Anton',
'monthly_due': '$ 500',
'billed': 'no'
},
{
'name': 'Jack',
'monthly_due': '$ 400',
'billed': 'no'
},
{
'name': 'Gabriel',
'monthly_due': '$ 300',
'billed': 'no'
},
{
'name': 'Gloria',
'monthly_due': '$ 442.65',
'billed': 'no'
},
{
'name': 'Ken',
'monthly_due': '$ 907.86',
'billed': 'no'
},
{
'name': 'Leonard',
'monthly_due': '$ 742.84',
'billed': 'no'
},
]