使用时间模块在Python脚本中进行单元测试

时间:2014-09-24 19:35:58

标签: python unit-testing

我正在学习使用unittest和python以及本例中的演练 http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html

所以我的测试脚本是这样的:

import json
import urllib
import time
#from util import *
import httplib
#import sys
#from scapy.all import *
import unittest

import os, sys, socket, struct, select, time 
from threading import Thread

import logging
import traceback



class testFirewall( unittest.TestCase ):
    def setUp(self):
        """

            set up data used in the tests.

            setUp is called before each test function execution.

            """

            self.controllerIp="127.0.0.1"
        self.switches = ["00:00:00:00:00:00:00:01"]
        self.startTime_ = time.time()
        self.failed = False
        self.reportStatus_ = True
        self.name_ = "Firewall"
        self.log = logging.getLogger("unittest")

    def tearDown(self):
        if self.failed:
            return
        duration = time.time() - self.startTime_
        self.cleanup(True)
        if self.reportStatus_:
            self.log.info("=== Test %s completed normally (%d sec)", self.name_, duration

    def cleanup(self, success):
        sys.excepthook = sys.__excepthook__
        try:
            return
        except NameError:
            self.log.error("Exception hit during cleanup, bypassing:\n%s\n\n" % traceback.format_exc())
            pass
        else:

                fail("Expected a NameError")


    def testStatusFirewall(self):
        command = "http://%s:8080/wm/firewall/module/status/json" % self.controllerIp
        x = urllib.urlopen(command).read()
        parsedResult = json.loads(x)
        return parsedResult['result']


    def suite():

            suite = unittest.TestSuite()

            suite.addTest(unittest.makeSuite(testFirewall))

            return suite    

if __name__ == '__main__':
    logging.basicConfig(filename='/tmp/testfirewall.log', level=logging.DEBUG, 
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')
    logger=logging.getLogger(__name__)  

    suiteFew = unittest.TestSuite()

        suiteFew.addTest(testFirewall("testStatusFirewall"))

        unittest.TextTestRunner(verbosity=2).run(suiteFew)

    #unittest.main()

        #unittest.TextTestRunner(verbosity=2).run(suite())

在使用python .py

在控制台中运行时

它给了我错误

File "TestTest.py", line 44
    def cleanup(self, success):
      ^
SyntaxError: invalid syntax

我想这是由于时间模块,但你可以看到我已经有了导入时间。

如果我评论包含其工作时间的那一行,可能是什么原因。

但我需要跟踪持续时间

这个问题的原因和解决方案是什么。

1 个答案:

答案 0 :(得分:1)

语法错误在您的tearDown方法中。

def tearDown(self):
    if self.failed:
        return
    duration = time.time() - self.startTime_
    self.cleanup(True)
    if self.reportStatus_:
        self.log.info(
            "=== Test %s completed normally (%d sec)",
            self.name_,
            duration
        )
self.log.info电话上

您忘记关闭括号,这是tearDown方法的最后一行。

我还建议你保持代码的风格符合PEP8