1

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!

2
  • Pyret is a Python dialect that is designed to interleave methods with tests for them... Commented Feb 12, 2015 at 13:58
  • 1
    "I am rapid prototyping". How much time have you saved by doing this? Commented Feb 12, 2015 at 13:59

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

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?
Why actually you might want to do this , @Colin?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.