def skip_dependon(depend): """ :param depend: 依赖的用例函数名,默认为空 :return: wraper_func """ def wraper_func(test_func): @wraps(test_func) # @wraps:避免被装饰函数自身的信息丢失 def inner_func(self): if depend == test_func.__name__: raise ValueError("{} cannot depend on itself".format(depend)) failures = str([fail[0] for fail in self._outcome.result.failures]) errors = str([error[0] for error in self._outcome.result.errors]) # skipped = str([error[0] for error in self._outcome.result.skipped]) or (depend in skipped) flag = (depend in failures) or (depend in errors) if failures.find(depend) != -1: test = unittest.skipIf(flag, "{} failed".format(depend))(test_func) elif errors.find(depend) != -1: test = unittest.skipIf(flag, "{} error".format(depend))(test_func) # elif skipped.find(depend) != -1: # test = unittest.skipIf(flag, "{} skipped".format(depend))(test_func) else: test = test_func return test(self) return inner_func return wraper_func
时间: 2024-02-14 14:23:30 浏览: 19
这是一个装饰器函数,用于给unittest的测试用例函数添加依赖关系。它接受一个参数`depend`,表示这个测试用例函数依赖的函数名,默认为空。它返回一个函数`wraper_func`,这个函数又返回一个函数`inner_func`,这个函数是对测试用例函数进行装饰的实际函数。
`inner_func`中首先对依赖函数名进行判断,如果依赖函数名和测试用例函数名相同,则抛出异常,因为一个测试用例不能依赖于自己。
然后通过`self._outcome.result`来获取测试结果,并判断依赖函数的测试结果。如果依赖函数执行失败(failures),则用`unittest.skipIf`装饰器将测试用例函数标记为跳过,跳过的原因是依赖函数执行失败。同样的,如果依赖函数执行出错(errors),也会将测试用例函数标记为跳过。
最后返回装饰后的测试用例函数。
相关问题
AttributeError: module 'unittest' has no attribute 'skip_dependon'
这个错误通常是因为你在使用 `unittest` 模块时错误地使用了 `skip_dependon` 属性,而实际上该属性不存在。
正确的属性是 `skipDependent`,可以使用类似以下的代码来跳过依赖测试:
```python
@unittest.skipDependent
def test_my_dependent_test(self):
# ...
```
如果你确信你的代码中没有拼写错误或者语法错误,那么可能是你使用的 `unittest` 版本过低,不支持该属性。可以尝试升级 `unittest` 模块或者使用其他的跳过依赖测试的方法。
编辑了一个装饰器 skip_dependon 使用时add
如果你自己定义了一个名为 `skip_dependon` 的装饰器,并且想在测试用例中使用该装饰器来跳过依赖测试,可以按照以下步骤:
1. 在你的测试文件中导入 `skip_dependon` 装饰器:
```python
from your_module import skip_dependon
```
2. 在需要跳过依赖测试的测试函数上使用 `@skip_dependon` 装饰器:
```python
def test_my_dependent_test(self):
# ...
test_my_dependent_test = skip_dependon(test_my_dependent_test)
```
或者更简洁地使用装饰器语法:
```python
@skip_dependon
def test_my_dependent_test(self):
# ...
```
注意,在使用 `@skip_dependon` 装饰器时,你需要确保该装饰器已经被定义在你的代码中。
如果你能提供更多的代码信息,我可以更具体地帮你定位问题。