1

I'm doing the Python Koans (on Python 2) and in the about_classes part got a bit lost.

This is the code I don't know what to do / what's happening:

class Dog5(object):
    def __init__(self, initial_name):
        self._name = initial_name

    @property
    def name(self):
        return self._name

def test_args_must_match_init(self):
    self.assertRaises(___, self.Dog5)  # Evaluates self.Dog5()

I understand why I get an error here, because the class needs an argument (and zero are given) but don't get what's the expected response here.

So lookin for a solution for this, I found this code:

def test_args_must_match_init(self):
    with self.assertRaises(TypeError):
            self.Dog5()

But I don't get it.

So now comes the question: What is that last piece of code doing?

What's the with assertRaises(TypeError): Dog5() doing?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
tglaria
  • 5,678
  • 2
  • 13
  • 17

2 Answers2

3

It is asserting that calling Dog5() with no arguments is going to raise a TypeError, which is going to succeed, ergo no AssertionError.

Documentation on assertRaises() is pretty straight-forward:

assertRaises(exception, msg=None)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

(emphasis mine)

When passed an exception as TypeError and an optional msg a Context Manager is created instead of a function as further documented:

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function.

It's more simple than it looks.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
2

From the docs:

assertRaises(exception, callable, *args, **kwds)

assertRaises(exception)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

So, with assertRaises(TypeError): Dog5() asserts that self.Dog5() raises a TypeError.

Python 2.7 introduced the possibility to use assertRaises as context manager (hence with with), while in previous python versions you would have called as self.assertRaises(TypeError, self.Dog5)

Railslide
  • 5,344
  • 2
  • 27
  • 34