Friday, 21 Dec 2018
While creating a function that uses
logging.info to log useful information on the first run of Opsdroid the percentage of
coverall dropped quite a bit. To counter that a test had to be created to assert if the
logging.info was called or not.
Opsdroid uses a file named
configuration.yml to keep track of all the configuration details. Upon the suggestion of Jacob(the creator and maintainer of the project) a
welcome-message: true line was added to the configuration file in case the user wishes to hide the welcome message.
welcome_message function is a very basic function that uses the
logging.info to log a quick get started information about Opsdroid.
opsdroid__main__(where the welcome_message function is located)
welcome_messagefunction using the dummy config file (which will always return the
logmock.calledwill return a boolean whether the mocked object has been called. Since we are sure that the dummy config file will always return True we do a simple
assertTrueto see if
When I wrote this pos, back in September of 2017, it seemed that there was no way to test if a logging message was logged. That changed in Feb when the unittest framework was updated and introduced a brilliant new assert.
Now, you can quickly check if a message was logged with the assert
Let’s say that your logger is called
_Logger and you are currently logging the message “hello” with the following code
_Logger.info("hello") for you to assert if the message was logged all you need to do is
As you can see, three lines of code are just reduced into a single one (or two if you need to call the function), which is great because it makes the testing code much more readable.