Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am rapid prototyping so for now I would like to write unit tests together with the code I am testing - rather than putting the tests in a separate file. However, I would only like to build the test an invoke them if we run the code in the containing file as main. As follows:

class MyClass:
    def __init(self)__:
        # do init stuff here

    def myclassFunction():
        # do something


if __name__ == '__main__':
    import unittest

    class TestMyClass(unittest.TestCase):
        def test_one(self):
            # test myclassFunction()

    suite = unittest.TestLoader().loadTestsFromTestCase(TestMyClass)
    unittest.TextTestRunner(verbosity=2).run(suite)

This of course doesn't run as unittest is unable to find or make use of the test class, TestMyClass. Is there a way to get this arrangement to work or do I have to pull everything out of the if __name__ == '__main__' scope except the invocation to unittest?

Thanks!

share|improve this question
    
Pyret is a Python dialect that is designed to interleave methods with tests for them... –  CommuSoft Feb 12 at 13:58
1  
"I am rapid prototyping". How much time have you saved by doing this? –  mbatchkarov Feb 12 at 13:59

1 Answer 1

If you move your TestMyClass above of if __name__ == '__main__' you will get exactly what you want: Tests will run only when file executed as main

Something like this

import unittest
class MyClass:
  def __init(self)__:
    # do init stuff here

  def myclassFunction():
    # do something


class TestMyClass(unittest.TestCase):
    def test_one(self):

if __name__ == '__main__':
    unittest.main()
share|improve this answer
    
You are right but that was the meaning of the last part of my question. Is there a way to make it work without pulling the test class out of the if __ name__ block? –  Colin Feb 12 at 14:45
    
Why actually you might want to do this , @Colin? –  micgeronimo Feb 12 at 15:49
    
Unit test in the same file? Truly saves time when debugging, especially when the class definition is unstable. Also, I would prefer to keep the unit test classes apart when inside the same file. The alternative, of course, is as shown in this answer, which isn't so bad but not as nice. –  Colin Feb 12 at 17:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.