Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #78610 > unrolled thread
| Started by | Milson Munakami <milsonmun@gmail.com> |
|---|---|
| First post | 2014-10-02 08:29 -0700 |
| Last post | 2014-10-03 22:55 +0100 |
| Articles | 4 — 3 participants |
Back to article view | Back to comp.lang.python
How to set the global variable so that it can be accessed and released inside other methods Milson Munakami <milsonmun@gmail.com> - 2014-10-02 08:29 -0700
Re: How to set the global variable so that it can be accessed and released inside other methods Chris Angelico <rosuav@gmail.com> - 2014-10-03 01:34 +1000
Re: How to set the global variable so that it can be accessed and released inside other methods Milson Munakami <milsonmun@gmail.com> - 2014-10-03 14:43 -0700
Re: How to set the global variable so that it can be accessed and released inside other methods Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-10-03 22:55 +0100
| From | Milson Munakami <milsonmun@gmail.com> |
|---|---|
| Date | 2014-10-02 08:29 -0700 |
| Subject | How to set the global variable so that it can be accessed and released inside other methods |
| Message-ID | <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> |
Hi,
I am newbie to Python,
I am trying to use unittest and python. My python script is like this:
#! /usr/bin/env python
__author__ = 'Milson Munakami'
__revision__ = '0.0.2'
import json
import urllib
import httplib
from scapy.all import *
import unittest
import os, sys, socket, struct, select, time
from threading import Thread
import logging
import traceback
from mininet.net import Mininet
from mininet.node import OVSSwitch, OVSKernelSwitch, Controller, RemoteController
from mininet.log import setLogLevel, info
from mininet.cli import CLI
class testFirewallS1( unittest.TestCase ):
#I am trying to set net variable to global
global net
######################
def setUp(self):
self.controllerIp="127.0.0.1"
self.switch = "00:00:00:00:00:00:00:01"
self.destinationIp = "10.0.0.1"
self.startTime_ = time.time()
self.failed = False
self.reportStatus_ = True
self.name_ = "Firewall"
self.log = logging.getLogger("unittest")
self.CreateNet()
self.SetPrecondition()
def CreateNet(self):
"Create an empty network and add nodes to it."
net = Mininet( controller=RemoteController )
info( '*** Adding controller\n' )
net.addController( 'c0' , controller=RemoteController,ip= "127.0.0.1", port=6633)
info( '*** Adding hosts\n' )
h1 = net.addHost( 'h1', ip='10.0.0.1' )
h2 = net.addHost( 'h2', ip='10.0.0.2' )
h3 = net.addHost( 'h3', ip='10.0.0.3' )
info( '*** Adding switch\n' )
s1 = net.addSwitch( 's1' )
info( '*** Creating links\n' )
net.addLink( h1, s1 )
net.addLink( h2, s1 )
net.addLink( h3, s1 )
info( '*** Starting network\n')
net.start()
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__
self.SetFinalcondition()
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 StatusFirewall(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 CountFirewallRules(self):
command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
x = urllib.urlopen(command).read()
return x
def CountFlowRules(self):
command = "http://%s:8080/wm/core/switch/%s/flow/json" % (self.controllerIp, self.switch)
x = urllib.urlopen(command).read()
parsedResult = json.loads(x)
content = parsedResult['00:00:00:00:00:00:00:01']
if content is None:
return "[]"
else:
return str(content)
def SetPrecondition(self):
command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp
urllib.urlopen(command).read()
# cleanup all Firewall rules
command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
x = urllib.urlopen(command).read()
parsedResult = json.loads(x)
for i in range(len(parsedResult)):
params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid']
command = "/wm/firewall/rules/json"
url = "%s:8080" % self.controllerIp
connection = httplib.HTTPConnection(url)
connection.request("DELETE", command, params)
connection.getresponse().read()
# sleep for REST command to get processed to avoid racing
time.sleep(5)
def SetFinalcondition(self):
command = "http://%s:8080/wm/firewall/module/disable/json" % self.controllerIp
urllib.urlopen(command).read()
# cleanup all Firewall rules
command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
x = urllib.urlopen(command).read()
parsedResult = json.loads(x)
for i in range(len(parsedResult)):
params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid']
command = "/wm/firewall/rules/json"
url = "%s:8080" % self.controllerIp
connection = httplib.HTTPConnection(url)
connection.request("DELETE", command, params)
connection.getresponse().read()
# sleep for REST command to get processed to avoid racing
time.sleep(5)
info( '*** Stopping network' )
net.stop()
#Precondition Test
def testPreConditionFirewall(self):
self.assertTrue("enabled" in self.StatusFirewall())
self.assertTrue("[]" in self.CountFirewallRules())
self.assertEqual("[]",self.CountFlowRules(), "should be empty")
#7
def testCreateFlow(self):
info( '*** Testing network connecivity\n')
net.pingAll()
#Using Scapy
#send(IP(dst="10.0.0.3")/ICMP()/"Hello World")
#info( '*** Running CLI\n' )
#CLI( net )
# Post Conditions Validation
self.assertTrue("enabled" in self.StatusFirewall())
self.assertTrue("[]" in self.CountFirewallRules())
self.assertNotEqual("[]",self.CountFlowRules(), "should not be empty rules cause it is added from Firewall with Action = []")
#8
def testCountFlow(self):
command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp
x = urllib.urlopen(command).read()
self.assertEqual("[]",self.CountFlowRules(), "should be empty")
# Post Conditions Validation
self.assertTrue("enabled" in self.StatusFirewall())
self.assertTrue("[]" in self.CountFirewallRules())
self.assertEqual("[]",self.CountFlowRules(), "should be empty")
#10
def testDeleteFlow(self):
# sleep for REST command to get processed to avoid racing
time.sleep(5)
command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp
x = urllib.urlopen(command).read()
self.assertEqual("[]",self.CountFlowRules(), "should be empty")
# Post Conditions Validation
self.assertTrue("enabled" in self.StatusFirewall())
self.assertTrue("[]" in self.CountFirewallRules())
self.assertEqual("[]",self.CountFlowRules(), "should be empty")
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(testFirewallS1))
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()
# Preconditions:
suiteFew.addTest(testFirewallS1("testPreConditionFirewall"))
# 7. Add one Flow Entry
suiteFew.addTest(testFirewallS1("testCreateFlow"))
# 8. Count Flow rules - empty
suiteFew.addTest(testFirewallS1("testCountFlow"))
# 9. Update a Flow Rule - Not Implemented due to Controller's Constraint
# 10. wait till the time-stamp period to validate the flow is deleted with that time.
suiteFew.addTest(testFirewallS1("testDeleteFlow"))
#Testing the Test Cases Begins Here
unittest.TextTestRunner(verbosity=2).run(suiteFew)
#unittest.main()
#unittest.TextTestRunner(verbosity=2).run(suite())
I tired to set a globla net variable inside the class and tring to access it from another methods like from def SetFinalcondition(self): and def testCreateFlow(self): but the error says:\
ERROR: testPreConditionFirewall (__main__.testFirewallS1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mm.py", line 68, in tearDown
self.cleanup(True)
File "mm.py", line 74, in cleanup
self.SetFinalcondition()
File "mm.py", line 144, in SetFinalcondition
net.stop()
NameError: global name 'net' is not defined
======================================================================
ERROR: testCreateFlow (__main__.testFirewallS1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mm.py", line 156, in testCreateFlow
net.pingAll()
NameError: global name 'net' is not defined
======================================================================
ERROR: testCreateFlow (__main__.testFirewallS1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mm.py", line 68, in tearDown
self.cleanup(True)
File "mm.py", line 74, in cleanup
self.SetFinalcondition()
File "mm.py", line 144, in SetFinalcondition
net.stop()
NameError: global name 'net' is not defined
======================================================================
ERROR: testCountFlow (__main__.testFirewallS1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mm.py", line 68, in tearDown
self.cleanup(True)
File "mm.py", line 74, in cleanup
self.SetFinalcondition()
File "mm.py", line 144, in SetFinalcondition
net.stop()
NameError: global name 'net' is not defined
======================================================================
ERROR: testDeleteFlow (__main__.testFirewallS1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mm.py", line 68, in tearDown
self.cleanup(True)
File "mm.py", line 74, in cleanup
self.SetFinalcondition()
File "mm.py", line 144, in SetFinalcondition
net.stop()
NameError: global name 'net' is not defined
How to fix it!
Thanks for any help
- Milson
[toc] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-10-03 01:34 +1000 |
| Message-ID | <mailman.14555.1412264077.18130.python-list@python.org> |
| In reply to | #78610 |
On Fri, Oct 3, 2014 at 1:29 AM, Milson Munakami <milsonmun@gmail.com> wrote: > #I am trying to set net variable to global > global net > > def CreateNet(self): > "Create an empty network and add nodes to it." > net = Mininet( controller=RemoteController ) You're almost there! All you have to do is move that global declaration into CreateNet itself. That's the only place where it's assigned to. I'm not sure why you have a class that sets up a global, though. It would be much more normal to use "self.net" everywhere instead. ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Milson Munakami <milsonmun@gmail.com> |
|---|---|
| Date | 2014-10-03 14:43 -0700 |
| Message-ID | <4a73c7f7-b221-47da-83fc-8547a4f3d110@googlegroups.com> |
| In reply to | #78610 |
Hi Chris,
I want to remove that CreateNet() part from the test class so that it will not create network every time in setup() because all the test cases are run and tested in same network!
But the test class method also need to access the net object
How can I do that?
Please Help.
Thanks,
Milson
On Thursday, October 2, 2014 9:30:21 AM UTC-6, Milson Munakami wrote:
> Hi,
>
>
>
> I am newbie to Python,
>
>
>
> I am trying to use unittest and python. My python script is like this:
>
>
>
> #! /usr/bin/env python
>
> __author__ = 'Milson Munakami'
>
> __revision__ = '0.0.2'
>
>
>
> import json
>
> import urllib
>
> import httplib
>
> from scapy.all import *
>
>
>
> import unittest
>
>
>
> import os, sys, socket, struct, select, time
>
> from threading import Thread
>
>
>
> import logging
>
> import traceback
>
>
>
> from mininet.net import Mininet
>
> from mininet.node import OVSSwitch, OVSKernelSwitch, Controller, RemoteController
>
> from mininet.log import setLogLevel, info
>
> from mininet.cli import CLI
>
>
>
> class testFirewallS1( unittest.TestCase ):
>
>
>
> #I am trying to set net variable to global
>
> global net
>
> ######################
>
>
>
> def setUp(self):
>
> self.controllerIp="127.0.0.1"
>
> self.switch = "00:00:00:00:00:00:00:01"
>
> self.destinationIp = "10.0.0.1"
>
> self.startTime_ = time.time()
>
> self.failed = False
>
> self.reportStatus_ = True
>
> self.name_ = "Firewall"
>
> self.log = logging.getLogger("unittest")
>
> self.CreateNet()
>
> self.SetPrecondition()
>
>
>
> def CreateNet(self):
>
> "Create an empty network and add nodes to it."
>
> net = Mininet( controller=RemoteController )
>
>
>
> info( '*** Adding controller\n' )
>
> net.addController( 'c0' , controller=RemoteController,ip= "127.0.0.1", port=6633)
>
>
>
> info( '*** Adding hosts\n' )
>
> h1 = net.addHost( 'h1', ip='10.0.0.1' )
>
> h2 = net.addHost( 'h2', ip='10.0.0.2' )
>
> h3 = net.addHost( 'h3', ip='10.0.0.3' )
>
>
>
> info( '*** Adding switch\n' )
>
> s1 = net.addSwitch( 's1' )
>
>
>
> info( '*** Creating links\n' )
>
> net.addLink( h1, s1 )
>
> net.addLink( h2, s1 )
>
> net.addLink( h3, s1 )
>
>
>
> info( '*** Starting network\n')
>
> net.start()
>
>
>
> 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__
>
> self.SetFinalcondition()
>
> 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 StatusFirewall(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 CountFirewallRules(self):
>
> command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
>
> x = urllib.urlopen(command).read()
>
> return x
>
>
>
> def CountFlowRules(self):
>
> command = "http://%s:8080/wm/core/switch/%s/flow/json" % (self.controllerIp, self.switch)
>
> x = urllib.urlopen(command).read()
>
> parsedResult = json.loads(x)
>
> content = parsedResult['00:00:00:00:00:00:00:01']
>
> if content is None:
>
> return "[]"
>
> else:
>
> return str(content)
>
>
>
> def SetPrecondition(self):
>
> command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp
>
> urllib.urlopen(command).read()
>
>
>
> # cleanup all Firewall rules
>
> command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
>
> x = urllib.urlopen(command).read()
>
> parsedResult = json.loads(x)
>
> for i in range(len(parsedResult)):
>
> params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid']
>
> command = "/wm/firewall/rules/json"
>
> url = "%s:8080" % self.controllerIp
>
> connection = httplib.HTTPConnection(url)
>
> connection.request("DELETE", command, params)
>
> connection.getresponse().read()
>
>
>
> # sleep for REST command to get processed to avoid racing
>
> time.sleep(5)
>
>
>
> def SetFinalcondition(self):
>
> command = "http://%s:8080/wm/firewall/module/disable/json" % self.controllerIp
>
> urllib.urlopen(command).read()
>
>
>
> # cleanup all Firewall rules
>
> command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp
>
> x = urllib.urlopen(command).read()
>
> parsedResult = json.loads(x)
>
> for i in range(len(parsedResult)):
>
> params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid']
>
> command = "/wm/firewall/rules/json"
>
> url = "%s:8080" % self.controllerIp
>
> connection = httplib.HTTPConnection(url)
>
> connection.request("DELETE", command, params)
>
> connection.getresponse().read()
>
>
>
> # sleep for REST command to get processed to avoid racing
>
> time.sleep(5)
>
>
>
> info( '*** Stopping network' )
>
> net.stop()
>
>
>
> #Precondition Test
>
> def testPreConditionFirewall(self):
>
> self.assertTrue("enabled" in self.StatusFirewall())
>
> self.assertTrue("[]" in self.CountFirewallRules())
>
> self.assertEqual("[]",self.CountFlowRules(), "should be empty")
>
>
>
> #7
>
> def testCreateFlow(self):
>
>
>
> info( '*** Testing network connecivity\n')
>
> net.pingAll()
>
>
>
> #Using Scapy
>
> #send(IP(dst="10.0.0.3")/ICMP()/"Hello World")
>
>
>
> #info( '*** Running CLI\n' )
>
> #CLI( net )
>
>
>
> # Post Conditions Validation
>
> self.assertTrue("enabled" in self.StatusFirewall())
>
> self.assertTrue("[]" in self.CountFirewallRules())
>
> self.assertNotEqual("[]",self.CountFlowRules(), "should not be empty rules cause it is added from Firewall with Action = []")
>
> #8
>
> def testCountFlow(self):
>
> command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp
>
> x = urllib.urlopen(command).read()
>
> self.assertEqual("[]",self.CountFlowRules(), "should be empty")
>
>
>
> # Post Conditions Validation
>
> self.assertTrue("enabled" in self.StatusFirewall())
>
> self.assertTrue("[]" in self.CountFirewallRules())
>
> self.assertEqual("[]",self.CountFlowRules(), "should be empty")
>
> #10
>
> def testDeleteFlow(self):
>
> # sleep for REST command to get processed to avoid racing
>
> time.sleep(5)
>
>
>
> command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp
>
> x = urllib.urlopen(command).read()
>
> self.assertEqual("[]",self.CountFlowRules(), "should be empty")
>
>
>
> # Post Conditions Validation
>
> self.assertTrue("enabled" in self.StatusFirewall())
>
> self.assertTrue("[]" in self.CountFirewallRules())
>
> self.assertEqual("[]",self.CountFlowRules(), "should be empty")
>
>
>
> def suite():
>
>
>
> suite = unittest.TestSuite()
>
>
>
> suite.addTest(unittest.makeSuite(testFirewallS1))
>
>
>
> 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()
>
>
>
> # Preconditions:
>
> suiteFew.addTest(testFirewallS1("testPreConditionFirewall"))
>
>
>
>
>
> # 7. Add one Flow Entry
>
> suiteFew.addTest(testFirewallS1("testCreateFlow"))
>
>
>
> # 8. Count Flow rules - empty
>
> suiteFew.addTest(testFirewallS1("testCountFlow"))
>
>
>
> # 9. Update a Flow Rule - Not Implemented due to Controller's Constraint
>
>
>
> # 10. wait till the time-stamp period to validate the flow is deleted with that time.
>
> suiteFew.addTest(testFirewallS1("testDeleteFlow"))
>
>
>
> #Testing the Test Cases Begins Here
>
> unittest.TextTestRunner(verbosity=2).run(suiteFew)
>
>
>
> #unittest.main()
>
> #unittest.TextTestRunner(verbosity=2).run(suite())
>
>
>
>
>
> I tired to set a globla net variable inside the class and tring to access it from another methods like from def SetFinalcondition(self): and def testCreateFlow(self): but the error says:\
>
>
>
>
>
> ERROR: testPreConditionFirewall (__main__.testFirewallS1)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "mm.py", line 68, in tearDown
>
> self.cleanup(True)
>
> File "mm.py", line 74, in cleanup
>
> self.SetFinalcondition()
>
> File "mm.py", line 144, in SetFinalcondition
>
> net.stop()
>
> NameError: global name 'net' is not defined
>
>
>
> ======================================================================
>
> ERROR: testCreateFlow (__main__.testFirewallS1)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "mm.py", line 156, in testCreateFlow
>
> net.pingAll()
>
> NameError: global name 'net' is not defined
>
>
>
> ======================================================================
>
> ERROR: testCreateFlow (__main__.testFirewallS1)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "mm.py", line 68, in tearDown
>
> self.cleanup(True)
>
> File "mm.py", line 74, in cleanup
>
> self.SetFinalcondition()
>
> File "mm.py", line 144, in SetFinalcondition
>
> net.stop()
>
> NameError: global name 'net' is not defined
>
>
>
> ======================================================================
>
> ERROR: testCountFlow (__main__.testFirewallS1)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "mm.py", line 68, in tearDown
>
> self.cleanup(True)
>
> File "mm.py", line 74, in cleanup
>
> self.SetFinalcondition()
>
> File "mm.py", line 144, in SetFinalcondition
>
> net.stop()
>
> NameError: global name 'net' is not defined
>
>
>
> ======================================================================
>
> ERROR: testDeleteFlow (__main__.testFirewallS1)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "mm.py", line 68, in tearDown
>
> self.cleanup(True)
>
> File "mm.py", line 74, in cleanup
>
> self.SetFinalcondition()
>
> File "mm.py", line 144, in SetFinalcondition
>
> net.stop()
>
> NameError: global name 'net' is not defined
>
>
>
>
>
> How to fix it!
>
> Thanks for any help
>
> - Milson
[toc] | [prev] | [next] | [standalone]
| From | Mark Lawrence <breamoreboy@yahoo.co.uk> |
|---|---|
| Date | 2014-10-03 22:55 +0100 |
| Message-ID | <mailman.14587.1412373388.18130.python-list@python.org> |
| In reply to | #78668 |
On 03/10/2014 22:43, Milson Munakami wrote: > Hi Chris, > I want to remove that CreateNet() part from the test class so that it will not create network every time in setup() because all the test cases are run and tested in same network! > > But the test class method also need to access the net object > > How can I do that? > > Please Help. > Thanks, > Milson You are far more likely to get answers if you don't top post and if you don't use the obnoxious google groups. I've snipped roughly 600 lines from your reply. To avoid sending the rubbish that many of us here don't want to see would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web