单击 python Cli.testing TypeError
click python Cli.testing TypeError
我有 2 个文件:
click_example.py
import click
@click.group(invoke_without_command=True)
@click.option('--apikey', default='My key',
help="API key to use.")
@click.pass_context
def main(ctx, apikey):
"""
A CLI for live and past football scores from various football leagues.
resources are given as commands and subresources and their filters as options
"""
headers = {'X-Auth-Token': apikey}
ctx.obj['headers'] = headers
@main.command()
@click.option('--limit', '-l', help='limit number of records')
def scorers(limit):
click.echo('limit is : %s' % limit)
if __name__ == '__main__':
main(obj={})
和一个测试文件:
test_cs.py
from click.testing import CliRunner
import unittest
from .clicksample import main
class Sample(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
def tearDown(self):
pass
def test_sample_command(self):
result = self.runner.invoke(main)
self.assertEqual(0, result.exit_code)
if __name__ == '__main__':
unittest.main()
我想知道为什么测试没有通过。当我 运行 来自命令行的 clicksample 脚本时,它按预期工作,但由于某种原因,它没有按预期在测试中退出。当我使用 pdb 戳结果时,我得到以下统计数据:
(Pdb) result
<Result TypeError("'NoneType' object does not support item assignment",)>
(Pdb) result.exit_code
-1
(Pdb)
您从未设置 ctx.obj
。这可以为您解决这个问题:
def main(ctx, apikey):
if ctx.obj is None:
ctx.obj = {}
...
我有 2 个文件:
click_example.py
import click
@click.group(invoke_without_command=True)
@click.option('--apikey', default='My key',
help="API key to use.")
@click.pass_context
def main(ctx, apikey):
"""
A CLI for live and past football scores from various football leagues.
resources are given as commands and subresources and their filters as options
"""
headers = {'X-Auth-Token': apikey}
ctx.obj['headers'] = headers
@main.command()
@click.option('--limit', '-l', help='limit number of records')
def scorers(limit):
click.echo('limit is : %s' % limit)
if __name__ == '__main__':
main(obj={})
和一个测试文件:
test_cs.py
from click.testing import CliRunner
import unittest
from .clicksample import main
class Sample(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
def tearDown(self):
pass
def test_sample_command(self):
result = self.runner.invoke(main)
self.assertEqual(0, result.exit_code)
if __name__ == '__main__':
unittest.main()
我想知道为什么测试没有通过。当我 运行 来自命令行的 clicksample 脚本时,它按预期工作,但由于某种原因,它没有按预期在测试中退出。当我使用 pdb 戳结果时,我得到以下统计数据:
(Pdb) result
<Result TypeError("'NoneType' object does not support item assignment",)>
(Pdb) result.exit_code
-1
(Pdb)
您从未设置 ctx.obj
。这可以为您解决这个问题:
def main(ctx, apikey):
if ctx.obj is None:
ctx.obj = {}
...