我有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 = {}
    ...

关于python - 单击python Cli.testing TypeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53001381/

10-10 07:39