简体   繁体   English

如何在python单元测试中测试python二进制文件?

[英]How to test a python binary in the python unit test?

I would like to test a python binary "main.py" with command line arguments in the unit test. 我想在单元测试中使用命令行参数测试python二进制“ main.py”。 The usage of this binary is as follows. 该二进制文件的用法如下。

main.py --input_file=input.txt --output_file=out.txt

When designing unit tests, I think it is better to test each component like a class or a method. 设计单元测试时,我认为最好像类或方法一样测试每个组件。

However, in some cases like the above one, I would like to do end-to-end testing of the whole python binary especially when it is already created by someone else. 但是,在某些情况下,例如上述情况,我想对整个python二进制文件进行端到端测试,尤其是当它已经由其他人创建时。 In the above case, I want to make it sure whether "main.py" generates "out.txt" correctly. 在上述情况下,我要确保“ main.py”是否正确生成“ out.txt”。

One option is using subprocess.check_call and create it to a temporary directory, and loads it and compares it with the golden (expected output). 一种选择是使用subprocess.check_call并将其创建到一个临时目录,然后将其加载并将其与黄金(预期的输出)进行比较。

Is it a good way? 这是个好方法吗?

Or, if there is any better way, could you please advise me? 或者,如果有更好的方法,请您告诉我吗?

This is called blackbox testing as the inner structure of the program is unknown to the tester. 这被称为黑盒测试,因为程序的内部结构对于测试人员是未知的。 If you insist on testing the module without getting to know what's happening inside, You could (as you mentioned) use exec or subprocess to check the validity of the output. 如果您坚持测试模块而又不知道内部发生了什么,则可以(如上所述)使用execsubprocess来检查输出的有效性。 But the more logical way is to use unittest libraries and try to test the code using the API it provides. 但更合乎逻辑的方式是使用unittest库,并尝试使用其提供的API测试代码。

If you're testing the handling of arguments as part of the unit tests, just look inside main.py and see how it handles arguments. 如果要在单元测试中测试参数的处理,只需查看main.py并查看其如何处理参数即可。

For example, you might have a test case that sets sys.argv and then calls main: 例如,您可能有一个测试用例,该用例设置了sys.argv然后调用main:

import sys

import myapp.main

sys.argv = '''main.py --input_file=input.txt --output_file=out.txt'''.split()

myapp.main.main()

# I have no idea what test you want to run.

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

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