这是我的LoginResourceHelperTest课程
from flask.ext.testing import TestCase
class LoginResourceHelper(TestCase):
content_type = 'application/x-www-form-urlencoded'
def test_create_and_login_user(self, email, password):
user = UserHelper.add_user(email, password)
self.assertIsNotNone(user)
response = self.client.post('/', content_type=self.content_type,
data=UserResourceHelper.get_user_json(
email, password))
self.assert200(response)
# HTTP 200 OK means the client is authenticated and cookie
# USER_TOKEN has been set
return user
def create_and_login_user(email, password='password'):
"""
Helper method, also to abstract the way create and login works.
Benefit? The guts can be changed in future without breaking the clients
that use this method
"""
return LoginResourceHelper().test_create_and_login_user(email, password)
Run Code Online (Sandbox Code Playgroud)
当我打电话时create_and_login_user('test_get_user'),我看到错误如下
line 29, in create_and_login_user
return LoginResourceHelper().test_create_and_login_user(email, password)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'core.expense.tests.harness.LoginResourceHelper.LoginResourceHelper'>: runTest
Run Code Online (Sandbox Code Playgroud)
Python的unittest模块(Flask在幕后使用)以特殊方式组织代码.
要从派生的类中运行特定方法,TestCase您需要执行以下操作:
LoginResourceHelper('test_create_and_login_user').test_create_and_login_user(email, password)
Run Code Online (Sandbox Code Playgroud)
为了理解为什么必须这样做,您需要了解默认 TestCase对象的工作原理.
通常,在继承时,TestCase期望有一个runTest方法:
class ExampleTestCase(TestCase):
def runTest(self):
# Do assertions here
Run Code Online (Sandbox Code Playgroud)
但是,如果您需要多个TestCases,则需要为每个单独执行此操作.
由于这是一件单调乏味的事情,他们决定采取以下措施:
class ExampleTestcase(TestCase):
def test_foo(self):
# Do assertions here
def test_bar(self):
# Do other assertions here
Run Code Online (Sandbox Code Playgroud)
这称为测试夹具.但是既然我们没有声明a runTest(),你现在必须指定你希望TestCase运行的方法 - 这就是你想要做的.
>>ExampleTestCase('test_foo').test_foo()
>>ExampleTestCase('test_bar').test_bar()
Run Code Online (Sandbox Code Playgroud)
通常,unittest模块将在后端执行所有这些操作以及其他一些操作:
但是,既然你正在规避正常的unittest执行,你必须做有unitest规律的工作.
为了深入了解,我强烈建议您阅读docs unittest.