|
28 | 28 | import os
|
29 | 29 | import sys
|
30 | 30 | import difflib
|
| 31 | +import functools |
31 | 32 |
|
32 | 33 | from PyQt4.QtCore import QVariant
|
33 | 34 | from qgis.core import QgsApplication, QgsFeatureRequest, QgsVectorLayer
|
@@ -154,8 +155,71 @@ def assertFilesEqual(self, filepath_expected, filepath_result):
|
154 | 155 | self.assertEqual(0, len(diff), ''.join(diff))
|
155 | 156 |
|
156 | 157 |
|
| 158 | +class _UnexpectedSuccess(Exception): |
| 159 | + """ |
| 160 | + The test was supposed to fail, but it didn't! |
| 161 | + """ |
| 162 | + pass |
| 163 | + |
| 164 | + |
| 165 | +def expectedFailure(*args): |
| 166 | + """ |
| 167 | + Will decorate a unittest function as an expectedFailure. A function |
| 168 | + flagged as expectedFailure will be succeed if it raises an exception. |
| 169 | + If it does not raise an exception, this will throw an |
| 170 | + `_UnexpectedSuccess` exception. |
| 171 | +
|
| 172 | + @expectedFailure |
| 173 | + def my_test(self): |
| 174 | + self.assertTrue(False) |
| 175 | +
|
| 176 | + The decorator also accepts a parameter to only expect a failure under |
| 177 | + certain conditions. |
| 178 | +
|
| 179 | + @expectedFailure(time.localtime().tm_year < 2002) |
| 180 | + def my_test(self): |
| 181 | + self.assertTrue(qgisIsInvented()) |
| 182 | + """ |
| 183 | + if hasattr(args[0], '__call__'): |
| 184 | + # We got a function as parameter: assume usage like |
| 185 | + # @expectedFailure |
| 186 | + # def testfunction(): |
| 187 | + func = args[0] |
| 188 | + |
| 189 | + @functools.wraps(func) |
| 190 | + def wrapper(*args, **kwargs): |
| 191 | + try: |
| 192 | + func(*args, **kwargs) |
| 193 | + except Exception: |
| 194 | + pass |
| 195 | + else: |
| 196 | + raise _UnexpectedSuccess |
| 197 | + return wrapper |
| 198 | + else: |
| 199 | + # We got a function as parameter: assume usage like |
| 200 | + # @expectedFailure(failsOnThisPlatform) |
| 201 | + # def testfunction(): |
| 202 | + condition = args[0] |
| 203 | + |
| 204 | + def realExpectedFailure(func): |
| 205 | + @functools.wraps(func) |
| 206 | + def wrapper(*args, **kwargs): |
| 207 | + if condition: |
| 208 | + try: |
| 209 | + func(*args, **kwargs) |
| 210 | + except Exception: |
| 211 | + pass |
| 212 | + else: |
| 213 | + raise _UnexpectedSuccess |
| 214 | + else: |
| 215 | + func(*args, **kwargs) |
| 216 | + return wrapper |
| 217 | + |
| 218 | + return realExpectedFailure |
| 219 | + |
157 | 220 | # Patch unittest
|
158 | 221 | unittest.TestCase = TestCase
|
| 222 | +unittest.expectedFailure = expectedFailure |
159 | 223 |
|
160 | 224 |
|
161 | 225 | def start_app():
|
|
0 commit comments