Geek Logbook

Tech sea log book

Assert or AssertEqual. Differences.

An assertion is not widely used in Python when we start programming. I think mainly because is something more related to testing rather than the creation of code deploying in production. 

But while you are gaining experience, and you start to incorporate more tools the assertion becomes one tool really useful to have. 

I’m going to talk about the assert used in the Unit Testing Framework, not the Assert Statement.  And despite the fact is possible to use an assertion inside a function I prefer to avoid them. And focus on using this framework in the unit testing. An idea mainly influenced the responses to this question in Software Engineering Stack Exchange: Is it a good idea to start a function with a bunch of assert statements?

The documentation tells us that: “The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.” Source: unittest – Unit testing framework

Assert help us to make some checks about expected vs real outputs. If the output is as we expected nothing happens. But if the output is different as we expected. We’ll receive an AssertError.

Before talking about assert in in testing. It’s worthy mention that there is a difference between the assert() keyword that the concept of assert inside the unittest framework. Therefore, we have to watch carefully and understand this concept.

For that difference you receive an error when trying, for example giving help without a quotation mark.

Totally differente if you tried to see the help information for unitest:

So, therefore, they are differents because assertEqual is a method that belongs to the class TestCase from the unittest module (python unittest docs).

The reason it works in your test code is most likely because you test class inherits from the TestCase class.

In this series I’m going to study the unittesting module.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>