How to run multiple test case from python nose test - python

I am a newbie in process of learning python and currently working on a automation project.
And i have N numbers of testcase which needs to be run on reading material people suggest me to use nosetest.
What is the way to run multiple testcase using nosetest?
And is the correct approach doing it:
import threading
import time
import logging
import GLOBAL
import os
from EPP import EPP
import Queue
import unittest
global EPP_Queue
from test1 import test1
from test2 import test2
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class all_test(threading.Thread,unittest.TestCase):
def cleanup():
if os.path.exists("/dev/epp_dev"):
os.unlink("/dev/epp_dev")
print "starts here"
server_ip ='192.168.10.15'
EppQueue = Queue.Queue(1)
EPP = threading.Thread(name='EPP', target=EPP,
args=('192.168.10.125',54321,'/dev/ttyS17',
EppQueue,))
EPP.setDaemon(True)
EPP.start()
time.sleep(5)
suite1 = unittest.TestLoader().loadTestsFromTestCase(test1)
suite2 = unittest.TestLoader().loadTestsFromTestCase(test2)
return unittest.TestSuite([suite1, suite2])
print "final"
raw_input("keyy")
def main():
unittest.main()
if __name__ == '__main__':
main()

Read
http://ivory.idyll.org/articles/nose-intro.html.
Download the package
http://darcs.idyll.org/~t/projects/nose-demo.tar.gz
Follow the instructions provided in the first link.

nosetest, when run from command line like 'nosetest' or 'nosetest-2.6' will recursively hunt for tests in the directory you execute it in.
So if you have a directory holding N tests, just execute it in that directory. They will all be executed.

Related

How do I make a module think its name is __main__? [duplicate]

This question already has answers here:
How to make __name__ == '__main__' when running module
(4 answers)
Closed 6 years ago.
I have a python script (actually, lots of scripts) with code that is executed only when this module is run as the main script:
if __name__ == '__main__':
print("I am the main script")
But now I want a testing script to load them as modules, so that it can then poke in their internal state. Rewriting (to turn the code block into a function) is not an option. How do I import a module in such a way that it thinks its name is __main__? I'm sure I've seen this done before, with the help of some import library or other, but it's not coming up in my searches.
You'd have to bypass the import machinery, and use exec instead:
import imp
main = imp.new_module('__main__')
with open(module_filename, 'r') as source:
exec(source.read(), vars(main))
Demo:
>>> source = '''\
... if __name__ == '__main__':
... print("I am the main script")
... '''
>>> import imp
>>> main = imp.new_module('__main__')
>>> exec(source, vars(main))
I am the main script
Rather than go this route, consider creating a function you call from the __main__ guard instead, so you can just import that function for testing:
def main():
print("I am the main script")
if __name__ == '__main__':
main()

Mocking __main__

I would like to ensure with tests that:
- the application cannot be imported
- the application can be started as a real application (i.e: python src.py)
I'm interested about that, why the following is not working:
src.py
class A:
def x(self):
print('this is x')
if __name__ == '__main__':
A().x()
test.py (snippet)
class Test(unittest.TestCase):
#mock.patch('src.A.x')
def test_main(self, mock_x):
import src
mock_x.assert_any_call()
This test fails... why?
Because the name of the module when imported is src, not __main__.
The easiest solution would be to move that code into a function:
def main():
A().x()
if __name__ == '__main__':
main()
and in your test, you would invoke src.main()
#mock.patch('src.A.x')
def test_main(self, mock_x):
import src
src.main()
mock_x.assert_any_call()
To test that a module is not importable you do not need to use mocks.
See assertRaises.
Just check if an error is thrown on import od module.
with self.assertRaises(...):
...

Importing values in config.py

I wanted to mix a config.py approach and ConfigParser to set some default values in config.py which could be overridden by the user in its root folder:
import ConfigParser
import os
CACHE_FOLDER = 'cache'
CSV_FOLDER = 'csv'
def main():
cp = ConfigParser.ConfigParser()
cp.readfp(open('defaults.cfg'))
cp.read(os.path.expanduser('~/.python-tools.cfg'))
CACHE_FOLDER = cp.get('folders', 'cache_folder')
CSV_FOLDER = cp.get('folders', 'csv_folder')
if __name__ == '__main__':
main()
When running this module I can see the value of CACHE_FOLDER being changed. However when in another module I do the following:
import config
def main()
print config.CACHE_FOLDER
This will print the original value of the variable ('cache').
Am I doing something wrong ?
The main function in the code you show only gets run when that module is run as a script (due to the if __name__ == '__main__' block). If you want that turn run any time the module is loaded, you should get rid of that restriction. If there's extra code that actually does something useful in the main function, in addition to setting up the configuration, you might want to split that part out from the setup code:
def setup():
# the configuration stuff from main in the question
def main():
# other stuff to be done when run as a script
setup() # called unconditionally, so it will run if you import this module
if __name__ == "__main__":
main() # this is called only when the module is run as a script

re-import module-under-test to lose context

Many Python modules preserve an internal state without defining classes, e.g. logging maintains several loggers accessible via getLogger().
How do you test such a module? Using the standard unittest tools, I would like the various tests inside a TestCase class to re-import my module-under-test so that each time it loses its context. Can this be done?
import unittest
import sys
class Test(unittest.TestCase):
def tearDown(self):
try:
del sys.modules['logging']
except KeyError:
pass
def test_logging(self):
import logging
logging.foo=1
def test_logging2(self):
import logging
print(logging.foo)
if __name__ == '__main__':
unittest.sys.argv.insert(1,'--verbose')
unittest.main(argv = unittest.sys.argv)
% test.py Test.test_logging passes:
test_logging (__main__.Test) ... ok
but
% test.py Test.test_logging2 does not:
test_logging2 (__main__.Test) ... ERROR
since the internal state of logging has been reset.
This will reimport the module as new for you:
import sys
del sys.modules['my_module']
import my_module

Only print when run as script?

Is there a better way to only print when run as a script, when __name__ == '__main__' ?
I have some scripts that I also import and use parts of.
Something like the below will work but is ugly, and would have to be defined in each script separately:
def printif(s):
if globals()['__name__'] == '__main__':
print (s)
return
I looked briefly at some of python's logging libraries but would prefer a two lighter solution...
edit:
I ended up doing something like this:
# mylog.py
import sys
import logging
log = logging.getLogger()
#default logging level
log.setLevel(logging.WARNING)
log.addHandler(logging.StreamHandler(sys.stdout))
And from the script:
import log from mylog
...
log.info(...)
log.warning(...)
...
if __name__ == '__main__':
#override when script is run..
log.setLevel(logger.INFO)
This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.
run_as_script = False
def printif(s):
if run_as_script:
print (s)
return
if __name__ == '__main__':
run_as_script = True
In light of user318904's comment on my other answer, I'll provide an alternative (although this may not work in all cases, it might just be "good enough").
For a separate module:
import sys
def printif(s):
if sys.argv[0] != '':
print (s)
Using a logging library is really not that heavyweight:
import logging
log = logging.getLogger('myscript')
def dostuff(...):
....
log.info('message!')
...
if __name__ == '__main__':
import sys
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler(sys.stdout))
...
One wart is the "WARNING: no handlers found for myscript" message that logging prints by default if you import this module (rather than run it as a script), and call your function without setting up logging. It'll be gone in Python 3.2. For Python 2.7, you can shut it off by adding
log.addHandler(logging.NullHandler())
at the top, and for older versions you'd have to define a NullHandler class like this:
class NullHandler(logging.Handler):
def emit(self, record):
pass
Looking back at all this, I say: go with Gerrat's suggestion. I'll leave mine here, for completeness.

Categories

Resources