问:使用py.test运行testsuite时未定义全局名称

时间:2016-05-17 13:40:46

标签: python pytest python-unittest

我有一个unittest套件,通过正常运行的ssh(使用paramiko)验证多个远程服务器的配置设置。我想使用pytest输出将它集成到Jenkins中,但是运行py.test的testsuite给出了以下错误:

NameError:未定义全局名称“_ssh”

$ py.test --junitxml results.xml bsr-multinode.py -v -x
======= test session starts ===============
platform linux2 -- Python 2.7.11+, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- /usr/bin/python
cachedir: .cache
rootdir: /home/dany, inifile: pytest.ini
collected 150 items 

bsr-multinode.py::myClass::test_test1 FAILED

------ generated xml file: /home/dany/results.xml ---------------
============ FAILURES ======================
__  myClass.test_test1 __________________________

self = <bsr-multinode.myClass testMethod=test_test1>

    def test_test1(self):
>       self.assertRegexpMatches(_ssh.execute('netstat -nlp | grep -vi unix | grep sshd'),'sshd','sshd not running')
E       NameError: global name '_ssh' is not defined

bsr-multinode.py:121: NameError
!!! Interrupted: stopping after 1 failures !!!!!!!
============= 1 failed in 0.50 seconds ====

$ python bsr-multinode.py 
ms-100-00
.......F..FFF.F.F.F.F.F.....F..F...
Ran 150 tests in 49.724s

FAILED (failures=35)
db-100-01
.......F..FFF.F.F.F.F.F.....F..F...
Ran 150 tests in 56.816s

FAILED (failures=56)

我在没有帮助的情况下尝试了不同的事情。任何线索都会受到欢迎。这是我的代码:

servers=["192.168.1.1","192.168.1.2"]

class sshClient:
    def __init__(self,host):
       self.client = paramiko.SSHClient()
       self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       try:
           self.client.connect(host,username="account", password="password")
       except paramiko.SSHException:
           print "Connection Error"

    def close(self):
        if self.client is not None:
            self.client.close()
            self.client = None

    def execute(self, command):
        stdin, stdout, stderr = self.client.exec_command(command)
        output=''.join(stdout.readlines())
        return output

class myClass(unittest.TestCase):
    def test_test1(self):
    self.assertRegexpMatches(_ssh.execute('netstat -nlp | grep -vi unix | grep sshd'),'sshd','sshd not running')


if __name__ == '__main__':
    for server in servers:
        _ssh = sshClient(server)
        hostname = _ssh.execute('hostname')
        hostname = hostname.replace("\n","")
        print hostname
        runner = unitest.TextTestRunner()
        unittest.main(testRunner=runner,exit=False)

0 个答案:

没有答案