Русские Блоги
Вы можете видеть, что выводится только один вывод, а последний не выполняется, потому что assert (3 == 4) вызывает исключение.
2. isinstance
Описание функции:
Когда мы определяем класс, мы фактически определяем тип данных. Типы данных, которые мы определяем, не отличаются от типов данных, которые поставляются с Python, таких как str, list и dict:
Чтобы определить, относится ли переменная к определенному типу, вы можете использовать isinstance () для определения:
Python assertIsInstance()
Summary: in this tutorial, you’ll learn how to use Python assertIsInstance() method to test if an object is an instance of a class.
Introduction to the Python assertIsInstance() method
The assertIsInstance() is a method of the TestCase class of the unittest module. The assertIsInstance() method tests if an object is an instance of a class.
The following shows the syntax of the assertIsInstance() method:
- obj is the object to test.
- cls is a class or a tuple of classes.
- msg is an optional string that will be displayed if the obj is not an instance of the cls class.
Internally, the assertIsInstance() uses the isinstance() function to check if the object is an instance of the cls class.
If the cls is not the class of the obj but the base class of the class of the obj, the test will also pass.
Since the object class is the base class of all classes, the assertIsInstance(obj, object) will always pass.
Python assertIsInstance() method examples
Let’s create a shape.py module with two classes Shape and Square . The Shape class is the base class of the Square class:
To make it simple, the Shape and Square classes have no implementation.
1) Using the Python assertIsInstance() method example
The following example uses the assertIsInstance() method to test if the square object is an instance of the Square class:
Because the square instance variable is an object of the Square class, the test passes.
2) Using the Python assertIsInstance() method with a base class example
The following example uses the assertIsInstance() method to test if the square is an instance of the Shape class:
3) Using the Python assertIsInstance() method to test if an object is an instance of the object class
The following example uses assertIsInstance() method to test if the square instance variable is an instance of the object class:
Python assertIsNotInstance() method
The assertIsNotInstance() is the opposite of the assertIsInstance() method. It tests if an object is not an instance of a class:
In this example, the test_is_not_instance() method uses the assertIsNotInstance() method to test if a Shape object is an instance of the Square class.
Why Learn Assert Statements For Unit Tests?

Knowing how to write assert statements in Python allows you to easily write mini-tests for your code.
Additionally testing frameworks such as PyTest can work directly with assert statements to form fully functioning UnitTests.

Table of Contents
You can also find a list of all of the different standard UnitTest Module examples here.
Firstly let’s review all of the different types of assert statements that we can make for PyTest.
PyTest Python Assert Statements List
NB: Whenever you see # Success Example, this means that the assert test will succeed. However when you see # Fail Example, this means that the assert test will fail.
1. Equal to or not equal to [value]
2. type() is [value]
3. isinstance
4. Boolean is [Boolean Type]
5. in and not in [iterable]
6. Greater than or less than [value]
7. Modulus % is equal to [value]
8. any() assert statements
Notice that the example list python list is True because at least one of the numbers is not a 0, all numbers above 0 are ‘Truthy’.
9. all() assert statements
10. Custom Python Objects
It’s possible to identify if a class is a specific type of object. We can do this by using:
11. Iterables
It’s also possible to determine whether a variable is an iterable with:
Want to improve your data skills?
See the best data engineering & data science books
Combining Multiple And / Or Statements With Assert Statements:
It’s also possible to combine multiple conditions with either OR or AND and to test the chained commands with the assert statement:
Testing Multiple Commands
Also we can test more than one thing at a time by having multiple assert statements inside of the same Python method:
Python 3.x UnitTest Assert Methods
Below you’ll find a list of all of the UnitTest Assert Methods:
| Method | Checks | Version |
|---|---|---|
| assertEqual | a == b | 3.x |
| assertNotEqual | a != b | 3.x |
| assertTrue | bool(x) is True | 3.x |
| assertFalse | bool(x) is False | 3.x |
| assertIs | a is b | 3.x |
| assertIsNot | a is not b | 3.x |
| assertIsNone | x is None | 3.x |
| assertIsNotNone | x is not None | 3.x |
| assertIn | a in b | 3.x |
| assertNotIn | a not in b | 3.x |
| assertIsInstance | is instance(a,b) | 3.x |
| assertNotIsInstance | not is instance(a,b) | 3.x |
| assertRaises | fun(*args,**kwds) raises exc | 3.x |
| assertRaisesRegexp | fun(*args,**kwds) raises exc(regex) | 3.x |
| assertAlmostEqual | round(a-b,7) == 0 | 3.x |
| assertNotAlmostEqual | round(a-b,7) != 0 | 3.x |
| assertGreater | a > b | 3.x |
| assertGreaterEqual | a >= b | 3.x |
| assertLess | a < b | 3.x |
| assertLessEqual | a <= b | 3.x |
| assertRegexpMatches | r.search(s) | 3.x |
| assertNotRegexpMatches | not r.search(s) | 3.x |
| assertItemsEqual | sorted(a) == sorted(b) | 3.x |
| assertDictContainsSubset | all the key/value pairs in a exist in b | 3.x |
| assertMultiLineEqual | strings | 3.x |
| assertSequenceEqual | sequences | 3.x |
| assertListEqual | lists | 3.x |
| assertTupleEqual | tuples | 3.x |
| assertSetEqual | sets or frozensets | 3.x |
| assertDictEqual | dicts | 3.x |
Typing Assert Statements
As well as using simple assert statements, by importing the types module of python we can make more abstract assert statements on specific Types:
Above we’ve tested two class instance methods to see if either of them is a lambda: x style function!
You can find all of the different types here.
Hopefully this provides you with an extensive list of assert statements and methods for your Unit Tests.
Please let me know if you have any more examples that you’d like me to add them to this post
Assert isinstance python что это

assertIsInstance () in Python is a unittest library function that is used in unit testing to check whether an object is an instance of a given class or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If the object is an instance ofthe given class it will return true else it returns false.
Syntax: assertIsInstance(object, className, message)
- object: Object which is checked as an instance of the given class
- className: Class name to be compared for object instance
- message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function: