No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
In new Python 2.7 release, unittest.main() has a new argument.
If 'exit' is set to False, sys.exit() is not called during the execution of unittest.main().
Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing
unittest.main()
to
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
More information is available here in the Python Library Reference.
Don't try to run unittest.main() from IDLE. It's trying to access sys.argv, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call unittest.main() in its own Python process.
Pop open the source code to unittest.py. unittest.main() is hard-coded to call sys.exit() after running all tests. Use TextTestRunner to run test suites from the prompt.
It's nice to be able to demonstrate that your tests work when first trying out the unittest module, and to know that you won't exit your Python shell. However, these solutions are version dependent.
Python 2.6
I'm using Python 2.6 at work, importing unittest2 as unittest (which is the unittest module supposedly found in Python 2.7).
The unittest.main(exit=False) doesn't work in Python 2.6's unittest2, while JoeSkora's solution does, and to reiterate it:
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
To break this down into its components and default arguments, with correct semantic names for the various composed objects:
import sys # sys.stderr is used in below default args
test_loader = unittest.TestLoader()
loaded_test_suite = test_loader.loadTestsFromTestCase(Test)
# Default args:
text_test_runner = unittest.TextTestRunner(stream=sys.stderr,
descriptions=True,
verbosity=1)
text_test_runner.run(loaded_test_suite)
Python 2.7 and 3
In Python 2.7 and higher, the following should work.
unittest.main(exit=False)
try:
sys.exit()
except SystemExit:
print('Simple as that, but you should really use a TestRunner instead')
Related
I am using Pylint and Nose along with sniffer to lint and test my python application on every save. This is sniffer in case you are unaware https://pypi.python.org/pypi/sniffer
Here is the runnable responsible for running nosetests and pylint from scent.py file for sniffer
from sniffer.api import * # import the really small API
from pylint import lint
from subprocess import call
import os
import nose
#runnable
def zimmer_tests(*args):
command = "nosetests some_module/test --nologcapture --with-coverage --cover-config-file=zimmer_coverage_config"
lint.Run(['some_module/app'], exit=False)
return call(command, shell=True) == 0
Here, first lint.Run() runs pylint on my app. Then nosetest is executed on the app using call()
The Problem is that after I save the file nosetests run on updated version of the file however Pylint uses the same old version. I have to restart sniffer every time for pylint to get new version of files.
I assume this is not a problem of sniffer's configuration since nosetests is able to get the new version of file every time. Still I am not sure.
My pylintrc file is almost the same we get from generate command pylint --generate-rcfile > .pylintrc with some minor application specific tweaks.
As pointed by #KlausD. in comments, the lint.Run() was using files from cache as it was being called from a still running process. Calling pylint from command line worked as expected.
Here is the modified code
#runnable
def zimmer_tests(*args):
command_nose = "nosetests some_module/test --nologcapture --with-coverage --cover-config-file=zimmer_coverage_config"
command_lint = "pylint some_module"
call(command_lint, shell=True)
return call(command_nose, shell=True) == 0
Hi I am running through the /models-master/tutorials/image/cifar10 examples provided by google at https://github.com/tensorflow/models.
I am running the tensorflow-1.0.1 and python 3.5 in a virtual env.
From the command line, and in the virtualenv, running:
python3 cifar10_train.py
Works fine.
But when I try:
pudb3 cifar10_train.py
I get this error:
Traceback (most recent call last):
File "~/interpreters/p35/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 44, in run
_sys.exit(main(_sys.argv[:1] +
flags_passthrough))
TypeError: main() takes 0 positional arguments
but 1 was given
Checking the args gives:
print (_sys.argv[:1])
['cifar10_train.py']
print (flags_passthrough)
[ ]
I know pudb is in the same virtualenv that runs the code from the command line, as pudb goes through the tensorflow import fine, and the virtualenv is the only location in which the tensorflow package resides.
I am assuming this is some issue with passing between some layer pudb introduces... does anyone have a quick suggestion for getting through this... I just want to step through the code :)
Thanks,
nt
I've encountered this same problem when using pudb and TensorFlow. It has to do with the tf.flags. I just use python's Argparse class and not tf.flags.
As an alternative, I believe you can leave the tf.flags as is and just add from pudb import set_trace; set_trace() in your code after the tensorflow import. Call your script as python script.py wihtout -m pudb and it shouldn't freak out.
vega's suggestions worked... thanks. I'd rate up your comment but I've got a rep of <15... what else is new :)
So as per vega...
Included "from pudb import set_trace" after the "import tensorflow as tf" statement. Then added set_trace() as follows...
def main(argv=None): # pylint: disable=unused-argument
cifar10.maybe_download_and_extract()
if tf.gfile.Exists(FLAGS.train_dir):
tf.gfile.DeleteRecursively(FLAGS.train_dir)
tf.gfile.MakeDirs(FLAGS.train_dir)
train()
if __name__ == '__main__':
set_trace()
tf.app.run()
Called the script from the command line:
python3 cifar10_train.py
And it worked as desired.
PuDB looks like its going to be a great tool.
It seems that tensorflow is calling the wrong main function.I had a similar problem when using cProfile and calling script with
python -m cProfile train.py
Seems like the problem was that tf.app.run called main inside cProfile which wasn't ready for argument passing. In my case the solution was to specify main in tf.app.run():
tf.app.run(main=main)
Also fake argument in main is neeeded def main(_):.
I'm writing a separate nose2 tests.py for my program and because I want it to run on both Windows and Linux fairly seamlessly I've decided to forgo using the normal commandline nose2 and instead import it in the file and run it from there.
if __name__ == '__main__':
import nose2
nose2.main()
This works fine, no problems. But I'd like the verbose output and I can't see how to get it to do this. I've tried:
nose2.main("-v")
nose2.main(kwargs="-v")
nose2.main(args="-v")
Anyone know how to get the imported version of nose2 to run in verbose mode?
Since the PluggableTestProgram class accepts the same parameters of unittest.TestProgram, you can pass verbosity to the main function as such:
nose2.main(verbosity=2) # default is 1
See: Unittest.main documentation about verbosity
On my Raspberry Pi model B, py.test and pytest are different
I am new to python and new to the Pi ...
So any clues welcomed
If I look at the command executed I have
For py.test:
#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pytest==2.7.2','console_scripts','py.test'
__requires__ = 'pytest==2.7.2'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('pytest==2.7.2', 'console_scripts', 'py.test')()
)
for pytest (run as python -m pytest ) :
#!/usr/bin/python -u
import warnings
warnings.simplefilter('default', DeprecationWarning)
from logilab.common.pytest import run
run()
Can someone explain why those 2 syntaxes ?
Could I use one or the other (and get the same results) ?
Many thanks
Both tools have nothing to do with each other. For some unfortunate reason logilab started shipping a binary called pytest in their logilab-common package, even thoug at that time the py.test testing tool already existed and it's package name already was pytest. And hence the confusion now.
But to clarify: py.test the testing tool from pytest.org installs a binary called py.test which is contained in the pytest python package and uses the pytest dstribution name on pypi.python.org.
I'm trying to write a Ruby script to execute all Python tests in a directory.
Here is the main part of the script:
system("python #{solution}/tests.py")
Is there a way to somehow understand if the tests have passed and to show output only for the ones that failed (or whatever else)? I just want to be able to tell for each test if it passed or not. (If not possible with Ruby, I'm open for solutions with Python, too)
The tests all look like this one:
import unittest
from solution import my_function
class MyFunctionTest(unittest.TestCase):
def test_my_function(self):
self.assertEqual(42, my_function(42))
if __name__ == '__main__':
unittest.main()
Thanks very much in advance! :)
You can print the output for failing tests with nosetests, which runs them all and condenses the passing tests:
$ nosetests
.............
----------------------------------------------------------------------
Ran 13 tests in 0.015s
OK
Adding a failing test:
$ nosetests
F.............
======================================================================
FAIL: test_failed (x32.tests.failing_test.FailingTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/leigh/Projects/x32/x32/tests/failing_test.py", line 5, in test_failed
self.assertEqual(1, 2)
AssertionError: 1 != 2
----------------------------------------------------------------------
Ran 14 tests in 0.013s
FAILED (failures=1)
There's a guide for nose here, as well: https://nose.readthedocs.org/en/latest/
Alternatively you can go to the parent directory and run something like python -m pytest . to execute the tests, however this will tell you which ones pass as well.