9

对不起,基本问题。我使用 unittest 方法在一个脚本中检查我的模型。现在,我的问题是如何从另一个文件调用这个脚本并保存测试结果。以下是我的代码示例:

**model_test.py**

import unittest
import model_eq #script has models

class modelOutputTest(unittest.TestCase):
    def setUp(self):
        #####Pre-defined inputs########
        self.dsed_in=[1,2]

        #####Pre-defined outputs########
        self.msed_out=[6,24]

        #####TestCase run variables########
        self.tot_iter=len(self.a_in)

    def testMsed(self):
        for i in range(self.tot_iter):
            fun = model_eq.msed(self.dsed_in[i],self.a_in[i],self.pb_in[i])
            value = self.msed_out[i]
            testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("msed",i,value,fun)
self.assertEqual(round(fun,3),round(self.msed_out[i],3),testFailureMessage)

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

我想要的下一步是创建另一个名为 test_page.py 的脚本,它运行单元测试脚本并将结果保存到变量(我需要将结果发布到网页)。

test_page.py    

from model_test.py import *
a=modelOutputTest.testMsed()

但是,我收到以下错误。

Traceback (most recent call last):
  File "D:\Dropbox\AppPest\rice\Rice_unittest.py", line 16, in <module>
    a= RiceOutputTest.testMsed()
TypeError: unbound method testMsed() must be called with RiceOutputTest instance as first argument (got nothing instead)

谁能给我一些建议?谢谢!

感谢尼克斯的帮助!我的下一个问题是:我需要在一个循环中使用两个给定的案例来测试这个函数。它张贴在这里

4

3 回答 3

18

你需要使用一个test runner

测试运行器 测试运行器是一个组件,它协调测试的执行并向用户提供结果。运行程序可以使用图形界面、文本界面或返回特殊值来指示执行测试的结果。

from unittest.case import TestCase
import unittest
from StringIO import StringIO
class MyTestCase(TestCase):
    def testTrue(self):
        '''
        Always true
        '''
        assert True

    def testFail(self):
        '''
        Always fails
        '''
        assert False

from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream)
result = runner.run(unittest.makeSuite(MyTestCase))
print 'Tests run ', result.testsRun
print 'Errors ', result.errors
pprint(result.failures)
stream.seek(0)
print 'Test output\n', stream.read()

>>> Output:  
>>> Tests run  2
>>> Errors  []
>>> [(<__main__.MyTestCase testMethod=testFail>,
>>> 'Traceback (most recent call last):\n  File "leanwx/test.py", line 15, in testFail\n                assert False\nAssertionError\n')]
>>> Test output
>>> F.
>>> ======================================================================
>>> FAIL: testFail (__main__.MyTestCase)
>>> ----------------------------------------------------------------------
>>> Traceback (most recent call last):
>>>   File "leanwx/test.py", line 15, in testFail
>>>     assert False
>>> AssertionError
>>>
>>>----------------------------------------------------------------------
>>>Ran 2 tests in 0.001s
>>>
>>>FAILED (failures=1)
于 2013-01-11T16:50:55.240 回答
1

假设您的单元测试位于“test”目录中:

# Tested in Python 3.8
# https://docs.python.org/3/library/unittest.html#module-unittest
from unittest import TestLoader, TestResult
from pathlib import Path


def run_tests():
    test_loader = TestLoader()
    test_result = TestResult()

    # Use resolve() to get an absolute path
    # https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve
    test_directory = str(Path(__file__).resolve().parent / 'test')

    test_suite = test_loader.discover(test_directory, pattern='test_*.py')
    test_suite.run(result=test_result)

    # See the docs for details on the TestResult object
    # https://docs.python.org/3/library/unittest.html#unittest.TestResult

    if test_result.wasSuccessful():
        exit(0)
    else:
        # Here you can either print or log your test errors and failures
        # test_result.errors or test_result.failures
        exit(-1)

if __name__ == '__main__':
    run_tests()
于 2021-04-21T18:20:05.047 回答
0

.py从标题中删除from model_test.py import *

于 2019-03-05T12:26:34.987 回答