0

I am learning to use unittest with python and walkthrough with this example http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html

so my test script is like this:

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())

while running it in console using python .py

It gives me error

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

I guess it is due to time module but as you can see I already had import time.

what can be the reason if I comment those line containing the time it works.

But i need to keep track of duration

What can be the reason and solution to this problem.

1
  • 1
    check your log in teardown Commented Sep 24, 2014 at 19:38

1 Answer 1

1

The syntax error is in your tearDown method.

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
        )

on the self.log.info call you forgot to close the parenthesis, that is the last line of your tearDown method.

I would also suggest you keep the style of your code conforming to PEP8

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, is there any way to test multiple dependent function in python unittest? @Rafael
@Milson, yes, if I understand your question correctly, you're looking for the mock library.
Thanks @Rafael if you got link of that library module? please share
@Milson I'm glad to help. Here is the link for the mock library docs: docs.python.org/3/library/unittest.mock.html, here is the link for the PyPI: pypi.python.org/pypi/mock, and here is a tutorial for mocking with python: toptal.com/python/an-introduction-to-mocking-in-python. If my original answer fixes your original question, I would appreciate if you could accept that as the correct answer. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.