Trying to run a unittest module - python

I have created a unittest module called test_blbmktdata.py to test some code. I am trying to run it from the console using the following command:
run test_blbmktdata.py
However I get the error message:
ERROR:root:File `'test_blbmktdata.py'` not found.
Please see below for the module code.
import unittest
class TestBlbMktData(unittest.TestCase):
staticName='StaticInstrumentData.csv'
def print(self,data):
print()
print(len(data))
print(data.head())
print(data.dtypes)
def read(self,name,func):
return func(os.path.join(self.current_dir,name))
def setUp(self):
self.current_dir=os.path.dirname(os.path.abspath(__file__))
def test_corp_act(self):
self.print(self.read(self.corpName,readCorpAction))
if __name__ == '__main__' :
unittest.main()
How can I run the code from the console?

Try python -m unittest test_blbmktdata in terminal
https://docs.python.org/2/library/unittest.html#command-line-interface

For running a python code say code.py you can simply use command
python code.py
on the terminal after you navigate to the same directory where code is located.

Related

My Python unittest script fails in Eclipse PyDev but works in Spyder

I am running Springsource Tool Suite 3.9.7.RELEASE with the PyDev 7.5.0 plugin. Eclipse Pydev is giving me an error with unittest cases which I do not get in Spyder.
I have constructed the following test script:
from unittest import TestCase
from unittest import TextTestRunner
class Test1(TestCase):
def runTest(self):
print("Running Test1 - This should not appear")
self.assertTrue(True, "Test1")
class Test2(TestCase):
def runTest(self):
print("Running Test2 - This should not appear")
self.assertTrue(True, "Test2")
if __name__ == '__main__':
runner = TextTestRunner()
print("Finished Running - This should appear")
When I run it from STS using Run As/Python unit-test it gives the following output:-
Finding files... done.
Importing test modules ... done.
Running Test1 - This should not appear
Running Test2 - This should not appear
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
When I run exactly the same scipt in Spyder is gives me:-
Finished Running - This should appear
The Spyder output is what I would expect and want. It looks like PyDev is grabbing every unittest TestCase object it can find and running them all when TextTestRunner is instantiated.
I have created this trivial example, but it arose from a real world project I am working on which uses both Python and Java. I can only develop it using Eclipse PyDev. I need to be able to specify which test cases I run using TextTestRunnner's run() method in the normal way. Can anyone help me here?

'module' object has no attribute 'py' when running from cmd

I'm currently learning unittesting, and I have stumbled upon a strange error:
If I run my script from inside PyCharm, everything works perfectly. If I run it from my cmd.exe (as administrator), I get the following error:
This is my code:
import unittest
class TutorialUnittest(unittest.TestCase):
def test_add(self):
self.assertEqual(23,23)
self.assertNotEqual(11,12)
# function for raising errors.
def test_raise(self):
with self.assertRaises(Exception):
raise Exception`
Just remove the .py extension.
You are running your tests using the -m command-line flag. The Python documentation will tell you more about it, just check out this link.
In a word, the -m option let you run a module, in your case the unittest module. This module expect to receive a module path or a class path following the Python format for module path (using dots). For example, if you want to run the FirstTest class in the mytests module in a mypackage folder you would use the following command line:
python -m unittest mypackage.mytests.FirstTest
Assuming that you are running the previous command line from the parent folder of mypackage. This allows you to select precisely the tests you want to run (even inside a module).
When you add the .py extension, unittest is looking for a py object (like a module or a class) inside the last element of the module path you gave but, yet this object does not exist. This is exactly what your terminal error tells:
AttributeError: ’module’ object has no attribute ’py’
you can add at the bottom of your script:
if __name__ == "__main__":
unittest.main()
Then you can run python test_my_function.py normally

How to run module from command line?

Suppose there is a module somewhere, which I can import with
from sound.effects import echo
How can I run echo directly from command line?
Command
python sound/effects/echo.py
does not work since the relative path is generally incorrect
If the module has top-level code executing on import, you can use the -m switch to run it from the command line (using Python attribute notation):
python -m sound.effect.echo
The module is then executed as a script, so a if __name__ == '__main__': guard will pass. See for example the timeit module, which executes the timeit.main() function when run from the command line like this.

NoseTest: running with coverage from Python script

I want to run NoseTest from a Python script. But I want not only run it, but also measure test coverage.
Just now I have the following code:
import os
import sys
import nose
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
import tests
if __name__ == "__main__":
config = nose.config.Config(verbosity=3, stopOnError=False, argv=["--with-coverage"])
result = nose.run(module=tests, config=config)
What should I add to get my coverage report?
Hell yeah! After some small debugging of Nose Test I've managed to do it!
if __name__ == "__main__":
file_path = os.path.abspath(__file__)
tests_path = os.path.join(os.path.abspath(os.path.dirname(file_path)), "tests")
result = nose.run(argv=[os.path.abspath(__file__),
"--with-cov", "--verbosity=3", "--cover-package=phased", tests_path])
EDIT: To run plugins with nose.run(), you need to use the 'plugins' keyword:
http://nose.readthedocs.org/en/latest/usage.html#using-plugins
Your code is all set -- you need to enable coverage via the runner. Simply run nose like this:
nosetests --with-coverage
There are more options here:
http://nose.readthedocs.org/en/latest/plugins/cover.html
FYI, you might need to run the following to get the coverage package:
pip install coverage

run program in Python shell

I have a demo file: test.py.
In the Windows Console I can run the file with: C:\>test.py
How can I execute the file in the Python Shell instead?
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
It depends on what is in test.py. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
For newer version of python:
exec(open(filename).read())
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
From the same folder, you can do:
import test

Categories