In this lesson, you’ll set up a virtual environment. For more information on this important coding practice, watch Working With Python Virtual Environments.
Testing Code With Assertions
00:00 Testing Your Code With Assertions. Testing is another field in the development process where assertions are useful. Testing boils down to comparing an observed value with an expected one to check if they’re equal or not. This kind of check perfectly fits into assertions.
Assertions must check for conditions that should typically be true, unless you have a bug in your code. This idea is another important concept behind testing. The
pytest third-party library is a popular testing framework for Python. At its core, you’ll find the
assert statement, which you can use to write most of your test cases in
All of these test cases use the
assert statement. Most of them are written using the assertion formats you’ve already seen in the course. They all showcase how you’d write real-world test cases to check different pieces of your code with
Now, why does
pytest favor plain
assert statements in test cases over a custom API, which is what other testing frameworks prefer? Firstly, the
assert statement allows
pytest to lower the entry barrier and somewhat flatten the learning curve because its users can take advantage of Python syntax they already know. And secondly, the users of
pytest don’t need to import anything from the library to start writing test cases.
They only need to start importing things if their test cases become complicated, demanding more advanced features. These advantage make working with
pytest a pleasant experience for beginners and people coming from other testing frameworks with custom APIs.
03:23 You can find out more about virtual environments in this Real Python course. With the virtual environment created and active, you need to install the library by issuing the command seen on-screen.
Remember the optimized mode disables assertions. You can check the current value of the
PYTHOPTIMIZE environment variable with a command. If you’re using the Windows command prompt, then this is the command you’ll need.
And for macOS or Linux, this is the command you’ll need. If
PYTHOPTIMIZE is set, then you’ll see the current value. One feature to note is that
pytest integrates nicely with the
The library can display error reports with detailed information about the failing assertions and why they’re failing. As an example, check out the lines starting with the
E letter in the previous output. They display error messages.
Become a Member to join the conversation.