Python unittest – Ran 0 tests in 0.000s

Question:

So I want to do this code Kata for practice.
I want to implement the kata with tdd in separate files:

The algorithm:

# stringcalculator.py  
def Add(string):
   return 1

and the tests:

# stringcalculator.spec.py 
from stringcalculator import Add
import unittest

class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

if __name__ == '__main__':
    unittest.main()

When running the testfile, I get:

Ran 0 tests in 0.000s

OK

It should return one failed test however. What do I miss here?

Asked By: MattSom

||

Answers:

As stated in the python unittest doc:

The simplest TestCase subclass will simply implement a test method
(i.e. a method whose name starts with test)

So you will need to change your method name to something like this:

def test_add_returns_zero_for_emptyString(self):
    self.assertEqual(Add(' '), 0)
Answered By: Taku

Sidenote: Also, the name of the file in which all the tests are there should start with ‘test_’

Answered By: Shashank

Same symptoms, but different problem. Make sure you’re not mixing up tabs and spaces for indentation. The problem may occur when you copy the code from an online resource and update it to your needs. Since tabs and spaces look very much alike in most editors, the test function may simply not be defined correctly.

Answered By: mikryz

I had a similar problem. My root cause was that I had placed the execution block for unittest.main inside the Test class. This kept messaging RAN 0 tests. Moving it outside of class work.

if __name__ == '__main__':
    unittest.main()
Answered By: Wolf7176
class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

 if __name__ == '__main__':
     unittest.main()

After considering above two points in above written code,
I got below error due to prefix space at line ( if __name__ == '__main__')

python3 test_flaskr.py 
  File "test_flaskr.py", line 66
    if __name__ == '__main__':
                             ^

Ensure that there is no prefix space and you need to write code at 1st column as below:

if __name__ == '__main__':
   unittest.main()
Answered By: Ravi Pullagurla

Do not define __init__; per that link, use def setUp(self) instead and unittest will call it. Also, do not define run; I renamed mine to _run and the problem finally went away.

Answered By: Emmet Brickowski

In my case, I added __init__.py to the current test directory and the problem goes away.

Answered By: Zubair Hassan