2
import logging

class TestMyClass(unittest.TestCase):
       def __init__(self):
            self.logger = logging.getLogger('MyClassLog')

       def setUp(self):

I am trying to instantiate the logger in the constructor. But I get this error: ... TypeError: init() takes exactly 1 argument (2 given)

Why is this? How to instantiate logger correctly?

4 Answers 4

3

You are overriding __init__. You can't do that in a TestCase like that, because your test case is going to be instantiated by the test runner, and the argument passed to it there is going to be the method to run, so you've quashed all the initialization that needs to be done (and not taken the correct amount of arguments).

If you want to do some logging, you can do that in a setUp method, or more likely, just globally.

Sign up to request clarification or add additional context in comments.

2 Comments

But setup runs for every test case. I don't want my logger to be instantiated for every testcase. How to avoid that?
@Julian: How do you set up unittest logging globally? I'm running my from IntelliJ, and also on the command line via 'python3.2 -m unittest discover'
2

You shouldn't have an __init__ method; do everything you need to do in the setUp method instead.

1 Comment

But setup runs for every test case. I don't want my logger to be instantiated for every testcase. How to avoid that?
2

You may try this..

class TestMyClass(unittest.TestCase):
def __init__(self, methodName):
    super(TestMyClass, self).__init__(methodName)
    self.logger = logging.getLogger('MyClassLog')

Comments

1

setUpClass() should let you do initialization for all the tests in your test case, and should do it only once.

Comments

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.