Python Selenium TypeError:test方法需3参数仅传入1个
问题分析与解决方案
这个错误的核心原因是unittest框架的测试方法规则:所有以test_开头的方法会被unittest自动识别为独立测试用例,调用时只会传入self这一个参数。但你定义的test_redirect_to_congito_login_page要求接收3个参数(self, admin_base_url, cognito_url),当unittest尝试自动调用它时,只传了1个参数,自然就抛出了TypeError。
具体修复步骤:
- 重命名非测试方法:把
test_redirect_to_congito_login_page的test_前缀去掉,改成内部方法的命名风格(比如_redirect_to_cognito_login_page),这样unittest就不会把它当成独立测试用例执行,只会在你手动调用(比如test_all里)的时候传入参数。 - 修正拼写错误:方法名里的
congito是拼写失误,应该是cognito,避免后续逻辑里的字符串匹配出现问题。 - 修复
tearDown装饰器:你给tearDown加了@classmethod装饰器,但tearDown是unittest的实例方法,必须去掉这个装饰器——否则self会指向类而非实例,访问self.driver时会出错。
修改后的关键代码片段:
class SeleniumTestPack(unittest.TestCase): driver = webdriver.Firefox() timeout = 30 def test_all(self): admin_base_url = args.url cognito_url = "test.auth.us-west-2.amazoncognito.com" user_full_name = "test User" email = "test@test.com" firstName = "Selenium" lastName = "User" try: # 调用修改后的内部方法 self._redirect_to_cognito_login_page(admin_base_url, cognito_url) self.delete_geckodriver_log() except Exception: self.driver.save_screenshot('exception.png') self.fail("Exception: %s" % (traceback.format_exc())) # 重命名方法,去掉test_前缀,修正拼写 def _redirect_to_cognito_login_page(self, admin_base_url, cognito_url): print "Test navigating to home page redirects to cognito login page" self.driver.get(admin_base_url) self.wait_for_element_loaded(By.ID, "div-forms") page_url = self.driver.current_url assert cognito_url in page_url # ...其他方法保持不变... # 去掉@classmethod装饰器 def tearDown(self): # close the browser window self.driver.quit()
额外提示:
- 你代码里的
print是Python 2语法,如果后续切换到Python 3,需要改成print(...)函数形式。 - 建议把
driver的初始化放到setUp方法里(而非类属性),这样每个测试用例都会有独立的浏览器实例,避免测试之间的状态污染。
内容的提问来源于stack exchange,提问作者Jayesh Dhandha
相关产品推荐
相关产品推荐

