将参数传递给python unittest

时间:2014-02-03 05:17:33

标签: python

我有一个功能测试'y1.py',我试图从python / django函数中传递参数。在调用函数里面我有:

import unittest, sys
import ft1.y1
ft1.y1.testVars = [1, 2, 3, "foo"]
unittest.main(module=ft1.y1, argv=sys.argv[:1], exit=False)

基于h.ttp://stackoverflow.com/questions/2812132/how-to-pass-variables-using-unittest-suite

y1.py:

   from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re    

class Y1(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.yahoo.com/"
        self.verificationErrors = []
        self.accept_next_alert = True
         print('tvars' +self.testVars )

     ....................


if __name__ == "__main__":
    unittest.main()

我得到了:

Traceback (most recent call last):
  File "F:\envs\r1\driver1\ft1\y1.py", line 17, in setUp
    print('tvars '+ y1.testVars )
AttributeError: type object 'y1' has no attribute 'testVars'    

----------------------------------------------------------------------
Ran 1 test in 2.330s    

FAILED (errors=1)
[02/Feb/2014 23:59:42] "GET /runtest/ HTTP/1.1" 200 7

我该如何解决这个问题?

编辑:

根据建议我将行改为:

print('tvars' + sys.module[__name__].testVars )

我得到了:

E
======================================================================
ERROR: test_y1 (ft1.y1.y1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "F:\envs\r1\driver1\ft1\y1.py", line 17, in setUp
    print('tvars' + sys.module[__name__].testVars )
AttributeError: 'module' object has no attribute 'module'    

----------------------------------------------------------------------
Ran 1 test in 2.981s    

FAILED (errors=1)

1 个答案:

答案 0 :(得分:1)

如果您尝试引用模块而不是类(您的testVars位于模块级别),则应该使用sys.modules[__name__].testVars,这样做:

print('tvars' +self.testVars )

成为:

print('tvars' + sys.modules[__name__].testVars )