Salome HOME
93909e1fb84e2ab7379ac1ffeef050f7d1f42c0c
[modules/kernel.git] / src / KERNEL_PY / kernel / pyunittester.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2011-2023  CEA, EDF, OPEN CASCADE
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 ## \defgroup pyunittester pyunittester
22 #  \{ 
23 #  \details Simple wrapper of the pyunit framework
24 #  \}
25
26 import sys
27 from salome.kernel import termcolor
28 def printfile(filename):
29     stream = open(filename,'r')
30     lines = stream.readlines()
31     stream.close()
32     for line in lines:
33         if not termcolor.canDisplayColor(sys.stdout):
34             msg = line.split('\n')[0]
35         else:
36             msg = termcolor.makeColoredMessage(line.split('\n')[0], termcolor.BLUE)
37         print(msg)
38
39 import os
40 import unittest
41 from unittest import TestCase
42 from .uiexception import DevelException
43
44 ## This class is a simple wrapper of the pyunit framework.
45 #  \ingroup pyunittester
46 class PyUnitTester():
47     """
48     This class is a simple wrapper of the pyunit framework.
49     """
50     def __init__(self):
51         self.__listTestSuite=[]
52         self.setLogFilename("testlog.txt")
53
54     def addTestCase(self,testCaseClass):
55         # We test some attributes to validate that the argument
56         # corresponds to a unittest.TestCase class (WARN: it's not an
57         # instance but a class keyword)
58         if "assertTrue" not in dir(testCaseClass):
59             raise DevelException("Not a pyunit test case")
60
61         suite = unittest.TestLoader().loadTestsFromTestCase(testCaseClass)
62         self.__listTestSuite.append(suite)
63
64     def setLogFilename(self, filename):
65         self.__logfilename = filename
66
67     def run(self):
68         # We first open the output stream
69         if os.path.exists(self.__logfilename):
70             os.remove(self.__logfilename)
71         logfile = open(self.__logfilename,'w')
72         
73         # Then, define and execute the runner to play the test suites
74         runner = unittest.TextTestRunner(stream=logfile,verbosity=2)
75         for suite in self.__listTestSuite:
76             runner.run(suite)
77
78         # Finally close the output stream and print the report
79         logfile.close()
80         self.printreport()
81
82     def printreport(self):
83         printfile(self.__logfilename)
84
85 ## This can be used to just execute a test function that is
86 #  considered as OK simply if no exception is raised (can be test by
87 #  an assertTrue).
88 #  \ingroup pyunittester
89 def execAndConvertExceptionToBoolean(function):
90     """
91     This can be used to just execute a test function that is
92     considered as OK simply if no exception is raised (can be test by
93     an assertTrue).
94     """
95     try:
96         result = function()
97         if result is None:
98             return True
99         return result
100     except Exception as e:
101         print(e)
102         return False
103
104 # Simple helper function for most cases where there is only one
105 # TestCase classe.
106 ## Run the test suite provided by the specified TestCase class.
107 #  \ingroup pyunittester
108 def run(testCaseClass):
109     """
110     Run the test suite provided by the specified TestCase class.
111     """
112     tester = PyUnitTester()
113     tester.addTestCase(testCaseClass)
114     tester.run()
115
116 #
117 # ==============================================================================
118 # Simple use cases
119 # ==============================================================================
120 #
121 class MyTestCase(unittest.TestCase):
122     def test_myTestOk_01(self):
123         r=True
124         print("myTestOk_01: should be OK")
125         self.assertTrue(r)
126
127     def test_myTestOk_02(self):
128         r=True
129         print("myTestOk_02: should be OK")
130         self.assertTrue(r)
131
132     def test_myTestNotOk(self):
133         r=False
134         print("myTestNotOk: should be NOT OK")
135         self.assertTrue(r)
136
137 def functionRaisingAnException():
138     raise Exception("An error occurs")
139
140 def functionReturningFalse():
141     return False
142
143 def functionReturningTrue():
144     return True
145
146 def functionReturningNothing():
147     print("functionReturningNothing")
148
149 class MyTestCase2(unittest.TestCase):
150     def test_myTest_01(self):
151         r=execAndConvertExceptionToBoolean(functionRaisingAnException)
152         print("test 01: this test should be NOT OK")
153         self.assertTrue(r)
154
155     def test_myTest_02(self):
156         r=execAndConvertExceptionToBoolean(functionReturningFalse)
157         print("test 02: this test should be NOT OK")
158         self.assertTrue(r)
159
160     def test_myTest_03(self):
161         r=execAndConvertExceptionToBoolean(functionReturningTrue)
162         print("test 03: this test should be OK")
163         self.assertTrue(r)
164
165     def test_myTest_04(self):
166         r=execAndConvertExceptionToBoolean(functionReturningNothing)
167         print("test 04: this test should be OK")
168         self.assertTrue(r)
169
170     def test_myTest_05(self):
171         r=True
172         print("test 05: this test should be OK")
173         self.assertTrue(r)
174
175
176 def TEST_basic_usecase():
177     tester = PyUnitTester()
178     # Note that the class keywords must be passed
179     tester.addTestCase(MyTestCase)
180     tester.addTestCase(MyTestCase2)
181     tester.run()
182     
183 if __name__ == "__main__":
184     TEST_basic_usecase()