Hypothesis
- Tutorial
Welcome to Hypothesis!
This article is a translation of the page Welcome to Hypothesis! taken from the official guide.
I could not find any useful information on the use of the Hypothesis in Russian except for the speech on Dec 14. 2017 Alexander Shorin at the Moscow Python Meetup 50
Hypothesis is a Python library for creating unit tests that are simpler to write and more efficient at startup by detecting boundary cases in code that you would not consider looking for. It is stable, powerful, and easily added to any existing test suite.
The algorithm of his work, allowing you to write tests that claim that something must be true for each case, and not just what you guessed to think about.
A normal unit test is something like the following:
- Prepare some data.
- Perform some data operations.
- Confirm the result.
Hypothesis allows you to write tests that look like this:
- For all data meeting some specifications.
- Perform some data operations.
- Confirm the result.
This is often called property based testing , and has been popularized in the Haskell Quickcheck library .
It works by generating random data that matches your specification and verifying that your function or method still holds and does not crash in this case. If he finds an example where this is not the case, he will accept this example and reduce its size, simplifying it, until he finds a much smaller example that still causes the problem. He will then save this example for later, so that as soon as he finds a problem with your code he will not forget
this in the future.
Writing tests in this form usually consists of deciding on the guarantees under which your code should do make - properties , which should always matter true
, no matter what the world gives you. Examples of such warranties include:
- Your code should not throw an exception or should only raise a special type of exception (this works especially well if you have a lot of internal
assert
s). - When you delete an object, it is no longer displayed.
- If you serialize and then deserialize the value, you will get the same value back.
Now that you know the basics of what it does hypothesis
, the rest of the documentation will help you understand how and why. It is divided into sections that you can see in the sidebar (or at the top of the menu if you are on a mobile phone). But most likely, you'll want to start with the Quick start guide and the Quick Start Guide which will give you a working hypothesis use examples and a detailed plan of what you need to know to start testing code with it, or check out some of the Introductory articles .