简体   繁体   English

使用 pytest 测试交互式模块

[英]Testing an interactive module with pytest

I have a python module which is designed to be used by non-programmers, interactively.我有一个 python 模块,旨在供非程序员以交互方式使用。 It is used within iPython, and on load, it asks for a couple of user inputs, prints some ascii art, that sort of thing.它在 iPython 中使用,在加载时,它会要求一些用户输入,打印一些 ascii 艺术,诸如此类。 This is implemented in the __init__.py of the module.这是在模块的__init__.py中实现的。

The module also contains a utils file tld(containing setup.py)/utils.py , with some functions in it.该模块还包含一个 utils 文件tld(containing setup.py)/utils.py ,其中包含一些功能。 I would like to test these.我想测试这些。 The utils file does not import anything from the rest of the module, and contains only pure functions. utils 文件不会从模块的 rest 导入任何内容,并且只包含纯函数。 The tests live in tld(containing setup.py)/tests/test_utils.py Currently, trying to run pytest results in a failure, as the module's __init__ file is run, which hangs whilst awaiting the above mentioned user input.测试位于tld(containing setup.py)/tests/test_utils.py目前,尝试运行 pytest 会导致失败,因为模块的__init__文件正在运行,该文件在等待上述用户输入时挂起。

Is there a way of getting pytest to run the tests in test_utils.py, without running the __init__.py of the python module?有没有办法让 pytest 运行 test_utils.py 中的测试,而不运行 python 模块的__init__.py Or some other way of getting around this issue?或者其他解决这个问题的方法?

I have tried running pytest tests/test_utils.py , but that had the same effect.我试过运行pytest tests/test_utils.py ,但效果相同。

I solved this by defining an initialize function inside the __init__.py of the module, which encapsulates all of the user interaction.我通过在模块的__init__.py中定义一个initialize function 来解决这个问题,它封装了所有的用户交互。 If module.initialize() is not explicitly called, no user input is requested, so the pytest tests can run as expected.如果没有显式调用module.initialize() ,则不需要用户输入,因此 pytest 测试可以按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM