我是一个通过Learn Python the Hard Way 工作的新手。
这个练习的重点是编写一个字扫描仪,当它由提供的单元测试运行时,它通过了鼻子测试。
在以下提供的单元测试上运行鼻子测试时,我收到了这个错误:
`TypeError:必须使用词典实例作为第一个参数调用未绑定的方法scan()(改为获取str实例)
课程提供的测试
from nose.tools import *
from ex48 import lexicon
def test_directions():
assert_equal(lex.scan("north"), [('direction', 'north')])
result = lex.scan("north south east")
assert_equal(result, [('direction', 'north'),
('direction', 'south'),
('direction', 'east)])
经过一番调查,我在这里发现了一个正在做同样练习的用户:
那里的答案建议在单元测试中实例化(实例化?)该方法。所以我做了以下修改,并在文件 ex48.py 中编写了我的类,它通过了鼻子测试。
修改后的测试
from nose.tools import *
from ex48 import lexicon
def test_directions():
lex = lexicon("north")
assert_equal(lex.scan("north"), [('direction', 'north')])
lex = lexicon("north south east")
result = lex.scan("north south east")
assert_equal(result, [('direction', 'north'),
('direction', 'south'),
('direction', 'east')])
ex48.py - 扫描仪
class lexicon(object):
def __init__(self, data):
#nosetests fails me if I don't put in some dummy
# __init__ function with a dummy line, not sure why.
self.direction = data
def scan(self, data):
split_data = data.split()
directions = ['north', 'south', 'east', 'west']
data_reply = []
#for loop for the length of the list
for split_data_item in split_data:
#If data is in the directions list
if split_data_item in directions:
#Add [('direction', data)] to a dict
data_reply.append(('direction', split_data_item))
#Return the list
return data_reply
我不确定是否要更改单元测试。我在这里找到了关于“直接实例化对象”的线索:
但不确定这是否适用。可以使扫描仪实例化自身,还是提供的单元测试是一个技巧“问题”并且必须修改?