简体   繁体   English

通过从Python中的另一个文件调用文件来对文件进行单元测试

[英]Unittesting a file by calling it from another file in Python

I am new to unnitest module. 我是最不熟悉的模块的新手。 I have a file that has unittest in it. 我有一个包含单元测试的文件。 The file is something like ... 该文件是像...

File1.py File1.py

class ABC (unittest.TestCase):
    def setUp(self):
        # Do some work here

    def test_123(self, a,b,c):
        # Do some work here

if __name__ == "__main__":
unittest.main()

* Now I am calling this file from another file by passing values to the function "test_123".* But python displays the following error. * 现在我通过将值传递给函数“ test_123”从另一个文件中调用此文件。*但是python显示以下错误。 Could anybody please help! 有人可以帮忙吗?

Traceback (most recent call last):
File "caller_file.py", line 20, in <module>
r = file1.ABC()
File "/usr/lib/python2.7/unittest/case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'file1.ABC'>: runTest

You can run file1.ABC test case like this: 您可以像这样运行file1.ABC测试用例:

import unittest
import file1

suite = unittest.TestLoader().loadTestsFromTestCase(file1.ABC)
unittest.TextTestRunner(verbosity=2).run(suite)

Also you need to add the self argument to the setUp and test_123 methods and self should be the sole argument. 另外,您需要将self参数添加到setUptest_123方法中,并且self应该是唯一的参数。

I run into similar problems with my unittests because missing entries in search path for modules. 我在单元测试中遇到了类似的问题,因为模块搜索路径中缺少条目。

I solved it by creating 我通过创建解决了

my_env = os.environ.copy()
        if not 'PYTHONPATH' in my_env:
            my_env['PYTHONPATH'] = ''

        my_env['PYTHONPATH'] += ';' + ';'.join(
                                    [os.path.abspath('.'),
                                    os.path.abspath('..'),
                                    os.path.abspath('..\\..')])

and then the call of the file 然后调用文件

_ = subprocess.check_output(filepath, shell=True, env=my_env)

I just added the current path environment because the calling-file is in the same directories. 我刚刚添加了当前路径环境,因为调用文件位于同一目录中。 Maybe you have to adjust that. 也许您必须进行调整。

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

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