Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Testing Be Assertive Quantitative Assertions

Edgar Lopez
Edgar Lopez
3,003 Points

assert x + y == z vs. self.assertEquals(self.instance, self.instance2)

Why do we use the simpler "assert x + y == z" format for our unit tests on the first couple tests, but then use "self.assertEquals(...." on the later tests?

When is one way used vs the other? what is the difference?

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

The built-in command assert throws an AssertionError that does not have built-in handling and your program and test will halt at he error.

Using self.assertFalse(), which comes from unittest.TestCase.assertFalse(), has built in logging and error handling to allow all tests to run to Error, Failure, or Success.

Sahar Nasiri
Sahar Nasiri
7,454 Points

Then why do we need to extend TestCase to use assert ? What is command assert in the TestCase class? Is it an attribute or a method?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

We are not extending TestCase, but rather we are calling the .assert() method that is part of the TestCase class assert methods

The regular assert is a built-in Python command assert()

Sahar Nasiri
Sahar Nasiri
7,454 Points

First, I thought the same but when I erase TestCase and use just those methods which use assert command I get 0 test! See:

import unittest

import moves


class MoveTests():

    def test_five_plus_five(self):
        assert 5 + 5 == 10

    def test_one_plus_one(self):
        assert not 1 + 1 == 3


if __name__ == '__main__':

    unittest.main()

If you run this you get: Ran 0 tests in 0.000s

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

unittest looks for TestCase objects, then runs the test_.... methods in the case. To make unittest see the tests, change the class signature:

# from...
class MoveTests():

# to ...
class MoveTests(unittest.TestCase):