当前位置: 首页>编程语言>正文

pytest测试用例通过但是没有打印passed pytest no tests were found

不多说了,最近因为兴趣学python,IDE使用PyCharm,到了讲测试一节,按照原码死活调不出来。
总是说No tests were found
最后发现,书上说除了测试类外,要使用
unittest.main()
来让Python运行这个文件夹中的测试。而在PyCharm中,如果这样写就会出现上述问题。当把这条改成

unittest.main

也就是去掉括号后,测试会正常运行。

另外若PyCharm建立后这样导入

from unittest import TestCase

可以将unittest.main换成这样

if __name__ == '__main__':
    TestCase

看了下原码,main这个变量是指向一个TestProgram实例的,可能因为版本更新的缘故用法不同
目前初学不知背后机理是什么,如果大家有好的解答还烦请下方留言讨论。

另外附上PyCharm快速建立Test的方法

以下是PyCharm官方教程。放过来适当翻译一下,当做备用

原文如下及对应翻译如下
Creating Tests

PyCharm suggests a way to create tests for classes and individual methods.
PyCharm建议用这样的方式来为一个方法(函数)或类建立测试

To create a test for a class or method, follow these general steps
为方法或者函数建立测试,有如下几步

In the editor, place the caret at the class declaration, or somewhere within a method.
编辑器中,把光标放在类声明或方法中间

Do one of the following:
做如下的其中一个步骤

On the main menu, choose Navigate | Test.
在主菜单中,点击Navigate→Test

On the context menu, choose Go To | Test.
在context menu(就是点右键)中,选择Go To→Test

Press Ctrl+Shift+T.
使用快捷键Ctrl+Shift+T.

PyCharm shows the list of available tests.
PyCharm将显示可用测试的列表

If the desired test doesn’t yet exist, click Create new test.
如果希望的测试没有出现在列表里,点击 Create new test.

The Create Test dialog box opens.
生成测试窗口会出现

In the Create Test dialog box, specify the following settings:
在窗口中,定位如下几种设置

Target directory, where the new test class will be generated.
Target directory,你希望测试类生成的文件夹

The name of the test file, and the name of the test class.
测试文件的名称以及测试类的名称

Select the check boxes next to the methods you want to include in the test class.
选择测试窗口中出现的你希望包含的测试方法

Note that if the caret has been placed within a method, only this method name is included in the list.
注意如果光标在某个方法中间,只有这个方法会出现在列表里

Click OK when ready. PyCharm generates the test file in the specified location.
点击OK,PyCharm会自动在你设置的位置生成测试文件

简单来说就是在方法或者类中间点生成测试,然后再窗口中设置生成文件的路径以及对应的文件名和类名,最后选择要测试的方法就行。
简单排版一下,希望能帮助到别人。翻译水平略渣,见谅
另外如果想看原文,可以直接到官方教程查看



https://www.xamrdz.com/lan/5ag1923119.html

相关文章: