1. CLI Interface
Now we will learn how to run unittest modules using the command line interface.
2. Example: code
Let's consider the test of the exponentiation operator. We have the test function "test negative" that squares minus three and verifies that the result is equal to nine. But how to run the test? We use the CLI interface for that. The command starts with "python minus m unittest", which means that we want to run a Python script using unittest. "Minus m" is the module flag followed by "unittest" - the name of the module that we want to run. Finally, we provide the name of the script - "test sqneg dot py".
3. Example: output
Now, we see the test results. First, we run the test script using "python minus m". Then unittest found and ran one test, and the "OK" at the bottom means it was successful. We also see the time that it took Python to conduct the test.
4. Keyword argument -k
There are a lot of flags in unittest that help us to customize a test launch and its output. One of them is a "keyword" flag - "minus k". This flag is similar to "minus k" of pytest - it lets us select and run only the methods and classes that match the pattern or substring. For instance, if we run the script from the previous example with the keyword "Squared", unittest will find our "Test Squared" class. Thus, the output in this case will contain the same one successful test.
5. Fail fast flag -f
Another important flag in unittest is "stop after a failure" flag or "minus f". This flag will force unittest to stop the execution when a test fails or when an error occurs.
We can use this flag to make sure that all of the tests are successful and none contain errors. Hence, if the execution reached the end, all the tests were OK and had zero errors.
6. Catch flag -c
If we want to have the option to stop the test execution, then we can pass the "catch" or the minus c" flag after the "unittest" and before the name of the test script. This argument lets us stop the test easily by pressing "Control C". When "Control C" is pressed, unittest will wait for the current test to end, and no others will run. Python will output all of the information about tests that have finished by then. If we hit "Control C" twice, the tests will stop immediately.
7. Verbose flag -v
Finally, the "verbose" flag tells the unittest to provide a more detailed output. In this case, we got information about all of the test scripts and test classes that ran.
8. Summary
In this video, we learned about CLI interface of unittest. We started with a basic command without any arguments and analyzed the output of the finished test. We can use the keyword argument to select specific test cases from the script. Fail fast flag helps us to ensure that all of the tests are successful. The catch flag lets us stop the test at any time. And finally, the verbose flag gives us more information within the output.
9. Let's practice!
Now you are familiar with the unittest CLI interface and will run tests yourself.