PyCharm and unittest won't run - python

I have a problem with PyCharm 3.0.1 I can't run basic unittests.
Here is my code :
import unittest from MysqlServer import MysqlServer
class MysqlServerTest(unittest.TestCase):
def setUp(self):
self.mysqlServer = MysqlServer("ip", "username", "password", "db", port)
def test_canConnect(self):
self.mysqlServer.connect()
self.fail()
if __name__ == '__main__':
unittest.main()
Here is All the stuff PyCharm give me
Unable to attach test reporter to test framework or test framework quit unexpectedly
It also says
AttributeError: class TestLoader has no attribute '__init__'
And the event log :
2:14:28 PM Empty test suite
The problem is when I run manually the Python file (with PyCharm, as a script)
Ran 1 tests in 0.019s
FAILED (failures=1)
Which is normal I make the test fail on purpose. I am a bit clueless on what is going on.
here more information :
Setting->Python Integrated Tools->Package requirements file: <PROJECT_HOME>/src/test
Default test runner: Unittests
pyunit 1.4.1 Is installed
EDIT: Same thing happen with the basic usage from unitests.py
import unittest
class IntegerArithmenticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEquals((1 + 2), 3)
self.assertEquals(0 + 1, 1)
def testMultiply(self):
self.assertEquals((0 * 10), 0)
self.assertEquals((5 * 8), 40)
if __name__ == '__main__':
unittest.main()

Although this wasn't the case with the original poster, I'd like to note that another thing that will cause this are test functions that don't begin with the word 'test.'
class TestSet(unittest.TestCase):
def test_will_work(self):
pass
def will_not_work(self):
pass

This is probably because you did not set your testing framework correctly in the settings dialogue.

Definitely a pycharm thingy, repeating from above,
Run --> Edit Configurations.
select the instances of the test, and press the red minus button.

I have the exact same problem. It turned out that the fact of recognizing an individual test was related to the file name. In my case, test_calculate_kpi.py, which PyCharm didn't recognize as a test when renamed to test_calculate_kpis.py, was immediately recognized.

4 steps to generate html reports with PyCharm and most default test runners (py.test, nosetest, unittest etc.):
make sure you give your test methods a prefix 'test' (as stated before by others), e.g. def test_run1()
the widespread example code from test report packageā€˜s documentation is
import unittest
import HtmlTestRunner
class TestGoodnessOfFitTests(unittest.TestCase):
def test_run1(self):
...
if __name__ == '__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='t.html'))
This code is usually located in a test class file which contains all the unittests and the "main"-catcher code. This code continuously yielded the warning Empty test suite for me. Therefore, remove all the if __name__ ... code. The file now only contains the TestGoodnessOfFitTests class. Now, additionally
create a new main.py in the same directory of the test class file and use the following code:
import unittest
import HtmlTestRunner
test_class = TestGoodnessOfFitTests()
unittest.main(module=test_class,
testRunner=HtmlTestRunner.HTMLTestRunner(output='t.html'))
Remove your old run configurations, right-click on your main.py and press Run 'main'. Verify correct settings under Preferences -> Python Integrated Tools -> Default test runner (in my case py.test and nose worked)
Output:
Running tests...
----------------------------------------------------------------------
test_gaussian_dummy_kolmogorov_cdf_1 (tests.evaluation_tests.TestGoodnessOfFitTests) ... OK (1.033877)s
----------------------------------------------------------------------
Ran 1 test in 0:00:01
OK
Generating HTML reports...

Even I had the same problem, I felt the workspace was not properly refreshed. Even I did File->Synchronize(Ctrl+Aly+y). But that wasn't the solution. I just renamed my test python file name and again I tried executing the code, it started worked fine.

I had the same problem. The file was named test_exercise_detectors.py (note the plural "detectors") and it was in a packed named test_exercise_detectors. Changing the name of the file to test_exercise_detector.py (singular "detector") fixed the problem.

Adding
if __name__ == "__main__":
unittest.main()
fixed the issue for me.

Related

Python unitest doesn't run test functions from PythonAnywhere

I'm having a problem with unittest testing, code and results below.
I try to run my test from the PythonAnywhere IDE, and it says that 0 test has been made.
I tested the code with prints to find out where things went wrong and I found out that interpreter doesn't even go into the function to see the test.
I know the test names should start with "test_", which they do.
Any other idea?
I am working on pythonAnywhere if it's matter somehow.
My code:
import unittest
import signUpForm
class Test_signUp(unittest.TestCase):
print ("i got to here")
def test_Utility(self):
print ("but never here")
# test all utlity functions in the sign up form. and delete the changes afterward
#check system addition and manipulation
self.assertEqual(addSystem ("dungeons" , 8000) , "added dungeons to systems list")
if __name__ == '__main__':
unittest.main(exit = False)
When I run this I get:
i got to here
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
>>>
That looks like a bug in the IDE in PythonAnywhere -- the easiest workaround would be to close the console in the editor (using exit()), then refresh the page, and start a new console using the "Bash console here" button that will appear where the old console was. Then you can use the command that #jfaccioni suggested in the comments to your question:
python3 -m unittest code.py
...but have your test results on the same browser tab as your editor.

Python unittest only running the first test and not the others

I am new to unittesting and trying to write tests for my code. In my test file, I have defined a test class and have two small tests for my file. However, when I run the file, only the first test runs.
Furthermore, the code I am importing the tests from, in separate functions than the one I am testing, is generating some plots, and those plots are being generated before the test is ran now.
Is there a way I could only run the tests, without having the file I'm importing the functions to be tested from run?
This is my code for the test class :
import unittest
from Expense import set_day_of_the_week
from Expense import add_two_expenses
class Heart_Rate_Model_Tests(unittest.TestCase):
def test_assign_initial_values(self):
day_returned = set_day_of_the_week('Monday')
self.assertEqual(day_return, 'Monday')
def test_add_two_expense(self):
food_expense = 12
drink_expense = 5
expense_sum = add_two_expense(food_expense, drink_expense)
self.assertEqual(17, expense_sum)
if __name__ == '__main__':
unittest.main()
The output obtained from the tests is :
Ran 1 test in 0.001s
OK
I have made changes to the first test to make it fail, and it does fail, therefore I'm sure it's the only test that is being ran, but changes made to it are seen
Writing a new test file has fixed the issue. I'm still not sure what it was, I'm assuming it was a configuration error on my side, leaving this here if somebody in the future has a similar issue
For everybody who has the same problem in he future:
Check your compiling configurations. There might be just one specific test chosen when you click on 'run'.

Why doesn't IDLE need 'if __name__ == "__main__": to run a test case, but PyCharm does?

I'm practicing working with unittest, and I tried the following in PyCharm:
import unittest
from format_name import name_formatted
class TestName_formatted(unittest.TestCase):
"""practice with unittest"""
def test_name(self):
"""Testing name_formatted function"""
formatted_name = name_formatted("mike", "Cronin")
self.assertEqual(formatted_name, "mike Cronin")
unittest.main()
After research, I saw that it was written like this:
if __name__ == "__main__":
unittest.main()
And suddenly it worked perfectly. HOWEVER, the reason I wrote it that way, without the if statement, is because that's how I learned it from "Python Crash Course" which uses GEANY and IDLE for its example code. And sure enough, in both of those programs, you don't need the if statement.
Why is it that in one IDE the code doesn't work and in the others it does?
You are running the code in PyCharm as if it were a normal Python application; which is why you need the if __name__ == '__main__' conditional. This is also best practice when writing modules (files) that can be imported or run at the command line - the case with unit tests.
PyCharm is basically trying to do python your_file_name.py
The reason IDLE doesn't need this is because IDLE is running the application by first loading the file in the Python shell.
What IDLE is doing is:
python
>>> import your_file_name
By doing so, the code is automatically evaluated, the function is called and thus the test runs.
I would also suggest reading the documentation on testing in PyCharm's manual as testing is something PyCharm has extensive support for. In that link you'll also notice the default stub (or template) for a sample test case already has the if __name__ == '__main__' check:

How to execute a python test using httpretty/sure

I'm new to python tests so don't hesitate to provide any obvious information.
Basically I want to do some RESTful tests using python, and found the httpretty and sure libraries which look really nice.
I have a python file containing:
#!/usr/bin/python
from sure import expect
import requests, httpretty
#httpretty.activate
def RestTest():
httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
body='{"status": "ok"}',
content_type="application/json")
response = requests.get("http://localhost:8090/test.json")
expect(response.json()).to.equal({"status": "ok"}
Which is basically the same as the example code provided at https://github.com/gabrielfalcao/HTTPretty
My question is; how do I simply run this test to see it either passing or failing? I tried just executing it using ./pythonFile but that doesn't work.
If your test is implemented as a Python function, then of course simply trying to execute the file isn't going to run the test: nothing in that file actually calls RestTest.
You need some sort of test framework that will call your tests and collate the results.
One such solution is python-nose, which will look for methods named test_* and run them. So if you were to rename RestTest to test_rest, you could run:
$ nosetests myfile.py
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
OK
The nosetests command has a variety of options that control which tests are run, how errors are handled and reported, and more.
Python 3 includes similar functionality in the unittest module, which is also available as a backport for Python 2 called unittest2. You could modify your code to take advantage of unittest like this:
#!/usr/bin/python
from sure import expect
import requests, httpretty
import unittest
class RestTest(unittest.TestCase):
#httpretty.activate
def test_rest(self):
httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
body='{"status": "ok"}',
content_type="application/json")
response = requests.get("http://localhost:8090/test.json")
expect(response.json()).to.equal({"status": "ok"})
if __name__ == '__main__':
unittest.main()
Running your file would now provide output similar to what we saw with
nosetests:
$ python myfile.py
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
OK
Have you tried calling your method?
Or does the annotation mean you don't have to explicitly call your method?
If I call your method, it seems like it works. If I change the value on one side of the expect, it complains properly about the values not matching.

Error when running Python parameterized test method

IDE: PyCharm Community Edition 3.1.1
Python: 2.7.6
I using DDT for test parameterization http://ddt.readthedocs.org/en/latest/example.html
I want to choose and run parameterized test method from test class in PyCharm -> see example:
from unittest import TestCase
from ddt import ddt, data
#ddt
class Test_parameterized(TestCase):
def test_print_value(self):
print 10
self.assertIsNotNone(10)
#data(10, 20, 30, 40)
def test_print_value_parametrized(self, value):
print value
self.assertIsNotNone(value)
When I navigate to the first test method test_print_value in code and hit ctrl+Shift+F10 (or use Run Unittest test_print... option from context menu)
then test is executed.
When I try the same with parameterized test I get error:
Test framework quit unexpectedly
And output contains:
/usr/bin/python2 /home/s/App/pycharm-community-3.1.1/helpers/pycharm/utrunner.py
/home/s/Documents/Py/first/fib/test_parametrized.py::Test_parameterized::test_print_value_parametrized true
Testing started at 10:35 AM ...
Traceback (most recent call last):
File "/home/s/App/pycharm-community-3.1.1/helpers/pycharm/utrunner.py", line 148, in <module>
testLoader.makeTest(getattr(testCaseClass, a[2]), testCaseClass))
AttributeError: 'TestLoader' object has no attribute 'makeTest'
Process finished with exit code 1
However when I run all tests in class (by navigating to test class name in code and using mentioned run test option) all parameterized and non parameterized tests are executed together without errors.
The problem is how to independently run prameterized method from the test class - workaround is putting one parameterized test per test class but it is rather messy solution.
Actually this is issue in PyCharm utrunner.py who runs unittests. If you are using DDT there is a wrapper #ddt and #data - it is responsible for creating separate tests for each data entry. In the background these tests have different names e.g.
#ddt
class MyTestClass(unittest.TestCase):
#data(1, 2)
def test_print(self, command):
print command
This would create tests named:
- test_print_1_1
- test_print_2_2
When you try to run one test from the class (Right Click -> Run 'Unittest test_print') PyCharm has a problem to load your tests print_1_1, print_2_2 as it is trying to load test_print test.
When you look at the code of utrunner.py:
if a[1] == "":
# test function, not method
all.addTest(testLoader.makeTest(getattr(module, a[2])))
else:
testCaseClass = getattr(module, a[1])
try:
all.addTest(testCaseClass(a[2]))
except:
# class is not a testcase inheritor
all.addTest(
testLoader.makeTest(getattr(testCaseClass, a[2]), testCaseClass))
and you will debug it you see that issue.
Ok. So my fix for that is to load proper tests from the class. It is just a workaround and it is not perfect, however as DDT is adding a TestCase as another method to the class it is hard to find a different way to detect right test cases than comparing by string. So instead of:
try:
all.addTest(testCaseClass(a[2]))
you can try to use:
try:
all_tests = testLoader.getTestCaseNames(getattr(module, a[1]))
for test in all_tests:
if test.startswith(a[2]):
if test.split(a[2])[1][1].isdigit():
all.addTest(testLoader.loadTestsFromName(test, getattr(module,a[1])))
Checking if digit is found after the main name is a workaround to exclude similar test cases:
test_print
test_print_another_case
But of course it would not exclude cases:
test_if_prints_1
test_if_prints_2
So in the worst case, if we haven't got a good name convention we will run similar tests, but in most cases it should just work for you.
When I ran into this error, it was because I had implemented an init function as follows:
def __init__(self):
super(ClassInheritingTestCase, self).__init__()
When I changed it to the following, it worked properly:
def __init__(self, *args, **kwargs):
super(ClassInheritingTestCase, self).__init__(*args, **kwargs)
The problem was caused by me not propagating the *args and **kwargs through properly.

Categories

Resources