在为已经编写的测试编写代码时,python会测试错误

时间:2016-06-20 08:29:23

标签: python python-2.7

以下是我已编写测试的代码:

def scan(self, *words): # '*words' lets you give a variable number of arguments to a function
    if len(words) <= 1 and words in direction:
        r = [('direction', words)
    else:
        for i in words:
            r = []
            r.append('direction', i)            
return r

以下是测试:

from nose.tools import *
from LEXICON import lexicon

def test_directions():
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
    result = lexicon.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                         ('direction', 'south'),
                         ('direction', 'east')])

这是我运行此代码时遇到的错误:

ERROR: Failure: SyntaxError (invalid syntax (lexicon.py, line 19))
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/george/Documents/git-docs/pythonlearning/ex48/tests/lexicon_tests.py", line 2, in <module>
    from LEXICON import lexicon
  File "/home/george/Documents/git-docs/pythonlearning/ex48/LEXICON/lexicon.py", line 19
    for i in words:
                  ^
SyntaxError: invalid syntax

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)

问题: for语句中的错误是什么?

2 个答案:

答案 0 :(得分:0)

你错过了添加结束括号&#39;]&#39;在第3行。 将其更改为

def scan(self, *words): # '*words' lets you give a variable number of arguments to a function
    if len(words) <= 1 and words in direction:
        r = [('direction', words)]
    else:
        for i in words:
            r = []
            r.append('direction', i)            
    return r

答案 1 :(得分:0)

当前的问题是缺少],但除此之外还有更多错误:

  • words in directions似乎没有多大意义,因为words仍然是一个列表,即使它只有一个元素;您可以使用words[0],但如果words为空,则会失败
  • 列表初始化r = []在循环中,即它始终只包含最后一个元素
  • 您无法将两个参数传递给append,您的意思是append(("direction", i))
  • return r处于错误的缩进级别

此外,您可以将整个功能转换为单个列表理解:

def scan(self, *words):
    return [("direction", w) for w in words if w in directions]

示例:

>>> directions = ["north", "south", "east", "west"]
>>> lex = lexicon()
>>> lex.scan()
[]
>>> lex.scan("north")
[('direction', 'north')]
>>> lex.scan("north", "south", "west", "not a direction")
[('direction', 'north'), ('direction', 'south'), ('direction', 'west')]

但请注意,*words假定单词将单独传递给函数,例如与scan("i", "went", "north")中一样。相反,如果您想将其称为scan("i went north"),则必须将split句子转换为函数内的单词:

def scan(self, sentence):
    words = sentence.split()
    return [("direction", w) for w in words if w in directions]