| 1 | # Testing |
| 2 | |
| 3 | ## Overview |
| 4 | |
| 5 | This covers special considerations when writing unit or integration tests for a cmd2 application. |
| 6 | |
| 7 | ## Testing Commands |
| 8 | |
| 9 | We encourage `cmd2` application developers to look at the |
| 10 | [cmd2 tests](https://github.com/python-cmd2/cmd2/tree/main/tests) for examples of how to perform |
| 11 | unit and integration testing of `cmd2` commands. There are various helpers that will do things like |
| 12 | capture and return stdout, stderr, and command-specific result data. |
| 13 | |
| 14 | ## Mocking |
| 15 | |
| 16 | If you need to mock anything in your cmd2 application, and most specifically in sub-classes of |
| 17 | [cmd2.Cmd][] or [cmd2.CommandSet][], you must use |
| 18 | [Autospeccing](https://docs.python.org/3/library/unittest.mock.html#autospeccing), |
| 19 | [spec=True](https://docs.python.org/3/library/unittest.mock.html#patch), or whatever equivalent is |
| 20 | provided in the mocking library you're using. |
| 21 | |
| 22 | In order to automatically load functions as commands, `cmd2` performs a number of reflection calls |
| 23 | to look up attributes of classes defined in your cmd2 application. Many mocking libraries will |
| 24 | automatically create mock objects to match any attribute being requested, regardless of whether |
| 25 | they're present in the object being mocked. This behavior can incorrectly instruct cmd2 to treat a |
| 26 | function or attribute as something it needs to recognize and process. To prevent this, you should |
| 27 | always mock with [Autospeccing](https://docs.python.org/3/library/unittest.mock.html#autospeccing) |
| 28 | or [spec=True](https://docs.python.org/3/library/unittest.mock.html#patch) enabled. If you don't |
| 29 | have autospeccing on, your unit tests will fail with an error message like: |
| 30 | |
| 31 | ```sh |
| 32 | cmd2.exceptions.CommandSetRegistrationError: Subcommand |
| 33 | <MagicMock name='cmdloop.subcommand_name' id='4506146416'> is not valid: must be a string. |
| 34 | Received <class 'unittest.mock.MagicMock'> instead |
| 35 | ``` |
| 36 | |
| 37 | ## Examples |
| 38 | |
| 39 | ```py |
| 40 | def test*mocked_methods(): |
| 41 | with mock.patch.object(MockMethodApp, 'foo', spec=True): |
| 42 | cli = MockMethodApp() |
| 43 | ``` |
| 44 | |
| 45 | Another one using [pytest-mock](https://pypi.org/project/pytest-mock) to provide a `mocker` fixture: |
| 46 | |
| 47 | ```py |
| 48 | def test_mocked_methods2(mocker): |
| 49 | mock_cmdloop = mocker.patch("cmd2.Cmd.cmdloop", autospec=True) |
| 50 | cli = cmd2.Cmd() |
| 51 | cli.cmdloop() |
| 52 | assert mock_cmdloop.call_count == 1 |
| 53 | ``` |