Search code examples
pythonpython-unittestpython-click

click python Cli.testing TypeError


I have 2 files:

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={})

and a test file:

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()

I want to know why the test does not pass. When I run the clicksample script from the command line it works as expected but for some reason it does not exit as expected in the test. When I poke the result using pdb I get the following stats:

(Pdb) result 
<Result TypeError("'NoneType' object does not support item assignment",)>
(Pdb) result.exit_code
-1
(Pdb)

Solution

  • You never set ctx.obj. This can fix that for you:

    def main(ctx, apikey):
        if ctx.obj is None:
            ctx.obj = {}
        ...