I have problem in importing pytest while writing a python code. "import pytest is grayed out.
Python is 3.8.3, Pycharm community edition.
pytest version 5.4.2, is successfully installed and can be seen in the project interpreter in pycharm. As well as I can see the installed path of pytest in python directory.
When running py.test command from console. It starts the test run shows "collected 0 items" and lastly ends with "NO TESTS RAN IN 0.05s"
If anyone running similar problems with some other packages kindly let me know.
TIA...
You simply run pytest from the commandline. There is no need to import pytest into a script. Take this Python script as an example:
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 4
To run pytest on it, from the terminal (after changing to the right directory):
$ pytest
And you will then see the test outcome in the commandline as pytest automatically picks up the python scripts names test_*.py, where * is any name, e.g. test_increment.py. To have a test from your Python script run, name it with test_ as well to begin with.
Running pytest in the terminal is an option. In addition, Pycharm has integrated test suite for automatic discovery and collection of test tasks. You can use hotkey ctrl+shift+10 to run the test tasks directly in current file .
Related
I have installed pytest using pip. Sample code below
import pytest
def example():
assert 9 == 9
My settings.json file looks like this
{
"python.testing.pytestArgs": [
"."
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true
}
I keep getting no tests ran in terminal when using the pytest filename.py command.
Python version : 3.9.1
pytest version : 6.2.2.
Anyone have any ideas?
Update: Jason's answer below is what worked. The problem was the naming of the file and methods. File name needed to end in '_test.py' for vscode to run tests and functions needed to start with 'test_' for both terminal and vscode to run.
Try renaming the file to "test_filename.py" and the test function to "test_example" so that they are detected by pytest.
https://docs.pytest.org/en/reorganize-docs/new-docs/user/naming_conventions.html
Also, a useful pytest option for debugging the ability to run tests is "--collect-only". It will attempt to only find tests without running them.
pytest --collect-only
VSCode has the ability to run tests itself, without you executing them in the terminal.
https://code.visualstudio.com/docs/python/testing
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
This is the structure of my project, and I would like to run the test that I have made from the command line.
I am using the following command:
python test_hotel.py
However I am getting the following error
ImportError: No module named 'hotel'
What can I do to solve this problem, and is there a way to execute the whole tests in a project from the command line.
Thanks in advance.
For running unittest from commandline, you should use this command:
python -m unittest tests.test_hotel
You need to make sure that you have followed the rules in writing unittests (https://docs.python.org/2/library/unittest.html)
As #shahram kalantari said to run a tests the command line is:
python -m unittest tests.test_hotel
If one wants to run the whole tests the command line is:
python -m unittest discover tests
If you want more information about what tests were run the -v flag should be included:
python -m unittest discover tests -v
I am having some trouble trying to debug some unit tests through the pudb debugger.
The tests run fine with python, but I had no luck runnign them with pudb.
I isolated the problem, getting to the following sample code:
class Math:
def pow(self, x, y):
return x ** y
import unittest
class MathTest(unittest.TestCase):
def testPow23(self):
self.assertEquals(8, Math().pow(2, 3))
def testPow24(self):
self.assertEquals(16, Math().pow(2, 4))
if __name__ == '__main__':
unittest.main()
The tests run fine:
$ python amodule.py
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
But if running through pudb, it gives me the output:
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
I've tried running using pudb amodule.py and also with python -m pudb.run amodule.py, but it makes no difference -- no tests are run in one or another way.
Should I be doing something different to debug unit tests using pudb?
Try placing a breakpoint on a useful line in your code:
from pudb import set_trace; set_trace()
The ways you tried to launch it might interfere with test discovery and/or not run your script with a __name__ of '__main__'.
Since this is a popular question, I feel I should also mention that most test running tools will require you to pass in a switch to prevent it from capturing the standard output and input (usually it's -s).
So, remember to run pytest -s when using Pytest, or nosetests -s for Nose, python manage.py test -s for Django tests, or check the documentation for your test running tool.
You can set a breakpoint even easier by:
import pudb; pu.db
I would like to use the built in Pytest runner of PyCharm together with the debugger without pre-configuring breakpoints.
The problem is that exceptions in my test are caught by Pytest so PyCharm's post mortem debugger cannot handle the exception.
I know using a breakpoint works but I would prefer not to run my test twice.
Found a way to do this in Unittest, I would like to know if something like this exists in Pytest.
Is there a way to catch unittest exceptions with PyCharm?
Are you using pytest-pycharm plugin? Looks like it works for me. Create virtualenv, pip install pytest pytest-pycharm, use this virtualenv at PyCharm Edit configuration -> Python Interpreter and then run with Debug ... Example:
import pytest
def test_me():
assert None
if __name__ == '__main__':
pytest.main(args=[__file__])
PyCharm debugger stops at assert None point, with (<class '_pytest.assertion.reinterpret.AssertionError'>, AssertionError(u'assert None',), None)
EDIT
Set Preferences > Tools > Python Integration Tools > Default test runner to py.test. Then Run > Debug 'py.test in test_me.py'