Kiểm tra Python in ra bàn điều khiển

Khung thử nghiệm đơn vị

python -m unittest tests/test_something.py
9 ban đầu được lấy cảm hứng từ JUnit và có hương vị tương tự như các khung thử nghiệm đơn vị chính trong các ngôn ngữ khác. Nó hỗ trợ tự động hóa thử nghiệm, chia sẻ mã thiết lập và tắt cho các thử nghiệm, tổng hợp các thử nghiệm thành các bộ sưu tập và tính độc lập của các thử nghiệm với khung báo cáo

Để đạt được điều này,

python -m unittest tests/test_something.py
9 hỗ trợ một số khái niệm quan trọng theo cách hướng đối tượng

lịch thi đấu

Một bộ cố định thử nghiệm thể hiện sự chuẩn bị cần thiết để thực hiện một hoặc nhiều thử nghiệm và bất kỳ hành động dọn dẹp nào có liên quan. Điều này có thể bao gồm, ví dụ, tạo cơ sở dữ liệu tạm thời hoặc proxy, thư mục hoặc khởi động quy trình máy chủ

trường hợp thử nghiệm

Một trường hợp thử nghiệm là đơn vị thử nghiệm riêng lẻ. Nó kiểm tra một phản hồi cụ thể đối với một bộ đầu vào cụ thể.

python -m unittest tests/test_something.py
9 cung cấp một lớp cơ sở,
python -m unittest -v test_module
3, có thể được sử dụng để tạo các trường hợp thử nghiệm mới

bộ kiểm tra

Bộ kiểm thử là tập hợp các trường hợp kiểm thử, bộ kiểm thử hoặc cả hai. Nó được sử dụng để tổng hợp các bài kiểm tra nên được thực hiện cùng nhau

người chạy thử

Trình chạy thử nghiệm là một thành phần điều phối việc thực hiện các thử nghiệm và cung cấp kết quả cho người dùng. Người chạy có thể sử dụng giao diện đồ họa, giao diện văn bản hoặc trả về một giá trị đặc biệt để chỉ ra kết quả thực hiện các bài kiểm tra

Xem thêm

Mô-đun
python -m unittest -v test_module
4

Một mô-đun hỗ trợ thử nghiệm khác với hương vị rất khác

Kiểm tra Smalltalk đơn giản. có hoa văn

Bài báo gốc của Kent Beck về các khung thử nghiệm sử dụng mẫu được chia sẻ bởi

python -m unittest tests/test_something.py
9

người khó tính

Khung đơn giản nhất của bên thứ ba với cú pháp nhẹ hơn để viết bài kiểm tra. Ví dụ,

python -m unittest -v test_module
6

Phân loại công cụ kiểm tra Python

Một danh sách đầy đủ các công cụ kiểm tra Python bao gồm các khung kiểm tra chức năng và thư viện đối tượng giả

Thử nghiệm trong Danh sách gửi thư Python

Một nhóm có sở thích đặc biệt để thảo luận về thử nghiệm và các công cụ thử nghiệm trong Python

Tập lệnh

python -m unittest -v test_module
7 trong bản phân phối nguồn Python là một công cụ GUI để khám phá và thực thi thử nghiệm. Điều này chủ yếu nhằm mục đích dễ sử dụng cho những người mới thử nghiệm đơn vị. Đối với môi trường sản xuất, các thử nghiệm nên được điều khiển bởi một hệ thống tích hợp liên tục như Buildbot, Jenkins, GitHub Actions hoặc AppVeyor

Ví dụ cơ bản¶

Mô-đun

python -m unittest tests/test_something.py
9 cung cấp một bộ công cụ phong phú để xây dựng và chạy thử nghiệm. Phần này chứng minh rằng một tập hợp con nhỏ của các công cụ đủ để đáp ứng nhu cầu của hầu hết người dùng

Đây là một đoạn script ngắn để kiểm tra ba phương thức chuỗi

import unittest

class TestStringMethods[unittest.TestCase]:

    def test_upper[self]:
        self.assertEqual['foo'.upper[], 'FOO']

    def test_isupper[self]:
        self.assertTrue['FOO'.isupper[]]
        self.assertFalse['Foo'.isupper[]]

    def test_split[self]:
        s = 'hello world'
        self.assertEqual[s.split[], ['hello', 'world']]
        # check that s.split fails when the separator is not a string
        with self.assertRaises[TypeError]:
            s.split[2]

if __name__ == '__main__':
    unittest.main[]

Một testcase được tạo bởi phân lớp

python -m unittest -v test_module
9. Ba bài kiểm tra riêng lẻ được xác định bằng các phương thức có tên bắt đầu bằng các chữ cái
python -m unittest tests/test_something.py
10. Quy ước đặt tên này thông báo cho người chạy thử nghiệm về phương thức nào đại diện cho các thử nghiệm

Mấu chốt của mỗi bài kiểm tra là một cuộc gọi tới

python -m unittest tests/test_something.py
11 để kiểm tra kết quả mong đợi; . Các phương pháp này được sử dụng thay cho câu lệnh
python -m unittest tests/test_something.py
15 để người chạy thử nghiệm có thể tích lũy tất cả các kết quả thử nghiệm và tạo báo cáo

Các phương thức

python -m unittest tests/test_something.py
16 và
python -m unittest tests/test_something.py
17 cho phép bạn xác định các lệnh sẽ được thực thi trước và sau mỗi phương thức kiểm tra. Chúng được đề cập chi tiết hơn trong phần Tổ chức mã kiểm tra .

Khối cuối cùng cho thấy một cách đơn giản để chạy thử nghiệm.

python -m unittest tests/test_something.py
18 cung cấp giao diện dòng lệnh cho tập lệnh thử nghiệm. Khi chạy từ dòng lệnh, tập lệnh trên sẽ tạo ra một đầu ra giống như thế này

python -m unittest tests/test_something.py
0

Chuyển tùy chọn

python -m unittest tests/test_something.py
19 cho tập lệnh thử nghiệm của bạn sẽ hướng dẫn
python -m unittest tests/test_something.py
18 kích hoạt mức độ chi tiết cao hơn và tạo ra kết quả sau

python -m unittest tests/test_something.py
3

Các ví dụ trên cho thấy các tính năng

python -m unittest tests/test_something.py
9 được sử dụng phổ biến nhất, đủ để đáp ứng nhiều nhu cầu kiểm tra hàng ngày. Phần còn lại của tài liệu khám phá bộ tính năng đầy đủ từ các nguyên tắc đầu tiên

Đã thay đổi trong phiên bản 3. 11. Hành vi trả về một giá trị từ một phương pháp thử nghiệm [không phải giá trị mặc định

python -m unittest tests/test_something.py
52], hiện không được dùng nữa.

Giao diện dòng lệnh¶

Mô-đun unittest có thể được sử dụng từ dòng lệnh để chạy thử nghiệm từ các mô-đun, lớp hoặc thậm chí các phương thức thử nghiệm riêng lẻ

python -m unittest tests/test_something.py
6

Bạn có thể chuyển vào một danh sách với bất kỳ sự kết hợp nào của tên mô-đun và tên phương thức hoặc lớp đủ điều kiện

Các mô-đun thử nghiệm cũng có thể được chỉ định theo đường dẫn tệp

python -m unittest tests/test_something.py

Điều này cho phép bạn sử dụng hoàn thành tên tệp shell để chỉ định mô-đun thử nghiệm. Tệp được chỉ định vẫn phải nhập được dưới dạng mô-đun. Đường dẫn được chuyển đổi thành tên mô-đun bằng cách xóa '. py' và chuyển đổi các dấu phân cách đường dẫn thành '. ’. Nếu bạn muốn thực thi tệp thử nghiệm không thể nhập dưới dạng mô-đun, thay vào đó, bạn nên thực thi tệp trực tiếp

Bạn có thể chạy thử nghiệm với nhiều chi tiết hơn [độ chi tiết cao hơn] bằng cách chuyển vào cờ -v

python -m unittest -v test_module

Khi được thực thi mà không có đối số Thử nghiệm Khám phá được bắt đầu.

python -m unittest tests/test_something.py
1

Để biết danh sách tất cả các tùy chọn dòng lệnh

python -m unittest tests/test_something.py
5

Đã thay đổi trong phiên bản 3. 2. Trong các phiên bản trước, chỉ có thể chạy các phương thức thử nghiệm riêng lẻ chứ không phải mô-đun hoặc lớp.

Tùy chọn dòng lệnh¶

unittest hỗ trợ các tùy chọn dòng lệnh này

-b, --bộ đệm

Đầu ra tiêu chuẩn và các luồng lỗi tiêu chuẩn được lưu vào bộ đệm trong quá trình chạy thử nghiệm. Đầu ra trong một bài kiểm tra vượt qua bị loại bỏ. Đầu ra được lặp lại bình thường khi kiểm tra lỗi hoặc lỗi và được thêm vào thông báo lỗi

-c, --bắt

Control-C trong quá trình chạy thử, đợi thử nghiệm hiện tại kết thúc rồi báo cáo tất cả các kết quả cho đến nay. Control-C thứ hai tăng ngoại lệ

python -m unittest tests/test_something.py
53 bình thường

Xem Xử lý tín hiệu để biết các chức năng cung cấp chức năng này

-f, --không thành công

Dừng chạy thử khi có lỗi hoặc lỗi đầu tiên

-k

Chỉ chạy thử nghiệm các phương thức và lớp phù hợp với mẫu hoặc chuỗi con. Tùy chọn này có thể được sử dụng nhiều lần, trong trường hợp đó, tất cả các trường hợp thử nghiệm khớp với bất kỳ mẫu nào đã cho đều được bao gồm

Các mẫu có chứa ký tự đại diện [

python -m unittest tests/test_something.py
54] được khớp với tên bài kiểm tra bằng cách sử dụng
python -m unittest tests/test_something.py
55;

Các mẫu được so khớp với tên phương thức kiểm tra đủ điều kiện do trình tải kiểm tra nhập vào

Ví dụ:

python -m unittest tests/test_something.py
56 khớp với
python -m unittest tests/test_something.py
57,
python -m unittest tests/test_something.py
58, nhưng không khớp với
python -m unittest tests/test_something.py
59

--người dân địa phương

Hiển thị các biến cục bộ trong truy nguyên

Mới trong phiên bản 3. 2. Các tùy chọn dòng lệnh

python -m unittest -v test_module
80,
python -m unittest -v test_module
81 và
python -m unittest -v test_module
82 đã được thêm vào.

Mới trong phiên bản 3. 5. Tùy chọn dòng lệnh

python -m unittest -v test_module
83.

Mới trong phiên bản 3. 7. Tùy chọn dòng lệnh

python -m unittest -v test_module
84.

Dòng lệnh cũng có thể được sử dụng để khám phá thử nghiệm, để chạy tất cả các thử nghiệm trong một dự án hoặc chỉ một tập hợp con

Khám phá thử nghiệm¶

Mới trong phiên bản 3. 2

Unittest hỗ trợ khám phá thử nghiệm đơn giản. Để tương thích với khám phá thử nghiệm, tất cả các tệp thử nghiệm phải là mô-đun hoặc gói importable from the top-level directory of the project [this means that their filenames must be valid identifiers].

Khám phá thử nghiệm được triển khai trong

python -m unittest -v test_module
85, nhưng cũng có thể được sử dụng từ dòng lệnh. Việc sử dụng dòng lệnh cơ bản là

python -m unittest -v test_module
8

Ghi chú

Là một phím tắt,

python -m unittest -v test_module
86 tương đương với
python -m unittest -v test_module
87. Nếu bạn muốn truyền đối số để kiểm tra khám phá, lệnh phụ
python -m unittest -v test_module
88 phải được sử dụng rõ ràng

Lệnh phụ

python -m unittest -v test_module
88 có các tùy chọn sau

-v, --dài dòng

Báo cáo dài dòng

-s, --start-directory directory

Directory to start discovery [

python -m unittest -v test_module
90 default]

-p, --pattern pattern

Pattern to match test files [

python -m unittest -v test_module
91 default]

-t, --top-level-directory directory

Top level directory of project [defaults to start directory]

The

python -m unittest -v test_module
92,
python -m unittest -v test_module
93, and
python -m unittest -v test_module
94 options can be passed in as positional arguments in that order. The following two command lines are equivalent

python -m unittest -v test_module
9

As well as being a path it is possible to pass a package name, for example

python -m unittest -v test_module
95, as the start directory. The package name you supply will then be imported and its location on the filesystem will be used as the start directory

Caution

Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import. For example

python -m unittest -v test_module
96 will be imported as
python -m unittest -v test_module
97

If you have a package installed globally and attempt test discovery on a different copy of the package then the import could happen from the wrong place. If this happens test discovery will warn you and exit

If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning

Test modules and packages can customize test loading and discovery by through the load_tests protocol

Changed in version 3. 4. Test discovery supports namespace packages for the start directory. Note that you need to specify the top level directory too [e. g.

python -m unittest -v test_module
98].

Changed in version 3. 11. Python 3. 11 dropped the namespace packages support. It has been broken since Python 3. 7. Start directory and subdirectories containing tests must be regular package that have

python -m unittest -v test_module
99 file.

Directories containing start directory still can be a namespace package. In this case, you need to specify start directory as dotted package name, and target directory explicitly. For example

python -m unittest tests/test_something.py
00

Organizing test code¶

The basic building blocks of unit testing are test cases — single scenarios that must be set up and checked for correctness. In

python -m unittest tests/test_something.py
9, test cases are represented by
python -m unittest -v test_module
9 instances. To make your own test cases you must write subclasses of
python -m unittest -v test_module
3 or use
python -m unittest tests/test_something.py
003

The testing code of a

python -m unittest -v test_module
3 instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases

The simplest

python -m unittest -v test_module
3 subclass will simply implement a test method [i. e. a method whose name starts with
python -m unittest tests/test_something.py
10] in order to perform specific testing code

python -m unittest tests/test_something.py
01

Note that in order to test something, we use one of the

python -m unittest tests/test_something.py
007 methods provided by the
python -m unittest -v test_module
3 base class. If the test fails, an exception will be raised with an explanatory message, and
python -m unittest tests/test_something.py
9 will identify the test case as a failure. Any other exceptions will be treated as errors

Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called

python -m unittest tests/test_something.py
16, which the testing framework will automatically call for every single test we run

python -m unittest tests/test_something.py
02

Ghi chú

The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings

If the

python -m unittest tests/test_something.py
16 method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed

Similarly, we can provide a

python -m unittest tests/test_something.py
17 method that tidies up after the test method has been run

python -m unittest tests/test_something.py
03

If

python -m unittest tests/test_something.py
16 succeeded,
python -m unittest tests/test_something.py
17 will be run whether the test method succeeded or not

Such a working environment for the testing code is called a test fixture. A new TestCase instance is created as a unique test fixture used to execute each individual test method. Thus

python -m unittest tests/test_something.py
16,
python -m unittest tests/test_something.py
17, and
python -m unittest tests/test_something.py
017 will be called once per test

It is recommended that you use TestCase implementations to group tests together according to the features they test.

python -m unittest tests/test_something.py
9 provides a mechanism for this. the test suite, represented by
python -m unittest tests/test_something.py
9’s
python -m unittest tests/test_something.py
020 class. In most cases, calling
python -m unittest tests/test_something.py
18 will do the right thing and collect all the module’s test cases for you and execute them

However, should you want to customize the building of your test suite, you can do it yourself

python -m unittest tests/test_something.py
04

You can place the definitions of test cases and test suites in the same modules as the code they are to test [such as

python -m unittest tests/test_something.py
022], but there are several advantages to placing the test code in a separate module, such as
python -m unittest tests/test_something.py
023

  • The test module can be run standalone from the command line

  • The test code can more easily be separated from shipped code

  • There is less temptation to change test code to fit the code it tests without a good reason

  • Test code should be modified much less frequently than the code it tests

  • Tested code can be refactored more easily

  • Tests for modules written in C must be in separate modules anyway, so why not be consistent?

  • If the testing strategy changes, there is no need to change the source code

Re-using old test code¶

Some users will find that they have existing test code that they would like to run from

python -m unittest tests/test_something.py
9, without converting every old test function to a
python -m unittest -v test_module
3 subclass

For this reason,

python -m unittest tests/test_something.py
9 provides a
python -m unittest tests/test_something.py
003 class. This subclass of
python -m unittest -v test_module
3 can be used to wrap an existing test function. Set-up and tear-down functions can also be provided

Given the following test function

python -m unittest tests/test_something.py
05

người ta có thể tạo một trường hợp thử nghiệm tương đương như sau, với các phương pháp thiết lập và phá bỏ tùy chọn

python -m unittest tests/test_something.py
06

Ghi chú

Even though

python -m unittest tests/test_something.py
003 can be used to quickly convert an existing test base over to a
python -m unittest tests/test_something.py
9-based system, this approach is not recommended. Taking the time to set up proper
python -m unittest -v test_module
3 subclasses will make future test refactorings infinitely easier

In some cases, the existing tests may have been written using the

python -m unittest -v test_module
4 module. If so,
python -m unittest -v test_module
4 provides a
python -m unittest tests/test_something.py
034 class that can automatically build
python -m unittest tests/test_something.py
035 instances from the existing
python -m unittest -v test_module
4-based tests

Skipping tests and expected failures¶

New in version 3. 1

Unittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as an “expected failure,” a test that is broken and will fail, but shouldn’t be counted as a failure on a

python -m unittest tests/test_something.py
037

Skipping a test is simply a matter of using the

python -m unittest tests/test_something.py
038 decorator or one of its conditional variants, calling
python -m unittest tests/test_something.py
039 within a
python -m unittest tests/test_something.py
16 or test method, or raising
python -m unittest tests/test_something.py
041 directly.

Basic skipping looks like this

python -m unittest tests/test_something.py
07

This is the output of running the example above in verbose mode

python -m unittest tests/test_something.py
08

Classes can be skipped just like methods

python -m unittest tests/test_something.py
09

python -m unittest tests/test_something.py
042 can also skip the test. This is useful when a resource that needs to be set up is not available

Expected failures use the

python -m unittest tests/test_something.py
043 decorator

python -m unittest tests/test_something.py
30

It’s easy to roll your own skipping decorators by making a decorator that calls

python -m unittest tests/test_something.py
038 on the test when it wants it to be skipped. This decorator skips the test unless the passed object has a certain attribute

python -m unittest tests/test_something.py
31

The following decorators and exception implement test skipping and expected failures

@unittest. skip[reason]

Unconditionally skip the decorated test. reason should describe why the test is being skipped

@unittest. skipIf[condition , reason]

Bỏ qua bài kiểm tra trang trí nếu điều kiện là đúng

@unittest. skipUnless[condition , reason]

Skip the decorated test unless condition is true

@unittest. expectedFailure

Mark the test as an expected failure or error. Nếu thử nghiệm thất bại hoặc lỗi trong chính chức năng thử nghiệm [chứ không phải ở một trong các phương pháp cố định thử nghiệm] thì nó sẽ được coi là thành công. If the test passes, it will be considered a failure

exception unittest. SkipTest[reason]

This exception is raised to skip a test

Usually you can use

python -m unittest tests/test_something.py
039 or one of the skipping decorators instead of raising this directly

Skipped tests will not have

python -m unittest tests/test_something.py
16 or
python -m unittest tests/test_something.py
17 run around them. Skipped classes will not have
python -m unittest tests/test_something.py
048 or
python -m unittest tests/test_something.py
049 run. Skipped modules will not have
python -m unittest tests/test_something.py
050 or
python -m unittest tests/test_something.py
051 run

Distinguishing test iterations using subtests¶

New in version 3. 4

When there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the

python -m unittest tests/test_something.py
052 context manager

For example, the following test

python -m unittest tests/test_something.py
32

will produce the following output

python -m unittest tests/test_something.py
33

Nếu không sử dụng phép thử phụ, quá trình thực thi sẽ dừng sau lỗi đầu tiên và lỗi sẽ khó chẩn đoán hơn vì giá trị của

python -m unittest tests/test_something.py
053 sẽ không được hiển thị

python -m unittest tests/test_something.py
34

Lớp và hàm¶

Phần này mô tả sâu về API của

python -m unittest tests/test_something.py
9

Các ca kiểm thử¶

lớp đơn vị kiểm tra. TestCase[tên phương thức=']

Các thể hiện của lớp

python -m unittest -v test_module
3 đại diện cho các đơn vị kiểm tra logic trong vũ trụ
python -m unittest tests/test_something.py
9. Lớp này dự định sẽ được sử dụng làm lớp cơ sở, với các thử nghiệm cụ thể được thực hiện bởi các lớp con cụ thể. Lớp này triển khai giao diện cần thiết cho người chạy thử nghiệm để cho phép nó thực hiện các bài kiểm tra và các phương thức mà mã kiểm tra có thể sử dụng để kiểm tra và báo cáo các loại lỗi khác nhau

Mỗi phiên bản của

python -m unittest -v test_module
3 sẽ chạy một phương thức cơ sở duy nhất. phương thức có tên methodName. Trong hầu hết các trường hợp sử dụng
python -m unittest -v test_module
3, bạn sẽ không thay đổi tên phương thức cũng như không triển khai lại phương thức mặc định của
python -m unittest tests/test_something.py
059

Đã thay đổi trong phiên bản 3. 2. ______33 có thể được khởi tạo thành công mà không cần cung cấp tên phương thức. Điều này giúp thử nghiệm với

python -m unittest -v test_module
3 từ trình thông dịch tương tác dễ dàng hơn.

Phiên bản

python -m unittest -v test_module
3 cung cấp ba nhóm phương thức. một nhóm được sử dụng để chạy thử nghiệm, một nhóm khác được triển khai thử nghiệm sử dụng để kiểm tra các điều kiện và báo cáo lỗi và một số phương pháp điều tra cho phép thu thập thông tin về bản thân thử nghiệm

Các phương thức trong nhóm đầu tiên [đang chạy thử nghiệm] là

thiết lập[]

Phương pháp được gọi để chuẩn bị vật cố định thử nghiệm. Điều này được gọi ngay trước khi gọi phương thức thử nghiệm; . Việc thực hiện mặc định không có gì

xé xuống[]

Phương thức được gọi ngay sau khi phương thức kiểm tra được gọi và kết quả được ghi lại. Điều này được gọi ngay cả khi phương thức kiểm tra đưa ra một ngoại lệ, vì vậy việc triển khai trong các lớp con có thể cần phải đặc biệt cẩn thận về việc kiểm tra trạng thái bên trong. Bất kỳ ngoại lệ nào, ngoại trừ

python -m unittest tests/test_something.py
063 hoặc
python -m unittest tests/test_something.py
041, được đưa ra theo phương pháp này sẽ được coi là lỗi bổ sung thay vì lỗi thử nghiệm [do đó làm tăng tổng số lỗi được báo cáo]. Phương thức này sẽ chỉ được gọi nếu
python -m unittest tests/test_something.py
16 thành công, bất kể kết quả của phương thức thử nghiệm là gì. Việc thực hiện mặc định không có gì

setUpClass[]

A class method called before tests in an individual class are run.

python -m unittest tests/test_something.py
068 được gọi với lớp là đối số duy nhất và phải được trang trí dưới dạng
python -m unittest tests/test_something.py
069

python -m unittest tests/test_something.py
35

Xem Đồ đạc loại và mô-đun để biết thêm chi tiết

Mới trong phiên bản 3. 2

tearDownClass[]

Một phương thức lớp được gọi sau khi các bài kiểm tra trong một lớp riêng lẻ đã chạy.

python -m unittest tests/test_something.py
070 được gọi với lớp là đối số duy nhất và phải được trang trí dưới dạng
python -m unittest tests/test_something.py
069

python -m unittest tests/test_something.py
36

Xem Đồ đạc loại và mô-đun để biết thêm chi tiết

Mới trong phiên bản 3. 2

run[result=None]

Run the test, collecting the result into the

python -m unittest tests/test_something.py
037 object passed as result. If result is omitted or
python -m unittest tests/test_something.py
52, a temporary result object is created [by calling the
python -m unittest tests/test_something.py
074 method] and used. The result object is returned to
python -m unittest tests/test_something.py
075’s caller

The same effect may be had by simply calling the

python -m unittest -v test_module
3 instance

Changed in version 3. 3. Previous versions of

python -m unittest tests/test_something.py
077 did not return the result. Neither did calling an instance.

skipTest[reason]

Calling this during a test method or

python -m unittest tests/test_something.py
16 skips the current test. See Skipping tests and expected failures for more information.

New in version 3. 1

subTest[msg=None , **params]

Return a context manager which executes the enclosed code block as a subtest. msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly

A test case can contain any number of subtest declarations, and they can be arbitrarily nested

See Distinguishing test iterations using subtests for more information.

New in version 3. 4

debug[]

Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger

The

python -m unittest -v test_module
3 class provides several assert methods to check for and report failures. The following table lists the most commonly used methods [see the tables below for more assert methods]

Method

Kiểm tra xem

Mới

python -m unittest tests/test_something.py
080

python -m unittest tests/test_something.py
081

python -m unittest tests/test_something.py
082

python -m unittest tests/test_something.py
083

python -m unittest tests/test_something.py
084

python -m unittest tests/test_something.py
085

python -m unittest tests/test_something.py
086

python -m unittest tests/test_something.py
087

python -m unittest tests/test_something.py
088

python -m unittest tests/test_something.py
089

3. 1

python -m unittest tests/test_something.py
090

python -m unittest tests/test_something.py
091

3. 1

python -m unittest tests/test_something.py
092

python -m unittest tests/test_something.py
093

3. 1

python -m unittest tests/test_something.py
094

python -m unittest tests/test_something.py
095

3. 1

python -m unittest tests/test_something.py
096

python -m unittest tests/test_something.py
097

3. 1

python -m unittest tests/test_something.py
098

python -m unittest tests/test_something.py
099

3. 1

python -m unittest tests/test_something.py
300

python -m unittest tests/test_something.py
301

3. 2

python -m unittest tests/test_something.py
302

python -m unittest tests/test_something.py
303

3. 2

All the assert methods accept a msg argument that, if specified, is used as the error message on failure [see also

python -m unittest tests/test_something.py
304]. Lưu ý rằng đối số từ khóa msg chỉ có thể được chuyển đến
python -m unittest tests/test_something.py
14,
python -m unittest tests/test_something.py
306,
python -m unittest tests/test_something.py
307,
python -m unittest tests/test_something.py
308 khi chúng được sử dụng làm trình quản lý ngữ cảnh

assertEqual[first , second , msg=None]

Kiểm tra xem thứ nhất và thứ hai có bằng nhau không. If the values do not compare equal, the test will fail

In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with

python -m unittest tests/test_something.py
309 the type-specific equality function will be called in order to generate a more useful default error message [see also the list of type-specific methods ].

Changed in version 3. 1. Added the automatic calling of type-specific equality function.

Changed in version 3. 2.

python -m unittest tests/test_something.py
310 added as the default type equality function for comparing strings.

assertNotEqual[first , second , msg=None]

Test that first and second are not equal. If the values do compare equal, the test will fail

assertTrue[expr , msg=None]assertFalse[expr , msg=None]

Test that expr is true [or false]

Note that this is equivalent to

python -m unittest tests/test_something.py
311 and not to
python -m unittest tests/test_something.py
312 [use
python -m unittest tests/test_something.py
313 for the latter]. This method should also be avoided when more specific methods are available [e. g.
python -m unittest tests/test_something.py
080 instead of
python -m unittest tests/test_something.py
315], because they provide a better error message in case of failure

assertIs[first , second , msg=None]assertIsNot[first , second , msg=None]

Test that first and second are [or are not] the same object

New in version 3. 1

assertIsNone[expr , msg=None]assertIsNotNone[expr , msg=None]

Test that expr is [or is not]

python -m unittest tests/test_something.py
52

New in version 3. 1

assertIn[member , container , msg=None]assertNotIn[member , container , msg=None]

Test that member is [or is not] in container

New in version 3. 1

assertIsInstance[obj , cls , msg=None]assertNotIsInstance[obj , cls , msg=None]

Test that obj is [or is not] an instance of cls [which can be a class or a tuple of classes, as supported by

python -m unittest tests/test_something.py
317]. To check for the exact type, use
python -m unittest tests/test_something.py
318

Mới trong phiên bản 3. 2

It is also possible to check the production of exceptions, warnings, and log messages using the following methods

Method

Kiểm tra xem

Mới

python -m unittest tests/test_something.py
319

python -m unittest tests/test_something.py
320 raises exc

python -m unittest tests/test_something.py
321

python -m unittest tests/test_something.py
320 raises exc and the message matches regex r

3. 1

python -m unittest tests/test_something.py
323

python -m unittest tests/test_something.py
320 raises warn

3. 2

python -m unittest tests/test_something.py
325

python -m unittest tests/test_something.py
320 raises warn and the message matches regex r

3. 2

python -m unittest tests/test_something.py
327

The

python -m unittest tests/test_something.py
328 block logs on logger with minimum level

3. 4

python -m unittest tests/test_something.py
329

The
python -m unittest tests/test_something.py
328 block does not log on

logger with minimum level

3. 10

assertRaises[exception , callable , *args , **kwds]assertRaises[exception , * , msg=None]

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to

python -m unittest tests/test_something.py
14. The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function

python -m unittest tests/test_something.py
37

When used as a context manager,

python -m unittest tests/test_something.py
14 accepts the additional keyword argument msg

The context manager will store the caught exception object in its

python -m unittest tests/test_something.py
333 attribute. This can be useful if the intention is to perform additional checks on the exception raised

python -m unittest tests/test_something.py
38

Changed in version 3. 1. Added the ability to use

python -m unittest tests/test_something.py
14 as a context manager.

Changed in version 3. 2. Added the

python -m unittest tests/test_something.py
333 attribute.

Changed in version 3. 3. Added the msg keyword argument when used as a context manager.

assertRaisesRegex[exception , regex , callable , *args , **kwds]assertRaisesRegex[exception , regex , * , msg=None]

Like

python -m unittest tests/test_something.py
14 but also tests that regex matches on the string representation of the raised exception. regex may be a regular expression object or a string containing a regular expression suitable for use by
python -m unittest tests/test_something.py
337. Examples

python -m unittest tests/test_something.py
39

or

python -m unittest tests/test_something.py
60

New in version 3. 1. Added under the name

python -m unittest tests/test_something.py
338.

Changed in version 3. 2. Renamed to

python -m unittest tests/test_something.py
306.

Changed in version 3. 3. Added the msg keyword argument when used as a context manager.

assertWarns[warning , callable , *args , **kwds]assertWarns[warning , * , msg=None]

Test that a warning is triggered when callable is called with any positional or keyword arguments that are also passed to

python -m unittest tests/test_something.py
307. The test passes if warning is triggered and fails if it isn’t. Any exception is an error. To catch any of a group of warnings, a tuple containing the warning classes may be passed as warnings

If only the warning and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function

python -m unittest tests/test_something.py
61

When used as a context manager,

python -m unittest tests/test_something.py
307 accepts the additional keyword argument msg

Trình quản lý bối cảnh sẽ lưu trữ đối tượng cảnh báo bị bắt trong thuộc tính

python -m unittest tests/test_something.py
342 của nó và dòng nguồn đã kích hoạt cảnh báo trong thuộc tính
python -m unittest tests/test_something.py
343 và
python -m unittest tests/test_something.py
344. This can be useful if the intention is to perform additional checks on the warning caught

python -m unittest tests/test_something.py
62

This method works regardless of the warning filters in place when it is called

Mới trong phiên bản 3. 2

Changed in version 3. 3. Added the msg keyword argument when used as a context manager.

assertWarnsRegex[warning , regex , callable , *args , **kwds]assertWarnsRegex[warning , regex , * , msg=None]

Like

python -m unittest tests/test_something.py
307 but also tests that regex matches on the message of the triggered warning. regex may be a regular expression object or a string containing a regular expression suitable for use by
python -m unittest tests/test_something.py
337. Example

python -m unittest tests/test_something.py
63

or

python -m unittest tests/test_something.py
64

Mới trong phiên bản 3. 2

Changed in version 3. 3. Added the msg keyword argument when used as a context manager.

assertLogs[logger=None , level=None]

A context manager to test that at least one message is logged on the logger or one of its children, with at least the given level

If given, logger should be a

python -m unittest tests/test_something.py
347 object or a
python -m unittest tests/test_something.py
348 giving the name of a logger. The default is the root logger, which will catch all messages that were not blocked by a non-propagating descendent logger

If given, level should be either a numeric logging level or its string equivalent [for example either

python -m unittest tests/test_something.py
349 or
python -m unittest tests/test_something.py
350]. The default is
python -m unittest tests/test_something.py
351

The test passes if at least one message emitted inside the

python -m unittest tests/test_something.py
328 block matches the logger and level conditions, otherwise it fails

The object returned by the context manager is a recording helper which keeps tracks of the matching log messages. It has two attributes

records

A list of

python -m unittest tests/test_something.py
353 objects of the matching log messages

output

A list of

python -m unittest tests/test_something.py
348 objects with the formatted output of matching messages

Example

python -m unittest tests/test_something.py
65

New in version 3. 4

assertNoLogs[logger=None , level=None]

A context manager to test that no messages are logged on the logger or one of its children, with at least the given level

If given, logger should be a

python -m unittest tests/test_something.py
347 object or a
python -m unittest tests/test_something.py
348 giving the name of a logger. The default is the root logger, which will catch all messages

If given, level should be either a numeric logging level or its string equivalent [for example either

python -m unittest tests/test_something.py
349 or
python -m unittest tests/test_something.py
350]. The default is
python -m unittest tests/test_something.py
351

Unlike

python -m unittest tests/test_something.py
360, nothing will be returned by the context manager

New in version 3. 10

There are also other methods used to perform more specific checks, such as

Method

Kiểm tra xem

Mới

python -m unittest tests/test_something.py
361

python -m unittest tests/test_something.py
362

python -m unittest tests/test_something.py
363

python -m unittest tests/test_something.py
364

python -m unittest tests/test_something.py
365

python -m unittest tests/test_something.py
366

3. 1

python -m unittest tests/test_something.py
367

python -m unittest tests/test_something.py
368

3. 1

python -m unittest tests/test_something.py
369

python -m unittest tests/test_something.py
370

3. 1

python -m unittest tests/test_something.py
371

python -m unittest tests/test_something.py
372

3. 1

python -m unittest tests/test_something.py
373

python -m unittest tests/test_something.py
374

3. 1

python -m unittest tests/test_something.py
375

python -m unittest tests/test_something.py
376

3. 2

python -m unittest tests/test_something.py
377

a and b have the same elements in the same number, regardless of their order

3. 2

assertAlmostEqual[first , second , places=7 , msg=None , delta=None]assertNotAlmostEqual[first , second , places=7 , msg=None , delta=None]

Kiểm tra xem thứ nhất và thứ hai có xấp xỉ [hoặc không xấp xỉ] bằng nhau bằng cách tính chênh lệch, làm tròn đến số vị trí thập phân đã cho [mặc định là 7] và so sánh với 0. Lưu ý rằng các phương pháp này làm tròn các giá trị đến số vị trí thập phân đã cho [i. e. như hàm

python -m unittest tests/test_something.py
378] và các chữ số không có nghĩa

Nếu delta được cung cấp thay vì vị trí thì chênh lệch giữa thứ nhất và thứ hai phải nhỏ hơn hoặc bằng [hoặc lớn hơn] delta

Cung cấp cả đồng bằng và địa điểm tăng

python -m unittest tests/test_something.py
379

Đã thay đổi trong phiên bản 3. 2. ______2380 tự động coi các đối tượng gần như bằng nhau để so sánh bằng nhau.

python -m unittest tests/test_something.py
381 tự động thất bại nếu các đối tượng so sánh bằng nhau. Đã thêm đối số từ khóa delta.

assertGreater[thứ nhất , thứ hai, msg=None]assertGreaterEqual[first, second, msg=None]assertLess[first, second, msg=None]assertLessEqual[first, second, msg=None]

Kiểm tra cái đầu tiên tương ứng là >, >=, < hoặc

Chủ Đề