python - Python unittesting - How to assert inside of setUpClass?
问题描述
In my setUpClass
I would like to create a resource in the database one time, which is then used for all of the tests in the class.
After I create the resource in setUpClass
, I would like to perform assertions on it right then and there. However, I'm not sure how to call assertions in setUpClass
, given that all of the assertion functions are instance methods, not class methods.
import unittest
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
# How would I assert that cls.foo['name'] == 'bar'?
# The following does not work, as the assertEquals function is not a class method
# cls.assertEquals(cls.foo['name'], 'bar')
@classmethod
def make_foo(cls, name):
# Calls a POST API to create a resource in the database
return {'name': name}
def test_foo_0(self):
# Do something with cls.foo
pass
def test_foo_1(self):
# do something else with cls.foo
pass
The only alternative I can think of is to raise an exception in setUpClass:
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
if cls.foo['name'] != 'bar':
raise Exception("Failed to create resource, cannot do the tests")
Of course, I do not want to call the assertions from each test, as this will just duplicate the code.
Edit: I don't think this workaround is good, because the failure message will point to the self.assertFalse(self.flag)
line, instead of the if cls.foo['name'] ~= 'bar'
line. In addition, if you created multiple resources, this would need multiple flags to disambiguate.
flag=False
@classmethod
def setUpClass(cls):
cls.foo = cls.make_foo(name='bar')
if cls.foo['name'] != 'bar':
cls.flag=True
def setUp(self):
self.assertFalse(self.flag)
解决方案
推荐阅读
- apache-nifi - Apache NiFi 识别表达式语言(routeText)中的关系
- ios - 在 iOS 13 上未调用supportedInterfaceOrientations
- opencv - 使用 cmake for raspberry pi 交叉编译 opencv 代码失败
- reactjs - 创建自定义组件时如何使用 react-select 类型?
- ruby-on-rails - 博客应用程序在提交表单时未将属性保存到数据库
- shell - 为什么使用 zsh 小部件执行交互式命令时会中断
- postgresql - postgresql中每n行的id列的返回值
- java - 尝试从课堂转到活动
- python - 如何使用 xlsxwriter 将主题单元格样式添加到单元格?
- javascript - Mongodb在靠近坐标的LineString上获取点